使用 IoT 中心发送云到设备消息 (Python)Send cloud-to-device messages with IoT Hub (Python)

Azure IoT 中心是一项完全托管的服务,有助于在数百万台设备和单个解决方案后端之间实现安全可靠的双向通信。Azure IoT Hub is a fully managed service that helps enable reliable and secure bi-directional communications between millions of devices and a solution back end. 从设备将遥测数据发送到 IoT 中心快速入门介绍了如何创建 IoT 中心、在其中预配设备标识,以及编写模拟设备应用来发送设备到云的消息。The Send telemetry from a device to an IoT hub quickstart shows how to create an IoT hub, provision a device identity in it, and code a simulated device app that sends device-to-cloud messages.

Note

本文介绍的功能仅在 IoT 中心的标准层中可用。The features described in this article are available only in the standard tier of IoT Hub. 有关基本和标准/免费 IoT 中心层的详细信息,请参阅选择合适的 IoT 中心层For more information about the basic and standard/free IoT Hub tiers, see Choose the right IoT Hub tier.

本教程在从设备将遥测数据发送到 IoT 中心的基础上编写。This tutorial builds on Send telemetry from a device to an IoT hub. 其中了说明了如何:It shows you how to:

  • 通过 IoT 中心,将云到设备的消息从解决方案后端发送到单个设备。From your solution back end, send cloud-to-device messages to a single device through IoT Hub.
  • 在设备上接收云到设备的消息。Receive cloud-to-device messages on a device.

可以在 IoT 中心开发人员指南中找到有关云到设备消息的详细信息。You can find more information on cloud-to-device messages in the IoT Hub developer guide.

在本教程末尾,你将运行两个 Python 控制台应用:At the end of this tutorial, you run two Python console apps:

  • SimulatedDevice.py从设备将遥测数据发送到 IoT 中心中创建的应用的修改版本),它连接到 IoT 中心并接收云到设备的消息。SimulatedDevice.py, a modified version of the app created in Send telemetry from a device to an IoT hub, which connects to your IoT hub and receives cloud-to-device messages.

  • SendCloudToDeviceMessage.py ,它将云到设备消息通过 IoT 中心发送到模拟设备应用。SendCloudToDeviceMessage.py, which sends cloud-to-device messages to the simulated device app through IoT Hub.

Note

IoT 中心通过 Azure IoT 设备 SDK 为许多设备平台和语言(包括 C、Java、Javascript 和 Python)提供 SDK 支持。IoT Hub has SDK support for many device platforms and languages (including C, Java, Javascript, and Python) through Azure IoT device SDKs. 有关如何使用 Python 将设备连接到本教程的代码,以及通常如何连接到 Azure IoT 中心的说明,请参阅 Azure IoT Python SDKFor instructions on how to use Python to connect your device to this tutorial's code, and generally to Azure IoT Hub, see the Azure IoT Python SDK.

先决条件Prerequisites

  • 确保已在防火墙中打开端口 8883。Make sure that port 8883 is open in your firewall. 本文中的设备示例使用 MQTT 协议,该协议通过端口 8883 进行通信。The device sample in this article uses MQTT protocol, which communicates over port 8883. 在某些公司和教育网络环境中,此端口可能被阻止。This port may be blocked in some corporate and educational network environments. 有关解决此问题的更多信息和方法,请参阅连接到 IoT 中心(MQTT)For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

在模拟设备应用上接收消息Receive messages in the simulated device app

