使用REST API,端点发送云到设备的消息Azure IoT中心

时间:2019-06-14 14:59:53

标签: python azure rest cloud azure-iot-hub

我正在尝试使用Azure IoT中心和REST api(不使用Azure IoT中心python SDK)将消息从云发送到我的设备。

我可以使用uri https://<myiothub>.azure-devices.net/devices/<devid>/messages/events?api-version=2018-06-30从设备成功向集线器发送消息(POST请求)。 https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-messages-c2d的文档中说/messages/devicebound处有一个服务端端点。但是,它们没有显示完整的示例,因此我不确定我应该使用的完整端点是什么,以及如何/在何处指定发送到哪个设备。

我还是尝试了以下方法:

curl -v POST \
  https://<myhub>.azure-devices.net/messages/devicebound?api-version=2018-06-30 \
  -H 'Authorization: SharedAccessSignature <sas>' \
  -H 'Content-Type: application/json' \
  -d '{
    "payload": {
      "key": "value"
    }
  }'

其中是通过Azure CLI az iot hub generate-sas-token -n <myhub>生成的。我收到错误消息

{"Message":"ErrorCode:ArgumentInvalid;Request must contain IoTHub custom 'To' header","ExceptionMessage":"Tracking ID:ec98ff8...

我切断了结尾。因此,我尝试添加一个“ To”标头,无论输入什么内容,它都会返回相同的错误消息。

我也尝试了Cloud-to-device Azure IoT REST API的建议,即通过端点https://main.iothub.ext.azure.com/api/Service/SendMessage/发送,但是没有运气。

2 个答案:

答案 0 :(得分:0)

要使用IoT中心API从设备端接收“云到设备”消息,您将必须执行以下请求-

curl -X GET \
  'https://{your hub}.azure-devices.net/devices/{your device id}/messages/deviceBound?api-version=2018-06-30' \
  -H 'Authorization: {your sas token}'

答案 1 :(得分:0)

方法如下:

  1. 使用文本编辑器创建一个SendCloudToDeviceMessage.py文件。

  2. SendCloudToDeviceMessage.py 文件的开头添加以下导入语句和变量:

import random
import sys
import iothub_service_client
from iothub_service_client import IoTHubMessaging, IoTHubMessage, IoTHubError

OPEN_CONTEXT = 0
FEEDBACK_CONTEXT = 1
MESSAGE_COUNT = 1
AVG_WIND_SPEED = 10.0
MSG_TXT = "{\"service client sent a message\": %.2f}"
  1. 将以下代码添加到SendCloudToDeviceMessage.py文件中。用您之前记下的IoT集线器连接字符串和设备ID替换“ {iot集线器连接字符串}”和“ {device id}”占位符值:
CONNECTION_STRING = "{IoTHubConnectionString}"
DEVICE_ID = "{deviceId}"
  1. 添加以下功能以将反馈消息打印到控制台:
def open_complete_callback(context):
    print ( 'open_complete_callback called with context: {0}'.format(context) )

def send_complete_callback(context, messaging_result):
    context = 0
    print ( 'send_complete_callback called with context : {0}'.format(context) )
    print ( 'messagingResult : {0}'.format(messaging_result) )
  1. 添加以下代码以向设备发送消息并在设备确认云到设备消息后处理反馈消息:
def iothub_messaging_sample_run():
    try:
        iothub_messaging = IoTHubMessaging(CONNECTION_STRING)

        iothub_messaging.open(open_complete_callback, OPEN_CONTEXT)

        for i in range(0, MESSAGE_COUNT):
            print ( 'Sending message: {0}'.format(i) )
            msg_txt_formatted = MSG_TXT % (AVG_WIND_SPEED + (random.random() * 4 + 2))
            message = IoTHubMessage(bytearray(msg_txt_formatted, 'utf8'))

            # optional: assign ids
            message.message_id = "message_%d" % i
            message.correlation_id = "correlation_%d" % i
            # optional: assign properties
            prop_map = message.properties()
            prop_text = "PropMsg_%d" % i
            prop_map.add("Property", prop_text)

            iothub_messaging.send_async(DEVICE_ID, message, send_complete_callback, i)

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

        iothub_messaging.close()

    except IoTHubError as iothub_error:
        print ( "Unexpected error {0}" % iothub_error )
        return
    except KeyboardInterrupt:
        print ( "IoTHubMessaging sample stopped" )
  1. 添加以下主要功能:
if __name__ == '__main__':
    print ( "Starting the IoT Hub Service Client Messaging Python sample..." )
    print ( "    Connection string = {0}".format(CONNECTION_STRING) )
    print ( "    Device ID         = {0}".format(DEVICE_ID) )

    iothub_messaging_sample_run()
  1. 保存并关闭 SendCloudToDeviceMessage.py 文件。

  2. 安装依赖项库:pip install azure-iothub-service-client

  3. 运行应用程序:python SendCloudToDeviceMessage.py

参考: https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/iot-hub/iot-hub-python-python-c2d.md