Receiving control commands

In the last chapter, you learned how to send data to the broker.

In the next step, the IoT device should be able to receive data in order to be remotely controlled.

working task 1

Apply the changes to the reaction to external control commands. Use an MQTT app to control the fan.

working task 2

Complete the program to control the heating with the variable “ActivateHeating”.

MQTT Callback

For this purpose, a “callback” function must be added. This callback function is automatically called by the system as soon as a broker issues a control command. In order for the IoT device to receive the commands, the device must log in to the broker for the notification (subscribe).

[...]

void setupMQTT() {
 mqttClient.setServer(mqttServer, 1883);
 mqttClient.setCallback(mqttCallback);
}

void mqttCallback(char* topic, byte* payload, unsigned int length) {
 Serial.print("Command is: ");
 Serial.println(topic);
 int p = (char)payload[0] - '0';
 if(("CRBK/"+HOST_NAME+"/ActivateFan")==String(topic)) {
   activateFan = p!=0;
 } 
 Serial.println();
} //end callback

void connectMQTT() {
 // Loop until we're reconnected
 while (!mqttClient.connected())
 {
   Serial.print("Try to connect MQTT ...");
   // random/unique mqttClient ID
   String mqttClientId = String("CRBK_")+String(HOST_NAME);
 
   // for authentification use username and password like: mqttClient.connect(mqttClientId,userName,passWord))
   if (mqttClient.connect(mqttClientId.c_str()))
   {
     Serial.println("connected");
     //once connected to MQTT broker, subscribe command
     mqttClient.subscribe(("CRBK/"+HOST_NAME+"/ActivateFan").c_str());
   } else {
     Serial.print("failed, errorcode=");
     Serial.print(mqttClient.state());
     Serial.println(" try again in 5 seconds");
     delay(5000);
   }
 }
} //end connectMQTT()

[...]

Leave a Reply