0

I'm configuring an ESP8266 using Arduino Uno.

I have several MQTT topics I wish it to subscribe, and I do not want to repeat code 3 or 4 times ( in Python I would have created a list - and make a for loop to subscribe all )

These are my topics:

//MQTT topic
const char* deviceName = "Sonoff1";
const char* deviceTopic = "HomePi/Switches/Sonoff1";
const char* msgTopic = "HomePi/Messages";
const char* groupTopic = "HomePi/All";

This is the function registering a single topic:

void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
                Serial.print("Attempting MQTT connection...");
                // Attempt to connect
                if (client.connect(deviceName,user, passw)) {
                        Serial.println("connected");
                        pub_msg("Power On");
                        client.subscribe(deviceTopic);
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        Serial.println(" try again in 5 seconds");
                        // Wait 5 seconds before retrying
                        delay(5000);
                }
        }
}

Appriciate you kind help,

Guy

  • 1
    make an array and use a for loop – Juraj Sep 15 '18 at 7:19
1

just for a closure:

added an array (thank to Juraj):const char* topicsArry[]={deviceTopic, msgTopic, groupTopic, "HomePi/Dvir/Clock", "HomePi/Dvir/Alerts"};

a for loop to over this that loop, and using sizeof ( which was not trivial for me ), led to :

void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
                Serial.print("Attempting MQTT connection...");
                // Attempt to connect
                if (client.connect(deviceName,user, passw)) {
                        Serial.println("connected");
                        pub_msg("Power On");
                        for (int i=0; i<=sizeof(topicsArry)/sizeof(char *); i++){
                          client.subscribe(topicsArry[i]);
                          char msg[50];
                          sprintf(msg, "Subscribed to %s",topicsArry[i]);
                          pub_msg(msg);
                        }
                } else {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        Serial.println(" try again in 5 seconds");
                        // Wait 5 seconds before retrying
                        delay(5000);
                }
        }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.