在本部分中,将创建一个 Python 控制台应用来模拟设备并从 IoT 中心接收云到设备消息。In this section, you create a Python console app to simulate the device and receive cloud-to-device messages from the IoT hub.

  1. 在工作目录中的命令提示符下,安装适用于 Python 的 Azure IoT 中心设备 SDKFrom a command prompt in your working directory, install the Azure IoT Hub Device SDK for Python:

    pip install azure-iot-device
    
  2. 使用文本编辑器,创建一个名为“SimulatedDevice.py” 的文件。Using a text editor, create a file named SimulatedDevice.py.

  3. SimulatedDevice.py 文件的开头添加以下 import 语句和变量:Add the following import statements and variables at the start of the SimulatedDevice.py file:

     import threading
     import time
     from azure.iot.device import IoTHubDeviceClient
    
     RECEIVED_MESSAGES = 0
    
  4. 将以下代码添加到 SimulatedDevice.py 文件。Add the following code to SimulatedDevice.py file. 将“{deviceConnectionString}”占位符值替换为你在从设备将遥测数据发送到 IoT 中心快速入门中创建的设备的设备连接字符串:Replace the "{deviceConnectionString}" placeholder value with the device connection string for the device you created in the Send telemetry from a device to an IoT hub quickstart:

    CONNECTION_STRING = "{deviceConnectionString}"
    
  5. 添加以下函数,用以在控制台中输出收到的消息:Add the following function to print received messages to the console:

    def message_listener(client):
        global RECEIVED_MESSAGES
        while True:
            message = client.receive_message()
            RECEIVED_MESSAGES += 1
            print("\nMessage received:")
    
            #print data and both system and application (custom) properties
            for property in vars(message).items():
                print ("    {0}".format(property))
    
            print( "Total calls received: {}".format(RECEIVED_MESSAGES))
            print()
    
  6. 添加以下代码,用以初始化客户端并等待接收云到设备消息:Add the following code to initialize the client and wait to receive the cloud-to-device message:

    def iothub_client_sample_run():
        try:
            client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
    
            message_listener_thread = threading.Thread(target=message_listener, args=(client,))
            message_listener_thread.daemon = True
            message_listener_thread.start()
    
            while True:
                time.sleep(1000)
    
        except KeyboardInterrupt:
            print ( "IoT Hub C2D Messaging device sample stopped" )
    
  7. 添加以下 main 函数:Add the following main function:

    if __name__ == '__main__':
        print ( "Starting the Python IoT Hub C2D Messaging device sample..." )
        print ( "Waiting for C2D messages, press Ctrl-C to exit" )
    
        iothub_client_sample_run()
    
  8. 保存并关闭 SimulatedDevice.py 文件。Save and close the SimulatedDevice.py file.

获取 IoT 中心连接字符串Get the IoT hub connection string

在本文中,你将创建一项后端服务,用于通过你在将遥测数据从设备发送到 IoT 中心中创建的 IoT 中心发送云到设备消息。In this article you create a backend service to send cloud-to-device messages through the IoT hub you created in Send telemetry from a device to an IoT hub. 若要发送云到设备消息,服务需要“服务连接”权限。 To send cloud-to-device messages, your service needs the service connect permission. 默认情况下,每个 IoT 中心都使用名为 service 的共享访问策略创建,该策略授予此权限。By default, every IoT Hub is created with a shared access policy named service that grants this permission.

若要获取 service 策略的 IoT 中心连接字符串,请执行以下步骤:To get the IoT Hub connection string for the service policy, follow these steps:

  1. Azure 门户中,选择“资源组” 。In the Azure portal, select Resource groups. 选择中心所在的资源组,然后从资源列表中选择中心。Select the resource group where your hub is located, and then select your hub from the list of resources.

  2. 在 IoT 中心的左侧窗格中,选择“共享访问策略” 。On the left-side pane of your IoT hub, select Shared access policies.

  3. 从策略列表中选择“service” 策略。From the list of policies, select the service policy.

  4. 在“共享访问密钥” 下,选择“连接字符串 - 主密钥” 所对应的“复制”图标并保存该值。Under Shared access keys, select the copy icon for the Connection string -- primary key and save the value.

    显示如何检索连接字符串

有关 IoT 中心共享访问策略和权限的详细信息,请参阅访问控制和权限For more information about IoT Hub shared access policies and permissions, see Access control and permissions.

发送云到设备的消息Send a cloud-to-device message

