From 20def400015ee9c01a7d593d42e71283009dfb52 Mon Sep 17 00:00:00 2001 From: Tobias Hopp Date: Sat, 21 Jan 2023 15:36:19 +0100 Subject: [PATCH] edit arduino code Took 5 seconds --- arduino/itender/itender.ino | 78 ++++++++++++++++++++++++++----------- 1 file changed, 55 insertions(+), 23 deletions(-) diff --git a/arduino/itender/itender.ino b/arduino/itender/itender.ino index c1437d1..419b4ae 100644 --- a/arduino/itender/itender.ino +++ b/arduino/itender/itender.ino @@ -1,39 +1,71 @@ /** * Official proxy code for iTender GPIO Communication **/ - #include -const int BUFFER_SIZE = 256; -char buffer[BUFFER_SIZE]; -int bufferIndex = 0; +// Define the size of the JSON buffer +#define JSON_BUFFER_SIZE 256 + +// Create a JSON object for incoming messages +StaticJsonDocument incomingJson; + +// Create a JSON object for outgoing messages +DynamicJsonDocument outgoingJson; void setup() { - Serial.begin(115200); + // Initialize serial communication + Serial.begin(9600); } +void(* resetFunc) (void) = 0; //declare reset function @ address 0 + void loop() { - if (Serial.available() > 0) { - char incomingByte = Serial.read(); - buffer[bufferIndex] = incomingByte; - bufferIndex++; + // Wait for a new line on the serial console + if (Serial.available()) { + // Read the incoming JSON message + DeserializationError error = deserializeJson(incomingJson, Serial); + if (error) { + // Handle error + } else { + // Extract the "type" and "data" fields from the JSON object + String id = incomingJson["id"]; + String type = incomingJson["type"]; + JsonVariant data = incomingJson["data"]; - if (incomingByte == '\n') { - buffer[bufferIndex] = '\0'; - bufferIndex = 0; + // Create a nested object in the root object + JsonObject outgoingData = outgoingJson.to().createNestedObject("data"); - StaticJsonDocument<200> doc; - DeserializationError error = deserializeJson(doc, buffer); - if (error) { - Serial.print(F("deserializeJson() failed: ")); - Serial.println(error.c_str()); - return; + outgoingData["success"] = true; + + // Handle the message based on the "type" field + switch (type) { + case "ACK": + // Handle ACK message + break; + case "SET_PIN": + // Handle SET_PIN message + break; + case "GET_VAL": + // Handle GET_VAL message + break; + case "GET_SENSOR": + // Handle GET_SENSOR message + break; + case "RESTART": + resetFunc(); //call reset + break; + default: + // Handle unknown message type + break; } - // Do something with the deserialized JSON object - int value = doc["value"]; - Serial.println(value); + // Prepare the outgoing JSON message + outgoingJson["id"] = id; + outgoingJson["type"] = type; + outgoingJson["data"] = ""; + + // Send the outgoing JSON message + serializeJson(outgoingJson, Serial); } } -} - +} \ No newline at end of file