I'm using the MQTT Java library by Paho to detect the status of some devices. I'm facing a weird problem, because every 5 minutes I got a Connection lost error. BTW, with the usage of the reconnect method it works well, but why I got this strange fact? I'm using these lines of code within a Java EE in @Singleton component, which starts at boot.
String id = MqttAsyncClient.generateClientId();
System.out.println("Mqtt " + id + " " + uuid + " " + topics);
MqttClient client = new MqttClient(mqttSettings.generateURI(), id, new MemoryPersistence());
MqttConnectOptions connOpts = new MqttConnectOptions();
connOpts.setCleanSession(true);
connOpts.setAutomaticReconnect(true);
connOpts.setUserName(mqttSettings.getUsername());
connOpts.setPassword(mqttSettings.getPassword().toCharArray());
if (statement) {
setStatement(uuid, connOpts);
}
client.setCallback(callback);
client.connect(connOpts);
System.out.println("Connected? "+client.isConnected());
client.subscribe(topics);
if (statement) {
try {
System.out.println("Publishing installation status online...");
publishOnline(client);
} catch (MqttException e) {
System.out.println("MQTT local");
e.printStackTrace();
}
}
return client;
Hope, we can shine some light over this discussion.
There are a few points which we need to take into account.
What is setAutoReconnect(true) What is KeepAlive time for an MQTT connection
As per eclipse.org
public void setAutomaticReconnect(boolean automaticReconnect)
Sets whether the client will automatically attempt to reconnect to the server if the connection is lost. If set to false, the client will not attempt to automatically reconnect to the server in the event that the connection is lost. If set to true, in the event that the connection is lost, the client will attempt to reconnect to the server. It will initially wait 1 second before it attempts to reconnect, for every failed reconnect attempt, the delay will double until it is at 2 minutes at which point the delay will stay at 2 minutes.
From MQTT v3.1.1 documentation from OASIS, Keepalive value is used as a pointer to let the client to check for connection. If the connection is invalid, client can take decision whether to reconnect or not based on the autoreconnect method.
By default, if Keepalive value is not given, default value of 60 seconds will be considered.
Keepalive behaviour is as given herewith.
If the Keep Alive value is non-zero and the Server does not receive a Control Packet from the Client within one and a half times the Keep Alive time period, it MUST disconnect the Network Connection to the Client as if the network had failed [MQTT-3.1.2-24].
So in your case, may be there is a connection disruption happening from the client side or from Server side due to a tcp connection time out.
Hope I was able to shed some light and help you understand this process