Skip to content

Instantly share code, notes, and snippets.

@luigibrancati
Last active March 9, 2022 18:56
Show Gist options
  • Select an option

  • Save luigibrancati/63dc7a72764490910ce45330619233f3 to your computer and use it in GitHub Desktop.

Select an option

Save luigibrancati/63dc7a72764490910ce45330619233f3 to your computer and use it in GitHub Desktop.
Code to run the APIs
#include "memory_utils.h"
#include <ArduinoJson.h>
StaticJsonDocument<250> responseJson;
char buffer[250];
void createJson(String message) {
responseJson.clear();
responseJson["message"] = message;
serializeJson(responseJson, buffer);
}
void getServerMessage(){
Serial.println("Getting message");
String message = readMessage("");
createJson(message);
server.send(200, "application/json", buffer);
}
void updateServerMessage(){
Serial.println("Updating message");
if (server.hasArg("plain") == false) {
Serial.println("Wrong json body!");
server.send(400, "application/json", "{}");
}
String body = server.arg("plain");
deserializeJson(responseJson, body);
if(!responseJson.containsKey("message")){
Serial.println("Wrong json body! Missing message field.");
server.send(400, "application/json", "Request missing message key.");
return;
}
else{
if(updateMessage(responseJson["message"])){
Serial.println("Setting message");
server.send(200, "application/json", "{}");
}
else{
Serial.println("Last read message is the same, not updating it in memory");
server.send(200, "application/json", "Last read message is the same, not updating it in memory.");
}
}
}
void setupRouting() {
//Sets a server routing so that each endpoint is assigned to an handler
// Message
server.on("/message", getServerMessage);
server.on("/message/set", HTTP_POST, updateServerMessage);
// start server
server.begin();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment