如何将来自传感器的二进制有效负载解码为Json有效负载

问题描述

我有这个传感器:

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

我正在使用Azure IoT中心流式传输来自设备的消息。

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

,我在这里找到了这个很棒的文档: 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.
    

解决方法

您可以使用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
}