微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 虚拟设备处理来自 azure IoT 中心的更改事件

如何解决Python 虚拟设备处理来自 azure IoT 中心的更改事件

所以,我对 python 还很陌生,遇到了一个我真的无法解决的问题。

我有一个用 python 编程的虚拟设备,它连接到 Azure IoT 中心。你们中的一些人可能知道,连接到 IoT 中心的设备有一个设备孪生,它定义了设备的属性。 (这是一个基本的 JSON 对象)

这样做的想法是,后端可以更改设备孪生,这可能会对设备的操作模式产生影响。

到目前为止,我只想实现以下非常基本的:

  1. 我的虚拟设备侦听设备孪生更改(不锁定我的代码
  2. 我更改了 Azure 中的设备孪生属性
  3. 事件触发并打印出新的设备孪生属性(最终,这应该调用一些其他代码,以更改操作模式)

到目前为止,我有以下几点:

async def main():
   
    async def printdesiredproperties():
        while True:
            test = await my_client.receive_twin_desired_properties_patch() #This returns a JSON dict
            print(test)
    
    task = asyncio.create_task(printdevicetwin()) #not correct way to attach event
    await task
    #Do other stuff

根据我在其他编程语言中的经验,我们习惯于分别使用 += 和 -= 附加和分离事件处理程序。

在 python 中似乎有很多方法可以实现这一点,但我真的没有成功。

my_client.receive_twin_desired_properties_patch() 是引发事件的原因,因为它会在 Azure 中进行更改时返回 JSON dict

解决方法

试试下面的代码:

import time
import threading

from azure.iot.device import IoTHubDeviceClient
from azure.iot.device.iothub.sync_clients import IoTHubModuleClient

CONNECTION_STRING = "<device conn str>"

def iothub_client_init():
    
    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
    
    return client

def twin_update_listener(client):
    while True:
        patch = client.receive_twin_desired_properties_patch()
        print("Twin patch received:")
        print(patch)
       

def iothub_client_init():
    client = IoTHubModuleClient.create_from_connection_string(CONNECTION_STRING)
    return client

def iothub_client_sample_run():
    try:
        client = iothub_client_init()

        twin_update_listener_thread = threading.Thread(target=twin_update_listener,args=(client,))
        twin_update_listener_thread.daemon = True
        twin_update_listener_thread.start()
        count = 0;
        while True:
            count += 1
            print ( "Sending data as reported property..." )
            reported_patch = {"ReportCount": count}
            client.patch_twin_reported_properties(reported_patch)
            print ( "Reported properties updated:" + str(count))
            time.sleep(5)
    except KeyboardInterrupt:
        print ( "IoT Hub Device Twin device sample stopped" )

if __name__ == '__main__':
    print ( "Starting the Python IoT Hub Device Twin device sample..." )
    print ( "IoTHubModuleClient waiting for commands,press Ctrl-C to exit" )

    iothub_client_sample_run()

虽然我在双胞胎的 desired 中更改了一些值: enter image description here

计数仍在继续,我们也收到了事件:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。