Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[paho-dev] Reconnection after a long time disconnected

Hi everyone,
I´m creating a Linux process that publish some events to a MQTT server using
PAHO library for C++.
I´m facing a problem regarding reconnection.  The process detects
disconnection and reconnects fine for some time but after that the
MQTT_connect() function always return -1 even if there is internet
connection.  
I’ve been checking everything and trying new things but I´m stuck.  Maybe
it’s a library bug?
It works fine for some hours but if it lose connection for a long time (a
night) it never connects again even if there’s network connection.  If you
restart the process it works again.

Here’s my code…
setup_mqtt() -> creates the client and set the options for the connection
connect_mqtt() -> connects and subscribe to some topics
lost_connection() -> calls connect_mqtt() every 60 seconds
conn_opts and sslopts are global variables

I have tried moving things from setup_mqtt() to connect_mqtt() but nothing
changed.
Any idea what’s going on?
Thank in advance.
Enrique.

bool setup_mqtt()
{
    MQTTClient_create(&client, (char*)address.c_str(), 
            (char*)client_id.c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
    log<<"Created client."<<endl;
    
    conn_opts= MQTTClient_connectOptions_initializer;
    sslopts = MQTTClient_SSLOptions_initializer;    

    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1; //reconnect? 0:1;
    if(user.length())
        conn_opts.username = (char*)user.c_str();
    if(pwd.length())
        conn_opts.password = (char*)pwd.c_str();    
    sslopts.trustStore = (char*)cert.c_str();
    conn_opts.ssl = &sslopts;
    //conn_opts.ssl->trustStore = (char*)cert.c_str();

    MQTTClient_setCallbacks(client, NULL, connection_lost, message_arrived,
message_delivered);

    connect_mqtt(false);

    return true;
}

bool connect_mqtt(bool reconnect)
{    
    log<<"Connecting to address "<<address<<endl;
		int rc;
    if((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        log<<"Failed to start connection, return code "<<rc<<endl;
        return false;
    }
    log<<"Connected."<<endl;
    
    log<<"Subscribing to topic "<<listen_topic<<", client "<<client_id<<",
QoS "<<qos<<endl;
    if(MQTTClient_subscribe(client, (char*)listen_topic.c_str(),
qos)!=MQTTCLIENT_SUCCESS)
    {
        log<<"Failed to subscribe."<<endl;
        return false;
    }

    log<<"Subscribed."<<endl;

    connection_down=false;

    return true;
}

void connection_lost(void *context, char *cause)
{
    log<<get_timestamp()<<"Connection lost."<<endl;

    connection_down=true;

    while(connection_down)
    {
        connect_mqtt(true);
        usleep(reconnect_interval);
    }
}







Back to the top