Nouveau : le pare-feu IA surveille toute la plateforme et explique chaque incident en termes simples. Découvrez comment ça marche

Reply To: NodeMCU gets the command as byte* payload and atoi gives me 0

Kevin A and Maria have both bits. I did nearly the same light controller for our office last year. Parse the JSON with ArduinoJson (it takes the buffer and length, so no null needed), pull the request id off the end of the topic, and answer on v1/rpc/res/ with that id. The « waiting for the device » stays because the board never gets an answer.

#include <ArduinoJson.h>
void callback(char* topic, byte* payload, unsigned int length) {
String t(topic);
String id = t.substring(t.lastIndexOf('/') + 1);   // "17"
StaticJsonDocument<256> doc;
if (deserializeJson(doc, payload, length)) return;
if (doc["method"] == "light.set") {
int level = doc["params"]["level"] | -1;          // -1 if missing
if (level >= 0 && level <= 100) {
analogWrite(D5, map(level, 0, 100, 0, 1023));
client.publish(("v1/rpc/res/" + id).c_str(), "{"ok":true}");
return;
}
}
client.publish(("v1/rpc/res/" + id).c_str(), "{"ok":false}");
}

ESP8266 analogWrite is 0-1023 by default, hence the map. And subscribe to v1/rpc/req/+ after every reconnect, not only in setup, or commands stop after the first Wi-Fi drop.

The topic list is on MQTT topics and payload reference.

Solution acceptée♥ 1