From 0f54743fa21f6b3c2ec711203e5e7c7266dd2d33 Mon Sep 17 00:00:00 2001 From: Anna Wiggins Date: Mon, 11 May 2020 17:01:12 +0000 Subject: [PATCH] Parse JSON instead of arbitrary format. This is a little bloated right now, but we might as well leave room for future feature creep. --- smartswitch.ino | 47 ++++++++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 19 deletions(-) diff --git a/smartswitch.ino b/smartswitch.ino index b4065e2..e17d02d 100644 --- a/smartswitch.ino +++ b/smartswitch.ino @@ -1,6 +1,7 @@ #include "config.h" #include #include +#include // how long to delay between each request to the // server, in ms. @@ -93,33 +94,41 @@ bool poll_server() { } void parse_webhook_response(String raw_data) { - int data[sizeof(PIN_MAP)] = {-1}; - // TODO: split the data and turn it into numbers + // int data[sizeof(PIN_MAP)] = {-1}; + // // TODO: split the data and turn it into numbers - while (raw_data.length() > 0) { - // read to a newline - String line = raw_data.substring(0, raw_data.indexOf('\n')); - raw_data.remove(0, raw_data.indexOf('\n') + 1); + // while (raw_data.length() > 0) { + // // read to a newline + // String line = raw_data.substring(0, raw_data.indexOf('\n')); + // raw_data.remove(0, raw_data.indexOf('\n') + 1); - // extract data from the line and add it to our incoming data array - int index = line.substring(0, raw_data.indexOf(' ')).toInt(); - int state = line.substring(raw_data.indexOf(' ')+1).toInt(); - data[index] = state; + // // extract data from the line and add it to our incoming data array + // int index = line.substring(0, raw_data.indexOf(' ')).toInt(); + // int state = line.substring(raw_data.indexOf(' ')+1).toInt(); + // 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 - // missing data more easily. - for (int i = 0; i < sizeof(data); i++) { - if (data[i] == -1) { - Serial.print("Did not receive data for pin "); - Serial.println(PIN_MAP[i][0]); - } - + JsonArray data = doc.as(); + int i = 0; + for (JsonVariant item : data) { if (tripped(i) && data[i] == HIGH) { 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."); } }