From 32232fa34c55b365093980fec113c25ab4e6b7c3 Mon Sep 17 00:00:00 2001 From: parallelbgls Date: Fri, 1 Aug 2014 11:15:30 +0800 Subject: [PATCH] 2014-08-01 update 2 Add protocal error handle. --- NA200H/ModBus.Net/TCPProtocalLinker.cs | 37 +++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/NA200H/ModBus.Net/TCPProtocalLinker.cs b/NA200H/ModBus.Net/TCPProtocalLinker.cs index 169d209..8642de1 100644 --- a/NA200H/ModBus.Net/TCPProtocalLinker.cs +++ b/NA200H/ModBus.Net/TCPProtocalLinker.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; namespace ModBus.Net @@ -7,6 +8,7 @@ namespace ModBus.Net { private static TcpSocket _socket; + public TcpProtocalLinker() { if (_socket == null) @@ -17,7 +19,13 @@ namespace ModBus.Net public override byte[] SendReceive(byte[] content) { - return BytesDecact(_socket.SendMsg(BytesExtend(content))); + byte[] receiveBytes = BytesDecact(_socket.SendMsg(BytesExtend(content))); + if (receiveBytes[1] > 127) + { + string message; + throw new ModbusProtocalErrorException(receiveBytes[2]); + } + return receiveBytes; } public override bool SendOnly(byte[] content) @@ -54,4 +62,31 @@ namespace ModBus.Net return newContent; } } + + public class ProtocalErrorException : Exception + { + public ProtocalErrorException(string message):base(message) + { + + } + } + + public class ModbusProtocalErrorException : ProtocalErrorException + { + public int ErrorMessageNumber { get; private set; } + private static readonly Dictionary ProtocalErrorDictionary = new Dictionary() + { + {1, "ILLEGAL_FUNCTION"}, + {2, "ILLEGAL_DATA_ACCESS"}, + {3, "ILLEGAL_DATA_VALUE"}, + {4, "SLAVE_DEVICE_FAILURE"}, + {5, "ACKNOWLWDGE"}, + {6, "SLAVE_DEVICE_BUSY"}, + }; + + public ModbusProtocalErrorException(int messageNumber) : base(ProtocalErrorDictionary[messageNumber]) + { + ErrorMessageNumber = messageNumber; + } + } } \ No newline at end of file