/// <summary> /// 接收数据 /// </summary> private void Recive() { string Command = null; byte[] bs = null; while (true) { Thread.Sleep(10); try { if (_SerialPort.IsOpen) { if (_SerialPort.BytesToRead > 0) { bs = new byte[_SerialPort.BytesToRead]; _SerialPort.Read(bs, 0, bs.Length); ReciveMessage.Append(BitConverter.ToString(bs).ToUpper().Trim().Replace("-", string.Empty)); Command = ReciveMessage.ToString(); ReciveMessage.Remove(0, AnalyCommand(ref Command)); if (!string.IsNullOrEmpty(Command)) { Data_Recive_Event?.Invoke(Command, COM); } } } else { Close_Event?.Invoke(); if (ReConnection) { new Task(ReConn).Start(); } break; } } catch (Exception e) { Exception_Event?.Invoke(e); } } }
/// <summary> /// 打开串口 /// </summary> public void Open() { try { if ((_SerialPort == null) || (!_SerialPort.IsOpen)) { if (_SerialPort == null) { _SerialPort = new System.IO.Ports.SerialPort("COM" + COM.ToString(), BaudRate); } else { _SerialPort.PortName = "COM" + COM.ToString(); _SerialPort.BaudRate = BaudRate; } _SerialPort.Open(); if (_SerialPort.IsOpen) { Open_Event?.Invoke(); //开启接收数据线程 new Task(Recive).Start(); } else { throw new Exception("串口打开失败"); } } else { throw new Exception("串口已打开"); } } catch (Exception e) { Exception_Event?.Invoke(e); } }