Parse JSON instead of arbitrary format. This is a little bloated right now, but we might as well leave room for future feature creep.

This commit is contained in:
Anna Rose 2020-05-11 17:01:12 +00:00
parent 7da086221b
commit 0f54743fa2

View File

@ -1,6 +1,7 @@
#include "config.h" #include "config.h"
#include <ESP8266WiFi.h> #include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h> #include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
// how long to delay between each request to the // how long to delay between each request to the
// server, in ms. // server, in ms.
@ -93,33 +94,41 @@ bool poll_server() {
} }
void parse_webhook_response(String raw_data) { void parse_webhook_response(String raw_data) {
int data[sizeof(PIN_MAP)] = {-1}; // int data[sizeof(PIN_MAP)] = {-1};
// TODO: split the data and turn it into numbers // // TODO: split the data and turn it into numbers
while (raw_data.length() > 0) { // while (raw_data.length() > 0) {
// read to a newline // // read to a newline
String line = raw_data.substring(0, raw_data.indexOf('\n')); // String line = raw_data.substring(0, raw_data.indexOf('\n'));
raw_data.remove(0, raw_data.indexOf('\n') + 1); // raw_data.remove(0, raw_data.indexOf('\n') + 1);
// extract data from the line and add it to our incoming data array // // extract data from the line and add it to our incoming data array
int index = line.substring(0, raw_data.indexOf(' ')).toInt(); // int index = line.substring(0, raw_data.indexOf(' ')).toInt();
int state = line.substring(raw_data.indexOf(' ')+1).toInt(); // int state = line.substring(raw_data.indexOf(' ')+1).toInt();
data[index] = state; // data[index] = state;
// }
StaticJsonDocument<256> doc;
DeserializationError err = deserializeJson(doc, raw_data);
if (err) {
Serial.print("Couldn't parse json data. Error code: ");
Serial.println(err.c_str());
} }
// we split this into a second loop so we can detect JsonArray data = doc.as<JsonArray>();
// missing data more easily. int i = 0;
for (int i = 0; i < sizeof(data); i++) { for (JsonVariant item : data) {
if (data[i] == -1) {
Serial.print("Did not receive data for pin ");
Serial.println(PIN_MAP[i][0]);
}
if (tripped(i) && data[i] == HIGH) { if (tripped(i) && data[i] == HIGH) {
continue; continue;
} }
pin_states[i] = data[i]; pin_states[i] = item;
i++;
}
if (data.size() < sizeof(pin_states) / sizeof(*pin_states)) {
Serial.println("Did not receive data for all pins.");
} }
} }