簡體   English   中英

使用 Azure Azure 將有效載荷發送到 IoT Hub 以用於 Azure 數字孿生 Function

[英]Sending payload to IoT Hub for using in Azure Digital Twin using an Azure Function

對於任何不正確的格式表示歉意,很長一段時間以來我在堆棧溢出上發布了任何內容。

我希望將 json 數據有效負載發送到 Azure IoT 中心,然后我將使用 Azure Function 應用程序對其進行處理,以在 Azure 數字孿生中顯示實時遙測數據。

我可以將有效負載發布到 IoT 中心並使用資源管理器查看它,但是我的 function 無法接收並在 Azure 數字孿生中顯示此遙測數據。 從谷歌搜索我發現 json 文件需要加密 utf-8 並設置為 application/json,我認為這可能是我當前嘗試修復此問題的問題。

我在下面包含了來自我的 azure function 應用程序的日志 stream 的片段,如圖所示消息的“正文”部分被打亂,這就是為什么我認為這可能是有效負載編碼方式的問題:

"iothub-message-source":"Telemetry"},"body":"eyJwb3dlciI6ICIxLjciLCAid2luZF9zcGVlZCI6ICIxLjciLCAid2luZF9kaXJlY3Rpb24iOiAiMS43In0="} 2023-01-27T13:39:05Z [Error] Error in ingest function: Cannot access child value on Newtonsoft.Json.Linq.JValue.

我當前的測試代碼如下,用於將有效載荷發送到 IoT 中心,潛在的問題是我沒有正確編碼有效載荷。

import datetime, requests 
import json

deviceID = "JanTestDT"
IoTHubName = "IoTJanTest"
iotHubAPIVer = "2018-04-01"
iotHubRestURI = "https://" + IoTHubName + ".azure-devices.net/devices/" + deviceID +     "/messages/events?api-version=" + iotHubAPIVer
SASToken = 'SharedAccessSignature'

Headers = {}
Headers['Authorization'] = SASToken
Headers['Content-Type'] = "application/json"
Headers['charset'] = "utf-8"

datetime =  datetime.datetime.now()
payload = {
'power': "1.7",
'wind_speed': "1.7",
'wind_direction': "1.7"
}

payload2 = json.dumps(payload, ensure_ascii = False).encode("utf8")

resp = requests.post(iotHubRestURI, data=payload2, headers=Headers)

我試圖以幾種不同的方式正確編碼有效負載,包括 request.post 中的 utf-8,但是這會產生一個錯誤,即無法對 dict 進行編碼,或者仍然在 Function 應用程序日志 stream 中加密主體無法解密它。

感謝您對此提供的任何幫助和/或指導 - 很樂意進一步詳細說明任何不清楚的地方。

為什么要使用 Azure IoT Hub Rest API 端點而不是使用 Python SDK 有什么特別的原因嗎? 此外,即使您在通過 Azure IoT Explorer 查看時看到 JSON 格式的值,通過 blob 等存儲端點查看時的消息格式也會顯示與您指出的不同格式。

我沒有用 REST API 測試 Python 代碼,但我有一個 Python SDK 對我有用。 請參考下面的代碼示例

import os
import random
import time
from datetime import date, datetime
from json import dumps
from azure.iot.device import IoTHubDeviceClient, Message


def json_serial(obj):
    """JSON serializer for objects not serializable by default json code"""

    if isinstance(obj, (datetime, date)):
        return obj.isoformat()
    raise TypeError("Type %s not serializable" % type(obj))


CONNECTION_STRING = "<AzureIoTHubDevicePrimaryConnectionString>"
TEMPERATURE = 45.0
HUMIDITY = 60
MSG_TXT = '{{"temperature": {temperature},"humidity": {humidity}, "timesent": {timesent}}}'


def run_telemetry_sample(client):
    print("IoT Hub device sending periodic messages")

    client.connect()

    while True:
        temperature = TEMPERATURE + (random.random() * 15)
        humidity = HUMIDITY + (random.random() * 20)
        x = datetime.now().isoformat()
        timesent = dumps(datetime.now(), default=json_serial)
        msg_txt_formatted = MSG_TXT.format(
            temperature=temperature, humidity=humidity, timesent=timesent)
        message = Message(msg_txt_formatted, content_encoding="utf-8", content_type="application/json")
        
        print("Sending message: {}".format(message))
        client.send_message(message)
        print("Message successfully sent")
        time.sleep(10)


def main():
    print("IoT Hub Quickstart #1 - Simulated device")
    print("Press Ctrl-C to exit")

    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)

    try:
        run_telemetry_sample(client)
    except KeyboardInterrupt:
        print("IoTHubClient sample stopped by user")
    finally:
        print("Shutting down IoTHubClient")
        client.shutdown()


if __name__ == '__main__':
    main()

您可以在代碼中編輯 MSG_TXT 變量以匹配負載格式並傳遞值。 請注意,SDK 使用來自 Azure IoT 設備庫的消息 class ,它具有內容類型和內容編碼的重載。 這是我在代碼中傳遞重載的方式message = Message(msg_txt_formatted, content_encoding="utf-8", content_type="application/json")

我已通過路由到 Blob 存儲容器來驗證消息,並且可以看到 JSON 格式的遙測數據。 請參考下面的圖像截圖,參考在終點捕獲的數據。

在此處輸入圖像描述

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM