阅读量:0
在C#中,使用串口通信时,可能会遇到各种异常情况。为了确保程序的稳定性和可靠性,我们需要对可能出现的异常进行处理,并记录相关日志。以下是一个简单的C#串口类,包含异常处理和日志记录功能:
using System; using System.IO.Ports; using System.Text; public class SerialPortHelper { private SerialPort _serialPort; private string _portName; private int _baudRate; private Parity _parity; private int _dataBits; private StopBits _stopBits; public SerialPortHelper(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits) { _portName = portName; _baudRate = baudRate; _parity = parity; _dataBits = dataBits; _stopBits = stopBits; } public void Open() { try { _serialPort = new SerialPort(_portName, _baudRate, _parity, _dataBits, _stopBits); _serialPort.Open(); Log("Serial port opened successfully."); } catch (Exception ex) { Log($"Error opening serial port: {ex.Message}"); } } public void Close() { try { if (_serialPort != null && _serialPort.IsOpen) { _serialPort.Close(); Log("Serial port closed successfully."); } } catch (Exception ex) { Log($"Error closing serial port: {ex.Message}"); } } public void Write(string data) { try { if (_serialPort != null && _serialPort.IsOpen) { _serialPort.Write(data); Log($"Data sent: {data}"); } } catch (Exception ex) { Log($"Error sending data: {ex.Message}"); } } public string Read() { try { if (_serialPort != null && _serialPort.IsOpen) { string data = _serialPort.ReadLine(); Log($"Data received: {data}"); return data; } } catch (Exception ex) { Log($"Error receiving data: {ex.Message}"); } return null; } private void Log(string message) { Console.WriteLine($"[{DateTime.Now}] {message}"); } }
在这个类中,我们使用了try-catch
语句来捕获可能出现的异常,并在Log
方法中记录日志。这样,我们可以在控制台或者其他地方查看到详细的日志信息,以便于分析和调试。
使用这个类的示例代码如下:
class Program { static void Main(string[] args) { SerialPortHelper serialPortHelper = new SerialPortHelper("COM1", 9600, Parity.None, 8, StopBits.One); serialPortHelper.Open(); serialPortHelper.Write("Hello, World!"); string response = serialPortHelper.Read(); serialPortHelper.Close(); } }
这个示例代码创建了一个SerialPortHelper
实例,连接到COM1端口,波特率为9600,无奇偶校验,8个数据位,1个停止位。然后发送一条消息,并接收响应,最后关闭串口。在整个过程中,所有的操作都会被记录到日志中。