| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337 |
- using IvfTl.Control.Entity;
- using IvfTl.Control.Entity.GlobalEnums;
- using ivf_tl_SerialHelper.Util;
- using ivf_tl_UtilHelper;
- using System.IO.Ports;
- namespace ivf_tl_SerialHelper
- {
- /// <summary>
- /// 串口发送接收助手
- /// </summary>
- public class Channel
- {
- /// <summary>
- /// 异常日志
- /// 异常、名称、参数
- /// </summary>
- public event Action<Exception, string, string, LogEnum> ExceptionLogEvent;
- /// <summary>
- /// 错误日志
- /// </summary>
- public event Action<string, LogEnum> ErrorLogEvent;
- /// <summary>
- /// 指令记录日志
- /// </summary>
- public event Action<int, DateTime, string, LogEnum> CommandLogEvent;
- /// <summary>
- /// 接收指令
- /// </summary>
- public event Action<CustomProtocol> DataReceived;
- /// <summary>
- ///
- /// </summary>
- /// <param name="house"></param>
- /// <param name="comName"></param>
- /// <param name="bufferManagerSize"></param>
- /// <param name="BaudRate"></param>
- /// <param name="DataBits"></param>
- /// <param name="stopBits"></param>
- /// <param name="parity"></param>
- /// <param name="ReadTimeout"></param>
- /// <param name="WriteTimeout"></param>
- public Channel(int house, string comName, int bufferManagerSize, int BaudRate, int DataBits, StopBits stopBits, Parity parity, int ReadTimeout, int WriteTimeout)
- {
- _comName = comName;
- _house = house;
- _bufferManagerSize = bufferManagerSize;
- _baudRate = BaudRate;
- _dataBits = DataBits;
- _stopBits = stopBits;
- _parity = parity;
- _readTimeout = ReadTimeout;
- _writeTimeout = WriteTimeout;
- ringBufferManager = new RingBufferManager(_bufferManagerSize);
- GetSerialPortValue(_house, _comName, _baudRate, _dataBits, _stopBits, _parity, _readTimeout, _writeTimeout);
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="house"></param>
- /// <param name="comName"></param>
- public Channel(int house, string comName)
- {
- _comName = comName;
- _house = house;
- ringBufferManager = new RingBufferManager(_bufferManagerSize);
- GetSerialPortValue(_house, _comName, _baudRate, _dataBits, _stopBits, _parity, _readTimeout, _writeTimeout);
- }
- public RingBufferManager ringBufferManager;
- public SerialPort serialPort;
- private CustomProtocol customProtocol;
- private int _house = 0;
- private string _comName;
- private int _bufferManagerSize = 1024;
- /// <summary>
- /// 波特率
- /// </summary>
- private int _baudRate = 9600;
- /// <summary>
- /// 数据位
- /// </summary>
- private int _dataBits = 8;
- /// <summary>
- /// 停止位
- /// </summary>
- private StopBits _stopBits = StopBits.One;
- /// <summary>
- /// 奇偶校验位
- /// </summary>
- private Parity _parity = Parity.None;
- /// <summary>
- /// 串口读取超时
- /// </summary>
- private int _readTimeout = 3000;
- /// <summary>
- /// 串口写入超时
- /// </summary>
- private int _writeTimeout = 3000;
- /// <summary>
- /// 获取实例
- /// </summary>
- /// <param name="house">houseid</param>
- /// <param name="comName">串口名称</param>
- /// <param name="bufferManagerSize">缓冲区大小</param>
- /// <param name="BaudRate">波特率</param>
- /// <param name="DataBits">数据位</param>
- /// <param name="stopBits">停止位</param>
- /// <param name="parity">奇偶校验位</param>
- /// <param name="ReadTimeout">串口读取超时</param>
- /// <param name="WriteTimeout">串口写入超时</param>
- /// <returns></returns>
- public bool GetSerialPortValue(int house, string comName, int BaudRate, int DataBits, StopBits stopBits, Parity parity, int ReadTimeout, int WriteTimeout)
- {
- try
- {
- serialPort = new SerialPort();
- serialPort.PortName = comName;
- //波特率
- serialPort.BaudRate = BaudRate;
- //数据位
- serialPort.DataBits = DataBits;
- //两个停止位
- serialPort.StopBits = stopBits;
- //无奇偶校验位
- serialPort.Parity = parity;
- serialPort.ReadTimeout = ReadTimeout;
- serialPort.WriteTimeout = WriteTimeout;
- serialPort.DataReceived += SerialPort_DataReceived;
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{_house}][{_comName}]创建SerialPort实例", $"[house:{house}][com:{comName}]", LogEnum.RunException);
- return false;
- }
- }
- /// <summary>
- /// 接收数据
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- /// <exception cref="NotImplementedException"></exception>
- private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- string loginfo = $"[{_house}][{customProtocol.comName}][{customProtocol.commandNumber}][{customProtocol.commandType}]";
- try
- {
- DateTime dateTime = DateTime.Now;
- byte[] buffer = new byte[serialPort.BytesToRead];
- serialPort.Read(buffer, 0, buffer.Length);
- CommandLogEvent?.Invoke(_house, DateTime.Now, $"{loginfo}[Rec:{StringHelper.ByteToHexStr(buffer)}]", LogEnum.PortComRecord);
- ringBufferManager.WriteBuffer(buffer, 0, buffer.Length);
- if (ringBufferManager.DataCount >= customProtocol.lenght)
- {
- if (ringBufferManager.DataCount > customProtocol.lenght)
- {
- ErrorLogEvent?.Invoke($"{loginfo}缓冲区字节数大于预期", LogEnum.RunError);
- }
- byte[] receivedBuffer = new byte[customProtocol.lenght];
- ringBufferManager.ReadBuffer(receivedBuffer, 0, customProtocol.lenght);
- //ringBufferManager.Clear(customProtocol.lenght);
- ringBufferManager.Clear();
- customProtocol.receivedBuffer = receivedBuffer;
- if (customProtocol.receivedBuffer[customProtocol.lenght - 2] != 0)
- {
- ErrorLogEvent?.Invoke($"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}][Receive:{StringHelper.ByteToHexStr(customProtocol.receivedBuffer)}]下位机操作失败回复", LogEnum.RunError);
- }
- var check = Commander.CheckORC(customProtocol.receivedBuffer);
- CommandLogEvent?.Invoke(_house, DateTime.Now, $"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}][Receive:{StringHelper.ByteToHexStr(customProtocol.receivedBuffer)}][校验结果:{check}]", LogEnum.HouseComRecord);
- if (!check)
- {
- ErrorLogEvent?.Invoke($"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}][Receive:{StringHelper.ByteToHexStr(customProtocol.receivedBuffer)}]下位机回复校验失败", LogEnum.RunError);
- }
- CommandLogEvent?.Invoke(_house, DateTime.Now, $"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}][Receive:{StringHelper.ByteToHexStr(customProtocol.receivedBuffer)}]", LogEnum.PortComRecord);
- DataReceived?.Invoke(customProtocol);
- }
- }
- catch (Exception ex)
- {
- string canshu = $"{loginfo}[Send:{StringHelper.ByteToHexStr(customProtocol.sendBuffer)}]";
- ExceptionLogEvent?.Invoke(ex, $"[{_house}][{customProtocol.comName}][{customProtocol.commandNumber}]串口接收数据", canshu, LogEnum.RunException);
- }
- }
- /// <summary>
- /// 发送数据
- /// </summary>
- /// <param name="protocol"></param>
- public bool Send(CustomProtocol protocol)
- {
- customProtocol = protocol;
- customProtocol.comName = _comName;
- string logInfo = $"[{_house}][{protocol.comName}][{protocol.commandNumber}][{protocol.commandType}][Send:{StringHelper.ByteToHexStr(protocol.sendBuffer)}]";
- try
- {
- serialPort.Write(customProtocol.sendBuffer, 0, customProtocol.sendBuffer.Length);
- CommandLogEvent?.Invoke(_house, DateTime.Now, logInfo, LogEnum.PortComRecord);
- return true;
- }
- catch (Exception e1)
- {
- ExceptionLogEvent?.Invoke(e1, $"[{_house}][{_comName}]发送指令", logInfo, LogEnum.RunException);
- return false;
- }
- }
- /// <summary>
- /// 打开串口
- /// </summary>
- public bool OpenPort()
- {
- try
- {
- serialPort.Open();
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{_house}模块{serialPort.PortName}串口打开", null, LogEnum.RunException);
- return false;
- }
- }
- /// <summary>
- /// 关闭串口
- /// </summary>
- public bool ClosePort()
- {
- try
- {
- serialPort.Close();
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"{_house}模块{serialPort.PortName}串口关闭", null, LogEnum.RunException);
- return false;
- }
- }
- /// <summary>
- /// 清理串口缓冲区
- /// </summary>
- /// <returns></returns>
- public bool DiscardPortBuffer()
- {
- try
- {
- serialPort.DiscardInBuffer();
- serialPort.DiscardOutBuffer();
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{_house}][{_comName}]清理串口缓冲区", null, LogEnum.RunException);
- return false;
- }
- }
- /// <summary>
- /// 释放串口类
- /// </summary>
- /// <returns></returns>
- public bool PortDispose()
- {
- try
- {
- serialPort.Dispose();
- return true;
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{_house}][{_comName}]释放串口类", null, LogEnum.RunException);
- return false;
- }
- }
- /// <summary>
- /// 重新打开串口
- /// </summary>
- /// <returns></returns>
- public bool ReopenPort()
- {
- ringBufferManager.Clear();
- for (int i = 0; i < 3; i++)
- {
- try
- {
- bool DiscardBuffer = DiscardPortBuffer();
- bool closePort = ClosePort();
- bool portdispose = PortDispose();
- var a = GetSerialPortValue(_house, _comName, _baudRate, _dataBits, _stopBits, _parity, _readTimeout, _writeTimeout);
- if (a)
- {
- var b = OpenPort();
- if (b)
- {
- return true;
- }
- }
- }
- catch (Exception ex)
- {
- ExceptionLogEvent?.Invoke(ex, $"[{_house}][{_comName}]重新打开串口", null, LogEnum.RunException);
- }
- }
- return false;
- }
- }
- }
|