如何在 Google Core IoT 中配置?

How to configure in Google Core IoT?

我在 Raspberry Pi 3 模型 B 中制作了一个 python 程序,它应该使用 MQTT 协议连接到 Google Cloud IoT Core 并获取配置。到目前为止,向 Core 发送数据一直有效,但我就是不知道配置是如何工作的!这是一个应该获得配置的代码:


    import time
    import datetime
    import jwt
    import ssl
    import json
    import paho.mqtt.client as mqtt


    time_now = datetime.datetime.utcnow()


    #make key
    token  = {'iat' : time_now ,
              'exp' : time_now + datetime.timedelta(minutes=60),
              'aud' : "[PROJECT]"}

    r = open("[PRIVATE KEY]", 'r')
    pub_key = r.read()

    jwt_key = jwt.encode(token, pub_key, algorithm='RS256')


    #connect to iot-core
    client = mqtt.Client(client_id='projects/[PROJECT]/locations/[LOCATION]/registries/[REGISTER]/devices/[DEVICE]')
    client.username_pw_set(username='unused', password=jwt_key)

    client.tls_set(ca_certs='/home/pi/.local/lib/python2.7/site-packages/grpc/_cython/_credentials/roots.pem', tls_version=ssl.PROTOCOL_TLSv1_2)
    client.connect("mqtt.googleapis.com", 8883)

    #configure and change state
    state = 0

    print state #naturally shows 0

    print client.subscribe([DEVICE]/config, qos=1) #doesn't print custom config either, just (0,1) 

    print state #still shows 0

Iot Core 设备 id 中的配置是:

{ "state": 1 }

即使在 运行 程序之后,设备的 "state" 变量仍保持为 0,核心的配置和状态历史表明配置为 "Not yet acknowledged by the device"

如何从 Core 获取设备的 "state" 变量从 0 变为 1?

你已经完成了一半的工作。 2 备注。

  1. 这可能是一个细节,但您将私钥命名为pub_key。而且你不关闭文件。

  2. Based on this tutorial,您只订阅了MQTT。 return 元组 (0,1) 表示 QOS = 1 上的 MQTT_ERR_SUCCESS。因此您已连接。伟大的!现在,做第二部分:消费通道中的消息,并制定您的逻辑(根据收到的消息,如果是您的用例,则更改应用程序中的状态)