 
 #define HUB_SIZE 4
 #include <IoTaDeviceHub.h>
-
 #include "iota_defines.h"
 #include "heartbeat.h"
 #include "LedSerialMaster.h"


void loop() {
	
	// Check if a new client has connected
	WiFiClient newClient = server.available();
	

	/*
	Connection process:
		1. client appears at wifi server
		2. read first byte transmitted by client connecting
		3. if client sent MAGIC_BYTE (65) continue
		4. send back magic byte+1
		5. wait for client to send an empty data packet addressed for FID
		6. add clientId to clientMap
		7. enjoy your fancy new connected client!
	*/

	if (newClient) {
		for (int i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
			if (unAuthClients[i].first < 0)
			{
				Serial.print("New unauth client at ");
				Serial.print(i);
				int now = micros();
				Serial.print(" t = ");
				Serial.println(now);
				unAuthClients[i].first = now;
				unAuthClients[i].second = newClient;
				i = MAX_UNAUTH_CLIENTS;
			}
		}	
	}
	
	int tnow = micros();
	int timeout_us = 4000000;
	for (int i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
		yield();
		if (tnow - unAuthClients[i].first > timeout_us && unAuthClients[i].first > 0) {
			//remove due to lack of connections
			Serial.print("Removing client timeout ");
			Serial.println(i);
			unAuthClients[i].first = -1;
		}
		else if(unAuthClients[i].first > 0)
		{	
			//Serial.print("Checking ");
			//Serial.println(i);
			//try to handshake
			if (unAuthClients[i].second.available() > 0) {
				uint8_t firstContact = unAuthClients[i].second.read();
				Serial.print("Unauth sent: ");
				Serial.println(firstContact);

				if (firstContact == MAGIC_BYTE) {
					Serial.println("Got first part of handshake, responding");
					unAuthClients[i].second.write(MAGIC_BYTE + 1);
				}
			}
			
		}
	}
	

	byte mac[6];
	WiFi.macAddress(mac);
	Serial.printf("Mac address: %h %h %h %h %h %h \n", mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]);
	Serial.printf("Chip id: %d\n", ESP.getChipId());
	uuid = (ESP.getChipId() << 32 | mac[0] << 24 | mac[1] << 16 | mac[2] << 9 | mac[3]);
	Serial.printf("UUID : %l", uuid);
	
	hub = new IoTaDeviceHub(uuid);
	hub->addFunc(&hb);
	hub->addFunc(&led);
	
	unAuthClients = new std::tuple<uint, connStatusEnum, WiFiClient>[MAX_UNAUTH_CLIENTS];
	for (int i = 0; i < MAX_UNAUTH_CLIENTS; i++) {
		std::get<authProg>(unAuthClients[i]) = NOT_CONNECTED;
	}

	clientMap = new iota::Map<long, WiFiClient*>(10);
