【问题标题】:How to decode a binary payload from a sensor into a Json payload如何将来自传感器的二进制有效负载解码为 Json 有效负载
【发布时间】:2020-10-09 20:34:07
【问题描述】:

我有这个传感器:

https://cdn.antratek.nl/media/wysiwyg/pdf/RM_Sound_Level_Sensor_20200319_BQW_02_0011.pdf

我正在使用 Azure IoT Hub 从设备流式传输消息。

由于这是一个 lorawan 传感器,我需要使用自定义解码器对有效载荷进行解码。

我在这里找到了这个很棒的文档: https://github.com/Azure/iotedge-lorawan-starterkit/blob/9124bc46519eccd81a9f0faf0bc8873e410d31a6/Samples/DecoderSample/ReadMe.md

我有一些代码:

internal static class LoraDecoders
{
    private static string DecoderValueSensor(string devEUI, byte[] payload, byte fport)
    {
        // EITHER: Convert a payload containing a string back to string format for further processing
        var result = Encoding.UTF8.GetString(payload);

        // OR: Convert a payload containing binary data to HEX string for further processing
        var result_binary = ConversionHelper.ByteArrayToString(payload);

        // Write code that decodes the payload here.

        // Return a JSON string containing the decoded data
        return JsonConvert.SerializeObject(new { value = result });

    }
}

现在问题是基于上面第 4.1.2 节的文档

这行之后我应该在 .net 中做什么:

 var result_binary = ConversionHelper.ByteArrayToString(payload);
    
            // Write code that decodes the payload here.
    

【问题讨论】:

  • 我会使用字符串结果。尝试添加 Console.WriteLine(result);

标签: c# json .net-core decode azure-iot-hub


【解决方案1】:

您可以使用bitwise operators in C# 解码有效负载。

例如,参考文档第 4.1.2 节中描述的 4 字节有效负载可以转换为 C# 结构:

enum SensorStatus
{
    KeepAlive = 0,
    TriggerThresholdEvent = 1
}

[StructLayout(LayoutKind.Sequential)]
struct Payload
{
    // Section 4.1.2 Payload
    private byte _status;
    private byte _battery;
    private byte _temp;
    private byte _decibel;

    // Decode
    public SensorStatus SensorStatus => (SensorStatus)(_status & 1);

    public int BatteryLevel => (25 + (_battery & 15)) / 10;

    public int Temperature => (_temp & 127) - 32;

    public int DecibelValue => _decibel;

    public bool HasDecibelValue => DecibelValue != 255;
}

要从 4 个字节数组创建这样的 sequential struct,您可以使用 Unsafe 类:

var payloadBytes = new byte[] { 1, 2, 3, 4 };
var payload = Unsafe.As<byte, Payload>(ref payloadBytes[0]);

然后您可以序列化您的 payload 结构:

JsonConvert.SerializeObject(payload, Formatting.Indented);

它产生 JSON:

{
  "SensorStatus": 1,
  "BatteryLevel": 2,
  "Temperature": -29,
  "DecibelValue": 4,
  "HasDecibelValue": true
}

【讨论】:

  • 谢谢,我会尽快尝试,如果有效,请告诉您
  • 您将我的代码中的 result_binary 参数放在哪里?
  • result_binary 是一个示例,它表明您可以将byte[] 转换为 HEX 格式并在 JSON 中返回,然后您的 API 客户端将解析十六进制字符串。或者,如果 byte[] 本质上是一个 utf8 编码的字符串,您可以将其解析回字符串,并以 JSON 格式返回字符串。他们都是例子。和我的一样。我根据规范将byte[] 数组直接从byte[] 解析为JSON,因此不再需要resultresult_binary
猜你喜欢
  • 1970-01-01
  • 2019-12-27
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 2017-02-02
  • 2016-01-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多