使用MQTT将命令发送到Google Cloud IoT Core中的多个设备

时间:2019-03-20 13:51:41

标签: python iot google-cloud-iot

如何使用MQTT和Google Cloud IoT Core将命令发送到注册表中的所有设备?

到目前为止,我所看到的所有示例仅为send the command to a single device。我是否必须循环播放设备并向其中的每一个发送消息?

谢谢。

1 个答案:

答案 0 :(得分:2)

您将需要list devices in a registry,然后按照您的建议在循环中调用sendCommandToDevice方法。

作为参考,它看起来像这样(在Python中):

command = '{ "state": "off" }'
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
    project_id, cloud_region, registry_id)

client = get_client(service_account_json)
devices = client.projects().locations().registries().devices(
    ).list(parent=registry_path).execute().get('devices', [])

for device in devices:
  device_path = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(
      project_id, cloud_region, registry_id, device.get('id'))

  config_body = {
    'binaryData': base64.urlsafe_b64encode(
      command.encode('utf-8')).decode('ascii')
  }

  client.projects().locations().registries().devices().sendCommandToDevice(
      name=device_path, body=config_body).execute()