Hi All
I've got a Home Assistant automation which sends 2 values to a MQTT payload.
This is getting received by my ESP32 no problem... but I can't seem to use those variables...
This output is give:
{ state: off, lightlevel: 1500!�?
0
0
Do you mean messageBuffer[length-1] = '\0'; It may help avoid corrupting anything near messageBuffer. Anyway, from your print out, it looks like messageBuffer does not contain valid JSON.
EDIT
and, as already pointed out, 30 does seem a bit short if you also want the closing brace '}' possibly with a preceding space :
first off you were absolutely right about the JSON not being properly formed.... The payload is actually being sent by a Home Assistant automation and there were " " missing... I've added them and the data is coming through now and I'm not getting the 0 results....
where the XXXXXXXX is below, what could I put that creates the type of string variable that I can use in my IF statement at the end??
void callback(char* topic, byte* payload, unsigned int length) {
char messageBuffer[50];
memcpy(messageBuffer, payload, length);
messageBuffer[length] = '\0';
StaticJsonDocument <256> doc;
deserializeJson(doc,messageBuffer);
**XXXXXXXX** state = doc["state"];
int lightlevel = doc["lightlevel"];
Serial.println(messageBuffer);
Serial.println(state);
Serial.println(lightlevel);
if (state == "on"){
if you go for c-strings, stick to c-strings functions, don't generate a String which will duplicate the value in memory... You'll eat up RAM for nothing
void callback(char* topic, byte* payload, unsigned int length) {
StaticJsonDocument <256> doc;
DeserializationError error = deserializeJson(doc, (char*) payload, length);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
} else {
const char* state = doc["state"];
int lightlevel = doc["lightlevel"];
Serial.println(state);
Serial.println(lightlevel);
if (strcmp(state, "on") == 0) { // see https://cplusplus.com/reference/cstring/strcmp/
// we got state "on"
....
} else {
// we (likely) got state "off"
....
}
}
}
really also drop the idea of making a copy of the buffer....
it's useless and costly and error prone as you don't know if length is >= 50 then you'll introduce a bug in your code.
The buffer is already available through the payload pointer, just use it.