Google Core IoT Device Offline Event or Connection Status

前端 未结 1 742
忘掉有多难
忘掉有多难 2020-12-20 20:54

Does anybody know of an easy way to trigger an event when a device on Google Core IoT goes offline? Before I switched to Google\'s IoT implementation, this was

相关标签:
1条回答
  • 2020-12-20 21:41

    Your cloud project does have access to the individual MQTT connect/disconnect events, but currently they only show up in the Stackdriver logs. Within the cloud console, you can create an exporter that will publish these events to a Pub/Sub topic:

    1. Visit the Stackdriver Logs in the Cloud Console.
    2. Enter the following advanced filter:

      resource.type="cloudiot_device"
      jsonPayload.eventType="DISCONNECT" OR "CONNECT"
      
    3. Click CREATE EXPORT

    4. Enter a value for Sink Name
    5. Select Cloud Pub/Sub for Sink Service
    6. Create a new Cloud Pub/Sub topic as the Sink Destination

    The exporter publishes the full LogEntry, which you can then consume from a cloud function subscribed to the same Pub/Sub topic:

    export const checkDeviceOnline = functions.pubsub.topic('online-state').onPublish(async (message) => {
      const logEntry = JSON.parse(Buffer.from(message.data, 'base64').toString());
      const deviceId = logEntry.labels.device_id;
    
      let online;
      switch (logEntry.jsonPayload.eventType) {
        case 'CONNECT':
          online = true;
          break;
        case 'DISCONNECT':
          online = false;
          break;
        default:
          throw new Error('Invalid message type');
      }
    
      // ...write updated state to Firebase...
    
    });
    

    Note that in cases of connectivity loss, the time lag between the device being unreachable and an actual DISCONNECT event could be as long the MQTT keep-alive interval. If you need an immediate check on whether a device is reachable, you can send a command to that device.

    0 讨论(0)
提交回复
热议问题