The previous article has introduced the composition of the Protocol, a protocol, generally has: protocol header + length + data + checksum, text format can be intuitively defined carriage return line is the end of the protocol, so we can omit the length of the data, increase the end of the protocol. That is: protocol header + data + checksum + data tail.
Text-mode data is easier to analyze. If the data is cached, you can consider using StringBuilder. Or do not cache or can. Most text formatting data has a newline end. You can change it slightly. For example, analysis of common NMEA 0183 format satellite coordinate data gga.
$GPGGA, 121252.000,3937.3032,n,11611.6046,e,1,05,2.0,45.9,m,-5.7,m,,0000*77
$ start
Gpgga command Word
* End
77 Checksum
A little modification of the previous code is possible. The example is not posted. The text format is simple, just for the content to be complete. Paste for reference. Only the area of analysis is much simplified.
voidComm_datareceived (Objectsender, Serialdatareceivedeventargs e) { if(Closing)return;//If you are shutting down, ignore the operation, return directly, and complete the serial listener thread one loop as soon as possible. Try{Listening=true;//set the tag to indicate that I have started working on the data and will use the system UI for a while. //text format is relatively simple, you can death. stringline = Comm. ReadLine ();//This will get the carriage return to the end of the line. But it's not starting from scratch, it's going to check. /////////////////////////////////////////////////////////////////////////////////////////////////////////// // //< protocol resolution >//because the recovered code is in the finally. You can return directly. if(line[0] !='$')return;//Although it may be a bit of rubbish, the data is unimportant. Just throw it away. The follow-up is all right. intStar = line. IndexOf ("*",1); if(Star = =-1)return; //calculates the XOR based on the later data and compares it to the number following the *. If different, no analysis is performed. Because of a checksum error//when the tail is determined to exist, the checksum is correct. You can analyze the data. //Analyze Data//slightly//because you want to access the UI resource, you need to use Invoke to synchronize the UI. This. Invoke ((EventHandler) (Delegate { //determine if it is displayed as 16 forbidden if(checkboxhexview.checked) {//stitching out 16 binary strings in turn foreach(byteBinchbuf) {Builder. Append (B.tostring ("X2") +" "); } } Else { //convert directly to a string by ASCII rulesBuilder. Append (Encoding.ASCII.GetString (BUF)); } //the appended form is added to the end of the text box and scrolls to the end. This. Txget.appendtext (builder. ToString ()); //Modify Receive CountLabelgetcount.text ="Get:"+Received_count. ToString (); })); } finally{Listening=false;//I'm done, the UI can shut down the serial port. } }
C # serial Operation series (4)--Protocol, Text Protocol data analysis (GO)