MQTT Callback on matched topic payload

Want to restart my device on if a MQTTCallback message matches say 5343.

What I am missing please?

void mqttCallback(char *topic, byte *payload, unsigned int len)
{

  SerialMon.print("Message arrived [");
  SerialMon.print(topic);
  SerialMon.print("]: ");
  SerialMon.write(payload, len);
  SerialMon.println();

    if (String(topic) == topicRestart) {
       if (!strcmp((char* )topic, (byte* )payload) == 5343) {
      // do something
     Serial.println("Restarting in 10 seconds..");
     delay(500);
     //ESP.restart();
    }
  }
} 

The command 'strcmp' compares two character arrays. The variable payload is a pointer to a byte array. Since you want to check the payload and have already checked content of topic, I am not sure why you have '(char*) topic' in the strcmp comparison?

The payload is sent as an array of ASCII characters, so the received payload will contain an array of the received ASCII character codes. You can convert by casting to char and using atoi to convert to an integer like this:

if ( atoi( (char*)payload ) == 5343 ) {
// do something
}

Just make sure that payload is never greater in value than a 16-bit integer, in which case you may need to use atol instead.

This works but will try your example, thanks

if (!strncmp((char *)payload, "5343", len)) {

Yes, that is another approach.

Thanks just been reading up on atol, parses the C-string str interpreting its content as an integral number, which is returned as a value of type int

Message arrived [name/topic1]: 2
Message arrived [name/topic1]: 1
Message arrived [name/topic1]: 5343
Restarting in 10 seconds..

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.