Skip to main content

Handle Unexpected Device Disconnections

Recommended Code Flow For Unexpected Device Disconnections

By default, devices enter a deep sleep state when they lose Internet connectivity. However, this mode of operation is not mandatory. The imp API provides tools to manage the unexpected loss of a connection should your application require that the device continue to operate in such circumstances.

To prepare the device to continue running when connectivity is lost, you need to include the API method server.settimeoutpolicy(). Its first parameter should be the policy constant RETURN_ON_ERROR.

To deal with a disconnection, your code needs to register a function to be called when connectivity is lost; you do this using server.onunexpecteddisconnect().

The RETURN_ON_ERROR policy prevents the device from automatically reconnecting once the device is certain it can’t connect (after the default auto-reconnect timeout of 60 seconds). To reconnect, your code will need to call server.connect() to re-establish the link with the server.

Sample Code

The following code shows a typical disconnection handler flow. It involves establishing the timeout policy at the start of the device code, defining the disconnection handler and registering it, and establishing a function that can be called periodically to attempt to reconnect the device to the server.

API Methods Used

Further Reading