上一篇已经介绍了协议的组成,一个协议,一般具有 :协议头+长度+数据+校验 , 文本格式可以直观的定义回车换行是协议的结尾,所以我们可以省略数据长度,增加协议尾。即: 协议头 + 数据 + 校验 + 数据尾 。
文本方式的数据比较容易分析。如果数据缓存,可以考虑用StringBuilder。或是不缓存也可以。文本格式数据大多有换行结尾。稍微修改即可。例如分析常见的NMEA 0183格式的卫星坐标数据GGA。
$GPGGA,121252.000,3937.3032,N,11611.6046,E,1,05,2.0,45.9,M,-5.7,M,,0000*77
$ 开始
GPGGA 命令字
* 结尾
77 校验
对上一篇代码稍作修改就可以了。例子不贴了。文本格式比较简单,只是为了内容完整。贴来做参考。只有分析的地方简化很多。
- void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- if (Closing) return;
- try
- {
- Listening = true;
-
- string line = comm.ReadLine();
-
-
-
- if(line[0] != '$') return;
- int star = line.IndexOf("*",1);
- if(star == -1) return;
-
-
-
-
-
-
-
- this.Invoke((EventHandler)(delegate
- {
-
- if (checkBoxHexView.Checked)
- {
-
- foreach (byte b in buf)
- {
- builder.Append(b.ToString("X2") + " ");
- }
- }
- else
- {
-
- builder.Append(Encoding.ASCII.GetString(buf));
- }
-
- this.txGet.AppendText(builder.ToString());
-
- labelGetCount.Text = "Get:" + received_count.ToString();
- }));
- }
- finally
- {
- Listening = false;
- }
- }
-
-