【发布时间】:2018-04-03 19:44:37
【问题描述】:
我正在关注this tutorial,并且我的代码已经将消息发布到/devices/sm1/events 主题,其中sm1 是我的设备ID。
我想知道如何订阅这个主题,因为教程说要使用/devices/sm1/config,但我收到的是空消息。我已经尝试过使用发布中使用的相同“路径” (/devices/sm1/events),但它也不起作用。
奇怪的是我给主题的名称是sm1,而与我的设备关联的主题在GoogleIoT控制台上显示为projects/myprojectname/topics/sm1。因此,除了要了解如何订阅上述主题外,我还感谢任何与在 GoogleIoT 中使用 pub/sub 主题的正确方法相关的任何解释(文档不是很清楚)。
这是我的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()
我的输出:
已连接状态:0
主题:/devices/sm1/config -- 有效负载:
主题:/devices/sm1/config -- Payload:
【问题讨论】:
标签: python google-cloud-platform publish-subscribe iot google-cloud-iot