gpt4 book ai didi

供 MQTT 设备订阅的 Azure C2D 消息

转载 作者:行者123 更新时间:2023-12-03 02:18:36 31 4
gpt4 key购买 nike

我已成功将两个实际设备连接到 Azure IoTHub(在同一个 IoT 中心),并希望第二个设备接收第一个设备发送的消息。因此,在普通的 MQTT 代理中,第二个设备仅订阅该主题,但 Azure没有普通的 MQTT 代理。

我现在想做的是编写一个 Azure 函数,每当通过事件中心触发器在 IoTHub 中接收到来自第一台设备的消息时,该函数就会触发;并将带有接收到的消息(字符串)的C2D消息发送到第二设备。要实现第二个设备订阅此主题:devices/secondDevice/messages/devicebound

这是我的函数

#r "Microsoft.Azure.EventHubs"


using System;
using System.Text;

using Microsoft.Azure.EventHubs;
using Microsoft.Azure.Devices;

static ServiceClient serviceClient;
static string connectionString = ".........pXH9WI.....";
static string targetDevice = "secondDevice";

public static async Task Run(EventData[] events, ILogger log)
{
var exceptions = new List<Exception>();
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
foreach (EventData eventData in events)
{
try
{
string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);

// Replace these two lines with your processing logic.
log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
await Task.Yield();
var commandMessage = new Message(Encoding.ASCII.GetBytes(messageBody));
await serviceClient.SendAsync(targetDevice, commandMessage); // send the message to the second device that the first device sent to IoTHub
}
catch (Exception e)
{
// We need to keep processing the rest of the batch - capture this exception and continue.
// Also, consider capturing details of the message that failed processing so it can be processed again later.
exceptions.Add(e);
}
}

// Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.
if (exceptions.Count > 1)
throw new AggregateException(exceptions);

if (exceptions.Count == 1)
throw exceptions.Single();
}

这是 .json 代码:

{
"bindings": [
{
"type": "eventHubTrigger",
"name": "events",
"direction": "inout",
"eventHubName": "samples-workitems",
"cardinality": "many",
"connection": "myIoTHub_events_IOTHUB",
"consumerGroup": "$Default"
}
]
}

我正在接收第一台设备的消息,但在第二台设备订阅的主题中没有看到该消息。 enter image description here

有什么想法吗?我通过门户网站完成所有这些工作是因为我目前在 VSCode 方面遇到了很多问题,并且希望快速解决这个 C2D 问题。

谢谢

最佳答案

第二个设备应按照 docs 订阅主题过滤器 # 。那么话题就变成了:

devices/secondDevice/messages/devicebound/#

关于供 MQTT 设备订阅的 Azure C2D 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70064075/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com