首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python虚拟设备处理来自azure IoT集线器的更改事件

Python虚拟设备处理来自azure IoT集线器的更改事件
EN

Stack Overflow用户
提问于 2020-12-23 12:11:11
回答 1查看 115关注 0票数 0

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

我有一个用python编程的虚拟设备,它连接到Azure IoT集线器。您可能知道,连接到IoT集线器的设备有一个设备孪生体,它定义了设备的属性。(它是一个基本的JSON对象)

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

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

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

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

代码语言:javascript
运行
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-04 04:56:50

试试下面的代码:

代码语言:javascript
运行
复制
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中更改一些值时:

计票仍在继续,我们也得到了这个事件:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65424087

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档