void leadHQHandle(void) { int rsize; unsigned short index[32]; // <10 keypairs in the incoming json // only continue if new data to read if (!Scout.wifi.client.available()) { return; } // Read a block of data and look for packets while ((rsize = hqIncoming.readClient(Scout.wifi.client, 128))) { int nl; while((nl = hqIncoming.indexOf('\n')) >= 0) { // look for a packet if (hqVerboseOutput) { Serial.print(F("looking for packet in: ")); Serial.println(hqIncoming); } // Parse JSON up to the first newline if (!js0n((const unsigned char*)hqIncoming.c_str(), nl, index, 32)) { leadIncoming(hqIncoming.c_str(), nl, index); } else { if (hqVerboseOutput) { Serial.println(F("JSON parse failed")); } } // Remove up to and including the newline hqIncoming.remove(0, nl + 1); } } }
// this is called on the main loop to try to (re)connect to the HQ void leadHQHandle(void) { static char *buffer = NULL; uint8_t block[128]; char *nl; int rsize, len; unsigned short index[32]; // <10 keypairs in the incoming json // only continue if new data to read if (!Scout.wifi.client.available()) { return; } // check to initialize our read buffer if (!buffer) { buffer = (char*)malloc(1); *buffer = 0; } // get all waiting data and look for packets while (rsize = Scout.wifi.client.read(block, sizeof(block))) { len = strlen(buffer); // process chunk of incoming data buffer = (char*)realloc(buffer, len + rsize + 1); if (!buffer) { return; // TODO, realloc error, need to restart? } memcpy(buffer + len, block, rsize); buffer[len + rsize] = 0; // null terminate // look for a packet if (hqVerboseOutput) { sp("looking for packet in: "); speol(buffer); } nl = strchr(buffer, '\n'); if (!nl) { continue; } // null terminate just the packet and process it *nl = 0; j0g(buffer, index, 32); if (*index) { leadIncoming(buffer, index); } else { if (hqVerboseOutput) { speol("JSON parse failed"); } } // advance buffer and resize, minimum is just the buffer end null nl++; len = strlen(nl); memmove(buffer, nl, len+1); buffer = (char*)realloc(buffer, len+1); // shrink } }