串口数据解析

与设备的通信,包括串口与TCP两种主要方式。

TCP通信时,可以与服务端约定指定类型的格式进行JSON传输,收到数据后直接解析即可。

串口通信与底层设备打交道的比较多,底层一般提供不了复杂格式的数据,多以HexString的长串形式进行传输。收到数据后,需要逐位进行对照解析,HexString越长,复杂性越高。

模拟开发

本地开发串口功能时,可以用VSPD模拟串口收发。
image

使用串口工具给COM1发送数据,打开COM2串口接收数据。
image

private readonly SerialPortHelper _spHelper;
public TestSerialPortDemo()
{
    _spHelper = new SerialPortHelper();
    _spHelper.DataReceivedEvent += SerialPort_DataReceivedEvent;
    _spHelper.Close();
    if (_spHelper.Init("COM2"))
    {
        _spHelper.SetStartIdentifier(new byte[] { 0xAA, 0xAA });
        _spHelper.SetEndIdentifier(new byte[] { 0xBB, 0xBB });
    }
}

private void SerialPort_DataReceivedEvent(object sender, EventArgs e)
{
    if (e is CustomSerialPortEventArgs arg)
    {
        var data = arg.Message;
        LogHelper.Info(WSCommFunc.Byte2HexStringX2(data));
    }
}

TCP开发可以参考:TCP模拟开发

posted @ 2022-10-24 15:35  wesson2019  阅读(391)  评论(0)    收藏  举报