【问题标题】:Azure IoT hub - Device is custom binary payload from device to IoT hub and needs way for parsingAzure IoT 中心 - 设备是从设备到 IoT 中心的自定义二进制有效负载,需要解析方式
【发布时间】:2019-05-21 08:08:07
【问题描述】:

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

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

设备模拟器上的代码:

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 转换为字节数组,但没有成功。

【问题讨论】:

  • 它是否显示任何错误?可以打印日志吗?

标签: azure azure-iot-hub


【解决方案1】:

不要使用字符串作为输入绑定属性,而是使用 EventData。有关完整示例,请参阅我的代码 here

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

然后,您可以将正文(原始内容)作为 stream 从消息对象中读取。

当您使用字符串时,IoTHub 绑定在内部尝试将消息正文解释为 UTF-8 编码的字符串 - 这显然在您的情况下失败。

【讨论】:

    【解决方案2】:

    尝试以下方法:

    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:\n\t{string.Join("\n\t", systemproperties.Select(i => $"{i.Key}={i.Value}"))}");
    
        log.Info($"\nProperties:\n\t{string.Join("\n\t", properties.Select(i => $"{i.Key}={i.Value}"))}");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-11
      • 2023-01-27
      • 1970-01-01
      • 2019-04-27
      • 2023-03-17
      • 1970-01-01
      相关资源
      最近更新 更多