【发布时间】:2014-02-28 04:57:11
【问题描述】:
我正在编写一个 C# 应用程序以同时从多个串行 COM 端口读取数据以分析 IPOD 的数据通信。发送的数据需要被解释为 HEX 字节。例如,
0xFF 0x55 0x01 0x00 0x04 0xC3 0xFF 0x55 ...
例如,我希望能够阅读并在富文本框中显示它
0xFF 0x55 0x01 0x00 0x04 0xC3
0xFF 0x55 ...
命令的开头包含一个header(0xFF 0x55),其余为命令+参数+校验和。
最好的方法是什么?
我目前有:
private delegate void SetTextDeleg(string text);
void sp_DataReceivedRx(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
try
{
string data = IPODRxPort.ReadExisting(); // Is this appropriate??
// Invokes the delegate on the UI thread, and sends the data that was received to the invoked method.
// ---- The "si_DataReceived" method will be executed on the UI thread which allows populating of the textbox.
this.BeginInvoke(new SetTextDeleg(si_DataReceivedRx), new object[] { data });
}
catch
{ }
}
private void si_DataReceivedRx(string data)
{
int dataLength = data.Length*2;
double numLines = dataLength / 16.0;
for (int i = 0; i < numLines; ++i)
IPODTx_rtxtBox.Text += "\n";
IPODRx_rtxtBox.Text += SpliceText(convertAsciiTextToHex(data), 32) + "\n";
}
我可以读取数据,但格式不正确。
我只是不确定从 com 端口获取十六进制数据并根据命令头 (0xFF 0x55) 逐行显示的最佳方法。
有什么建议吗?
【问题讨论】:
-
使用
Read(byte[] buffer, int offset, int count)函数而不是ReadExisting,因为通信协议不是基于文本的。之前调用BytesToRead属性,检测所需的数组大小。 -
你不是很亲密。您需要更好地描述消息格式,“ipod”并不是一个很好的选择器。