Skip to main content

device.ondisconnect(callback)

Registers a function that will be called when the device disconnects from the agent

Availability

Agent

Parameters

Name Type Description
callback Function The function that will be called automatically when the imp-enabled device disconnects

Returns

Nothing

Description

This method registers a function to be executed whenever this agent’s device disconnects, whether deliberately — for instance, because server.sleepfor() has been called — or due to an error.

The callback function may include a single, optional parameter, but this parameter is reserved for future use. Currently any data passed into the parameter will be replaced with an empty table.

Only one callback can be registered at any one time; registering another callback will stop the current one from being called.

In the agent’s initial state, no device.ondisconnect() callback is registered. Until the agent is restarted, the callback can’t be removed, only replaced.

The callback will only be triggered by a state transition: the device has to have first connected for the agent to register that it has subsequently disconnected, and thus execute the callback. If the device was never online to begin with, the callback will not be run. Equally, if the device disconnects then reconnects quickly, the agent may not notice the brief disconnection and, again, the callback will not be triggered.

The agent pings the device every nine minutes; if the device fails to acknowledge the ping within 20 seconds, it is declared to be offline. This period longer for cellular.

In addition, the agent-device connection’s TCP keepalive scheme is configured so that the server will register that the device is not connected after 106 seconds. When the device acknowledges a server ping, a 55-second keepalive timer is instantiated. When the timer fires, the device is pinged. If the device does not acknowledge this ping, it is pinged a second time after 17 seconds and then again after a further 17 seconds. If this third ping is not acknowledged within 17 seconds, the agent is informed that the device is offline.

If the agent’s own ping is sent just after the device has disconnected immediately following the acknowledgement of a server ping, the device’s disconnection could be registered in around 20 seconds.

Example Code

The following agent code registers two in-line callback functions that log, respectively, the string "Device connected to agent" and "Device disconnected from agent" whenever these events takes place. The device code sets the imp to go into a deep sleep after ten seconds. Deep sleep lasts for 20 seconds, after which the imp warm boots. Upon a warm boot, the imp is disconnected and remains in that stats until Squirrel attempts to contact the server — which here takes place in the first line of the device code.