xoseperez / sonoffsc

Itead Studio SonoffSC custom firmware with MQTT and Domoticz support
GNU General Public License v3.0
104 stars 35 forks source link

Can't get the mqqtSubscribe function to work #5

Closed Justblair closed 7 years ago

Justblair commented 7 years ago

In my Callback I try to subscribe to /sonoffsc/rgb to listen for instructions to trigger light changes.

I try this: // When connected, subscribe to the topic if (type == MQTT_CONNECT_EVENT) { mqttSubscribe(MQTT_RGB_TOPIC); // Feel I should be using mqttSubscribe here... } where:

define MQTT_TOPIC "/sonoffsc"

define MQTT_RGB_TOPIC "/rgb"

but it does not work....

This works: // When connected, subscribe to the topic if (type == MQTT_CONNECT_EVENT) { mqttSubscribeRaw(MQTT_RGB_TOPIC); // Feel I should be using mqttSubscribe here... } where:

define MQTT_RGB_TOPIC "/sonoffsc/rgb"

i can't help feeling that the mqttSubscribe is more consistant.

xoseperez commented 7 years ago

When you are using mqttSubscribe is prepends the root topic to the topic you pass as an argument (the subtopic), but when a message is received you get the whole topic (root + subtopic). If you are comparing the topic you get in the callback to MQTT_RGB_TOPIC with strcmp it won't match.

Justblair commented 7 years ago

void mqttCallback(unsigned int type, const char topic, const char payload) {

// When connected, subscribe to the topic
if (type == MQTT_CONNECT_EVENT) {
    mqttSubscribe(MQTT_RGB_TOPIC);
    // Feel I should be using mqttSubscribe here... 
}

// 
if (type == MQTT_MESSAGE_EVENT) {
    String mqttTopic = (MQTT_TOPIC + (String)MQTT_RGB_TOPIC);
    if (strcmp(topic, mqttTopic.c_str) == 0) {
        sendColor((char*)payload);
    }
}

}

Is this what you mean?

Justblair commented 7 years ago

OK apart from missing the brackets on c_str, that seems to work..