Azure IoT Hub-设备是从设备到IoT Hub的自定义二进制有效载荷,需要解析的方式



我有一个将二进制数据包发送到服务器的设备。我想将其迁移到Azure IoT中心。我想坚持二进制数据本身,并在Azure函数中解析二进制数据。

我使用Azure SDK在.NET中编写了设备模拟器,并编写了Azure函数,该函数在IoT Hub上接收到的消息时会触发。

设备模拟器上的代码:

double currentTemperature = 23.0;
byte[] temp= BitConverter.GetBytes(currentTemperature);
double currentHumidity = 24.0;
byte[] humidity= BitConverter.GetBytes(currentHumidity);
List<byte> bytes = new List<byte>();
bytes.AddRange(temp);
bytes.AddRange(humidity);
DeviceClient s_deviceClient; // Created device client here.
var message = new Microsoft.Azure.Devices.Client.Message(bytes.ToArray());
await s_deviceClient.SendEventAsync(message);

在Azure函数中 - 如果我转换

public static void Run(string myIoTHubMessage, ILogger log)
{
    byte[] dataArray = Encoding.ASCII.GetBytes(myIoTHubMessage);
}

在这里,我尝试了不同类型的编码来掩盖 myiothubmessage to byte数组,但它没有起作用。

尝试以下内容:

using System;
public static void Run(byte[] myIoTHubMessage, IDictionary<string, object> properties, IDictionary<string, object> systemproperties, TraceWriter log)
{
    log.Info($"Temperature = {BitConverter.ToDouble(myIoTHubMessage, 0)}");
    log.Info($"Humidity = {BitConverter.ToDouble(myIoTHubMessage, 8)}");
    log.Info($"nSystemProperties:nt{string.Join("nt", systemproperties.Select(i => $"{i.Key}={i.Value}"))}");
    log.Info($"nProperties:nt{string.Join("nt", properties.Select(i => $"{i.Key}={i.Value}"))}");
}

,而不是使用字符串作为输入绑定属性,而是使用EventData。在此处查看我的代码以获取一个完整的示例。

[FunctionName("IotHubMessageProcessor")]
public static void Run([IoTHubTrigger("messages/events", Connection = "iothubevents_cs", ConsumerGroup = "receiverfunction")]EventData message, ILogger log)

然后,您可以从消息对象的流中读取正文(原始内容(。

当您使用字符串时,IOTHUB绑定内部试图将消息主体解释为UTF -8编码字符串 - 显然在您的情况下会失败。

最新更新