Serial Data Processing

Source: Internet
Author: User
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. io. ports; using system. runtime. compilerservices; using system. diagnostics; using system. threading; using util. log; namespace seriallibrary {public class seriallib {# region custom private bool running; // The current running state private SerialPort sp; // serial control private long received_count, send_count; // total sent bytes, total received bytes private byte [] Received; // The cache private int received_offset of all received data; // The idle position of the Current Buffer private int receiv_offset; // the location of the obtained command, next available start position const int buf_size = 512; const byte STX = 0x02; // STX const byte etx = 0x03; // etx private dictionary <byte, waitevent> waitlist; # endregion public seriallib () {send_count = 0; received_count = 0; received_offset = 0; resource_offset = 0; waitlist = new dictionary <byte, waitevent> (); Running = False; SP = new SerialPort (); SP. readbuffersize = 512; SP. writebuffersize = 512; SP. baudrate = 9600; SP. stopbits = stopbits. one; SP. databits = 8; SP. parity = parity. none; received = new byte [buf_size]; SP. datareceived + = new serialdatareceivedeventhandler (sp_datareceived);} // The command waits for a response // class waitevent: idisposable {public manualresetevent event; Public byte [] Recv; public waitevent () {Recv = NULL; event = new manualresetevent (false);} public void dispose () {Recv = NULL; event. dispose (); event = NULL ;}/// receives serial data, extracts valid commands, and sends them to the thread pool for processing. // lock the entire method, prevents the value of the global variable from being affected after receiving the message multiple times. You must complete this operation before receiving [methodimpl (methodimploptions. Synchronized)] private void sp_datareceived (Object sender, serialdatareceivedeventargs e) {If (! Running) return; SerialPort sp = (SerialPort) sender; int n = sp. bytestoread; If (received_offset + n> buf_size) // The data packet is too large to be placed. Only the number of bytes that can be put down is received. {pack_received_buffer (); // compression if (received_offset + n> buf_size) // It cannot be received after compression. Reduce the receiving space {n = buf_size-received_offset;} received_count + = N; // total number of bytes received byte [] Buf = new byte [N]; SP. read (BUF, 0, n); array. copy (BUF, 0, received, received_offset, n); received_offse T + = N; // offset debug after migration. writeline ("receiving location-{0}, command location-{1}, total received bytes-{2}, total sent bytes-{3}", received_offset, pai_offset, received_count, send_count); debug. writeline ("received data:" + dump_buffer (BUF); // query the Protocol end by protocol length int datalen = get_int (received ed, 1__offset + 1, 2 ); int end_offset = __offset + 3 + datalen; // end_offset = end_offset <received_offset? End_offset: cmd_offset + 1; // prevent reading junk bytes if (received [end_offset]! = Etx) return; // the received data is incomplete. Wait for the next while (received ed [end_offset]! = Etx & end_offset <received_offset) end_offset ++; If (end_offset = received_offset) {// if no valid content exists after more than 256 bytes are found, clear all. The data in a single package should not exceed 128 If (end_offset> 1__offset + 256) {inclued_offset = 0; 1__offset = 0;} return; // No end character is found} end_offset ++; // move one byte behind, and insert the package into the LRC Checksum byte [] 1__buf = new byte [end_offset-1__offset + 1]; array. copy (sorted ed, sorted _offset, sorted _buf, 0, sorted _buf.length); // copy a complete threadpool command. queueuserworkitem (receive_serial_data, pai_buf); pai_offset = end_offset + 1; // skip LRC to the next if (inclued_offset> Buf _ Size * 0.85) // The cache location exceeds 85%. It is practically impossible, unless it is disturbed by full garbled characters {pack_received_buffer () ;}} private void receive_serial_data (Object Data) {byte [] cmd_buf = (byte []) data; debug. writeline ("processing data:" + dump_buffer (pai_buf); log. info ("processing data:" + dump_buffer (pai_buf); byte LRC = pai_buf [pai_buf.length-1]; // get the last byte, LRC if (LRC! = Calc_lrc (pai_buf, 3, pai_buf.length-2) {debug. writeline ("Data LRC verification failed, not processed");} Byte encoding type = pai_buf [3]; lock (waitlist) {If (waitlist. containskey (partition type) {int dlength = get_int (partition _buf, 1, 2); waitevent we = waitlist [partition type]; If (dlength> 0) {We. recv = new byte [dlength + 5]; array. copy (pai_buf, 0, we. recv, 0, dlength + 5); // if any data is returned, return together with the command type} We. event. set () ;}}///// start the serial port ///// /Serial port number of the card connection module // public int start (INT port) {If (running) return 0; // if it has been enabled, the success SP is returned directly. portname = string. format ("com {0}", Port); try {sp. open (); SP. discardinbuffer (); SP. discardoutbuffer (); running = true; log. info ("card module serial port com" + port. tostring () + "started successfully"); Return 0;} catch (exception e) {log. error ("failed to start the serial port:", e); return 1 ;}///// close the serial port ///Public void stop () {If (running) {try {If (sp. ISO Pen) sp. close (); log. info ("the serial port of the card module is disabled successfully");} catch (exception e) {log. error ("Serial Port close exception:", e) ;}running = false ;}} ////// send the serial port command ///// command type /// send data /// receive data. It may be null // 0 indicates that the processing is successful, 3 indicates that no response is returned, and other values include public int process (byte multicast type, byte [] data, out byte [] recvdata, int wait) {recvdata = NULL; 1__offset = 0; int dlength = data. length; byte [] cmd = new byte [dlength + 6]; // 1 head length + 2 length (BCD) + 1 command length (BCD) + 4-length terminal number (BCD) + 4-length table file serial number (BCD) + N-Length Packet + 1 tail length + 1 Verification length int datalen = data. length + 1; bcdstr_to_byte_array (datalen. tostring (), ref cmd, 1, 2); // set the Data Length to two bytes. CMD [0] = STX; struct type = in T2bcd (struct type); cmd [3] = struct type; array. copy (data, 0, CMD, 4, dlength); cmd [4 + dlength] = etx; cmd [5 + dlength] = calc_lrc (CMD, 3, cmd. length-2); send_count + = cmd. length; debug. writeline ("sending command:" + dump_buffer (CMD); log. info ("sending command:" + dump_buffer (CMD); try {sp. write (CMD, 0, cmd. length); If (wait = 0) return 0; // you do not need to receive a reply. // wait for the reply. The wait time is wait seconds. waitevent we = new waitevent (); lock (waitlist) {Wait List [partition type] = We;} datetime dt = datetime. Now; dt = DT. addseconds (wait); While (! We. event. waitone (50) & datetime. Now <DT) {thread. Sleep (50);} If (! We. event. waitone (1) {lock (waitlist) {waitlist. remove (release type);} debug. writeline ("command timed out, no response received"); return 3; // No response received} If (we. recv! = NULL) {recvdata = new byte [We. recv. length]; array. copy (we. recv, recvdata, we. recv. length); log. info ("Command accepted:" + dump_buffer (recvdata);} Lock (waitlist) {waitlist. remove (partition type);} We. dispose (); We = NULL; return 0;} catch (exception e) {log. error ("serial port exception handling:", e); return 1 ;}//// convert the integer to BCD code, 12 (DEC) --> 0x12 // Private byte int2bcd (int x) {x = (byte) x; Return (byte) (X/10*16) + X % 10);} // convert BCD to an integer, 0x12 --> 12 (DEC) /// // Private int bcd2int (byte X) {return (x/16*10) + (X % 16 );} ///// convert the BCD string into bytes, specify the length to the specified position: // Private void bcdstr_to_byte_array (string bcdstr, ref byte [] array, int start, int length) {int I = bcdstr. length; int K = 0; byte X; string st; while (I> 0) {if (I> 1) ST = bcdstr. substring (I-2, 2); else ST = bcds Tr. substring (0, 1); // if it is not a dual-character alignment, the next character is left to be converted if (! Byte. tryparse (St, out X) x = 0; array [start + Length-k-1] = int2bcd (x); k ++; I-= 2 ;} while (start + Length-k-1> = Start) {array [start + Length-k-1] = 0; k ++ ;}} ///// compress the receiving buffer so that valid data is moved forward. The space is at the rear of the space. // Private void pack_received_buffer () {// The subsequent cache space is insufficient. Move forward, overwrite the space byte [] swap = new byte [buf_size]; array. copy (received, cmd_offset, swap, 0, received_offset-cmd_offset); array. copy (SWAP, 0, received, 0, received_offset-cmd_offset); received_offset = received_offset-cmd_offset; cmd_offset = 0;} private string dump_buffer (byte [] buffer) {stringbuilder sp = new stringbuilder (1024); int n = 0; foreach (byte X in buffer) {sp. appendformat ("{0: X2}", x); N ++; If (n> 512) break; // The cache is limited and can only process up to 512 bytes} return sp. tostring ();} private int get_int (byte [] buffer, int start, int length) {int n = 0; stringbuilder strbuilder = new stringbuilder (); for (INT I = start; I <start + Length & I <buffer. length; I ++) {strbuilder. appendformat ("{0: X2}", buffer [I]);} n = convert. toint32 (strbuilder. tostring (); Return n ;}//// calculate the LRC check, XOR // Private byte calc_lrc (byte [] data, int start, int end) {byte LRC = 0; int dlength = data. length; For (INT I = start; I <End & I <dlength; I ++) {LRC ^ = data [I] ;}return LRC ;}}}

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.