Serial Communication class, WPF

Source: Internet
Author: User

Refer to the previous data, wrote a common serial port class,

String send types are used in two ways, char[] and byte[];

The data receive also uses two kinds of char[] and byte[] two kinds.

The class code is pasted out:

  Public classSerialportmanager {Private BOOL_recstaus =true;//Receive status Word        Private BOOL_comportisopen; Private voidSetafterclose ()//successful shutdown of the serial or serial port after the loss of the settings{_comportisopen=false;//serial port status set to OFF State        }        Private voidSetcomlose ()//successful shutdown of the serial or serial port after the loss of the settings{setafterclose ();//successful shutdown of the serial or serial port after the loss of the settings        }         PublicSerialPort Currentserialport {Get;Set; } =NewSerialPort ();  Public byte[] Receiveddatapacket {Get;Set; }  Public BOOLOpenSerialPort (SerialPort serialportpara) {Currentserialport=Serialportpara; if(_comportisopen = =false)//Comportisopen = = False current serial port is off, button event is open serial port            {                Try //try to open the serial port{currentserialport.readtimeout=8000;//Serial read Timeout 8 secondsCurrentserialport.writetimeout =8000;//Serial Port Write timeout 8 seconds, in 1ms automatically send data when unplug the serial port, write timeout 5 seconds, will automatically stop sending, if no time-out setting, then the program suspended animationCurrentserialport.readbuffersize =1024x768;//Data Read CacheCurrentserialport.writebuffersize =1024x768;//Data Write CacheCurrentserialport.datareceived + = comreceive;//Serial receive interruptCurrentserialport.open (); _comportisopen=true;//The serial port open status Word changed to True                }                Catch(Exception Exception)//If the serial port is occupied by another, it cannot be opened{_comportisopen=false; ReceiveCompleted=false; Throw NewException ("Unable open serial port"+exception.                Message); }                return true; }            return true; }         Public Char[] Receiveddatapacketchar {Get;Set; }  Public BOOLreceivecompleted {Get;Set; } Private voidComreceive (Objectsender, Serialdatareceivedeventargs e) {receivecompleted=false; if(_recstaus)//If you have enabled the receive            {                Try{Thread.Sleep ( -); Receiveddatapacket=New byte[Currentserialport.bytestoread]; Receiveddatapacketchar=New Char[Currentserialport.bytestoread]; //Change to char datas                    if(Bytemode) {currentserialport.read (Receiveddatapacket,0, receiveddatapacket.length); }                    Else{currentserialport.read (Receiveddatapacketchar,0, Currentserialport.bytestoread); } receivecompleted=true; }                Catch(Exception) {if(Currentserialport.isopen = =false)//if Comport.isopen = = False, it indicates that the serial port is missing{setcomlose ();//post-serial loss related settings                    }                    Else                    {                        Throw NewException ("Unable to receive data"); }                }            }            Else //Pause Receive{currentserialport.discardinbuffer ();//Clear Receive Cache            }        }         Public BOOLSenddatapacket (stringdatapacket) {            Char[] Datapacketchar =Datapacket.tochararray (); returnSenddatapacket (Datapacketchar); }         Public BOOLSenddatapacket (byte[] datapackeg) {            Try{Bytemode=true; Currentserialport.write (Datapackeg,0, datapackeg.length); }            Catch(Exception Exception) {Console.WriteLine (Exception.                Message); return false; }            return true; }         Public BOOLCloseserialport () {Try//try to close the serial port{currentserialport.discardoutbuffer ();//Clear Send CacheCurrentserialport.discardinbuffer ();//Clear Receive Cache//Waitclose = true;//activates the off-state word, which is used to determine if the serial port is shutting down in invoke of the serial receive methodCurrentserialport.close ();//Close the serial port//waitclose = false;//Turn off the status word to determine if the serial port is shutting down in the serial Receive method invokeSetafterclose ();//successful shutdown of the serial or serial port after the loss of the settings_comportisopen =false; }            Catch//If the serial port is lost when the string is not closed, the serial port will be turned off abnormally            {                if(Currentserialport.isopen = =false)//determine the current serial port status, if Comport.isopen==false, the serial port is missing{setcomlose (); }                Else//Unable to close the serial port for unknown reason                {                    Throw NewException ("unable close serial port"); }            }            return true; }         Public BOOLBytemode {Get;Set; }  Public BOOLSenddatapacket (Char[] senddata) {            Try{Bytemode=false; Currentserialport.write (SendData,0, SendData.            Length); }            Catch(Exception Exception) {Console.WriteLine (Exception.                Message); return false; }            return true; }    }

Calling method: char[]

 PrivateSerialportmanager _serialportmanager =NewSerialportmanager ();Char[] Bytes ={(Char)0xAA,(Char)0xFF,(Char)0x55,                (Char)0xFF, (Char)0x06, (Char)0x20,                (Char)0xAA,(Char)0XEE,(Char)0x55,(Char)0xEE}; _serialportmanager.senddatapacket (bytes);

Byte[]

byte New byte []            {                0xAA,0XFF,0X55,                0XFF,0x06 ,0X20,0XAA,0XEE,0X55,0XEE            };            _serialportmanager.senddatapacket (Byteordor);

Data receive array corresponding to use

 Public byte Get Set ; }  Public Char Get set; }

actually available.

Serial Communication class, WPF

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.