/// <summary> /// 打开串口 /// </summary> /// <param name="serialPort">串口对象</param> private void OpenSerialPort(GodSerialPort.GodSerialPort serialPort) { _flag = serialPort.Open(); serialPort.UseDataReceived(_flag, (sp, bytes) => { Logger.Debug("【Received】:: " + bytes.ToHexString()); ParseReceiveData(bytes); }); if (_flag) { Logger.Info("端口已打开"); } }
/// <summary> /// 检查串口连接状态,如果异常,尝试重启 /// </summary> /// <param name="serialPort">串口对象</param> private void CheckPortStatusHandler(GodSerialPort.GodSerialPort serialPort) { Task.Factory.StartNew(() => { while (true) { _flag = serialPort.IsOpen; if (!_flag) { serialPort.UseDataReceived(_flag); Logger.Error("端口已断开"); OpenSerialPort(serialPort); } Task.Delay(1000).Wait(); } }); }