2010-06-09 01:50 19739人閱讀
上一篇已經介紹了協議的組成,一個協議,通常具備 :協議頭+長度+數據+校驗 , 文本格式能夠直觀的定義回車換行是協議的結尾,因此咱們能夠省略數據長度,增長協議尾。即: 協議頭 + 數據 + 校驗 + 數據尾 。緩存
文本方式的數據比較容易分析。若是數據緩存,能夠考慮用StringBuilder。或是不緩存也能夠。文本格式數據大多有換行結尾。稍微修改便可。例如分析常見的NMEA 0183格式的衛星座標數據GGA。post
$GPGGA,121252.000,3937.3032,N,11611.6046,E,1,05,2.0,45.9,M,-5.7,M,,0000*77ui
$ 開始this
GPGGA 命令字spa
* 結尾.net
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;
- }
- }
-
-