上位机与通信组件(二)
1、串口对象接收回调事件
1 serialPort.DataReceived += SerialPort_DataReceived; // 数据接收 2 3 void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) 4 { 5 SerialPort serialPort1 = (sender as SerialPort); 6 byte[] buffer = new byte[serialPort1.BytesToRead]; 7 (sender as SerialPort).Read(buffer, 0, serialPort1.BytesToRead); 8 }
2、串口断线重连
(1)接口断接
1 private void Reconnect() 2 { 3 SerialPort serialPort = new SerialPort(); 4 serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One); 5 serialPort.Open(); 6 7 while (true) 8 { 9 if (serialPort.IsOpen) 10 { 11 Console.WriteLine("已连接"); 12 } 13 else 14 { 15 try 16 { 17 Console.WriteLine("串口断开,正在重新连接"); 18 serialPort.Open(); 19 break; 20 } 21 catch(Exception ex) 22 { 23 Console.WriteLine(ex.Message); 24 } 25 } 26 } 27 }
(2)链路断接,需要设备双方处理,发心跳