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



我有这个传感器:

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.

您可以在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的字节数组创建这样的顺序结构,可以使用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
}

最新更新