简体   繁体   中英

Persistent device connection status over MQTT with JWT, using GCP IoT Core

I have a few devices that produce data over MQTT sent to GCP IoT core. I want to monitor if the device is currently connected or disconnected from the MQTT broker. This was already answered elsewhere on SO and this is the approach I'm currently using: monitor Stackdriver logs for CONNECT/DISCONNECT messages and publish them to a separate Pub/Sub topic. This topic is then read by a Firebase Function to update my device online/offline field.

This works in theory, but due to the JWT expiration field, I am forced to re-connect my devices every time the token is expired, causing a lot of spurious online/offline triggers. Is there a way perhaps refresh the token while keeping the connection? Or a better approach to simply monitor connectivity of a device?

I can probably use the hearbeat event and only consider device being offline if no hearbeat was received within N amount of minutes, or even periodically sending some kind of ping command to the device. Although, it would be nice to simply know if device is currently connected or not.

For a pure MQTT solution, what I was already doing, and what Orlandog suggested is correct, but doesn't solve the underlying problem of receiving DISCONNECT/CONNECT messages everytime a JWT token is refreshed. That's just how the protocol is supposed to work.

What I ended up with is using balena.io on my devices, which runs docker containers with my apps on balena OS, and the OS itself is connected through a VPN. So regardless of the MQTT state of my app I can use balena API to monitor device online state. This API is then polled using firebase cloud function.

To summarise:

  • IoT Core app sending/receiving MQTT with JWT refresh as a docker container
  • Balena OS with configured network, connected to Balena VPN
  • Balena API which lets you query device status
  • Cloud Function which calls balena API and stores values in Firebase

Balena is free up to 10 devices and they support a good range of hardware.

I think that the way you are monitoring the devices through the implementation with Stackdriver logging and PubSub is the most appropriate.

At the same time, regarding to the expiration of the JWT token, I recommend you verify this documentation , it provides several examples of how to refresh the token and thus prevent devices from being disconnected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM