NodeMCU reçoit la commande en byte* payload et atoi me renvoie 0
Traduit de English par IA ·
Bonjour, je débute encore. J’ai un NodeMCU (ESP8266) avec PubSubClient qui pilote une bande LED via un MOSFET. Sur ma carte Hermetry, il y a un curseur qui envoie une commande appelée light.set. Je vois le message arriver dans le moniteur série :
topic: v1/rpc/req/17
payload: {"method":"light.set","params":{"level":42}}
Mais dans mon callback, je n’arrive pas à extraire le 42. J’ai essayé :
void callback(char* topic, byte* payload, unsigned int length) {
int level = atoi((char*)payload);
analogWrite(D5, level);
}
level vaut toujours 0, parfois un grand nombre aléatoire. La bande ne change pas. Je pense aussi que le curseur affiche « Sent; waiting for the device » indéfiniment. Qu’est-ce que je fais de mal ?
Hello, still learning. I have a NodeMCU (ESP8266) with PubSubClient controlling a LED strip through a MOSFET. On my Hermetry board there’s a slider that sends a command called light.set. I can see the message arrive in the serial monitor:
topic: v1/rpc/req/17
payload: {"method":"light.set","params":{"level":42}}
But in my callback I can’t get the 42 out. I tried:
void callback(char* topic, byte* payload, unsigned int length) {
int level = atoi((char*)payload);
analogWrite(D5, level);
}
level is always 0, sometimes a random big number. The strip doesn’t change. I also think the slider shows « Sent; waiting for the device » forever. What am I doing wrong?
Traduit de English par IA ·
Peut-être faudrait-il d’abord la convertir en String ? String s = (char*)payload;
Maybe cast it to a String first? String s = (char*)payload;
Traduit de English par IA ·
Le payload n’est pas terminé par un caractère nul, donc le lire comme une chaîne C dépasse la fin. C’est ce nombre aléatoire.
The payload isn’t null-terminated, so reading it as a C string runs past the end. That’s the random number.
Traduit de English par IA ·
Même avec un null à la fin, atoi sur {« method »:… renvoie 0 parce que le premier caractère est une accolade. Vous devez analyser le JSON.
Even with a null at the end, atoi on {« method »:… gives 0 because the first character is a brace. You need to parse the JSON.
Traduit de English par IA ·
Kevin A et Maria ont tous deux raison sur un point. J’ai réalisé presque le même contrôleur de lumière pour notre bureau l’an dernier. Analyse le JSON avec ArduinoJson (il prend le buffer et la longueur, donc pas besoin de null), récupère l’identifiant de la requête à la fin du topic, et réponds sur v1/rpc/res/ avec cet identifiant. Le « waiting for the device » reste, car la carte ne reçoit jamais de réponse.
#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}");
}
Sur ESP8266, analogWrite va de 0 à 1023 par défaut, d’où le map. Et abonne-toi à v1/rpc/req/+ après chaque reconnexion, pas seulement dans setup, sinon les commandes s’arrêtent après la première coupure Wi-Fi.
La liste des topics se trouve dans la MQTT topics and payload reference.
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.
Traduit de English par IA ·
Ça marche !! La bande se règle maintenant avec le curseur et la carte affiche Done. Je répondais aussi sur v1/rpc/req/17 au lieu de res, donc même quand j’obtenais le bon nombre, rien ne revenait. Merci Emily.
It works!! The strip dims with the slider now and the board says Done. I had also been answering on v1/rpc/req/17 instead of res, so even when I got the number right nothing came back. Thank you Emily.
- Vous devez être connecté pour répondre à ce sujet.
Rejoignez la discussion
Connectez-vous pour poser et répondre à des questions, aimer les messages utiles et marquer la réponse qui a résolu votre problème. Chaque contribution rapporte des points et des niveaux.

