Google IoT - 接收通知的正确模式(订阅工作) [英] Google IoT - Right mode to receive notifications (subscribe working)

查看:262
本文介绍了Google IoT - 接收通知的正确模式(订阅工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注本教程,我已经将代码发布到 / devices / sm1 / events 主题,其中 sm1 是我的设备ID。



我想知道如何订阅这个主题,因为本教程说使用 / devices / sm1 / config 但我收到空消息。我已经尝试使用发布时使用的相同路径( / devices / sm1 / events ),但它也不起作用。



奇怪的是,我给这个主题的名字是 sm1 ,并且与我的设备关联的主题在GoogleIoT控制台上显示为项目/ myprojectname /主题/ SM1 。因此,除了发现如何订阅上述主题,我还要感谢任何有关在GoogleIoT中使用pub / sub主题的正确方法的解释(文档不太清楚)。

这是我的 subscribe.py

  mqtt_url = mqtt.googleapis.com
mqtt_port = 8883
topic =/ devices / sm1 / config

def on_connect(客户端,用户数据,标志,响应代码):
print(与状态连接:{0}。format(response_code))
client.subscribe(topic,1)

def on_message(client,userdata,msg):
print(Topic:{0} - Payload:{1}。format(msg.topic,msg.payload))

if __name__ ==__main__:
客户端= mqtt.Client(projects / {} / locations / {} / registries / {} / devices / {}格式(
project_id,
cloud_region,
registry_id,
device_id))

client.username _pw_set(username ='unused',
password = jwt_maker.create_jwt(project_id,
private_key,
algorithm =RS256))

client.tls_set(root_ca ,
certfile = public_crt,
keyfile = private_key,
cert_reqs = ssl.CERT_REQUIRED,
tls_version = ssl.PROTOCOL_TLSv1_2,
ciphers =无)


client.on_connect = on_connect
client.on_message = on_message

print连接到Google IoT Broker ...
client.connect(mqtt_url, mqtt_port,keepalive = 60)
client.loop_forever()

我的输出:


连接状态:0

主题:/ devices / sm1 / config - 有效载荷:

主题:/ devices / sm1 / config - 有效负载:



解决方案

在阅读@GabeWeiss的回答评论部分的讨论后,我认为你想要什么有点混乱以实现和如何(或什么)你试图使用Pub / Sub。

鉴于我认为这里的问题更概念化,让我先引荐你关于云物联网核心关键概念的通用文档页面,您将在哪里实际上可以找到有关Cloud IoT Core和Pub / Sub之间关系的一些信息。总之,设备遥测数据将发布到Cloud IoT Core主题中,后者通过Data Broker发布到Cloud Pub / Sub主题中,您可以将其用于外部用于其他目的:触发云功能,分析数据流等数据



现在,如果您按照 Cloud IoT Core快速入门指南,您将看到在给定的时间点,您如何创建一个绑定到发布设备遥测事件的发布/订阅主题的设备注册表。如果您不想写入您希望写入多个主题的默认发布/订阅主题,您可以按照关于文档的其他部分

最后,讨论订阅主题(云IoT核心主题,而不是发布/订阅主题,因为只有前者与设备相关),则可以使用以下命令,其中(作为示例),设备正在订阅配置主题,其中配置更新已发布:

 #这是设备将接收配置更新的主题。 
mqtt_config_topic ='/devices/{}/config'.format(device_id)

#订阅配置主题。
client.subscribe(mqtt_config_topic,qos = 1)

然后,使用 on_message ()函数,您可以处理发布在您实际订阅的主题上的消息。请注意,有效内容必须以字符串形式进行分析( str(message.payload))。

  def on_message(unused_client,unused_userdata,message):
payload = str(message.payload)
print('Received message \'{} \'on topic \' {} \'with Qos {}'。format(
payload,message.topic,str(message.qos)))

然后,在您的问题中,您表示您首先订阅了 / devices / {device-id} / config ,但这可能不会成为你想要的东西,因为这是配置更新发布的主题(即不是发布遥测事件的地方)。然后,我明白您应该订阅 / devices / {device-id} / events 这是发布遥测指标的实际MQTT主题。如果这不起作用,则可能存在另一个相关问题,所以请确保您正确解析消息变量,并尝试使用带注册表创建的默认主题的Pub / Sub,以检查遥测指标是否正确发布。

I am following this tutorial and I already have my code publishing messages to /devices/sm1/events topic, in which sm1 is my device id.

I would like to know how to subscribe to this topic since the tutorial says to use /devices/sm1/config but I am getting empty messages. I already tried use the same "path" used in publishing (/devices/sm1/events), but it also did not work.

It is strange that the name I gave to the topic was sm1 and the topic associated to my device is on GoogleIoT console is exhibited as projects/myprojectname/topics/sm1. So, besides to discover how to subscribe to mentioned topic, I appreciate also any explanation related to the correct way of using pub/sub topics in GoogleIoT (the documentation is not so clear).

This is my subscribe.py:

mqtt_url = "mqtt.googleapis.com"
mqtt_port = 8883
topic = "/devices/sm1/config"

def on_connect(client, userdata, flags, response_code):
    print("Connected with status: {0}".format(response_code))
    client.subscribe(topic, 1)

def on_message(client, userdata, msg):
    print("Topic: {0}  --  Payload: {1}".format(msg.topic, msg.payload))

if __name__ == "__main__":    
    client = mqtt.Client("projects/{}/locations/{}/registries/{}/devices/{}".format(
                         project_id,
                         cloud_region,
                         registry_id,
                         device_id))

    client.username_pw_set(username='unused',
                           password=jwt_maker.create_jwt(project_id,
                                               private_key,
                                               algorithm="RS256"))

    client.tls_set(root_ca,
                   certfile = public_crt,
                   keyfile = private_key,
                   cert_reqs = ssl.CERT_REQUIRED,
                   tls_version = ssl.PROTOCOL_TLSv1_2,
                   ciphers = None)


    client.on_connect = on_connect
    client.on_message = on_message

    print "Connecting to Google IoT Broker..."
    client.connect(mqtt_url, mqtt_port, keepalive=60)
    client.loop_forever()

My output:

Connected with status: 0
Topic: /devices/sm1/config -- Payload:
Topic: /devices/sm1/config -- Payload:

解决方案

After reading the discussion in the comments section in the answer by @GabeWeiss, I think there is a bit of confusion of what you want to achieve and how (or what for) are you trying to use Pub/Sub.

Given that I think the issue here is more conceptual, let me first refer you to a generic documentation page about Cloud IoT Core key concepts, where you will actually find some information regarding the relationship between Cloud IoT Core and Pub/Sub. In summary, device telemetry data is published into a Cloud IoT Core topic, which later, through the Data Broker, is published into a Cloud Pub/Sub topic, which you can use externally for other purposes: triggering Cloud Functions, analyzing the stream of data with Dataflow, etc.

Now, if you follow the Quickstart guide of Cloud IoT Core, you will see how, at a given point, you create a device registry which is bound to a Pub/Sub topic where device telemetry events are published. If instead of writing to the default Pub/Sub topic you wish to write to multiple topics, you can follow the explanations under this other section on the documentation.

Finally, getting to the issue of subscribing to topics (Cloud IoT Core topics, and not Pub/Sub topics, as only the former are relevant for the devices), you can subscribe to MQTT topics with the following command, where (as an example), the device is subscribing to the config topic, where configuration updates are published:

# This is the topic that the device will receive configuration updates on.
mqtt_config_topic = '/devices/{}/config'.format(device_id)

# Subscribe to the config topic.
client.subscribe(mqtt_config_topic, qos=1)

Then, with the on_message() function you can can process messages published on the topics where you are actually subscribed. Note that the payload has to be parsed as string (str(message.payload)).

def on_message(unused_client, unused_userdata, message):
    payload = str(message.payload)
    print('Received message \'{}\' on topic \'{}\' with Qos {}'.format(
            payload, message.topic, str(message.qos)))

Then, in your question you stated that you first subscribed to /devices/{device-id}/config, but this might not be what you want, as this is the topic were configuration updates are published (i.e. not where telemetry events are published). Then, I understand that you should subscribe to /devices/{device-id}/events which is the actual MQTT topic where telemetry metrics are published. If that does not work, there might be another issue related, so make sure that you are parsing the message variable correctly, and maybe try to use Pub/Sub with the default topic created with the registry in order to check whether telemetry metrics are being properly published or not.

这篇关于Google IoT - 接收通知的正确模式(订阅工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