Create MQTT function with (PubSubClient)

Hi,
I wanted to create a function.cpp/ function.h where I put the functions connectWiFi, clientCallback, reconnectMQTTClient, createMQTTClient.

I have problems with the last two. I don't know how to specify the input argument PubSubClient.
I declare PubSubClient in main.cpp as:

WiFiClient testclient;
PubSubClient client(testclient);

PubSubClient uses a Class inside Class, but I don't know how to use it as input argument.

My reconnectMQTTClient function:

void reconnectMQTTClient( **????PubSubClient argument????** , std::string CLIENT_NAME, std::string SERVER_COMMAND_TOPIC)
{

    while (!client.connected())
    {
        Serial.print("Attempting MQTT connection...");

        if (client.connect(CLIENT_NAME.c_str()))
        {
            Serial.println("connected");
            client.subscribe(SERVER_COMMAND_TOPIC.c_str());
        }
        else
        {
            Serial.print("Retying in 5 seconds - failed, rc=");
            Serial.println(client.state());

            delay(5000);
        }
    }
}

If everything is main.cpp, no problem. Maybe somebody already tried that and could help.

Pass everything by reference (add a & after the type) so that you use the very same instance and not a copy. Same goes for the Strings if you want to save memory

So possibly something like


void reconnectMQTTClient(PubSubClient & psClient , std::string & CLIENT_NAME, std::string  & SERVER_COMMAND_TOPIC)
{
  …

And you call it with
reconnectMQTTClient (client,…)

1 Like

Thank you so much. @J-M-L

I was stuck, I thought I already tried that.

Passing as reference, I have to read more about that.

have fun!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.