Last active
January 31, 2025 12:35
-
-
Save jamesgregson/ecd73752e66f19eeb0fab46e5114e26e to your computer and use it in GitHub Desktop.
JSON-RPC with NodeMCU and ArduinoJSON
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ArduinoJson.h> | |
#include <ESP8266WiFi.h> //ESP8266 Core WiFi Library (you most likely already have this in your sketch) | |
#include <DNSServer.h> //Local DNS Server used for redirecting all requests to the configuration portal | |
#include <ESP8266WebServer.h> //Local WebServer used to serve the configuration portal | |
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager WiFi Configuration Magic | |
// change the IP address in the following line, should return "hello world" wrapped in JSON-RPC boilerplate | |
// curl -d '{"jsonrpc": "2.0", "method": "concatenate", "params": ["hello", "world"], "id": 5}' -H "Content-Type: application/json" -X POST http://192.168.0.24/api | |
ESP8266WebServer http_server(80); | |
volatile int counter=0; | |
void setup() { | |
Serial.begin(115200); | |
Serial.println("Configuring WiFi..."); | |
WiFiManager wifiManager; | |
//wifiManager.resetSettings(); | |
wifiManager.autoConnect("SetupDevice"); | |
Serial.println("Setting up JSON-RPC server..."); | |
http_server.on("/api", HTTP_POST, handle_json ); | |
http_server.begin(); | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
http_server.handleClient(); | |
counter++; | |
delay(100); | |
} | |
void handle_json(){ | |
DynamicJsonBuffer jsonBuffer; | |
JsonObject& root = jsonBuffer.parseObject(http_server.arg("plain")); | |
Serial.println( "=====================" ); | |
Serial.println( String("jsonrpc: ") + root["jsonrpc"].as<String>() ); | |
Serial.println( String("id: ") + root["id"].as<String>() ); | |
Serial.println( String("method: ") + root["method"].as<String>() ); | |
Serial.println( String("params: ") + root["params"].as<String>() ); | |
int id = root["id"].as<int>(); | |
String k1 = root["params"][0].as<String>(); | |
String k2 = root["params"][1].as<String>(); | |
JsonObject& resp = jsonBuffer.createObject(); | |
resp["jsonrpc"] = "2.0"; | |
resp["id"] = id; | |
resp["result"] = k1 + " " + k2; | |
Serial.println("Response:"); | |
resp.printTo(Serial); | |
String out; | |
resp.printTo(out); | |
http_server.send( 200, "application/json", out.c_str() ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment