adamvr/MQTT.js — pull request #153 by elliottye (2013-12-20 09:56:28+00:00)
Title: Altered reconnect logic after keep-alive timeout

This is a fix that addresses the problems observed from issue #148 in which an MQTT Client misbehaves due to unavailable networks. According to the MQTT protocol spec, a client is responsible of closing connection and reconnecting to the server either when server is down or network is unreachable within a loop of reasonable time period.

So the fix is really about how to try reconnecting after keep-alive timeout, which can be implemented in the MqttClient._checkPing() method:
```js
/**
* _checkPing - check if a pingresp has come back, and ping the server again
*
* @api private
*/
MqttClient.prototype._checkPing = function () {
if (this.pingResp) {
this.pingResp = false;
this.conn.pingreq();
} else {
this._cleanUp();
this.emit('close'); // announces a close event to the user and triggers reconnecting process automatically
}
};
```
Emitting a close event was what I did to ignite a reconnect process, which also does state manipulation and cleanups, like setting this.connected = false; and removing pingTimer. And finally a reconnectTimer will be set and triggered in defined time period.

A unit test, named client.fault_tolerance.js under the test folder (as well as a companion server_process file under test/helpers/), was written exclusively to verify the correct setting of a reconnectTimer that enables reconnecting after server being terminated.