gpt4 book ai didi

c# - 在字节 [] 中查找 MBUS 电报

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:31 26 4
gpt4 key购买 nike

我正在尝试从串行端口读取 MBUS 电报。我将串口中的所有内容都放入一个字节数组中。

每个 MBUS 电报都以这种模式(十六进制)开头:68 XX XX 68
其中 XX 是以字节为单位的电报长度。

例子: Example http://img97.imageshack.us/img97/6004/mbustele.jpg

这里是一个示例,突出显示的是长度为 99(十六进制)的电报的开头

我想把每一个电报都添加到这样的列表中

List<byte[]> telegramms;

如何实现这个想法?

最佳答案

我刚刚在 VisualStudio 2010 中输入了这个,它对字节顺序做出了各种假设,并且没有管理 MBus 数据包大于串行端口采样字节的潜在问题,或者更重要的是, 如果数据包 header 本身跨越了来自串行端口的数据包之间的边界。

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace StackOverflowTest
{
[TestClass]
public class ByteTest
{
private bool FindEndMark(byte[] source, int index, out int size)
{
int endIndex = index + 3;
if (endIndex > source.Count())
{
// need to cope with the fact that the datapacket might be shorter than the MBus message.
throw new Exception("end count > length of array");
}

if (source[endIndex] == 0x68)
{
// According to the updated spec, the size is emitted twice as a verification
if (source[index + 1] == source[index + 2])
{
size = source[index] + 1;
return true;
}
}
size = 0;
return false;
}

[TestMethod]
public void FindMbusDatagram()
{
byte[] src = new byte[]
{
// Random junk to start
00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb, 0xc, 0xd,
// An MBus Packet
0x68, 06, 00, 0x68, 08, 05, 72, 00, 00, 00,
// More junk
00, 00, 00, 0x16, 00, 00, 00, 00, 01,
// Put a rogue 0x68 in so we can prove we don't get false positives in the datastream
0x68, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb, 0xc, 0xd,
// Another Packet
0x68, 01, 00, 0x68, 0xFF,
//final junk
00, 16, 00, 00, 00, 01, 02, 03
};

List<byte[]> packets = new List<byte[]>();

for (int i = 0; i < src.Length; i++ )
{
if (src[i] != 0x68)
{
continue;
}
else
{
int packetSize = 0;
if (FindEndMark(src, i, out packetSize))
{
if (packetSize > (src.Length - i))
{
// read more data from your port and append it somehow.
}
else
{
// We're packetSize+4 includes the header information + checksum and end
// NB: packetSize+5 is a checksum byte
// NB: packetSize+6 should be 0x16 according to the MBus spec.
byte[] packet = new byte[packetSize + 4];
int count = 0;

// Copy the packet + header into a byte[]
for (int j = i; j < (i + packetSize + 4); j++)
{
packet[count++] = src[j];
}

packets.Add(packet);

// Move the counter along
i += (packetSize + 4);
}
}
}
}

// Should have two packets here.
Assert.IsTrue(packets.Count > 0);
}
}
}

关于c# - 在字节 [] 中查找 MBUS 电报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7105647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com