简体   繁体   中英

callback to check specific MQTT topic (not just check the payload)

I currently use the below callback to check the PAYLOAD of incoming MQTT messages, but does anyone know how I could continue to do this but also find messages coming under a specific TOPIC?

void callback(char * topic, byte * payload, unsigned int length) {
    char p[length + 1];
    memcpy(p, payload, length);
    p[length] = NULL;

    if (!strcmp(p, "home")) {
        Particle.publish(DEVICE_NAME, HOME_MSSG, 60, PRIVATE);
    } else if (!strcmp(p, "chome")) {
        Particle.publish(DEVICE_NAME, CHOME_MSSG, 60, PRIVATE);
    } 
}

The topic can be handled in pretty much the same way as the payload; eg

if (!strcmp(topic, "thisIsATopic")) {
        // do something
}

Note that the payload is copied for two reasons:

  • The buffer is reused once the callback returns (so if you store that pointer and refer to it later it may not contain what you expect).
  • The message is binary so it is important to ensure a \0 is added to the end if using functions like strcmp (to avoid overruns).

It looks like the library you are using copies the topic so you should be fine using that as-is (unlike with some other libraries ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM