One of the design problems I came across while building the UGV project is how to check the network connectivity status of the device from the control unit: is it connected to the internet or not?
Different cloud services provide different mechanism to get that information. As I experienced with Microsoft Azure, device twins provide a connectivity property but you shouldn’t rely on it as they mentioned, so an alternative they suggest a Heartbeat pattern.
AWS IoT on the other hand publishes a Connect/Disconnect events via MQTT.
Nevertheless, I was concerned about the generic mechanism of how to get that information from design point of view and how to implement it from scratch. Whether you’re using a dedicated cloud-service for your IoT solution, or using a custom implementation, I found two solutions:
- Heartbeat Pattern
- Websocket Server
Heartbeat Pattern (Polling)
The heartbeat pattern is the first pattern that comes to mind. It’s simply about sending periodic heartbeat signals (could be HTTP requests) to the device (every 30 seconds, for example) and wait for its response. If the time is out with no response, this means that the device is not connected to the internet. Otherwise, it is connected.
Now this pattern works perfectly, but I didn’t want to intentionally check the connectivity status of the device from my side, I wanted the device to tell me once it’s connected or disconnected. Just like when you’re chatting someone, once they’re online, you would be notified at the exact same moment. The chatting service doesn’t check the connectivity status of all your friends’ devices periodically.
From design point of view, if you have thousands of devices, you will need to send thousands of heartbeat requests every a few seconds. This may overload your servers.
What I wanted is once any of the devices is connected or disconnected, I should be passively notified. This mechanism could be implemented using WebSockets
Websocket provides a bidirectional communication between two entities: a client (your device) and a server. Once your device is powered up, it should directly open a connection session with your websocket server. This session will stay alive until your device loses its internet connection. Whenever a session is opened, the websocket will count up the number connected clients, and you may save the identifier of the client / device. And when the session is closed, the number of connected clients counts down, and you may then remove the identifier of the disconnected client.
This way, from your dashboard, you get a list of the all the connected devices in real-time.
Altough under the hood, the websocket server implements the heartbeat pattern just like the one I mentioned above. But the main advantage of it is that it runs over TCP protocol which has much lower latency than the usual HTTP.