-->
Page 1 of 1

What is the difference between these 2 startup code?

PostPosted: Wed Jan 13, 2016 1:35 am
by helpme
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?

Re: What is the difference between these 2 startup code?

PostPosted: Wed Jan 13, 2016 8:54 pm
by helpme
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");
}