Using System; Using System. Collections. Generic; Using System. Text; Using System. IO. Ports; Using System. ComponentModel; Using System. Threading;
Namespace Cserver { Class ToCom { Private System. IO. Ports. SerialPort serialPort1 = new SerialPort (); Public delegate byte [] getDate (byte [] bts ); Private getDate mygetDate; Private string com;
Public ToCom (string com) { This.com = com; SerialPort1.PortName = com; // port number SerialPort1.BaudRate = 9600; // Bit Rate SerialPort1.Parity = Parity. None; // Parity SerialPort1.StopBits = StopBits. One; // stop bit SerialPort1.ReadTimeout = 1000; // read timeout, that is, if no data is read within 1000, a timeout exception occurs. } # Region send and receive data Public void SendMsg (string senStr) {
SerialPort1.Open ();
Byte [] myByte = StringToByte_2 (senStr );
SerialPort1.Write (myByte, 0, myByte. Length ); SerialPort1.Close ();
} Public string ReadMsg () { SerialPort1.Open (); String rd = "null "; # Region Old Data Reading Method /// ------------ Mothed1 ---- // Int I = serialPort1.ReadBufferSize; // Byte [] data = Convert. FromBase64String (serialPort1.ReadLine ());
// Rd = Encoding. Unicode. GetString (data ); /// Mothed2 // Int DataLength = serialPort1.BytesToRead;
// Int I = 0;
// StringBuilder sb = new StringBuilder ();
// While (I <DataLength) //{
// Byte [] ds = new byte [1, 1024];
// Int len = serialPort1.Read (ds, 0, 1024 );
/// Sb. Append (Encoding. ASCII. GetString (ds, 0, len )); // Sb. Append (ByteToString (ds ));
// I + = len;
//} /// Mothed2 // Byte [] data = new byte [serialPort1.BytesToRead]; // Int I = serialPort1.Read (data, 0, SerialPort1.BytesToRead );
// Rd = ByteToString (data );
# Endregion
// Mothed3 Byte [] data = new byte [serialPort1.BytesToRead]; Int I = serialPort1.Read (data, 0, serialPort1.BytesToRead );
Rd = ByteToString (data ); Return rd;
} // String getdate (byte [])
Public void Sp_DataReceived (object sender, System. IO. Ports. SerialDataReceivedEventArgs e) { Byte [] readBuffer = new byte [serialPort1.ReadBufferSize]; SerialPort1.Read (readBuffer, 0, readBuffer. Length ); // This. Invoke (interfaceUpdataHandle, new string [] { Encoding. UTF8.GetString (readBuffer )});
// This. Invoke (interfaceUpdataHandle, new string [] { ToCom. ByteToString (readBuffer )}); String s = ToCom. ByteToString (readBuffer );
} # Endregion
/// <Summary> /// Serial port read (non-blocking reading of the serial port until there is no data in the serial port buffer) /// </Summary> /// <Param name = "readBuf"> serial port data buffer </param> /// <Param name = "bufRoom"> serial port data buffer size </param> /// <Param name = "HowTime"> set the serial port read discard time </param> /// <Param name = "ByteTime"> maximum byte interval </param> /// <Returns> actual number of data entries read by the serial port </returns> Public int ReadComm (out Byte [] readBuf, int bufRoom, int HowTime, int ByteTime) { // Throw new System. NotImplementedException (); ReadBuf = new Byte [64]; Array. Clear (readBuf, 0, readBuf. Length );
Int nReadLen, nBytelen; If (serialPort1.IsOpen = false) Return-1; NBytelen = 0; SerialPort1.ReadTimeout = HowTime;
Try { ReadBuf [nBytelen] = (byte) serialPort1.ReadByte (); Byte [] bTmp = new byte [1, 1023]; Array. Clear (bTmp, 0, bTmp. Length );
NReadLen = ReadBlock (out bTmp, bufRoom-1, ByteTime );
If (nReadLen> 0) { Array. Copy (bTmp, 0, readBuf, 1, nReadLen ); NBytelen = 1 + nReadLen;
}
Else if (nReadLen = 0) NBytelen = 1; } Catch (Exception ex) { Throw new Exception (ex. Message );
}
Return nBytelen; } /// <Summary> /// Synchronous reading of the serial port (blocking reading of the serial port until there is no data in the serial port buffer, and no data is determined by the time-out between characters) /// </Summary> /// <Param name = "ReadBuf"> serial port data buffer </param> /// <Param name = "ReadRoom"> serial port data buffer size </param> /// <Param name = "ByteTime"> maximum byte interval </param> /// <Returns> Number of bytes actually read from the serial port </returns> Public int ReadBlock (out byte [] ReadBuf, int ReadRoom, int ByteTime) { // Throw new System. NotImplementedException (); ReadBuf = new byte [1, 1024]; Array. Clear (ReadBuf, 0, ReadBuf. Length );
Sbyte nBytelen; // Long nByteRead;
If (serialPort1.IsOpen = false) Return 0; NBytelen = 0; SerialPort1.ReadTimeout = ByteTime;
While (nBytelen <(ReadRoom-1 )) { Try { ReadBuf [nBytelen] = (byte) serialPort1.ReadByte (); NBytelen ++; // add one } Catch (Exception ex) { Throw new Exception (ex. Message ); Break; } } ReadBuf [nBytelen] = 0x00; Return nBytelen;
}
/// <Summary> /// Convert character array to string hexadecimal /// </Summary> /// <Param name = "InBytes"> binary bytes </param> /// <Returns> similar to "01 02 0F" </returns> Public static string ByteToString (byte [] InBytes) { String StringOut = ""; Foreach (byte InByte in InBytes) { StringOut = StringOut + String. Format ("{0: X2}", InByte) + ""; }
Return StringOut. Trim (); } /// <Summary> /// Strhex to byte array /// </Summary> /// <Param name = "InString"> similar to "01 02 0F" separated by Spaces </Param> /// <Returns> </returns> Public static byte [] StringToByte (string InString) { String [] ByteStrings; ByteStrings = InString. Split ("". ToCharArray ()); Byte [] ByteOut; ByteOut = new byte [ByteStrings. Length]; For (int I = 0; I <= ByteStrings. Length-1; I ++) { ByteOut [I] = byte. Parse (ByteStrings [I], System. Globalization. NumberStyles. HexNumber ); } Return ByteOut; }
/// <Summary> /// Strhex to byte array /// </Summary> /// <Param name = "InString"> similar to "01 02 0F", there is no space in the middle </Param> /// <Returns> </returns> Public static byte [] StringToByte_2 (string InString) { Byte [] ByteOut; InString = InString. Replace ("",""); Try { String [] ByteStrings = new string [InString. Length/2]; Int j = 0; For (int I = 0; I <ByteStrings. Length; I ++) {
ByteStrings [I] = InString. Substring (j, 2 ); J + = 2; }
ByteOut = new byte [ByteStrings. Length]; For (int I = 0; I <= ByteStrings. Length-1; I ++) { ByteOut [I] = byte. Parse (ByteStrings [I], System. Globalization. NumberStyles. HexNumber ); } } Catch (Exception ex) {
Throw new Exception (ex. Message ); }
Return ByteOut; } /// <Summary> /// Convert string to hexadecimal string /// </Summary> /// <Param name = "InString"> unico </param> /// <Returns> similar to "01 0f" </returns> Public static string Str_To_0X (string InString) { Return ByteToString (UnicodeEncoding. Default. GetBytes (InString )); } } } |