[Switch] C # serial port operation series (5) -- prototype of the communication library

Source: Internet
Author: User

The serial port is very simple, and programming based on the serial port is also very easy. In addition to a bunch of uncommon concepts and cross-thread access details, newbies also have a difficult problem to overcome, namely Protocol parsing. The previous article has explained:

OneProtocol in binary formatIt generally includes: protocol header + Data Segment Length+Data+Verification

OneText protocol in ASCII format, Generally includes: Data Header+Body+Data end ID

There may be many similar commands, and similar code will be repeatedly written many times. I don't think this is difficult for me. However, many times I don't want to write something similar. Instead, I need to build a framework like this, this is definitelyPhysical ActivityAnd you also needPatienceAndCareful.

Since my last project, I began to consider writing a universal communication library that supports many functions. However, it is closely integrated with the company's content and is not suitable for open-source applications or marketing purposes. I reorganized and abstracted various concepts. It is hoped that new friends can reduce their learning difficulty and invest more quickly in other aspects.

 

Please note that I do not know how to generalize in this article. I am introducing how to design such a communication library.

Communication library, not a serial LibrarySo I want to have a base class that can describe the base class or interface of various communication methods. Microsoft has already done so and he calls it stream. I think the bad reason is that the Length attribute, peek method, and seek method are not available, and many methods and attributes are not supported. If this type of hardware is used, just like a mine, you may accidentally write an unsupported operation and report an error during running. Therefore, I want to redesign the hardware of the stream device. I abstracted an interface: icommunication. Provides basic features and operations for stream devices, such as opening, closing, reading and writing, Character Set, and valid data length.

In order to have oneCommon configuration classes, I defined an interface: icommunicationsetting.

When you implement a device, you need to implement icommunication and write a set class to implement the icommunicationsetting interface. Don't worry. This is to be abstract and write a general code that never needs to be rewritten. With two interfaces, I can even write functions or software dependent on this interface. Of course, I still need to write about the protocol analysis.

SinceThere are two types of protocols, It is natural to write binaryxxx and textxxx. Yes, there are two classes.

For more details, any data is not valid for an indefinite period. For example, if you get the voltage from the lower computer, it will be invalid after several seconds. Therefore, you must consider timing failure, so I implemented the validity check. Data should be searched, analyzed, and notified in the byte array. So I pulled out these public parts. I wrote an interface called: ianalyzer and wrote the default implementation, so I had the analyzeresult class. At the same time, it distinguishes two protocol methods and creates sub-classes: binaryanalyzeresult and textanalyzeresult.

Who will use icommunication and ianalyzer? Don't worry, the relationship is a little tight. I won't throw it to the outside, but it is more complicated to do so, isn't it. So I wrote a class with the analysis function: wyzcomm.

Use

This class implements data collection, caching, analyzer calls, and event call notifications. The control of data deadlocks is done here for all the troubles you think. So when I write this class, I certainly don't know how many protocols will there be in the future, right? What should we do? I cannot write the analyzer, so I wrote the interface: ianalyzercollection, because the article starts from the serial port, I first provided the Implementation of the serial port:

SerialPort (the same name as Microsoft, but not the same) implements the icommunication interface. I defined a serialportsetting class and implemented icommunicationsetting.

So far. The communication library framework is complete. This is all the content that requires attention when using the communication library. Below, I have compiled a simple implementation for practical demonstration. To demonstrate a function. Assume that I have a program that needs to analyze both the binary data format and the ASCII text data format. The data is different. After the communication library is used, I don't need to rewrite the data cache, disable deadlock processing, and notify the data to the interface. I only need to write two protocol classes and one protocol collection class. My data analysis is complete.

 

The first is a text protocol, the header is WYZ, the end of the Protocol is a carriage return line, and the middle is an integer. I only need to set the header and tail to write data analysis.

[C-sharp]View plaincopy
  1. Public class mydata1: textanalyzeresult <int>
  2. {
  3. Public mydata1 ()
  4. {
  5. This. beginofline = "WYZ ";
  6. This. endofline = "/R/N ";
  7. }
  8. Public override void analyze ()
  9. {
  10. String S = encoding. getstring (raw );
  11. Match m = RegEx. Match (S, "// D + ");
  12. If (M. Success)
  13. {
  14. This. Data = int. parse (M. value );
  15. This. Valid = true;
  16. }
  17. }
  18. }

 

 

Then I defined a binary protocol and analyzed a piece of data containing two sub-items.

First, I will define the specific data type.

[C-sharp]View plaincopy
  1. Public class sampledata
  2. {
  3. Public int version {Get; set ;}
  4. Public float voltage {Get; set ;}
  5. Public sampledata ()
  6. {
  7. Version = 0;
  8. Voltage = 0;
  9. }
  10. Public override string tostring ()
  11. {
  12. Return string. Format ("{0}, {1}", version. tostring (), voltage. tostring ());
  13. }
  14. }

 

Then I write the protocol analysis class

[C-sharp]View plaincopy
  1. Public class mydata2: binaryanalyzeresult <sampledata>
  2. {
  3. Public mydata2 ()
  4. {
  5. This. _ mask = new byte [] {0xaa, 0xbb, 0xcc };
  6. This. Timeout = 5; // if data is not received after more than 5 seconds, the data is invalid.
  7. // Customize the verification method. This example is used to add and modulo any number one by one. I chose 42.
  8. This. checksum = (BUF, offset, count) =>
  9. {
  10. Byte checksum = 0;
  11. For (INT I = offset; I <OFFSET + count; I ++)
  12. {
  13. Checksum = (byte) (checksum + Buf [I]) % 42 );
  14. }
  15. Return checksum;
  16. };
  17. }
  18. Public override void analyze ()
  19. {
  20. Int offset = _ mask. length + lenlength; // _ mask. length indicates the marked byte, _ mask. length + 1 indicates the second byte after marking, and one byte indicates the length.
  21. This. Data. Version = bitconverter. toint32 (raw, offset + 0 );
  22. This. Data. voltage = bitconverter. tosingle (raw, offset + 4 );
  23. This. Valid = true; // note that you must set the valid data status.
  24. }
  25. }

 

 

Finished. A serial port-based, simultaneous analysis of two types of data, the data has the validity judgment, support independent data notification interface, the overall original data cache display function. Finished.

In order to demonstrate the function, I wrote a new verification method. Of course, you don't need to worry about it. By default, the exception or verification is supported, and common verification will be added later. crc16, CRC32, parity.

 

Simulate sending data as follows:

Text Format transmission: wyz123 <CR> <LF>

Sending in binary format: aa bb cc 08 0a 00 00 00 fa 3E F7 42 05

 

Example of vs2008 project source code

[Switch] C # serial port operation series (5) -- prototype of the communication library

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.