Chat freely about anything...

User avatar
By helpme
#38655 I have a working code for starting up MQTT. I am using the SMING framework. The relevant code section is like this;

Code: Select allMqttClient mqtt("192.168.1.4", 1883, onMessageReceived);

void startMqttClient()
{
   mqtt.connect("esp8266");
   mqtt.subscribe("ToXXX");
}

void connectOk()
{
   Serial.println("I'm CONNECTED");
   // Run MQTT client
   startMqttClient();
}

void init()
{
   Serial.begin(SERIAL_BAUD_RATE); // 115200 by default
   Serial.systemDebugOutput(false);

   WifiStation.config(WIFI_SSID, WIFI_PWD);
   WifiStation.enable(true);

   WifiAccessPoint.enable(false);

   WifiStation.waitConnection(connectOk, 20, connectFail); //We recommend 20+ seconds for connection timeout at start
}


I then made a small modification and things stopped working. Here are the changes;

Code: Select allvoid startMqttClient(MqttClient mqtt_client)
{
   mqtt_client.connect("esp8266");
   mqtt_client.subscribe("ToXXX");
}

void connectOk()
{
   Serial.println("I'm CONNECTED");
   // Run MQTT client
   startMqttClient(mqtt);   
}


What I did was to add the function parameter MqttClient to the function startMqttClient(). This simple change caused MQTT connection to fail. What is wrong with the code?
User avatar
By helpme
#38722 Just realized I asked a stupid question. Forgot my C++ basics. MQTTClient object needs to be passed by reference because function needs to make changes to object (connect and subscribe). Original code of passing by value cannot work because changes were not allowed to object.

Here is the answer;

Code: Select allvoid startMqttClient(MqttClient &mqtt_client)
{
   mqtt_client.connect("esp8266");
   mqtt_client.subscribe("ToXXX");
}