在本部分中,将创建一个 Python 控制台应用,用于向模拟设备应用发送云到设备消息。In this section, you create a Python console app that sends cloud-to-device messages to the simulated device app. 需要在从设备将遥测数据发送到 IoT 中心快速入门中添加的设备的设备 ID。You need the device ID of the device you added in the Send telemetry from a device to an IoT hub quickstart. 还需要先前在获取 IoT 中心连接字符串中复制的 IoT 中心连接字符串。You also need the the IoT hub connection string you copied previously in Get the IoT hub connection string.

  1. 在工作目录中,打开命令提示符并安装安装适用于 Python 的 Azure IoT 中心服务 SDK 。In your working directory, open a command prompt and install the Azure IoT Hub Service SDK for Python.

    pip install azure-iot-hub
    
  2. 使用文本编辑器,创建一个名为“SendCloudToDeviceMessage.py” 的文件。Using a text editor, create a file named SendCloudToDeviceMessage.py.

  3. SendCloudToDeviceMessage.py 文件的开头添加以下 import 语句和变量:Add the following import statements and variables at the start of the SendCloudToDeviceMessage.py file:

    import random
    import sys
    from azure.iot.hub import IoTHubRegistryManager
    
    MESSAGE_COUNT = 2
    AVG_WIND_SPEED = 10.0
    MSG_TXT = "{\"service client sent a message\": %.2f}"
    
  4. 将以下代码添加到 SendCloudToDeviceMessage.py 文件。Add the following code to SendCloudToDeviceMessage.py file. {iot hub connection string}{device id} 占位符值替换为之前记下的 IoT 中心连接字符串和设备ID:Replace the {iot hub connection string} and {device id} placeholder values with the IoT hub connection string and device ID you noted previously:

    CONNECTION_STRING = "{IoTHubConnectionString}"
    DEVICE_ID = "{deviceId}"
    
  5. 添加以下代码,以便将消息发送到设备:Add the following code to send messages to your device:

    def iothub_messaging_sample_run():
        try:
            # Create IoTHubRegistryManager
            registry_manager = IoTHubRegistryManager(CONNECTION_STRING)
    
            for i in range(0, MESSAGE_COUNT):
                print ( 'Sending message: {0}'.format(i) )
                data = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2))
    
                props={}
                # optional: assign system properties
                props.update(messageId = "message_%d" % i)
                props.update(correlationId = "correlation_%d" % i)
                props.update(contentType = "application/json")
    
                # optional: assign application properties
                prop_text = "PropMsg_%d" % i
                props.update(testProperty = prop_text)
    
                registry_manager.send_c2d_message(DEVICE_ID, data, properties=props)
    
            try:
                # Try Python 2.xx first
                raw_input("Press Enter to continue...\n")
            except:
                pass
                # Use Python 3.xx in the case of exception
                input("Press Enter to continue...\n")
    
        except Exception as ex:
            print ( "Unexpected error {0}" % ex )
            return
        except KeyboardInterrupt:
            print ( "IoT Hub C2D Messaging service sample stopped" )
    
  6. 添加以下 main 函数:Add the following main function:

    if __name__ == '__main__':
        print ( "Starting the Python IoT Hub C2D Messaging service sample..." )
    
        iothub_messaging_sample_run()
    
  7. 保存并关闭 SendCloudToDeviceMessage.py 文件。Save and close SendCloudToDeviceMessage.py file.

运行应用程序Run the applications

现在,已准备就绪,可以运行应用程序了。You are now ready to run the applications.

  1. 在工作目录中的命令提示符处,运行以下命令以侦听云到设备消息:At the command prompt in your working directory, run the following command to listen for cloud-to-device messages:

    python SimulatedDevice.py
    

    运行模拟设备应用

  2. 在工作目录中打开一个新的命令提示符,然后运行以下命令以发送云到设备消息:Open a new command prompt in your working directory and run the following command to send cloud-to-device messages:

    python SendCloudToDeviceMessage.py
    

    运行应用以发送云到设备的命令

  3. 记下设备收到的消息。Note the messages received by the device.

    收到的消息

后续步骤Next steps

在本教程中,已学习如何发送和接收云到设备的消息。In this tutorial, you learned how to send and receive cloud-to-device messages.

若要了解有关使用 IoT 中心开发解决方案的详细信息,请参阅 IoT 中心开发人员指南To learn more about developing solutions with IoT Hub, see the IoT Hub developer guide.