From 3c6f18dc694a783bda06fee08345f3c88ca1f789 Mon Sep 17 00:00:00 2001 From: parallelbgls Date: Wed, 17 May 2017 14:59:23 +0800 Subject: [PATCH] Add serilog --- .../Modbus.Net.Core/Modbus.Net.Core.csproj | 1 + .../Modbus.Net.Modbus.csproj | 4 - .../Modbus.Net.OPC/Modbus.Net.OPC.csproj | 1 - .../Modbus.Net.Siemens.csproj | 4 - Modbus.Net/Modbus.Net/ComConnector.cs | 246 +++++++++++------- Modbus.Net/Modbus.Net/Modbus.Net.csproj | 7 + Modbus.Net/src/Base.Common/TcpConnector.cs | 74 +++--- 7 files changed, 198 insertions(+), 139 deletions(-) diff --git a/Modbus.Net/Modbus.Net.Core/Modbus.Net.Core.csproj b/Modbus.Net/Modbus.Net.Core/Modbus.Net.Core.csproj index c1c1818..0578162 100644 --- a/Modbus.Net/Modbus.Net.Core/Modbus.Net.Core.csproj +++ b/Modbus.Net/Modbus.Net.Core/Modbus.Net.Core.csproj @@ -56,6 +56,7 @@ + diff --git a/Modbus.Net/Modbus.Net.Modbus/Modbus.Net.Modbus.csproj b/Modbus.Net/Modbus.Net.Modbus/Modbus.Net.Modbus.csproj index fef1838..d0c29f2 100644 --- a/Modbus.Net/Modbus.Net.Modbus/Modbus.Net.Modbus.csproj +++ b/Modbus.Net/Modbus.Net.Modbus/Modbus.Net.Modbus.csproj @@ -23,10 +23,6 @@ bin\Debug\net45\Modbus.Net.Modbus.xml - - - - diff --git a/Modbus.Net/Modbus.Net.OPC/Modbus.Net.OPC.csproj b/Modbus.Net/Modbus.Net.OPC/Modbus.Net.OPC.csproj index 34e799c..3f38142 100644 --- a/Modbus.Net/Modbus.Net.OPC/Modbus.Net.OPC.csproj +++ b/Modbus.Net/Modbus.Net.OPC/Modbus.Net.OPC.csproj @@ -25,7 +25,6 @@ - diff --git a/Modbus.Net/Modbus.Net.Siemens/Modbus.Net.Siemens.csproj b/Modbus.Net/Modbus.Net.Siemens/Modbus.Net.Siemens.csproj index b863ece..3c27504 100644 --- a/Modbus.Net/Modbus.Net.Siemens/Modbus.Net.Siemens.csproj +++ b/Modbus.Net/Modbus.Net.Siemens/Modbus.Net.Siemens.csproj @@ -22,10 +22,6 @@ bin\Debug\net45\Modbus.Net.Siemens.xml - - - - diff --git a/Modbus.Net/Modbus.Net/ComConnector.cs b/Modbus.Net/Modbus.Net/ComConnector.cs index 7802356..3454532 100644 --- a/Modbus.Net/Modbus.Net/ComConnector.cs +++ b/Modbus.Net/Modbus.Net/ComConnector.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; +using Serilog; namespace Modbus.Net { @@ -65,6 +66,10 @@ namespace Modbus.Net /// private bool m_disposed; + private int _sendCount; + private int _receiveCount; + private int _errorCount; + /// /// 构造器 /// @@ -135,47 +140,37 @@ namespace Modbus.Net /// /// 串口数据缓冲 /// 串口数据缓冲空间大小 - /// 设置串口读放弃时间 - /// 字节间隔最大时间 + /// 设置串口读放弃时间 + /// 字节间隔最大时间 /// 串口实际读入数据个数 - public int ReadComm(out byte[] readBuf, int bufRoom, int HowTime, int ByteTime) - { - //throw new System.NotImplementedException(); + public int ReadComm(out byte[] readBuf, int bufRoom, int howTime, int byteTime) + { readBuf = new byte[1023]; Array.Clear(readBuf, 0, readBuf.Length); - int nReadLen, nBytelen; if (SerialPort.IsOpen == false) return -1; - nBytelen = 0; - SerialPort.ReadTimeout = HowTime; + var nBytelen = 0; + SerialPort.ReadTimeout = howTime; - - try + while (SerialPort.BytesToRead > 0) { - while (SerialPort.BytesToRead > 0) + readBuf[nBytelen] = (byte) SerialPort.ReadByte(); + var bTmp = new byte[bufRoom]; + Array.Clear(bTmp, 0, bTmp.Length); + + var nReadLen = ReadBlock(bTmp, bufRoom, byteTime); + + if (nReadLen > 0) { - readBuf[nBytelen] = (byte) SerialPort.ReadByte(); - var bTmp = new byte[bufRoom]; - Array.Clear(bTmp, 0, bTmp.Length); - - nReadLen = ReadBlock(bTmp, bufRoom, ByteTime); - - if (nReadLen > 0) - { - Array.Copy(bTmp, 0, readBuf, nBytelen + 1, nReadLen); - nBytelen += 1 + nReadLen; - } - - else if (nReadLen == 0) - { - nBytelen += 1; - } + Array.Copy(bTmp, 0, readBuf, nBytelen + 1, nReadLen); + nBytelen += 1 + nReadLen; + } + + else if (nReadLen == 0) + { + nBytelen += 1; } - } - catch (Exception ex) - { - throw new Exception(ex.Message); } return nBytelen; @@ -184,31 +179,23 @@ namespace Modbus.Net /// /// 串口同步读(阻塞方式读串口,直到串口缓冲区中没有数据,靠字符间间隔超时确定没有数据) /// - /// 串口数据缓冲 - /// 串口数据缓冲空间大小 - /// 字节间隔最大时间 + /// 串口数据缓冲 + /// 串口数据缓冲空间大小 + /// 字节间隔最大时间 /// 从串口实际读入的字节个数 - public int ReadBlock(byte[] ReadBuf, int ReadRoom, int ByteTime) + public int ReadBlock(byte[] readBuf, int readRoom, int byteTime) { - sbyte nBytelen; - //long nByteRead; - if (SerialPort.IsOpen == false) return 0; - nBytelen = 0; - SerialPort.ReadTimeout = ByteTime; + sbyte nBytelen = 0; + SerialPort.ReadTimeout = byteTime; - while (nBytelen < ReadRoom - 1 && SerialPort.BytesToRead > 0) - try - { - ReadBuf[nBytelen] = (byte) SerialPort.ReadByte(); - nBytelen++; // add one - } - catch (Exception ex) - { - throw new Exception(ex.Message); - } - ReadBuf[nBytelen] = 0x00; + while (nBytelen < readRoom - 1 && SerialPort.BytesToRead > 0) + { + readBuf[nBytelen] = (byte) SerialPort.ReadByte(); + nBytelen++; // add one + } + readBuf[nBytelen] = 0x00; return nBytelen; } @@ -216,72 +203,63 @@ namespace Modbus.Net /// /// 字符数组转字符串16进制 /// - /// 二进制字节 + /// 二进制字节 /// 类似"01 02 0F" - public static string ByteToString(byte[] InBytes) + public static string ByteToString(byte[] inBytes) { - var StringOut = ""; - foreach (var InByte in InBytes) - StringOut = StringOut + string.Format("{0:X2}", InByte) + " "; + var stringOut = ""; + foreach (var inByte in inBytes) + stringOut = stringOut + $"{inByte:X2}" + " "; - return StringOut.Trim(); + return stringOut.Trim(); } /// /// strhex 转字节数组 /// - /// 类似"01 02 0F" 用空格分开的 + /// 类似"01 02 0F" 用空格分开的 /// - public static byte[] StringToByte(string InString) + public static byte[] StringToByte(string inString) { - string[] ByteStrings; - ByteStrings = InString.Split(" ".ToCharArray()); - byte[] ByteOut; - ByteOut = new byte[ByteStrings.Length]; - for (var i = 0; i <= ByteStrings.Length - 1; i++) - ByteOut[i] = byte.Parse(ByteStrings[i], NumberStyles.HexNumber); - return ByteOut; + var byteStrings = inString.Split(" ".ToCharArray()); + var byteOut = new byte[byteStrings.Length]; + for (var i = 0; i <= byteStrings.Length - 1; i++) + byteOut[i] = byte.Parse(byteStrings[i], NumberStyles.HexNumber); + return byteOut; } /// /// strhex 转字节数组 /// - /// 类似"01 02 0F" 中间无空格 + /// 类似"01 02 0F" 中间无空格 /// - public static byte[] StringToByte_2(string InString) + public static byte[] StringToByte_2(string inString) { - byte[] ByteOut; - InString = InString.Replace(" ", ""); - try - { - var ByteStrings = new string[InString.Length / 2]; - var j = 0; - for (var i = 0; i < ByteStrings.Length; i++) - { - ByteStrings[i] = InString.Substring(j, 2); - j += 2; - } + inString = inString.Replace(" ", ""); - ByteOut = new byte[ByteStrings.Length]; - for (var i = 0; i <= ByteStrings.Length - 1; i++) - ByteOut[i] = byte.Parse(ByteStrings[i], NumberStyles.HexNumber); - } - catch (Exception ex) + var byteStrings = new string[inString.Length / 2]; + var j = 0; + for (var i = 0; i < byteStrings.Length; i++) { - throw new Exception(ex.Message); + byteStrings[i] = inString.Substring(j, 2); + j += 2; } - return ByteOut; + var byteOut = new byte[byteStrings.Length]; + for (var i = 0; i <= byteStrings.Length - 1; i++) + byteOut[i] = byte.Parse(byteStrings[i], NumberStyles.HexNumber); + + return byteOut; } /// /// 字符串 转16进制字符串 /// - /// unico + /// unico /// 类似“01 0f” - public static string Str_To_0X(string InString) + public static string Str_To_0X(string inString) { - return ByteToString(Encoding.Default.GetBytes(InString)); + return ByteToString(Encoding.Default.GetBytes(inString)); } /// @@ -310,10 +288,12 @@ namespace Modbus.Net //ignore } SerialPort.Dispose(); + Log.Information("Com interface {Com} Disposed", _com); Connectors[_com] = null; Connectors.Remove(_com); } Linkers.Remove(_slave); + Log.Information("Com connector {ConnectionToken} Removed", ConnectionToken); } m_disposed = true; } @@ -364,10 +344,12 @@ namespace Modbus.Net if (!Linkers.ContainsKey(_slave)) Linkers.Add(_slave, _com); SerialPort.Open(); + Log.Information("Com client {ConnectionToken} connect success", ConnectionToken); return true; } - catch (Exception) + catch (Exception e) { + Log.Error(e, "Com client {ConnectionToken} connect error", ConnectionToken); return false; } } @@ -391,12 +373,15 @@ namespace Modbus.Net try { Dispose(); + Log.Information("Com client {ConnectionToken} disconnect success", ConnectionToken); return true; } - catch + catch (Exception e) { + Log.Error(e, "Com client {ConnectionToken} disconnect error", ConnectionToken); return false; } + Log.Error(new Exception("Linkers or Connectors Dictionary not found"), "Com client {ConnectionToken} disconnect error", ConnectionToken); return false; } @@ -438,19 +423,48 @@ namespace Modbus.Net { SerialPort.Open(); } - catch (Exception) + catch (Exception err) { + Log.Error(err, "Com client {ConnectionToken} open error", ConnectionToken); Dispose(); SerialPort.Open(); } + + byte[] returnBytes; + lock (SerialPort.Lock) { - SerialPort.Write(sendbytes, 0, sendbytes.Length); + try + { + Log.Verbose("Com client {ConnectionToken} send msg length: {Length}", ConnectionToken, sendbytes.Length); + Log.Verbose("Com client {ConnectionToken} send msg: {SendBytes}", ConnectionToken, sendbytes); + SerialPort.Write(sendbytes, 0, sendbytes.Length); + } + catch (Exception err) + { + Log.Error(err, "Com client {ConnectionToken} send msg error", ConnectionToken); + return null; + } + RefreshSendCount(); + + try + { + returnBytes = ReadMsg(); + Log.Verbose("Com client {ConnectionToken} receive msg length: {Length}", ConnectionToken, returnBytes.Length); + Log.Verbose("Com client {ConnectionToken} receive msg: {SendBytes}", ConnectionToken, returnBytes); + } + catch (Exception e) + { + Log.Error(e, "Com client {ConnectionToken} read msg error", ConnectionToken); + return null; + } + RefreshReceiveCount(); } - return ReadMsg(); + return returnBytes; } - catch + catch (Exception err) { + Log.Error(err, "Com client {ConnectionToken} read error", ConnectionToken); Dispose(); return null; } @@ -480,19 +494,33 @@ namespace Modbus.Net { SerialPort.Open(); } - catch (Exception) + catch (Exception err) { + Log.Error(err, "Com client {ConnectionToken} open error", ConnectionToken); Dispose(); SerialPort.Open(); } lock (SerialPort.Lock) { - SerialPort.Write(sendbytes, 0, sendbytes.Length); + try + { + Log.Verbose("Com client {ConnectionToken} send msg length: {Length}", ConnectionToken, sendbytes.Length); + Log.Verbose("Com client {ConnectionToken} send msg: {SendBytes}", ConnectionToken, sendbytes); + SerialPort.Write(sendbytes, 0, sendbytes.Length); + } + catch (Exception err) + { + Log.Error(err, "Com client {ConnectionToken} send msg error", ConnectionToken); + Dispose(); + return false; + } + RefreshSendCount(); } return true; } - catch (Exception) + catch (Exception err) { + Log.Error(err, "Com client {ConnectionToken} reopen error", ConnectionToken); return false; } } @@ -511,13 +539,33 @@ namespace Modbus.Net Array.Copy(data, 0, returndata, 0, i); return returndata; } - catch (Exception) + catch (Exception e) { + Log.Error(e, "Com client {ConnectionToken} read error", ConnectionToken); + RefreshErrorCount(); Dispose(); return null; } } #endregion + + private void RefreshSendCount() + { + _sendCount++; + Log.Verbose("Tcp client {ConnectionToken} send count: {SendCount}", ConnectionToken, _sendCount); + } + + private void RefreshReceiveCount() + { + _receiveCount++; + Log.Verbose("Tcp client {ConnectionToken} receive count: {SendCount}", ConnectionToken, _receiveCount); + } + + private void RefreshErrorCount() + { + _errorCount++; + Log.Verbose("Tcp client {ConnectionToken} error count: {ErrorCount}", ConnectionToken, _errorCount); + } } } \ No newline at end of file diff --git a/Modbus.Net/Modbus.Net/Modbus.Net.csproj b/Modbus.Net/Modbus.Net/Modbus.Net.csproj index 00e6daa..ef209ac 100644 --- a/Modbus.Net/Modbus.Net/Modbus.Net.csproj +++ b/Modbus.Net/Modbus.Net/Modbus.Net.csproj @@ -52,6 +52,7 @@ + @@ -60,4 +61,10 @@ + + + Component + + + \ No newline at end of file diff --git a/Modbus.Net/src/Base.Common/TcpConnector.cs b/Modbus.Net/src/Base.Common/TcpConnector.cs index 8317870..8f1a56e 100644 --- a/Modbus.Net/src/Base.Common/TcpConnector.cs +++ b/Modbus.Net/src/Base.Common/TcpConnector.cs @@ -2,6 +2,7 @@ using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; +using Serilog; namespace Modbus.Net { @@ -34,12 +35,15 @@ namespace Modbus.Net private readonly string _host; private readonly int _port; - // 2MB 的接收缓冲区,目的是一次接收完服务器发回的消息 + /// + /// 1MB 的接收缓冲区 + /// private readonly byte[] _receiveBuffer = new byte[1024]; - private int _errorCount; - private int _receiveCount; private int _sendCount; + private int _receiveCount; + private int _errorCount; + private TcpClient _socketClient; private int _timeoutTime; @@ -69,7 +73,7 @@ namespace Modbus.Net /// public int TimeoutTime { - get { return _timeoutTime; } + get => _timeoutTime; set { _timeoutTime = value; @@ -111,9 +115,14 @@ namespace Modbus.Net if (_socketClient != null) { CloseClientSocket(); - _socketClient.Client.Dispose(); +#if NET40 || NET45 || NET451 || NET452 + _socketClient.Close(); +#else + _socketClient.Dispose(); +#endif + Log.Debug("Tcp client {ConnectionToken} Disposed", ConnectionToken); } - m_disposed = true; + m_disposed = true; } } @@ -159,19 +168,19 @@ namespace Modbus.Net } catch (Exception e) { - AddInfo("client connected exception: " + e.Message); + Log.Error(e, "Tcp client {ConnectionToken} connect error", ConnectionToken); } if (_socketClient.Connected) { - AddInfo("client connected."); + Log.Information("Tcp client {ConnectionToken} connected", ConnectionToken); return true; } - AddInfo("connect failed."); + Log.Error("Tcp client {ConnectionToken} connect failed.", ConnectionToken); return false; } catch (Exception err) { - AddInfo("client connect exception: " + err.Message); + Log.Error(err, "Tcp client {ConnectionToken} connect exception", ConnectionToken); return false; } } @@ -187,17 +196,13 @@ namespace Modbus.Net try { -#if NET40 || NET45 || NET451 || NET452 - _socketClient.Close(); -#else - _socketClient.Dispose(); -#endif - AddInfo("client disconnected successfully."); + Dispose(); + Log.Information("Tcp client {ConnectionToken} disconnected successfully", ConnectionToken); return true; } catch (Exception err) { - AddInfo("client disconnected exception: " + err.Message); + Log.Error(err, "Tcp client {ConnectionToken} disconnected exception", ConnectionToken); return false; } finally @@ -206,11 +211,6 @@ namespace Modbus.Net } } - private void AddInfo(string message) - { - Console.WriteLine(message); - } - /// /// 发送数据,不需要返回任何值 /// @@ -236,15 +236,18 @@ namespace Modbus.Net await ConnectAsync(); var stream = _socketClient.GetStream(); + + Log.Verbose("Tcp client {ConnectionToken} send text len = {Length}", ConnectionToken, datagram.Length); + Log.Verbose("Tcp client {ConnectionToken} send text = {Datagram}", ConnectionToken, datagram); await stream.WriteAsync(datagram, 0, datagram.Length); RefreshSendCount(); - //this.AddInfo("send text len = " + datagramText.Length.ToString()); + return true; } catch (Exception err) { - AddInfo("send exception: " + err.Message); + Log.Error(err, "Tcp client {ConnectionToken} send exception", ConnectionToken); CloseClientSocket(); return false; } @@ -275,16 +278,22 @@ namespace Modbus.Net await ConnectAsync(); var stream = _socketClient.GetStream(); + + Log.Verbose("Tcp client {ConnectionToken} send text len = {Length}", ConnectionToken, datagram.Length); + Log.Verbose("Tcp client {ConnectionToken} send: {Datagram}", ConnectionToken, datagram); await stream.WriteAsync(datagram, 0, datagram.Length); - + RefreshSendCount(); - //this.AddInfo("send text len = " + datagramText.Length.ToString()); - return await ReceiveAsync(stream); + var receiveBytes = await ReceiveAsync(stream); + Log.Verbose("Tcp client {ConnectionToken} receive text len = {Length}", ConnectionToken, receiveBytes.Length); + Log.Verbose("Tcp client {ConnectionToken} receive: {Datagram}", ConnectionToken, receiveBytes); + + return receiveBytes; } catch (Exception err) { - AddInfo("send exception: " + err.Message); + Log.Error(err, "Tcp client {ConnectionToken} send exception", ConnectionToken); CloseClientSocket(); return null; } @@ -308,7 +317,7 @@ namespace Modbus.Net } catch (Exception err) { - AddInfo("receive exception: " + err.Message); + Log.Error(err, "Tcp client {ConnectionToken} receive exception", ConnectionToken); CloseClientSocket(); return null; } @@ -323,7 +332,7 @@ namespace Modbus.Net var replyMessage = new byte[len]; Array.Copy(_receiveBuffer, replyMessage, len); - //this.AddInfo("reply: " + replyMesage); + Log.Verbose("Tcp client {ConnectionToken} reply: {replyMessage}",ConnectionToken, replyMessage); RefreshReceiveCount(); if (len <= 0) @@ -335,16 +344,19 @@ namespace Modbus.Net private void RefreshSendCount() { _sendCount++; + Log.Verbose("Tcp client {ConnectionToken} send count: {SendCount}", ConnectionToken, _sendCount); } private void RefreshReceiveCount() { _receiveCount++; + Log.Verbose("Tcp client {ConnectionToken} receive count: {SendCount}", ConnectionToken, _receiveCount); } private void RefreshErrorCount() { _errorCount++; + Log.Verbose("Tcp client {ConnectionToken} error count: {ErrorCount}", ConnectionToken, _errorCount); } private void CloseClientSocket() @@ -358,7 +370,7 @@ namespace Modbus.Net } catch (Exception ex) { - AddInfo("client close exception: " + ex.Message); + Log.Error(ex, "Tcp client {ConnectionToken} client close exception", ConnectionToken); } } }