简体   繁体   English

Python 虚拟设备句柄更改事件来自 azure IoT 集线器

[英]Python virtual device handle changed event from azure IoT hub

So, I'm fairly new to python and have run into an issue which I really can't wrap my head around.所以,我对 python 还很陌生,遇到了一个我真的无法解决的问题。

I have a virtual device that I have programmed in python that connects to Azure IoT hub.我有一个在 python 中编程的虚拟设备,它连接到 Azure IoT 集线器。 As some of you probably know, devices that are connected to IoT hub have a device twin, which defines the properties of the device.有些人可能知道,连接到 IoT 中心的设备有一个设备孪生,它定义了设备的属性。 (It's a basic JSON object) (这是一个基本的 JSON 对象)

The idea with this is, that the backend can change the device twin, which on the device may have an effect on the mode of operation.这样做的想法是,后端可以更改设备孪生,这可能会影响设备上的操作模式。

Thus far, I just want to achieve the following, which is very basic:到目前为止,我只想实现以下,这是非常基本的:

  1. My virtual device listens for device twin changes (Without locking my code)我的虚拟设备监听设备孪生更改(不锁定我的代码)
  2. I change a device twin property in Azure我在 Azure 中更改了设备孪生属性
  3. The event fires and prints out the new device twin properties (Eventully, this should call some other code, to change the mode of operation)事件触发并打印出新的设备孪生属性(最终,这应该调用一些其他代码,以更改操作模式)

So far I have the following:到目前为止,我有以下内容:

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

From my experience in other programming languages, we are used to attaching and detaching eventhandlers with respectively += and -=.根据我在其他编程语言方面的经验,我们习惯于分别使用 += 和 -= 附加和分离事件处理程序。

In python there seems to be a lot of ways to achieve this, however I really haven't had success with any of them.在 python 中似乎有很多方法可以实现这一点,但是我真的没有成功。

my_client.receive_twin_desired_properties_patch() is what raise an event, in the sense that it returns a JSON dict when a change is made in Azure my_client.receive_twin_desired_properties_patch()是引发事件的原因,因为它在 Azure 中进行更改时返回 JSON dict

Try the code below:试试下面的代码:

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()

While I change some value in desired of twin:虽然我改变了双胞胎desired的一些值: 在此处输入图像描述

Counting is continuing and we also get the event:计数仍在继续,我们也得到了事件:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM