edit arduino code

Took 5 seconds
This commit is contained in:
Tobias Hopp 2023-01-21 15:36:19 +01:00
parent 8abb7737c6
commit 20def40001

View File

@ -1,39 +1,71 @@
/**
* Official proxy code for iTender GPIO Communication
**/
#include <ArduinoJson.h>
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<JSON_BUFFER_SIZE> incomingJson;
// Create a JSON object for outgoing messages
DynamicJsonDocument<JSON_BUFFER_SIZE> 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<JsonObject>().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);
}
}
}
}