diff --git a/Modbus.Net/Modbus.Net.Core/App.config b/Modbus.Net/Modbus.Net.Core/App.config
index e85257a..8874465 100644
--- a/Modbus.Net/Modbus.Net.Core/App.config
+++ b/Modbus.Net/Modbus.Net.Core/App.config
@@ -1,13 +1,14 @@
-
+
+
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.Core/ConfigurationManager.cs b/Modbus.Net/Modbus.Net.Core/ConfigurationManager.cs
index 9fb6291..09dd844 100644
--- a/Modbus.Net/Modbus.Net.Core/ConfigurationManager.cs
+++ b/Modbus.Net/Modbus.Net.Core/ConfigurationManager.cs
@@ -1,20 +1,39 @@
-using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace Modbus.Net
{
+ ///
+ /// Simulate ConfigurationManager in System.Configuration
+ ///
public static class ConfigurationManager
{
- private static IConfigurationBuilder builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
+ ///
+ /// Configuration Builder
+ ///
+ private static readonly IConfigurationBuilder Builder = new ConfigurationBuilder()
+ .SetBasePath(RootPath ?? Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddXmlFile("App.config");
- private static IConfigurationRoot Configuration => builder.Build();
+ ///
+ /// RootPath of App.config and appsettings.json
+ ///
+ public static string RootPath { get; set; } = null;
+ ///
+ /// Configuration Root
+ ///
+ private static IConfigurationRoot Configuration => Builder.Build();
+
+ ///
+ /// AppSettings
+ ///
public static IConfigurationSection AppSettings => Configuration.GetSection("AppSettings");
+ ///
+ /// ConnectionStrings
+ ///
public static IConfigurationSection ConnectionStrings => Configuration.GetSection("ConnectionStrings");
}
}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.Modbus/AddressTranslatorModbus.cs b/Modbus.Net/Modbus.Net.Modbus/AddressTranslatorModbus.cs
index 7822cf6..3edcd80 100644
--- a/Modbus.Net/Modbus.Net.Modbus/AddressTranslatorModbus.cs
+++ b/Modbus.Net/Modbus.Net.Modbus/AddressTranslatorModbus.cs
@@ -12,10 +12,12 @@ namespace Modbus.Net.Modbus
/// 读功能码
///
protected Dictionary ReadFunctionCodeDictionary;
+
///
/// 功能码翻译至标准Modbus地址位置
///
protected Dictionary TransDictionary;
+
///
/// 写功能码
///
@@ -201,6 +203,7 @@ namespace Modbus.Net.Modbus
/// 读功能码
///
protected Dictionary ReadFunctionCodeDictionary;
+
///
/// 写功能码
///
diff --git a/Modbus.Net/Modbus.Net.Modbus/ModbusAsciiProtocalLinker.cs b/Modbus.Net/Modbus.Net.Modbus/ModbusAsciiProtocalLinker.cs
index f314fca..a37c55a 100644
--- a/Modbus.Net/Modbus.Net.Modbus/ModbusAsciiProtocalLinker.cs
+++ b/Modbus.Net/Modbus.Net.Modbus/ModbusAsciiProtocalLinker.cs
@@ -8,7 +8,8 @@ namespace Modbus.Net.Modbus
///
public class ModbusAsciiProtocalLinker : ComProtocalLinker
{
- public ModbusAsciiProtocalLinker(string com, int slaveAddress) : base(com, 9600, Parity.None, StopBits.One, 8, slaveAddress)
+ public ModbusAsciiProtocalLinker(string com, int slaveAddress)
+ : base(com, 9600, Parity.None, StopBits.One, 8, slaveAddress)
{
}
@@ -18,14 +19,10 @@ namespace Modbus.Net.Modbus
//CRC校验失败
var contentString = Encoding.ASCII.GetString(content);
if (!Crc16.GetInstance().LrcEfficacy(contentString))
- {
throw new ModbusProtocalErrorException(501);
- }
//Modbus协议错误
if (byte.Parse(contentString.Substring(3, 2)) > 127)
- {
throw new ModbusProtocalErrorException(byte.Parse(contentString.Substring(5, 2)));
- }
return true;
}
}
diff --git a/Modbus.Net/Modbus.Net.Modbus/ModbusProtocal.cs b/Modbus.Net/Modbus.Net.Modbus/ModbusProtocal.cs
index ccf49b5..f261609 100644
--- a/Modbus.Net/Modbus.Net.Modbus/ModbusProtocal.cs
+++ b/Modbus.Net/Modbus.Net.Modbus/ModbusProtocal.cs
@@ -47,7 +47,8 @@ namespace Modbus.Net.Modbus
///
public abstract class ModbusProtocal : BaseProtocal
{
- protected ModbusProtocal(byte slaveAddress, byte masterAddress, Endian endian) : base(slaveAddress, masterAddress, endian)
+ protected ModbusProtocal(byte slaveAddress, byte masterAddress, Endian endian)
+ : base(slaveAddress, masterAddress, endian)
{
}
@@ -73,7 +74,8 @@ namespace Modbus.Net.Modbus
var translateAddress = addressTranslator.AddressTranslate(startAddress, true);
FunctionCode = (byte) translateAddress.Area;
StartAddress = (ushort) translateAddress.Address;
- GetCount = (ushort) Math.Ceiling(getCount/addressTranslator.GetAreaByteLength(translateAddress.AreaString));
+ GetCount =
+ (ushort) Math.Ceiling(getCount / addressTranslator.GetAreaByteLength(translateAddress.AreaString));
}
public byte SlaveAddress { get; }
@@ -140,7 +142,7 @@ namespace Modbus.Net.Modbus
StartAddress = (ushort) translateAddress.Address;
var writeByteValue = ValueHelper.GetInstance(endian).ObjectArrayToByteArray(writeValue);
WriteCount =
- (ushort) (writeByteValue.Length/addressTranslator.GetAreaByteLength(translateAddress.AreaString));
+ (ushort) (writeByteValue.Length / addressTranslator.GetAreaByteLength(translateAddress.AreaString));
WriteByteCount = (byte) writeByteValue.Length;
WriteValue = writeByteValue;
}
diff --git a/Modbus.Net/Modbus.Net.Modbus/ModbusProtocalLinkerBytesExtend.cs b/Modbus.Net/Modbus.Net.Modbus/ModbusProtocalLinkerBytesExtend.cs
index b079c45..ae67594 100644
--- a/Modbus.Net/Modbus.Net.Modbus/ModbusProtocalLinkerBytesExtend.cs
+++ b/Modbus.Net/Modbus.Net.Modbus/ModbusProtocalLinkerBytesExtend.cs
@@ -61,9 +61,7 @@ namespace Modbus.Net.Modbus
var newContent = new List();
newContent.AddRange(Encoding.ASCII.GetBytes(":"));
foreach (var number in content)
- {
newContent.AddRange(Encoding.ASCII.GetBytes(number.ToString("X2")));
- }
newContent.AddRange(Encoding.ASCII.GetBytes(Crc16.GetInstance().GetLRC(content)));
newContent.Add(0x0d);
newContent.Add(0x0a);
diff --git a/Modbus.Net/Modbus.Net.Modbus/ModbusRtuProtocalLinker.cs b/Modbus.Net/Modbus.Net.Modbus/ModbusRtuProtocalLinker.cs
index 0d91f6b..6fa4466 100644
--- a/Modbus.Net/Modbus.Net.Modbus/ModbusRtuProtocalLinker.cs
+++ b/Modbus.Net/Modbus.Net.Modbus/ModbusRtuProtocalLinker.cs
@@ -7,7 +7,8 @@ namespace Modbus.Net.Modbus
///
public class ModbusRtuProtocalLinker : ComProtocalLinker
{
- public ModbusRtuProtocalLinker(string com, int slaveAddress) : base(com, 9600, Parity.None, StopBits.One, 8, slaveAddress)
+ public ModbusRtuProtocalLinker(string com, int slaveAddress)
+ : base(com, 9600, Parity.None, StopBits.One, 8, slaveAddress)
{
}
@@ -16,14 +17,10 @@ namespace Modbus.Net.Modbus
if (!base.CheckRight(content).Value) return false;
//CRC校验失败
if (!Crc16.GetInstance().CrcEfficacy(content))
- {
throw new ModbusProtocalErrorException(501);
- }
//Modbus协议错误
if (content[1] > 127)
- {
throw new ModbusProtocalErrorException(content[2]);
- }
return true;
}
}
diff --git a/Modbus.Net/Modbus.Net.Modbus/ModbusTcpProtocal.cs b/Modbus.Net/Modbus.Net.Modbus/ModbusTcpProtocal.cs
index d403e21..a15b339 100644
--- a/Modbus.Net/Modbus.Net.Modbus/ModbusTcpProtocal.cs
+++ b/Modbus.Net/Modbus.Net.Modbus/ModbusTcpProtocal.cs
@@ -12,7 +12,8 @@ namespace Modbus.Net.Modbus
{
}
- public ModbusTcpProtocal(string ip, byte slaveAddress, byte masterAddress, Endian endian) : base(slaveAddress, masterAddress, endian)
+ public ModbusTcpProtocal(string ip, byte slaveAddress, byte masterAddress, Endian endian)
+ : base(slaveAddress, masterAddress, endian)
{
ProtocalLinker = new ModbusTcpProtocalLinker(ip);
}
diff --git a/Modbus.Net/Modbus.Net.Modbus/ModbusTcpProtocalLinker.cs b/Modbus.Net/Modbus.Net.Modbus/ModbusTcpProtocalLinker.cs
index 87a8a22..f0cfe6e 100644
--- a/Modbus.Net/Modbus.Net.Modbus/ModbusTcpProtocalLinker.cs
+++ b/Modbus.Net/Modbus.Net.Modbus/ModbusTcpProtocalLinker.cs
@@ -7,7 +7,8 @@ namespace Modbus.Net.Modbus
///
public class ModbusTcpProtocalLinker : TcpProtocalLinker
{
- public ModbusTcpProtocalLinker(string ip) : base(ip, int.Parse(ConfigurationManager.AppSettings["ModbusPort"] ?? "502"))
+ public ModbusTcpProtocalLinker(string ip)
+ : base(ip, int.Parse(ConfigurationManager.AppSettings["ModbusPort"] ?? "502"))
{
}
@@ -20,14 +21,10 @@ namespace Modbus.Net.Modbus
if (!base.CheckRight(content).Value) return false;
//长度校验失败
if (content[5] != content.Length - 6)
- {
throw new ModbusProtocalErrorException(500);
- }
//Modbus协议错误
if (content[7] > 127)
- {
throw new ModbusProtocalErrorException(content[2] > 0 ? content[2] : content[8]);
- }
return true;
}
}
diff --git a/Modbus.Net/Modbus.Net.Modbus/ModbusUtility.cs b/Modbus.Net/Modbus.Net.Modbus/ModbusUtility.cs
index fac9f5b..5f6cbb2 100644
--- a/Modbus.Net/Modbus.Net.Modbus/ModbusUtility.cs
+++ b/Modbus.Net/Modbus.Net.Modbus/ModbusUtility.cs
@@ -27,14 +27,15 @@ namespace Modbus.Net.Modbus
///
/// Modbus基础Api入口
///
- public class ModbusUtility : BaseUtility, IUtilityMethodTime
+ public class ModbusUtility : BaseUtility, IIUtilityMethodTime
{
///
/// Modbus协议类型
///
private ModbusType _modbusType;
- public ModbusUtility(int connectionType, byte slaveAddress, byte masterAddress, Endian endian = Endian.BigEndianLsb)
+ public ModbusUtility(int connectionType, byte slaveAddress, byte masterAddress,
+ Endian endian = Endian.BigEndianLsb)
: base(slaveAddress, masterAddress)
{
Endian = endian;
@@ -43,7 +44,8 @@ namespace Modbus.Net.Modbus
AddressTranslator = new AddressTranslatorModbus();
}
- public ModbusUtility(ModbusType connectionType, string connectionString, byte slaveAddress, byte masterAddress, Endian endian = Endian.BigEndianLsb)
+ public ModbusUtility(ModbusType connectionType, string connectionString, byte slaveAddress, byte masterAddress,
+ Endian endian = Endian.BigEndianLsb)
: base(slaveAddress, masterAddress)
{
Endian = endian;
@@ -120,6 +122,47 @@ namespace Modbus.Net.Modbus
}
}
+ ///
+ /// 读时间
+ ///
+ /// 设备的时间
+ public async Task GetTimeAsync()
+ {
+ try
+ {
+ var inputStruct = new GetSystemTimeModbusInputStruct(SlaveAddress);
+ var outputStruct =
+ await Wrapper.SendReceiveAsync(
+ Wrapper[typeof(GetSystemTimeModbusProtocal)], inputStruct);
+ return outputStruct?.Time ?? DateTime.MinValue;
+ }
+ catch (Exception)
+ {
+ return DateTime.MinValue;
+ }
+ }
+
+ ///
+ /// 写时间
+ ///
+ /// 需要写入的时间
+ /// 写入是否成功
+ public async Task SetTimeAsync(DateTime setTime)
+ {
+ try
+ {
+ var inputStruct = new SetSystemTimeModbusInputStruct(SlaveAddress, setTime);
+ var outputStruct =
+ await Wrapper.SendReceiveAsync(
+ Wrapper[typeof(SetSystemTimeModbusProtocal)], inputStruct);
+ return outputStruct?.WriteCount > 0;
+ }
+ catch (Exception)
+ {
+ return false;
+ }
+ }
+
public override void SetConnectionType(int connectionType)
{
ModbusType = (ModbusType) connectionType;
@@ -138,7 +181,8 @@ namespace Modbus.Net.Modbus
var inputStruct = new ReadDataModbusInputStruct(SlaveAddress, startAddress,
(ushort) getByteCount, AddressTranslator);
var outputStruct = await
- Wrapper.SendReceiveAsync(Wrapper[typeof (ReadDataModbusProtocal)], inputStruct);
+ Wrapper.SendReceiveAsync(Wrapper[typeof(ReadDataModbusProtocal)],
+ inputStruct);
return outputStruct?.DataValue;
}
catch
@@ -160,7 +204,8 @@ namespace Modbus.Net.Modbus
var inputStruct = new WriteDataModbusInputStruct(SlaveAddress, startAddress, setContents,
AddressTranslator, Endian);
var outputStruct = await
- Wrapper.SendReceiveAsync(Wrapper[typeof (WriteDataModbusProtocal)], inputStruct);
+ Wrapper.SendReceiveAsync(Wrapper[typeof(WriteDataModbusProtocal)],
+ inputStruct);
return outputStruct?.WriteCount == setContents.Length;
}
catch
@@ -168,44 +213,5 @@ namespace Modbus.Net.Modbus
return false;
}
}
-
- ///
- /// 读时间
- ///
- /// 设备的时间
- public async Task GetTimeAsync()
- {
- try
- {
- var inputStruct = new GetSystemTimeModbusInputStruct(SlaveAddress);
- var outputStruct =
- await Wrapper.SendReceiveAsync(Wrapper[typeof(GetSystemTimeModbusProtocal)], inputStruct);
- return outputStruct?.Time ?? DateTime.MinValue;
- }
- catch (Exception)
- {
- return DateTime.MinValue;
- }
- }
-
- ///
- /// 写时间
- ///
- /// 需要写入的时间
- /// 写入是否成功
- public async Task SetTimeAsync(DateTime setTime)
- {
- try
- {
- var inputStruct = new SetSystemTimeModbusInputStruct(SlaveAddress, setTime);
- var outputStruct =
- await Wrapper.SendReceiveAsync(Wrapper[typeof(SetSystemTimeModbusProtocal)], inputStruct);
- return outputStruct?.WriteCount > 0;
- }
- catch (Exception)
- {
- return false;
- }
- }
}
}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/AddressFormaterOpc.cs b/Modbus.Net/Modbus.Net.OPC/AddressFormaterOpc.cs
index a880837..2d9a4f6 100644
--- a/Modbus.Net/Modbus.Net.OPC/AddressFormaterOpc.cs
+++ b/Modbus.Net/Modbus.Net.OPC/AddressFormaterOpc.cs
@@ -6,7 +6,8 @@ namespace Modbus.Net.OPC
///
/// Opc地址编码器
///
- public class AddressFormaterOpc : AddressFormater where TMachineKey : IEquatable where TUnitKey : IEquatable
+ public class AddressFormaterOpc : AddressFormater where TMachineKey : IEquatable
+ where TUnitKey : IEquatable
{
///
/// 协议构造器
@@ -14,7 +15,8 @@ namespace Modbus.Net.OPC
/// 如何通过BaseMachine和AddressUnit构造Opc的标签
/// 调用这个编码器的设备
/// 每两个标签之间用什么符号隔开,默认为/
- public AddressFormaterOpc(Func, AddressUnit, string[]> tagGeter, BaseMachine machine,
+ public AddressFormaterOpc(Func, AddressUnit, string[]> tagGeter,
+ BaseMachine machine,
char seperator = '/')
{
Machine = machine;
@@ -35,9 +37,7 @@ namespace Modbus.Net.OPC
var strings = TagGeter(Machine, findAddress);
var ans = "";
for (var i = 0; i < strings.Length; i++)
- {
ans += strings[i].Trim().Replace(" ", "") + Seperator;
- }
ans = ans.Substring(0, ans.Length - 1);
return ans;
}
diff --git a/Modbus.Net/Modbus.Net.OPC/ClientExtend.cs b/Modbus.Net/Modbus.Net.OPC/ClientExtend.cs
index 7539f34..d745f7a 100644
--- a/Modbus.Net/Modbus.Net.OPC/ClientExtend.cs
+++ b/Modbus.Net/Modbus.Net.OPC/ClientExtend.cs
@@ -1,16 +1,16 @@
using System;
+using System.Collections.Generic;
using System.Threading.Tasks;
using Hylasoft.Opc.Common;
using Hylasoft.Opc.Da;
-using Opc;
-using Opc.Da;
-using System.Collections.Generic;
using Hylasoft.Opc.Ua;
namespace Modbus.Net.OPC
{
public interface IClientExtend : IDisposable
{
+ Node RootNodeBase { get; }
+
void Connect();
T Read(string tag);
@@ -24,8 +24,6 @@ namespace Modbus.Net.OPC
Task FindNodeAsync(string tag);
Task> ExploreFolderAsync(string tag);
-
- Node RootNodeBase { get; }
}
public class MyDaClient : DaClient, IClientExtend
diff --git a/Modbus.Net/Modbus.Net.OPC/FBox/FBoxOpcDaManchine.cs b/Modbus.Net/Modbus.Net.OPC/FBox/FBoxOpcDaManchine.cs
index 991f80c..074d867 100644
--- a/Modbus.Net/Modbus.Net.OPC/FBox/FBoxOpcDaManchine.cs
+++ b/Modbus.Net/Modbus.Net.OPC/FBox/FBoxOpcDaManchine.cs
@@ -1,27 +1,20 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
using System.Configuration;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
namespace Modbus.Net.OPC.FBox
{
public class FBoxOpcDaMachine : OpcDaMachine
{
- public string LocalSequence { get; set; }
-
- public string LinkerName { get; set; }
-
public FBoxOpcDaMachine(string localSequence, string linkerName,
- IEnumerable getAddresses, bool keepConnect) : base(ConfigurationManager.AppSettings["FBoxOpcDaHost"], getAddresses, keepConnect)
+ IEnumerable getAddresses, bool keepConnect)
+ : base(ConfigurationManager.AppSettings["FBoxOpcDaHost"], getAddresses, keepConnect)
{
LocalSequence = localSequence;
LinkerName = linkerName;
AddressFormater =
- new AddressFormaterOpc(
+ new AddressFormaterOpc(
(machine, unit) =>
- new string[]
+ new[]
{
"(.*)", ((FBoxOpcDaMachine) machine).LinkerName, ((FBoxOpcDaMachine) machine).LocalSequence,
unit.Name
@@ -33,5 +26,9 @@ namespace Modbus.Net.OPC.FBox
: this(localSequence, linkerName, getAddresses, false)
{
}
+
+ public string LocalSequence { get; set; }
+
+ public string LinkerName { get; set; }
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcConnector.cs b/Modbus.Net/Modbus.Net.OPC/OpcConnector.cs
index 8c4eb6f..6c10bc7 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcConnector.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcConnector.cs
@@ -1,25 +1,25 @@
-using Hylasoft.Opc.Common;
-using System;
+using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
+using Hylasoft.Opc.Common;
namespace Modbus.Net.OPC
{
public abstract class OpcConnector : BaseConnector
{
- protected IClientExtend Client;
-
protected bool _connect;
- public override string ConnectionToken { get; }
- public override bool IsConnected => _connect;
+ protected IClientExtend Client;
protected OpcConnector(string host)
{
ConnectionToken = host;
- }
+ }
+
+ public override string ConnectionToken { get; }
+ public override bool IsConnected => _connect;
public override bool Disconnect()
{
@@ -56,15 +56,12 @@ namespace Modbus.Net.OPC
private void FoldWith(List tagSplitList, char splitChar, char startChar, char endChar)
{
- for (int i = 0; i < tagSplitList.Count; i++)
- {
- if (tagSplitList[i].Count(ch=>ch == startChar) > tagSplitList[i].Count(ch=>ch == endChar))
- {
- for (int j = i + 1; j < tagSplitList.Count; j++)
- {
+ for (var i = 0; i < tagSplitList.Count; i++)
+ if (tagSplitList[i].Count(ch => ch == startChar) > tagSplitList[i].Count(ch => ch == endChar))
+ for (var j = i + 1; j < tagSplitList.Count; j++)
if (tagSplitList[j].Contains(endChar))
{
- for (int k = i + 1; k <= j; k++)
+ for (var k = i + 1; k <= j; k++)
{
tagSplitList[i] += splitChar + tagSplitList[i + 1];
tagSplitList.RemoveAt(i + 1);
@@ -72,9 +69,6 @@ namespace Modbus.Net.OPC
i--;
break;
}
- }
- }
- }
}
private string[] SplitTag(string tag, char split)
@@ -108,7 +102,7 @@ namespace Modbus.Net.OPC
Value = BigEndianValueHelper.Instance.GetBytes(result, result.GetType())
};
}
- return new OpcParamOut()
+ return new OpcParamOut
{
Success = false,
Value = Encoding.ASCII.GetBytes("NoData")
@@ -132,17 +126,17 @@ namespace Modbus.Net.OPC
catch (Exception e)
{
AddInfo("opc write exception:" + e.Message);
- return new OpcParamOut()
+ return new OpcParamOut
{
Success = false
};
}
- return new OpcParamOut()
+ return new OpcParamOut
{
Success = true
};
}
- return new OpcParamOut()
+ return new OpcParamOut
{
Success = false
};
@@ -151,7 +145,7 @@ namespace Modbus.Net.OPC
catch (Exception e)
{
AddInfo("opc client exception:" + e.Message);
- return new OpcParamOut()
+ return new OpcParamOut
{
Success = false,
Value = Encoding.ASCII.GetBytes("NoData")
@@ -203,4 +197,4 @@ namespace Modbus.Net.OPC
return Task.FromResult(Connect());
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcDaConnector.cs b/Modbus.Net/Modbus.Net.OPC/OpcDaConnector.cs
index 1beddcb..4813ef2 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcDaConnector.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcDaConnector.cs
@@ -1,9 +1,5 @@
-using Hylasoft.Opc.Common;
-using System;
+using System;
using System.Collections.Generic;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
namespace Modbus.Net.OPC
{
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcDaMachine.cs b/Modbus.Net/Modbus.Net.OPC/OpcDaMachine.cs
index ef5eeec..681fee1 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcDaMachine.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcDaMachine.cs
@@ -3,7 +3,8 @@ using System.Collections.Generic;
namespace Modbus.Net.OPC
{
- public class OpcDaMachine : OpcMachine where TKey : IEquatable where TUnitKey : IEquatable
+ public class OpcDaMachine : OpcMachine where TKey : IEquatable
+ where TUnitKey : IEquatable
{
public OpcDaMachine(string connectionString, IEnumerable> getAddresses, bool keepConnect)
: base(getAddresses, keepConnect)
@@ -21,12 +22,12 @@ namespace Modbus.Net.OPC
public class OpcDaMachine : OpcMachine
{
- public OpcDaMachine(string connectionString, IEnumerable getAddresses, bool keepConnect)
+ public OpcDaMachine(string connectionString, IEnumerable getAddresses, bool keepConnect)
: base(getAddresses, keepConnect)
{
BaseUtility = new OpcDaUtility(connectionString);
- ((OpcUtility)BaseUtility).GetSeperator +=
- () => ((AddressFormaterOpc)AddressFormater).Seperator;
+ ((OpcUtility) BaseUtility).GetSeperator +=
+ () => ((AddressFormaterOpc) AddressFormater).Seperator;
}
public OpcDaMachine(string connectionString, IEnumerable getAddresses)
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcDaProtocalLinker.cs b/Modbus.Net/Modbus.Net.OPC/OpcDaProtocalLinker.cs
index f65da98..c98b617 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcDaProtocalLinker.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcDaProtocalLinker.cs
@@ -1,10 +1,9 @@
using System.Configuration;
-using System.Text;
namespace Modbus.Net.OPC
{
///
- /// Opc Da协议连接器
+ /// Opc Da协议连接器
///
public class OpcDaProtocalLinker : OpcProtocalLinker
{
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcDaUtility.cs b/Modbus.Net/Modbus.Net.OPC/OpcDaUtility.cs
index f59ee5c..d52232d 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcDaUtility.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcDaUtility.cs
@@ -1,7 +1,4 @@
-using System;
-using System.Threading.Tasks;
-
-namespace Modbus.Net.OPC
+namespace Modbus.Net.OPC
{
///
/// Opc Da协议Api入口
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcMachine.cs b/Modbus.Net/Modbus.Net.OPC/OpcMachine.cs
index 034508b..3803e54 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcMachine.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcMachine.cs
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
namespace Modbus.Net.OPC
{
@@ -32,4 +29,4 @@ namespace Modbus.Net.OPC
AddressCombinerSet = new AddressCombinerSingle();
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcProtocal.cs b/Modbus.Net/Modbus.Net.OPC/OpcProtocal.cs
index 119b088..6f48d67 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcProtocal.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcProtocal.cs
@@ -1,6 +1,4 @@
-using System.Text;
-
-namespace Modbus.Net.OPC
+namespace Modbus.Net.OPC
{
///
/// Opc协议
@@ -41,7 +39,7 @@ namespace Modbus.Net.OPC
public override OpcParamIn Format(IInputStruct message)
{
var r_message = (ReadRequestOpcInputStruct) message;
- return new OpcParamIn()
+ return new OpcParamIn
{
IsRead = true,
Tag = r_message.Tag,
@@ -88,7 +86,7 @@ namespace Modbus.Net.OPC
public override OpcParamIn Format(IInputStruct message)
{
var r_message = (WriteRequestOpcInputStruct) message;
- return new OpcParamIn()
+ return new OpcParamIn
{
IsRead = false,
Tag = r_message.Tag,
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcProtocalLinker.cs b/Modbus.Net/Modbus.Net.OPC/OpcProtocalLinker.cs
index c042357..d76b2cf 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcProtocalLinker.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcProtocalLinker.cs
@@ -1,7 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.Text;
using System.Threading.Tasks;
namespace Modbus.Net.OPC
@@ -51,10 +48,8 @@ namespace Modbus.Net.OPC
{
if (content == null || !content.Success) return false;
if (content.Value.Length == 6 && Encoding.ASCII.GetString(content.Value) == "NoData")
- {
return null;
- }
return base.CheckRight(content);
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcUaConnector.cs b/Modbus.Net/Modbus.Net.OPC/OpcUaConnector.cs
index 8636986..8fc4152 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcUaConnector.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcUaConnector.cs
@@ -1,11 +1,5 @@
-using Hylasoft.Opc.Common;
-using Hylasoft.Opc.Ua;
-using System;
+using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Text.RegularExpressions;
-using System.Threading.Tasks;
namespace Modbus.Net.OPC
{
@@ -31,4 +25,4 @@ namespace Modbus.Net.OPC
return _instances[host];
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcUaMachine.cs b/Modbus.Net/Modbus.Net.OPC/OpcUaMachine.cs
index 92b00dd..7e49287 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcUaMachine.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcUaMachine.cs
@@ -1,19 +1,17 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
namespace Modbus.Net.OPC
{
- public class OpcUaMachine : OpcMachine where TKey : IEquatable where TUnitKey : IEquatable
+ public class OpcUaMachine : OpcMachine where TKey : IEquatable
+ where TUnitKey : IEquatable
{
public OpcUaMachine(string connectionString, IEnumerable> getAddresses, bool keepConnect)
: base(getAddresses, keepConnect)
{
BaseUtility = new OpcUaUtility(connectionString);
- ((OpcUtility)BaseUtility).GetSeperator +=
- () => ((AddressFormaterOpc)AddressFormater).Seperator;
+ ((OpcUtility) BaseUtility).GetSeperator +=
+ () => ((AddressFormaterOpc) AddressFormater).Seperator;
}
public OpcUaMachine(string connectionString, IEnumerable> getAddresses)
@@ -28,8 +26,8 @@ namespace Modbus.Net.OPC
: base(getAddresses, keepConnect)
{
BaseUtility = new OpcUaUtility(connectionString);
- ((OpcUtility)BaseUtility).GetSeperator +=
- () => ((AddressFormaterOpc)AddressFormater).Seperator;
+ ((OpcUtility) BaseUtility).GetSeperator +=
+ () => ((AddressFormaterOpc) AddressFormater).Seperator;
}
public OpcUaMachine(string connectionString, IEnumerable getAddresses)
@@ -37,4 +35,4 @@ namespace Modbus.Net.OPC
{
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcUaProtocal.cs b/Modbus.Net/Modbus.Net.OPC/OpcUaProtocal.cs
index 762d487..b146880 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcUaProtocal.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcUaProtocal.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Threading.Tasks;
namespace Modbus.Net.OPC
{
@@ -33,4 +29,4 @@ namespace Modbus.Net.OPC
return true;
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcUaProtocalLinker.cs b/Modbus.Net/Modbus.Net.OPC/OpcUaProtocalLinker.cs
index 8048b97..31b3279 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcUaProtocalLinker.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcUaProtocalLinker.cs
@@ -1,14 +1,9 @@
-using System;
-using System.Collections.Generic;
-using System.Configuration;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Configuration;
namespace Modbus.Net.OPC
{
///
- /// Opc Da协议连接器
+ /// Opc Da协议连接器
///
public class OpcUaProtocalLinker : OpcProtocalLinker
{
@@ -21,4 +16,4 @@ namespace Modbus.Net.OPC
BaseConnector = OpcUaConnector.Instance(host);
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcUaUtility.cs b/Modbus.Net/Modbus.Net.OPC/OpcUaUtility.cs
index 6502f2a..e061c28 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcUaUtility.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcUaUtility.cs
@@ -1,10 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Modbus.Net.OPC
+namespace Modbus.Net.OPC
{
///
/// Opc Da协议Api入口
@@ -16,4 +10,4 @@ namespace Modbus.Net.OPC
Wrapper = new OpcUaProtocal(ConnectionString);
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/OpcUtility.cs b/Modbus.Net/Modbus.Net.OPC/OpcUtility.cs
index 50ce8a5..5b8f454 100644
--- a/Modbus.Net/Modbus.Net.OPC/OpcUtility.cs
+++ b/Modbus.Net/Modbus.Net.OPC/OpcUtility.cs
@@ -1,25 +1,22 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using System.Threading.Tasks;
namespace Modbus.Net.OPC
{
public abstract class OpcUtility : BaseUtility>
- {
+ {
+ public delegate char GetSeperatorDelegate();
+
protected OpcUtility(string connectionString) : base(0, 0)
{
ConnectionString = connectionString;
AddressTranslator = new AddressTranslatorOpc();
}
- public delegate char GetSeperatorDelegate();
+ public override Endian Endian => Endian.BigEndianLsb;
public event GetSeperatorDelegate GetSeperator;
- public override Endian Endian => Endian.BigEndianLsb;
-
public override void SetConnectionType(int connectionType)
{
throw new NotImplementedException();
@@ -33,7 +30,8 @@ namespace Modbus.Net.OPC
var readRequestOpcInputStruct = new ReadRequestOpcInputStruct(startAddress, split);
var readRequestOpcOutputStruct =
await
- Wrapper.SendReceiveAsync(Wrapper[typeof(ReadRequestOpcProtocal)], readRequestOpcInputStruct);
+ Wrapper.SendReceiveAsync(Wrapper[typeof(ReadRequestOpcProtocal)],
+ readRequestOpcInputStruct);
return readRequestOpcOutputStruct?.GetValue;
}
catch (Exception)
@@ -50,7 +48,8 @@ namespace Modbus.Net.OPC
var writeRequestOpcInputStruct = new WriteRequestOpcInputStruct(startAddress, split, setContents[0]);
var writeRequestOpcOutputStruct =
await
- Wrapper.SendReceiveAsync(Wrapper[typeof(WriteRequestOpcProtocal)], writeRequestOpcInputStruct);
+ Wrapper.SendReceiveAsync(Wrapper[typeof(WriteRequestOpcProtocal)],
+ writeRequestOpcInputStruct);
return writeRequestOpcOutputStruct?.WriteResult == true;
}
catch (Exception e)
@@ -59,4 +58,4 @@ namespace Modbus.Net.OPC
}
}
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.OPC/packages.config b/Modbus.Net/Modbus.Net.OPC/packages.config
deleted file mode 100644
index 1b83f0e..0000000
--- a/Modbus.Net/Modbus.Net.OPC/packages.config
+++ /dev/null
@@ -1,4 +0,0 @@
-
-
-
-
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.Siemens/AddressFormaterSiemens.cs b/Modbus.Net/Modbus.Net.Siemens/AddressFormaterSiemens.cs
index da96bb5..923e4c1 100644
--- a/Modbus.Net/Modbus.Net.Siemens/AddressFormaterSiemens.cs
+++ b/Modbus.Net/Modbus.Net.Siemens/AddressFormaterSiemens.cs
@@ -17,7 +17,7 @@
}
///
- /// Siemens地址格式化(Siemens格式)
+ /// Siemens地址格式化(Siemens格式)
///
public class AddressFormaterSimenseStandard : AddressFormater
{
@@ -25,26 +25,16 @@
{
if (area.Length > 1 &&
area.ToUpper().Substring(0, 2) == "DB")
- {
return area.ToUpper() + "." + "DB" + address;
- }
- else
- {
- return area.ToUpper() + address;
- }
+ return area.ToUpper() + address;
}
public override string FormatAddress(string area, int address, int subAddress)
{
if (area.Length > 1 &&
area.ToUpper().Substring(0, 2) == "DB")
- {
return area.ToUpper() + "." + "DB" + address + "." + subAddress;
- }
- else
- {
- return area.ToUpper() + address + "." + subAddress;
- }
+ return area.ToUpper() + address + "." + subAddress;
}
}
}
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net.Siemens/AddressTranslatorSiemens.cs b/Modbus.Net/Modbus.Net.Siemens/AddressTranslatorSiemens.cs
index f1f59ea..b19dbb2 100644
--- a/Modbus.Net/Modbus.Net.Siemens/AddressTranslatorSiemens.cs
+++ b/Modbus.Net/Modbus.Net.Siemens/AddressTranslatorSiemens.cs
@@ -53,7 +53,7 @@ namespace Modbus.Net.Siemens
return new AddressDef
{
AreaString = "DB" + head,
- Area = int.Parse(head)*256 + AreaCodeDictionary["DB"],
+ Area = int.Parse(head) * 256 + AreaCodeDictionary["DB"],
Address = int.Parse(tail),
SubAddress = int.Parse(sub)
};
@@ -96,7 +96,7 @@ namespace Modbus.Net.Siemens
{"Q", 0x82},
{"M", 0x83},
{"DB", 0x84},
- {"V", 0x184},
+ {"V", 0x184}
};
}
@@ -118,15 +118,13 @@ namespace Modbus.Net.Siemens
SubAddress = addressSplit.Length == 2 ? 0 : int.Parse(addressSplit[2])
};
}
- int i = 0;
+ var i = 0;
int t;
while (!int.TryParse(address[i].ToString(), out t) && i < address.Length)
- {
i++;
- }
if (i == 0 || i >= address.Length) throw new FormatException();
- string head = address.Substring(0, i);
- string[] tail = address.Substring(i).Split('.');
+ var head = address.Substring(0, i);
+ var tail = address.Substring(i).Split('.');
return new AddressDef
{
AreaString = head,
diff --git a/Modbus.Net/Modbus.Net.Siemens/SiemensPpiProtocal.cs b/Modbus.Net/Modbus.Net.Siemens/SiemensPpiProtocal.cs
index d91aa63..a14fc97 100644
--- a/Modbus.Net/Modbus.Net.Siemens/SiemensPpiProtocal.cs
+++ b/Modbus.Net/Modbus.Net.Siemens/SiemensPpiProtocal.cs
@@ -29,9 +29,7 @@ namespace Modbus.Net.Siemens
public override async Task SendReceiveAsync(params object[] content)
{
if (ProtocalLinker == null || !ProtocalLinker.IsConnected)
- {
await ConnectAsync();
- }
return await base.SendReceiveAsync(Endian, content);
}
@@ -51,17 +49,17 @@ namespace Modbus.Net.Siemens
var inputStruct = new ComCreateReferenceSiemensInputStruct(SlaveAddress, MasterAddress);
var outputStruct =
await await
- ForceSendReceiveAsync(this[typeof (ComCreateReferenceSiemensProtocal)],
- inputStruct).
+ ForceSendReceiveAsync(this[typeof(ComCreateReferenceSiemensProtocal)],
+ inputStruct).
ContinueWith(async answer =>
{
if (!ProtocalLinker.IsConnected) return false;
var inputStruct2 = new ComConfirmMessageSiemensInputStruct(SlaveAddress, MasterAddress);
var outputStruct2 =
(ComConfirmMessageSiemensOutputStruct)
- await
- ForceSendReceiveAsync(this[typeof (ComConfirmMessageSiemensProtocal)],
- inputStruct2);
+ await
+ ForceSendReceiveAsync(this[typeof(ComConfirmMessageSiemensProtocal)],
+ inputStruct2);
return outputStruct2 != null;
});
return outputStruct;
diff --git a/Modbus.Net/Modbus.Net.Siemens/SiemensPpiProtocalLinker.cs b/Modbus.Net/Modbus.Net.Siemens/SiemensPpiProtocalLinker.cs
index b8d93f1..6c8c0e0 100644
--- a/Modbus.Net/Modbus.Net.Siemens/SiemensPpiProtocalLinker.cs
+++ b/Modbus.Net/Modbus.Net.Siemens/SiemensPpiProtocalLinker.cs
@@ -65,15 +65,11 @@ namespace Modbus.Net.Siemens
if (!base.CheckRight(content).Value) return false;
var fcsCheck = 0;
if (content.Length == 1 && content[0] == 0xe5)
- {
return true;
- }
if (content.Length == 6 && content[3] == 0) return true;
for (var i = 4; i < content.Length - 2; i++)
- {
fcsCheck += content[i];
- }
- fcsCheck = fcsCheck%256;
+ fcsCheck = fcsCheck % 256;
if (fcsCheck != content[content.Length - 2]) return false;
if (content[content.Length - 1] != 0x16) return false;
if (content[1] != content.Length - 6) return false;
diff --git a/Modbus.Net/Modbus.Net.Siemens/SiemensProtocal.cs b/Modbus.Net/Modbus.Net.Siemens/SiemensProtocal.cs
index df178d5..588e15c 100644
--- a/Modbus.Net/Modbus.Net.Siemens/SiemensProtocal.cs
+++ b/Modbus.Net/Modbus.Net.Siemens/SiemensProtocal.cs
@@ -104,7 +104,8 @@ namespace Modbus.Net.Siemens
public abstract class SiemensProtocal : BaseProtocal
{
- protected SiemensProtocal(byte slaveAddress, byte masterAddress) : base(slaveAddress, masterAddress, Endian.BigEndianLsb)
+ protected SiemensProtocal(byte slaveAddress, byte masterAddress)
+ : base(slaveAddress, masterAddress, Endian.BigEndianLsb)
{
}
}
@@ -142,7 +143,7 @@ namespace Modbus.Net.Siemens
public override byte[] Format(IInputStruct message)
{
var r_message = (ComCreateReferenceSiemensInputStruct) message;
- var crc = (r_message.SlaveAddress + r_message.MasterAddress + 0x49)%256;
+ var crc = (r_message.SlaveAddress + r_message.MasterAddress + 0x49) % 256;
return Format((byte) 0x10, r_message.SlaveAddress, r_message.MasterAddress, (byte) 0x49, (byte) crc,
(byte) 0x16);
}
@@ -274,7 +275,7 @@ namespace Modbus.Net.Siemens
public override byte[] Format(IInputStruct message)
{
var r_message = (ComConfirmMessageSiemensInputStruct) message;
- var crc = r_message.SlaveAddress + r_message.MasterAddress + 0x5c%256;
+ var crc = r_message.SlaveAddress + r_message.MasterAddress + 0x5c % 256;
return Format((byte) 0x10, r_message.SlaveAddress, r_message.MasterAddress, (byte) 0x5c, (byte) crc,
(byte) 0x16);
}
@@ -370,8 +371,8 @@ namespace Modbus.Net.Siemens
var address = addressTranslator.AddressTranslate(startAddress, true);
Offset = address.Address;
var area = address.Area;
- Area = (byte) (area%256);
- DbBlock = Area == 0x84 ? (ushort) (area/256) : (ushort) 0;
+ Area = (byte) (area % 256);
+ DbBlock = Area == 0x84 ? (ushort) (area / 256) : (ushort) 0;
NumberOfElements = getCount;
}
@@ -426,7 +427,7 @@ namespace Modbus.Net.Siemens
var numberOfElements = r_message.NumberOfElements;
var dbBlock = r_message.DbBlock;
var area = r_message.Area;
- var offsetBit = r_message.Offset*8;
+ var offsetBit = r_message.Offset * 8;
var offsetBitBytes = BigEndianValueHelper.Instance.GetBytes(offsetBit);
return Format(new byte[4], slaveAddress, masterAddress, (byte) 0x6c, protoId, rosctr, redId, pduRef, parLg,
datLg, serviceId, numberOfVariables
@@ -442,7 +443,7 @@ namespace Modbus.Net.Siemens
var accessResult = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
var dataType = BigEndianValueHelper.Instance.GetByte(messageBytes, ref pos);
var length = BigEndianValueHelper.Instance.GetUShort(messageBytes, ref pos);
- var byteLength = length/8;
+ var byteLength = length / 8;
var values = new byte[byteLength];
Array.Copy(messageBytes, pos, values, 0, byteLength);
return new ReadRequestSiemensOutputStruct(pduRef, (SiemensAccessResult) accessResult,
@@ -465,8 +466,8 @@ namespace Modbus.Net.Siemens
var address = addressTranslator.AddressTranslate(startAddress, true);
Offset = address.Address;
var area = address.Area;
- Area = (byte) (area%256);
- DbBlock = Area == 0x84 ? (ushort) (area/256) : (ushort) 0;
+ Area = (byte) (area % 256);
+ DbBlock = Area == 0x84 ? (ushort) (area / 256) : (ushort) 0;
WriteValue = writeValue;
}
@@ -514,11 +515,11 @@ namespace Modbus.Net.Siemens
var numberOfElements = (ushort) valueBytes.Length;
var dbBlock = r_message.DbBlock;
var area = r_message.Area;
- var offsetBit = r_message.Offset*8;
+ var offsetBit = r_message.Offset * 8;
var offsetBitBytes = BigEndianValueHelper.Instance.GetBytes(offsetBit);
const byte reserved = 0x00;
const byte type = (byte) SiemensDataType.OtherAccess;
- var numberOfWriteBits = (ushort) (valueBytes.Length*8);
+ var numberOfWriteBits = (ushort) (valueBytes.Length * 8);
return Format(new byte[4], slaveAddress, masterAddress, (byte) 0x7c, protoId, rosctr, redId, pduRef, parLg,
datLg, serviceId, numberOfVariables
, variableSpec, vAddrLg, syntaxId, typeR, numberOfElements, dbBlock, area,
diff --git a/Modbus.Net/Modbus.Net.Siemens/SiemensProtocalLinkerBytesExtend.cs b/Modbus.Net/Modbus.Net.Siemens/SiemensProtocalLinkerBytesExtend.cs
index 180c244..64af6bd 100644
--- a/Modbus.Net/Modbus.Net.Siemens/SiemensProtocalLinkerBytesExtend.cs
+++ b/Modbus.Net/Modbus.Net.Siemens/SiemensProtocalLinkerBytesExtend.cs
@@ -35,10 +35,8 @@ namespace Modbus.Net.Siemens
0, 4);
var check = 0;
for (var i = 4; i < newContent.Length - 2; i++)
- {
check += newContent[i];
- }
- check = check%256;
+ check = check % 256;
newContent[newContent.Length - 2] = (byte) check;
newContent[newContent.Length - 1] = 0x16;
return newContent;
diff --git a/Modbus.Net/Modbus.Net.Siemens/SiemensTcpProtocal.cs b/Modbus.Net/Modbus.Net.Siemens/SiemensTcpProtocal.cs
index 3150fa6..fc1d577 100644
--- a/Modbus.Net/Modbus.Net.Siemens/SiemensTcpProtocal.cs
+++ b/Modbus.Net/Modbus.Net.Siemens/SiemensTcpProtocal.cs
@@ -19,12 +19,16 @@ namespace Modbus.Net.Siemens
private int _connectTryCount;
public SiemensTcpProtocal(byte tdpuSize, ushort tsapSrc, ushort tsapDst, ushort maxCalling, ushort maxCalled,
- ushort maxPdu) : this(tdpuSize, tsapSrc, tsapDst, maxCalling, maxCalled, maxPdu, ConfigurationManager.AppSettings["IP"])
+ ushort maxPdu)
+ : this(tdpuSize, tsapSrc, tsapDst, maxCalling, maxCalled, maxPdu, ConfigurationManager.AppSettings["IP"])
{
}
public SiemensTcpProtocal(byte tdpuSize, ushort tsapSrc, ushort tsapDst, ushort maxCalling, ushort maxCalled,
- ushort maxPdu, string ip) : this(tdpuSize, tsapSrc, tsapDst, maxCalling, maxCalled, maxPdu, ip, int.Parse(ConfigurationManager.AppSettings["SiemensPort"]))
+ ushort maxPdu, string ip)
+ : this(
+ tdpuSize, tsapSrc, tsapDst, maxCalling, maxCalled, maxPdu, ip,
+ int.Parse(ConfigurationManager.AppSettings["SiemensPort"] ?? "102"))
{
}
@@ -50,9 +54,7 @@ namespace Modbus.Net.Siemens
public override async Task SendReceiveAsync(params object[] content)
{
if (ProtocalLinker == null || !ProtocalLinker.IsConnected)
- {
await ConnectAsync();
- }
return await base.SendReceiveAsync(Endian, content);
}
@@ -92,7 +94,7 @@ namespace Modbus.Net.Siemens
return
//先建立连接,然后建立设备的引用
await await
- ForceSendReceiveAsync(this[typeof (CreateReferenceSiemensProtocal)], inputStruct)
+ ForceSendReceiveAsync(this[typeof(CreateReferenceSiemensProtocal)], inputStruct)
.ContinueWith(async answer =>
{
if (!ProtocalLinker.IsConnected) return false;
@@ -101,9 +103,9 @@ namespace Modbus.Net.Siemens
_maxPdu);
var outputStruct2 =
(EstablishAssociationSiemensOutputStruct)
- await
- SendReceiveAsync(this[typeof (EstablishAssociationSiemensProtocal)],
- inputStruct2);
+ await
+ SendReceiveAsync(this[typeof(EstablishAssociationSiemensProtocal)],
+ inputStruct2);
return outputStruct2 != null;
});
}
diff --git a/Modbus.Net/Modbus.Net.Siemens/SiemensUtility.cs b/Modbus.Net/Modbus.Net.Siemens/SiemensUtility.cs
index 84cab37..4d81d49 100644
--- a/Modbus.Net/Modbus.Net.Siemens/SiemensUtility.cs
+++ b/Modbus.Net/Modbus.Net.Siemens/SiemensUtility.cs
@@ -183,7 +183,8 @@ namespace Modbus.Net.Siemens
0xd3c7, SiemensTypeCode.Byte, startAddress, (ushort) getByteCount, AddressTranslator);
var readRequestSiemensOutputStruct =
await
- Wrapper.SendReceiveAsync(Wrapper[typeof (ReadRequestSiemensProtocal)],
+ Wrapper.SendReceiveAsync(
+ Wrapper[typeof(ReadRequestSiemensProtocal)],
readRequestSiemensInputStruct);
return readRequestSiemensOutputStruct?.GetValue;
}
@@ -207,7 +208,8 @@ namespace Modbus.Net.Siemens
0xd3c8, startAddress, setContents, AddressTranslator);
var writeRequestSiemensOutputStruct =
await
- Wrapper.SendReceiveAsync(Wrapper[typeof (WriteRequestSiemensProtocal)],
+ Wrapper.SendReceiveAsync(
+ Wrapper[typeof(WriteRequestSiemensProtocal)],
writeRequestSiemensInputStruct);
return writeRequestSiemensOutputStruct?.AccessResult == SiemensAccessResult.NoError;
}
diff --git a/Modbus.Net/Modbus.Net/App.config b/Modbus.Net/Modbus.Net/App.config
index 46b488f..44dba52 100644
--- a/Modbus.Net/Modbus.Net/App.config
+++ b/Modbus.Net/Modbus.Net/App.config
@@ -1,14 +1,15 @@
-
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/Modbus.Net/Modbus.Net/ComConnector.cs b/Modbus.Net/Modbus.Net/ComConnector.cs
index 257289f..7802356 100644
--- a/Modbus.Net/Modbus.Net/ComConnector.cs
+++ b/Modbus.Net/Modbus.Net/ComConnector.cs
@@ -9,8 +9,14 @@ using System.Threading.Tasks;
namespace Modbus.Net
{
+ ///
+ /// 具有发送锁的串口
+ ///
public class SerialPortLock : SerialPort
{
+ ///
+ /// 发送锁
+ ///
public object Lock { get; set; } = new object();
}
@@ -19,42 +25,87 @@ namespace Modbus.Net
///
public class ComConnector : BaseConnector, IDisposable
{
- public delegate byte[] GetDate(byte[] bts);
-
- private static Dictionary Connectors { get; } = new Dictionary();
- private static Dictionary Linkers { get; } = new Dictionary();
-
+ ///
+ /// 波特率
+ ///
private readonly int _baudRate;
- //private GetDate mygetDate;
+ ///
+ /// 串口地址
+ ///
private readonly string _com;
+
+ ///
+ /// 数据位
+ ///
private readonly int _dataBits;
+
+ ///
+ /// 奇偶校验
+ ///
private readonly Parity _parity;
- private readonly StopBits _stopBits;
- private readonly int _timeoutTime;
+
+ ///
+ /// 从站号
+ ///
private readonly string _slave;
- private bool m_disposed = false;
+ ///
+ /// 停止位
+ ///
+ private readonly StopBits _stopBits;
+ ///
+ /// 超时时间
+ ///
+ private readonly int _timeoutTime;
+
+ ///
+ /// Dispose是否执行
+ ///
+ private bool m_disposed;
+
+ ///
+ /// 构造器
+ ///
+ /// 串口地址:从站号
+ /// 波特率
+ /// 校验位
+ /// 停止位
+ /// 数据位
+ /// 超时时间
public ComConnector(string com, int baudRate, Parity parity, StopBits stopBits, int dataBits, int timeoutTime)
{
- _com = com.Split(':')[0];
- _timeoutTime = timeoutTime;
- _baudRate = baudRate;
- _parity = parity;
- _stopBits = stopBits;
- _dataBits = dataBits;
- _slave = com.Split(':')[1];
-
//端口号
+ _com = com.Split(':')[0];
//读超时
- //比特率
- //奇偶校验
+ _timeoutTime = timeoutTime;
+ //波特率
+ _baudRate = baudRate;
+ //奇偶校验
+ _parity = parity;
//停止位
+ _stopBits = stopBits;
//数据位
- //从站号标识
+ _dataBits = dataBits;
+ //从站号
+ _slave = com.Split(':')[1];
}
+ ///
+ /// 连接中的串口
+ ///
+ private static Dictionary Connectors { get; } = new Dictionary()
+ ;
+
+ ///
+ /// 连接中的连接器
+ ///
+ private static Dictionary Linkers { get; } = new Dictionary();
+
+ ///
+ /// 连接关键字(串口号:从站号)
+ ///
public override string ConnectionToken => _slave + ":" + _com;
private SerialPortLock SerialPort
@@ -72,7 +123,7 @@ namespace Modbus.Net
///
public void Dispose()
{
- Dispose(true);
+ Dispose(true);
//.NET Framework 类库
// GC..::.SuppressFinalize 方法
//请求系统不要调用指定对象的终结器。
@@ -117,7 +168,9 @@ namespace Modbus.Net
}
else if (nReadLen == 0)
+ {
nBytelen += 1;
+ }
}
}
catch (Exception ex)
@@ -146,7 +199,6 @@ namespace Modbus.Net
SerialPort.ReadTimeout = ByteTime;
while (nBytelen < ReadRoom - 1 && SerialPort.BytesToRead > 0)
- {
try
{
ReadBuf[nBytelen] = (byte) SerialPort.ReadByte();
@@ -156,7 +208,6 @@ namespace Modbus.Net
{
throw new Exception(ex.Message);
}
- }
ReadBuf[nBytelen] = 0x00;
return nBytelen;
}
@@ -171,9 +222,7 @@ namespace Modbus.Net
{
var StringOut = "";
foreach (var InByte in InBytes)
- {
StringOut = StringOut + string.Format("{0:X2}", InByte) + " ";
- }
return StringOut.Trim();
}
@@ -190,9 +239,7 @@ namespace Modbus.Net
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;
}
@@ -207,7 +254,7 @@ namespace Modbus.Net
InString = InString.Replace(" ", "");
try
{
- var ByteStrings = new string[InString.Length/2];
+ var ByteStrings = new string[InString.Length / 2];
var j = 0;
for (var i = 0; i < ByteStrings.Length; i++)
{
@@ -217,9 +264,7 @@ namespace Modbus.Net
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)
{
@@ -285,24 +330,28 @@ namespace Modbus.Net
#region 发送接收数据
+ ///
+ /// 是否正在连接
+ ///
public override bool IsConnected
{
get
{
if (SerialPort != null && !SerialPort.IsOpen)
- {
SerialPort.Dispose();
- }
return SerialPort != null && SerialPort.IsOpen && Linkers.ContainsKey(_slave);
}
}
+ ///
+ /// 连接串口
+ ///
+ /// 是否连接成功
public override bool Connect()
{
try
{
if (!Connectors.ContainsKey(_com))
- {
Connectors.Add(_com, new SerialPortLock
{
PortName = _com,
@@ -312,29 +361,33 @@ namespace Modbus.Net
DataBits = _dataBits,
ReadTimeout = _timeoutTime
});
- }
if (!Linkers.ContainsKey(_slave))
- {
Linkers.Add(_slave, _com);
- }
SerialPort.Open();
return true;
}
- catch (Exception e)
+ catch (Exception)
{
return false;
}
}
+ ///
+ /// 连接串口
+ ///
+ /// 是否连接成功
public override Task ConnectAsync()
{
return Task.FromResult(Connect());
}
+ ///
+ /// 断开串口
+ ///
+ /// 是否断开成功
public override bool Disconnect()
{
if (Linkers.ContainsKey(_slave) && Connectors.ContainsKey(_com))
- {
try
{
Dispose();
@@ -344,28 +397,43 @@ namespace Modbus.Net
{
return false;
}
- }
return false;
}
- public void SendMsg(string senStr)
+ ///
+ /// 带返回发送数据
+ ///
+ /// 需要发送的数据
+ /// 是否发送成功
+ public string SendMsg(string sendStr)
{
- var myByte = StringToByte_2(senStr);
+ var myByte = StringToByte_2(sendStr);
- SendMsg(myByte);
+ var returnBytes = SendMsg(myByte);
+
+ return ByteToString(returnBytes);
}
+ ///
+ /// 无返回发送数据
+ ///
+ /// 需要发送的数据
+ /// 是否发送成功
public override Task SendMsgWithoutReturnAsync(byte[] message)
{
return Task.FromResult(SendMsgWithoutReturn(message));
}
+ ///
+ /// 带返回发送数据
+ ///
+ /// 需要发送的数据
+ /// 是否发送成功
public override byte[] SendMsg(byte[] sendbytes)
{
try
{
if (!SerialPort.IsOpen)
- {
try
{
SerialPort.Open();
@@ -375,7 +443,6 @@ namespace Modbus.Net
Dispose();
SerialPort.Open();
}
- }
lock (SerialPort.Lock)
{
SerialPort.Write(sendbytes, 0, sendbytes.Length);
@@ -389,17 +456,26 @@ namespace Modbus.Net
}
}
+ ///
+ /// 带返回发送数据
+ ///
+ /// 需要发送的数据
+ /// 是否发送成功
public override Task SendMsgAsync(byte[] message)
{
return Task.FromResult(SendMsg(message));
}
+ ///
+ /// 无返回发送数据
+ ///
+ /// 需要发送的数据
+ /// 是否发送成功
public override bool SendMsgWithoutReturn(byte[] sendbytes)
{
try
{
if (!SerialPort.IsOpen)
- {
try
{
SerialPort.Open();
@@ -409,7 +485,6 @@ namespace Modbus.Net
Dispose();
SerialPort.Open();
}
- }
lock (SerialPort.Lock)
{
SerialPort.Write(sendbytes, 0, sendbytes.Length);
@@ -422,24 +497,12 @@ namespace Modbus.Net
}
}
- public string ReadMsgStr()
- {
- var rd = "";
-
- var data = ReadMsg();
-
- rd = ByteToString(data);
- return rd;
- }
-
- public byte[] ReadMsg()
+ private byte[] ReadMsg()
{
try
{
if (!SerialPort.IsOpen)
- {
SerialPort.Open();
- }
byte[] data;
Thread.Sleep(100);
diff --git a/Modbus.Net/Modbus.Net/ComProtocalLinker.cs b/Modbus.Net/Modbus.Net/ComProtocalLinker.cs
index 13d4461..98c7c89 100644
--- a/Modbus.Net/Modbus.Net/ComProtocalLinker.cs
+++ b/Modbus.Net/Modbus.Net/ComProtocalLinker.cs
@@ -15,6 +15,7 @@ namespace Modbus.Net
/// 校验位
/// 停止位
/// 数据位
+ /// 从站地址
protected ComProtocalLinker(int baudRate, Parity parity, StopBits stopBits, int dataBits, int slaveAddress)
: this(ConfigurationManager.AppSettings["COM"], baudRate, parity, stopBits, dataBits, slaveAddress)
{
@@ -28,6 +29,7 @@ namespace Modbus.Net
/// 校验位
/// 停止位
/// 数据位
+ /// 从站地址
protected ComProtocalLinker(string com, int baudRate, Parity parity, StopBits stopBits, int dataBits,
int slaveAddress)
: this(
@@ -45,10 +47,12 @@ namespace Modbus.Net
/// 停止位
/// 数据位
/// 超时时间
+ /// 从站地址
protected ComProtocalLinker(string com, int baudRate, Parity parity, StopBits stopBits, int dataBits,
int connectionTimeout, int slaveAddress)
{
- BaseConnector = new ComConnector(com + ":" + slaveAddress, baudRate, parity, stopBits, dataBits, connectionTimeout);
+ BaseConnector = new ComConnector(com + ":" + slaveAddress, baudRate, parity, stopBits, dataBits,
+ connectionTimeout);
}
}
}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/AddressCombiner.cs b/Modbus.Net/src/Base.Common/AddressCombiner.cs
index 4ad03d5..305fb93 100644
--- a/Modbus.Net/src/Base.Common/AddressCombiner.cs
+++ b/Modbus.Net/src/Base.Common/AddressCombiner.cs
@@ -34,7 +34,8 @@ namespace Modbus.Net
///
/// 地址转换器
/// 单个发送协议允许的数据最长长度(字节)
- public AddressCombinerContinus(AddressTranslator addressTranslator, int maxLength) : base(addressTranslator, maxLength)
+ public AddressCombinerContinus(AddressTranslator addressTranslator, int maxLength)
+ : base(addressTranslator, maxLength)
{
}
}
@@ -44,11 +45,6 @@ namespace Modbus.Net
///
public class AddressCombinerContinus : AddressCombiner where TKey : IEquatable
{
- ///
- /// 协议的数据最长长度(字节)
- ///
- protected int MaxLength { get; set; }
-
///
/// 构造函数
///
@@ -60,6 +56,11 @@ namespace Modbus.Net
MaxLength = maxLength;
}
+ ///
+ /// 协议的数据最长长度(字节)
+ ///
+ protected int MaxLength { get; set; }
+
///
/// 地址转换器
///
@@ -75,8 +76,8 @@ namespace Modbus.Net
//按从小到大的顺序对地址进行排序
var groupedAddresses = from address in addresses
orderby
- AddressHelper.GetProtocalCoordinate(address.Address, address.SubAddress,
- AddressTranslator.GetAreaByteLength(address.Area))
+ AddressHelper.GetProtocalCoordinate(address.Address, address.SubAddress,
+ AddressTranslator.GetAreaByteLength(address.Area))
group address by address.Area
into grouped
select grouped;
@@ -111,7 +112,7 @@ namespace Modbus.Net
{
//如果当前地址小于已经记录的地址域,表示这个地址的开始已经记录过了
if (AddressHelper.GetProtocalCoordinate(address.Address, address.SubAddress,
- AddressTranslator.GetAreaByteLength(address.Area)) <
+ AddressTranslator.GetAreaByteLength(address.Area)) <
AddressHelper.GetProtocalCoordinateNextPosition(preNum,
preType,
AddressTranslator.GetAreaByteLength(address.Area)))
@@ -119,20 +120,18 @@ namespace Modbus.Net
originalAddresses.Add(address);
//如果当前地址的末尾被记录,表示地址被记录的地址域覆盖,这个地址没有记录的必要
if (AddressHelper.GetProtocalCoordinateNextPosition(
- AddressHelper.GetProtocalCoordinate(address.Address, address.SubAddress,
- AddressTranslator.GetAreaByteLength(address.Area)),
- address.DataType,
- AddressTranslator.GetAreaByteLength(address.Area)) <=
+ AddressHelper.GetProtocalCoordinate(address.Address, address.SubAddress,
+ AddressTranslator.GetAreaByteLength(address.Area)),
+ address.DataType,
+ AddressTranslator.GetAreaByteLength(address.Area)) <=
AddressHelper.GetProtocalCoordinateNextPosition(preNum,
preType,
AddressTranslator.GetAreaByteLength(address.Area)))
- {
continue;
- }
}
//如果当前地址大于记录的地址域的开头,则表示地址已经不连续了
else if (AddressHelper.GetProtocalCoordinate(address.Address, address.SubAddress,
- AddressTranslator.GetAreaByteLength(address.Area)) >
+ AddressTranslator.GetAreaByteLength(address.Area)) >
AddressHelper.GetProtocalCoordinateNextPosition(preNum,
preType,
AddressTranslator.GetAreaByteLength(address.Area)))
@@ -144,12 +143,12 @@ namespace Modbus.Net
Address = (int) Math.Floor(initNum),
GetCount =
(int)
- Math.Ceiling(
- AddressHelper.MapProtocalGetCountToAbstractByteCount(
- preNum - (int) Math.Floor(initNum),
- AddressTranslator.GetAreaByteLength(address.Area),
- BigEndianValueHelper.Instance.ByteLength[preType.FullName])),
- DataType = typeof (byte),
+ Math.Ceiling(
+ AddressHelper.MapProtocalGetCountToAbstractByteCount(
+ preNum - (int) Math.Floor(initNum),
+ AddressTranslator.GetAreaByteLength(address.Area),
+ BigEndianValueHelper.Instance.ByteLength[preType.FullName])),
+ DataType = typeof(byte),
OriginalAddresses = originalAddresses.ToList()
});
initNum = address.Address;
@@ -174,24 +173,25 @@ namespace Modbus.Net
Address = (int) Math.Floor(initNum),
GetCount =
(int)
- Math.Ceiling(
- AddressHelper.MapProtocalGetCountToAbstractByteCount(
- preNum - (int) Math.Floor(initNum), AddressTranslator.GetAreaByteLength(area),
- BigEndianValueHelper.Instance.ByteLength[preType.FullName])),
- DataType = typeof (byte),
+ Math.Ceiling(
+ AddressHelper.MapProtocalGetCountToAbstractByteCount(
+ preNum - (int) Math.Floor(initNum), AddressTranslator.GetAreaByteLength(area),
+ BigEndianValueHelper.Instance.ByteLength[preType.FullName])),
+ DataType = typeof(byte),
OriginalAddresses = originalAddresses.ToList()
});
}
- List> newAns = new List>();
+ var newAns = new List>();
foreach (var communicationUnit in ans)
{
- double oldByteCount = communicationUnit.GetCount * BigEndianValueHelper.Instance.ByteLength[communicationUnit.DataType.FullName];
+ var oldByteCount = communicationUnit.GetCount *
+ BigEndianValueHelper.Instance.ByteLength[communicationUnit.DataType.FullName];
while (oldByteCount * BigEndianValueHelper.Instance.ByteLength[communicationUnit.DataType.FullName] >
MaxLength)
{
var newOriginalAddresses = new List>();
var oldOriginalAddresses = communicationUnit.OriginalAddresses.ToList();
- var newByteCount = 0.0;
+ var newByteCount = 0.0;
do
{
var currentAddressUnit = oldOriginalAddresses.First();
@@ -200,7 +200,6 @@ namespace Modbus.Net
oldByteCount -= BigEndianValueHelper.Instance.ByteLength[currentAddressUnit.DataType.FullName];
newOriginalAddresses.Add(currentAddressUnit);
oldOriginalAddresses.RemoveAt(0);
-
} while (newByteCount < MaxLength);
var newCommunicationUnit = new CommunicationUnit
{
@@ -212,9 +211,9 @@ namespace Modbus.Net
(int)
Math.Ceiling(newByteCount /
BigEndianValueHelper.Instance.ByteLength[communicationUnit.DataType.FullName]),
- OriginalAddresses = newOriginalAddresses,
+ OriginalAddresses = newOriginalAddresses
};
-
+
newAns.Add(newCommunicationUnit);
}
communicationUnit.GetCount =
@@ -334,12 +333,12 @@ namespace Modbus.Net
EndUnit = continusAddress,
GapNumber =
(int)
- Math.Ceiling(AddressHelper.MapProtocalCoordinateToAbstractCoordinate(
- continusAddress.Address, preCommunicationUnit.Address,
- AddressTranslator.GetAreaByteLength(continusAddress.Area)) -
- preCommunicationUnit.GetCount*
- BigEndianValueHelper.Instance.ByteLength[
- preCommunicationUnit.DataType.FullName])
+ Math.Ceiling(AddressHelper.MapProtocalCoordinateToAbstractCoordinate(
+ continusAddress.Address, preCommunicationUnit.Address,
+ AddressTranslator.GetAreaByteLength(continusAddress.Area)) -
+ preCommunicationUnit.GetCount *
+ BigEndianValueHelper.Instance.ByteLength[
+ preCommunicationUnit.DataType.FullName])
};
addressesGaps.Add(gap);
}
@@ -350,12 +349,14 @@ namespace Modbus.Net
var jumpNumberInner = JumpNumber;
foreach (var orderedGap in orderedGaps)
{
- if (orderedGap.GapNumber <= 0) continue;
+ if (orderedGap.GapNumber <= 0) continue;
var nowAddress = orderedGap.EndUnit;
var index = continusAddresses.IndexOf(nowAddress);
index--;
var preAddress = continusAddresses[index];
- if (nowAddress.GetCount*BigEndianValueHelper.Instance.ByteLength[nowAddress.DataType.FullName] + preAddress.GetCount*BigEndianValueHelper.Instance.ByteLength[preAddress.DataType.FullName] + orderedGap.GapNumber > MaxLength) continue;
+ if (nowAddress.GetCount * BigEndianValueHelper.Instance.ByteLength[nowAddress.DataType.FullName] +
+ preAddress.GetCount * BigEndianValueHelper.Instance.ByteLength[preAddress.DataType.FullName] +
+ orderedGap.GapNumber > MaxLength) continue;
jumpNumberInner -= orderedGap.GapNumber;
if (jumpNumberInner < 0) break;
continusAddresses.RemoveAt(index);
@@ -367,11 +368,11 @@ namespace Modbus.Net
Address = preAddress.Address,
GetCount =
(int)
- (preAddress.GetCount*BigEndianValueHelper.Instance.ByteLength[preAddress.DataType.FullName]) +
+ (preAddress.GetCount * BigEndianValueHelper.Instance.ByteLength[preAddress.DataType.FullName]) +
orderedGap.GapNumber +
(int)
- (nowAddress.GetCount*BigEndianValueHelper.Instance.ByteLength[nowAddress.DataType.FullName]),
- DataType = typeof (byte),
+ (nowAddress.GetCount * BigEndianValueHelper.Instance.ByteLength[nowAddress.DataType.FullName]),
+ DataType = typeof(byte),
OriginalAddresses = preAddress.OriginalAddresses.ToList().Union(nowAddress.OriginalAddresses)
};
continusAddresses.Insert(index, newAddress);
@@ -430,8 +431,9 @@ namespace Modbus.Net
var addressUnits = addresses as IList> ?? addresses.ToList();
var count = addressUnits.Sum(address => BigEndianValueHelper.Instance.ByteLength[address.DataType.FullName]);
return
- new AddressCombinerNumericJump((int) (count*Percentage/100.0), MaxLength, AddressTranslator).Combine(
- addressUnits);
+ new AddressCombinerNumericJump((int) (count * Percentage / 100.0), MaxLength, AddressTranslator)
+ .Combine(
+ addressUnits);
}
}
}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/AddressHelper.cs b/Modbus.Net/src/Base.Common/AddressHelper.cs
index cb8dcf9..ce16ee6 100644
--- a/Modbus.Net/src/Base.Common/AddressHelper.cs
+++ b/Modbus.Net/src/Base.Common/AddressHelper.cs
@@ -17,7 +17,7 @@ namespace Modbus.Net
public static double MapAbstractCoordinateToProtocalCoordinate(double abstractAddress, int startAddress,
double byteLength)
{
- return abstractAddress/byteLength + startAddress;
+ return abstractAddress / byteLength + startAddress;
}
///
@@ -30,7 +30,7 @@ namespace Modbus.Net
public static double MapProtocalCoordinateToAbstractCoordinate(double protocalAddress, int startAddress,
double byteLength)
{
- return (protocalAddress - startAddress)*byteLength;
+ return (protocalAddress - startAddress) * byteLength;
}
///
@@ -43,7 +43,7 @@ namespace Modbus.Net
public static double MapProtocalGetCountToAbstractByteCount(double protocalGetCount, double areaLength,
double byteLength)
{
- return protocalGetCount*areaLength + byteLength;
+ return protocalGetCount * areaLength + byteLength;
}
///
@@ -55,7 +55,7 @@ namespace Modbus.Net
///
public static double GetProtocalCoordinate(int address, int subAddress, double byteLength)
{
- return address + subAddress*(0.125/byteLength);
+ return address + subAddress * (0.125 / byteLength);
}
///
@@ -66,7 +66,7 @@ namespace Modbus.Net
///
public static double GetAbstractCoordinate(int address, int subAddress)
{
- return address + subAddress*0.125;
+ return address + subAddress * 0.125;
}
///
@@ -80,7 +80,7 @@ namespace Modbus.Net
double byteLength)
{
return protocalAddress +
- BigEndianValueHelper.Instance.ByteLength[nextPositionBetweenType.FullName]/byteLength;
+ BigEndianValueHelper.Instance.ByteLength[nextPositionBetweenType.FullName] / byteLength;
}
///
diff --git a/Modbus.Net/src/Base.Common/AddressTranslator.cs b/Modbus.Net/src/Base.Common/AddressTranslator.cs
index 39c1c68..98553a3 100644
--- a/Modbus.Net/src/Base.Common/AddressTranslator.cs
+++ b/Modbus.Net/src/Base.Common/AddressTranslator.cs
@@ -11,14 +11,17 @@ namespace Modbus.Net
/// 地址区域的字符串描述
///
public string AreaString { get; set; }
+
///
/// 地址区域的数字描述
///
public int Area { get; set; }
+
///
/// 地址
///
public int Address { get; set; }
+
///
/// 子地址
///
@@ -34,6 +37,7 @@ namespace Modbus.Net
/// 地址区域的编码
///
public int Code { get; set; }
+
///
/// 地址区域的单个地址占用的字节数
///
@@ -79,26 +83,22 @@ namespace Modbus.Net
if (split.Length == 2)
{
if (int.TryParse(split[0], out num1) && int.TryParse(split[1], out num2))
- {
return new AddressDef
{
Area = num1,
Address = num2
};
- }
}
else if (split.Length == 3)
{
if (int.TryParse(split[0], out num1) && int.TryParse(split[1], out num2) &&
int.TryParse(split[3], out num3))
- {
return new AddressDef
{
Area = num1,
Address = num2,
SubAddress = num3
};
- }
}
throw new FormatException();
}
diff --git a/Modbus.Net/src/Base.Common/AsyncHelper.cs b/Modbus.Net/src/Base.Common/AsyncHelper.cs
index 842fd28..ea16dce 100644
--- a/Modbus.Net/src/Base.Common/AsyncHelper.cs
+++ b/Modbus.Net/src/Base.Common/AsyncHelper.cs
@@ -5,7 +5,7 @@ using System.Threading.Tasks;
namespace Modbus.Net
{
///
- /// AsyncHelper Class
+ /// AsyncHelper Class
///
public static class AsyncHelper
{
diff --git a/Modbus.Net/src/Base.Common/BaseMachine.cs b/Modbus.Net/src/Base.Common/BaseMachine.cs
index 6f8bf21..3cfabb5 100644
--- a/Modbus.Net/src/Base.Common/BaseMachine.cs
+++ b/Modbus.Net/src/Base.Common/BaseMachine.cs
@@ -28,7 +28,7 @@ namespace Modbus.Net
///
/// Id
- ///
+ ///
Id
}
@@ -54,7 +54,7 @@ namespace Modbus.Net
///
/// Id
- ///
+ ///
Id
}
@@ -80,7 +80,7 @@ namespace Modbus.Net
///
/// Id
- ///
+ ///
Id
}
@@ -125,7 +125,8 @@ namespace Modbus.Net
///
/// 设备的Id类型
/// 设备中使用的AddressUnit的Id类型
- public abstract class BaseMachine : IMachineMethodData, IMachineProperty where TKey : IEquatable
+ public abstract class BaseMachine : IMachineMethodData, IMachineProperty
+ where TKey : IEquatable
where TUnitKey : IEquatable
{
private readonly int _maxErrorCount = 3;
@@ -166,11 +167,6 @@ namespace Modbus.Net
private int ErrorCount { get; set; }
- ///
- /// 是否处于连接状态
- ///
- public bool IsConnected => BaseUtility.IsConnected;
-
///
/// 地址编码器
///
@@ -206,11 +202,6 @@ namespace Modbus.Net
///
public IEnumerable> GetAddresses { get; set; }
- ///
- /// 是否保持连接
- ///
- public bool KeepConnect { get; set; }
-
///
/// 从站号
///
@@ -221,31 +212,6 @@ namespace Modbus.Net
///
public byte MasterAddress { get; set; }
- ///
- /// 设备的连接器
- ///
- public IUtilityProperty BaseUtility { get; protected set; }
-
- ///
- /// 设备的Id
- ///
- public TKey Id { get; set; }
-
- ///
- /// 设备所在工程的名称
- ///
- public string ProjectName { get; set; }
-
- ///
- /// 设备的名称
- ///
- public string MachineName { get; set; }
-
- ///
- /// 标识设备的连接关键字
- ///
- public string ConnectionToken => BaseUtility.ConnectionToken;
-
///
/// 读取数据
///
@@ -267,9 +233,7 @@ namespace Modbus.Net
var ans = new Dictionary();
//检测并连接设备
if (!BaseUtility.IsConnected)
- {
await BaseUtility.ConnectAsync();
- }
//如果无法连接,终止
if (!BaseUtility.IsConnected) return null;
//遍历每一个实际向设备获取数据的连续地址
@@ -282,17 +246,17 @@ namespace Modbus.Net
AddressFormater.FormatAddress(communicateAddress.Area, communicateAddress.Address,
communicateAddress.SubAddress),
(int)
- Math.Ceiling(communicateAddress.GetCount*
- BigEndianValueHelper.Instance.ByteLength[
- communicateAddress.DataType.FullName]));
+ Math.Ceiling(communicateAddress.GetCount *
+ BigEndianValueHelper.Instance.ByteLength[
+ communicateAddress.DataType.FullName]));
//如果没有数据,终止
- if (datas == null || (datas.Length != 0 && datas.Length <
- (int)
- Math.Ceiling(communicateAddress.GetCount*
- BigEndianValueHelper.Instance.ByteLength[
- communicateAddress.DataType.FullName])))
+ if (datas == null || datas.Length != 0 && datas.Length <
+ (int)
+ Math.Ceiling(communicateAddress.GetCount *
+ BigEndianValueHelper.Instance.ByteLength[
+ communicateAddress.DataType.FullName]))
return null;
@@ -300,13 +264,13 @@ namespace Modbus.Net
{
//字节坐标的位置
var localPos = AddressHelper.MapProtocalCoordinateToAbstractCoordinate(address.Address,
- communicateAddress.Address,
- AddressTranslator.GetAreaByteLength(communicateAddress.Area)) +
- address.SubAddress*0.125;
+ communicateAddress.Address,
+ AddressTranslator.GetAreaByteLength(communicateAddress.Area)) +
+ address.SubAddress * 0.125;
//字节坐标的主地址位置
var localMainPos = (int) localPos;
//字节坐标的子地址位置
- var localSubPos = (int) ((localPos - localMainPos)*8);
+ var localSubPos = (int) ((localPos - localMainPos) * 8);
//根据类型选择返回结果的键是通讯标识还是地址
string key;
@@ -341,16 +305,12 @@ namespace Modbus.Net
//如果没有数据返回空
if (datas.Length == 0)
- {
ans.Add(key, new ReturnUnit
{
PlcValue = null,
UnitExtend = address.UnitExtend
});
- }
else
- {
- //将获取的数据和对应的通讯标识对应
ans.Add(key,
new ReturnUnit
{
@@ -358,17 +318,14 @@ namespace Modbus.Net
Convert.ToDouble(
ValueHelper.GetInstance(BaseUtility.Endian)
.GetValue(datas, ref localMainPos, ref localSubPos,
- address.DataType))*address.Zoom,
+ address.DataType)) * address.Zoom,
UnitExtend = address.UnitExtend
});
- }
}
}
//如果不保持连接,断开连接
if (!KeepConnect)
- {
BaseUtility.Disconnect();
- }
//返回数据
if (ans.All(p => p.Value.PlcValue == null)) ans = null;
ErrorCount = 0;
@@ -379,9 +336,7 @@ namespace Modbus.Net
Console.WriteLine(ConnectionToken + " " + e.Message);
ErrorCount++;
if (ErrorCount >= _maxErrorCount)
- {
Disconnect();
- }
return null;
}
}
@@ -409,9 +364,7 @@ namespace Modbus.Net
{
//检测并连接设备
if (!BaseUtility.IsConnected)
- {
await BaseUtility.ConnectAsync();
- }
//如果设备无法连接,终止
if (!BaseUtility.IsConnected) return false;
var addresses = new List>();
@@ -428,8 +381,8 @@ namespace Modbus.Net
GetAddresses.SingleOrDefault(
p =>
AddressFormater.FormatAddress(p.Area, p.Address, p.SubAddress) == value.Key ||
- (p.DataType != typeof (bool) &&
- AddressFormater.FormatAddress(p.Area, p.Address) == value.Key));
+ p.DataType != typeof(bool) &&
+ AddressFormater.FormatAddress(p.Area, p.Address) == value.Key);
break;
}
case MachineSetDataType.CommunicationTag:
@@ -478,10 +431,11 @@ namespace Modbus.Net
var addressStart = AddressFormater.FormatAddress(communicateAddress.Area,
communicateAddress.Address);
- var datasReturn = await BaseUtility.InvokeUtilityMethod>("GetDatasAsync",
- AddressFormater.FormatAddress(communicateAddress.Area, communicateAddress.Address, 0),
- (int)
- Math.Ceiling(communicateAddress.GetCount*
+ var datasReturn =
+ await BaseUtility.InvokeUtilityMethod>("GetDatasAsync",
+ AddressFormater.FormatAddress(communicateAddress.Area, communicateAddress.Address, 0),
+ (int)
+ Math.Ceiling(communicateAddress.GetCount *
BigEndianValueHelper.Instance.ByteLength[
communicateAddress.DataType.FullName]));
@@ -492,9 +446,9 @@ namespace Modbus.Net
//如果没有数据,终止
if (datas == null || datas.Length <
(int)
- Math.Ceiling(communicateAddress.GetCount*
- BigEndianValueHelper.Instance.ByteLength[
- communicateAddress.DataType.FullName]))
+ Math.Ceiling(communicateAddress.GetCount *
+ BigEndianValueHelper.Instance.ByteLength[
+ communicateAddress.DataType.FullName]))
return false;
foreach (var addressUnit in communicateAddress.OriginalAddresses)
@@ -503,21 +457,21 @@ namespace Modbus.Net
var byteCount =
AddressHelper.MapProtocalGetCountToAbstractByteCount(
addressUnit.Address - communicateAddress.Address +
- addressUnit.SubAddress*0.125/
+ addressUnit.SubAddress * 0.125 /
AddressTranslator.GetAreaByteLength(communicateAddress.Area),
AddressTranslator.GetAreaByteLength(communicateAddress.Area), 0);
//字节坐标主地址
var mainByteCount = (int) byteCount;
//字节坐标自地址
- var localByteCount = (int) ((byteCount - (int) byteCount)*8);
+ var localByteCount = (int) ((byteCount - (int) byteCount) * 8);
//协议坐标地址
- var localPos = byteCount/AddressTranslator.GetAreaByteLength(communicateAddress.Area);
+ var localPos = byteCount / AddressTranslator.GetAreaByteLength(communicateAddress.Area);
//协议坐标子地址
var subPos =
(int)
- ((localPos - (int) localPos)/
- (0.125/AddressTranslator.GetAreaByteLength(communicateAddress.Area)));
+ ((localPos - (int) localPos) /
+ (0.125 / AddressTranslator.GetAreaByteLength(communicateAddress.Area)));
//协议主地址字符串
var address = AddressFormater.FormatAddress(communicateAddress.Area,
communicateAddress.Address + (int) localPos, subPos);
@@ -536,7 +490,7 @@ namespace Modbus.Net
//获取要写入的值
value =
values.SingleOrDefault(
- p => p.Key == address || (address2 != null && p.Key == address2));
+ p => p.Key == address || address2 != null && p.Key == address2);
break;
}
case MachineSetDataType.CommunicationTag:
@@ -561,22 +515,20 @@ namespace Modbus.Net
}
}
//将要写入的值加入队列
- var data = Convert.ChangeType(value.Value/addressUnit.Zoom, dataType);
+ var data = Convert.ChangeType(value.Value / addressUnit.Zoom, dataType);
if (!valueHelper.SetValue(datas, mainByteCount, localByteCount, data))
return false;
}
//写入数据
await
- BaseUtility.InvokeUtilityMethod>("SetDatasAsync",addressStart,
+ BaseUtility.InvokeUtilityMethod>("SetDatasAsync", addressStart,
valueHelper.ByteArrayToObjectArray(datas,
new KeyValuePair(communicateAddress.DataType, communicateAddress.GetCount)));
}
//如果不保持连接,断开连接
if (!KeepConnect)
- {
BaseUtility.Disconnect();
- }
}
catch (Exception e)
{
@@ -587,22 +539,39 @@ namespace Modbus.Net
}
///
- /// 通过Id获取数据字段定义
+ /// 是否处于连接状态
///
- /// 数据字段Id
- /// 数据字段
- public AddressUnit GetAddressUnitById(TUnitKey addressUnitId)
- {
- try
- {
- return GetAddresses.SingleOrDefault(p => p.Id.Equals(addressUnitId));
- }
- catch (Exception)
- {
- Console.WriteLine("Id重复,请检查");
- return null;
- }
- }
+ public bool IsConnected => BaseUtility.IsConnected;
+
+ ///
+ /// 是否保持连接
+ ///
+ public bool KeepConnect { get; set; }
+
+ ///
+ /// 设备的连接器
+ ///
+ public IUtilityProperty BaseUtility { get; protected set; }
+
+ ///
+ /// 设备的Id
+ ///
+ public TKey Id { get; set; }
+
+ ///
+ /// 设备所在工程的名称
+ ///
+ public string ProjectName { get; set; }
+
+ ///
+ /// 设备的名称
+ ///
+ public string MachineName { get; set; }
+
+ ///
+ /// 标识设备的连接关键字
+ ///
+ public string ConnectionToken => BaseUtility.ConnectionToken;
///
/// 调用Machine中的方法
@@ -617,24 +586,14 @@ namespace Modbus.Net
{
if (this is TMachineMethod)
{
- Type t = typeof(TMachineMethod);
- object returnValue = t.GetRuntimeMethod(methodName, parameters.Select(p => p.GetType()).ToArray())
+ var t = typeof(TMachineMethod);
+ var returnValue = t.GetRuntimeMethod(methodName, parameters.Select(p => p.GetType()).ToArray())
.Invoke(this, parameters);
return (TReturnType) returnValue;
}
throw new InvalidCastException($"Machine未实现{typeof(TMachineMethod).Name}的接口");
}
- ///
- /// 获取Utility
- ///
- /// Utility实现的接口名称
- ///
- public TUtilityMethod GetUtility() where TUtilityMethod : class, IUtilityMethod
- {
- return BaseUtility as TUtilityMethod;
- }
-
///
/// 连接设备
///
@@ -670,6 +629,34 @@ namespace Modbus.Net
{
return Id.ToString();
}
+
+ ///
+ /// 通过Id获取数据字段定义
+ ///
+ /// 数据字段Id
+ /// 数据字段
+ public AddressUnit GetAddressUnitById(TUnitKey addressUnitId)
+ {
+ try
+ {
+ return GetAddresses.SingleOrDefault(p => p.Id.Equals(addressUnitId));
+ }
+ catch (Exception)
+ {
+ Console.WriteLine("Id重复,请检查");
+ return null;
+ }
+ }
+
+ ///
+ /// 获取Utility
+ ///
+ /// Utility实现的接口名称
+ ///
+ public TUtilityMethod GetUtility() where TUtilityMethod : class, IUtilityMethod
+ {
+ return BaseUtility as TUtilityMethod;
+ }
}
internal class BaseMachineEqualityComparer : IEqualityComparer>
@@ -832,7 +819,7 @@ namespace Modbus.Net
/// 是否一致
public bool Equals(AddressUnit other)
{
- return (Area.ToUpper() == other.Area.ToUpper() && Address == other.Address) || Id.Equals(other.Id);
+ return Area.ToUpper() == other.Area.ToUpper() && Address == other.Address || Id.Equals(other.Id);
}
}
@@ -915,6 +902,6 @@ namespace Modbus.Net
///
/// Id
///
- TKey Id { get; set; }
+ TKey Id { get; set; }
}
}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/BaseMachineExtend.cs b/Modbus.Net/src/Base.Common/BaseMachineExtend.cs
index 019bbb2..7fb0b73 100644
--- a/Modbus.Net/src/Base.Common/BaseMachineExtend.cs
+++ b/Modbus.Net/src/Base.Common/BaseMachineExtend.cs
@@ -20,7 +20,7 @@ namespace Modbus.Net
return (from getValue in getValues
where getValue.Value.PlcValue != null
select new KeyValuePair(getValue.Key, getValue.Value.PlcValue.Value)).ToDictionary(
- p => p.Key, p => p.Value);
+ p => p.Key, p => p.Value);
}
}
}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/BaseProtocal.cs b/Modbus.Net/src/Base.Common/BaseProtocal.cs
index 627be11..5b7b5f7 100644
--- a/Modbus.Net/src/Base.Common/BaseProtocal.cs
+++ b/Modbus.Net/src/Base.Common/BaseProtocal.cs
@@ -13,7 +13,8 @@ namespace Modbus.Net
///
/// 构造器
///
- protected BaseProtocal(byte slaveAddress, byte masterAddress, Endian endian) : base(slaveAddress, masterAddress, endian)
+ protected BaseProtocal(byte slaveAddress, byte masterAddress, Endian endian)
+ : base(slaveAddress, masterAddress, endian)
{
}
@@ -25,13 +26,9 @@ namespace Modbus.Net
public override async Task SendReceiveAsync(params object[] content)
{
if (ProtocalLinker == null || !ProtocalLinker.IsConnected)
- {
await ConnectAsync();
- }
if (ProtocalLinker != null)
- {
return await ProtocalLinker.SendReceiveAsync(ProtocalUnit.TranslateContent(Endian, content));
- }
return null;
}
}
@@ -39,7 +36,8 @@ namespace Modbus.Net
///
/// 基本协议
///
- public abstract class BaseProtocal : IProtocal where TProtocalUnit : ProtocalUnit
+ public abstract class BaseProtocal :
+ IProtocal where TProtocalUnit : ProtocalUnit
{
///
/// 构造器
@@ -56,11 +54,12 @@ namespace Modbus.Net
/// 协议的端格式
///
protected Endian Endian { get; set; }
-
+
///
/// 从站地址
///
public byte SlaveAddress { get; set; }
+
///
/// 主站地址
///
@@ -82,12 +81,10 @@ namespace Modbus.Net
{
var protocalName = type.FullName;
if (Protocals.ContainsKey(protocalName))
- {
return Protocals[protocalName];
- }
//自动寻找存在的协议并将其加载
var protocalUnit =
- Activator.CreateInstance(type.GetTypeInfo().Assembly.GetType(protocalName)) as TProtocalUnit;
+ Activator.CreateInstance(type.GetTypeInfo().Assembly.GetType(protocalName)) as TProtocalUnit;
if (protocalUnit == null) throw new InvalidCastException("没有相应的协议内容");
protocalUnit.Endian = Endian;
Register(protocalUnit);
@@ -100,16 +97,6 @@ namespace Modbus.Net
///
protected Dictionary Protocals { get; }
- ///
- /// 注册一个协议
- ///
- /// 需要注册的协议
- protected void Register(TProtocalUnit linkProtocal)
- {
- if (linkProtocal == null) return;
- Protocals.Add(linkProtocal.GetType().FullName, linkProtocal);
- }
-
///
/// 发送协议,通过传入需要使用的协议内容和输入结构
///
@@ -121,18 +108,6 @@ namespace Modbus.Net
return AsyncHelper.RunSync(() => SendReceiveAsync(unit, content));
}
- ///
- /// 发送协议,通过传入需要使用的协议内容和输入结构
- ///
- /// 协议的实例
- /// 输入信息的结构化描述
- /// 输出信息的结构化描述
- /// IOutputStruct的具体类型
- public virtual T SendReceive(TProtocalUnit unit, IInputStruct content) where T : class, IOutputStruct
- {
- return AsyncHelper.RunSync(() => SendReceiveAsync(unit, content));
- }
-
///
/// 发送协议,通过传入需要使用的协议内容和输入结构
///
@@ -141,40 +116,9 @@ namespace Modbus.Net
/// 输出信息的结构化描述
public virtual async Task SendReceiveAsync(TProtocalUnit unit, IInputStruct content)
{
- return await SendReceiveAsync(unit, content);
+ return await SendReceiveAsync(unit, content);
}
- ///
- /// 发送协议,通过传入需要使用的协议内容和输入结构
- ///
- /// 协议的实例
- /// 输入信息的结构化描述
- /// 输出信息的结构化描述
- /// IOutputStruct的具体类型
- public virtual async Task SendReceiveAsync(TProtocalUnit unit, IInputStruct content) where T : class, IOutputStruct
- {
- var t = 0;
- var formatContent = unit.Format(content);
- if (formatContent != null)
- {
- TParamOut receiveContent;
- //如果为特别处理协议的话,跳过协议扩展收缩
- if (unit is ISpecialProtocalUnit)
- {
- receiveContent = await ProtocalLinker.SendReceiveWithoutExtAndDecAsync(formatContent);
- }
- else
- {
- receiveContent = await ProtocalLinker.SendReceiveAsync(formatContent);
- }
- if (receiveContent != null)
- {
- return unit.Unformat(receiveContent, ref t);
- }
- }
- return null;
- }
-
///
/// 发送协议内容并接收,一般方法
///
@@ -195,6 +139,54 @@ namespace Modbus.Net
throw new NotImplementedException();
}
+ ///
+ /// 注册一个协议
+ ///
+ /// 需要注册的协议
+ protected void Register(TProtocalUnit linkProtocal)
+ {
+ if (linkProtocal == null) return;
+ Protocals.Add(linkProtocal.GetType().FullName, linkProtocal);
+ }
+
+ ///
+ /// 发送协议,通过传入需要使用的协议内容和输入结构
+ ///
+ /// 协议的实例
+ /// 输入信息的结构化描述
+ /// 输出信息的结构化描述
+ /// IOutputStruct的具体类型
+ public virtual T SendReceive(TProtocalUnit unit, IInputStruct content) where T : class, IOutputStruct
+ {
+ return AsyncHelper.RunSync(() => SendReceiveAsync(unit, content));
+ }
+
+ ///
+ /// 发送协议,通过传入需要使用的协议内容和输入结构
+ ///
+ /// 协议的实例
+ /// 输入信息的结构化描述
+ /// 输出信息的结构化描述
+ /// IOutputStruct的具体类型
+ public virtual async Task SendReceiveAsync(TProtocalUnit unit, IInputStruct content)
+ where T : class, IOutputStruct
+ {
+ var t = 0;
+ var formatContent = unit.Format(content);
+ if (formatContent != null)
+ {
+ TParamOut receiveContent;
+ //如果为特别处理协议的话,跳过协议扩展收缩
+ if (unit is ISpecialProtocalUnit)
+ receiveContent = await ProtocalLinker.SendReceiveWithoutExtAndDecAsync(formatContent);
+ else
+ receiveContent = await ProtocalLinker.SendReceiveAsync(formatContent);
+ if (receiveContent != null)
+ return unit.Unformat(receiveContent, ref t);
+ }
+ return null;
+ }
+
///
/// 协议连接开始
///
@@ -214,9 +206,7 @@ namespace Modbus.Net
public virtual bool Disconnect()
{
if (ProtocalLinker != null)
- {
return ProtocalLinker.Disconnect();
- }
return false;
}
}
diff --git a/Modbus.Net/src/Base.Common/BaseUtility.cs b/Modbus.Net/src/Base.Common/BaseUtility.cs
index 86172fb..09a4dde 100644
--- a/Modbus.Net/src/Base.Common/BaseUtility.cs
+++ b/Modbus.Net/src/Base.Common/BaseUtility.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Reflection;
using System.Threading.Tasks;
///
@@ -13,10 +12,12 @@ public enum Endian
/// 小端
///
LittleEndianLsb,
+
///
/// 大端-小端位
///
BigEndianLsb,
+
///
/// 大端-大端位
///
@@ -26,7 +27,7 @@ public enum Endian
namespace Modbus.Net
{
///
- /// 基础Api入口
+ /// 基础Api入口
///
public abstract class BaseUtility : BaseUtility
{
@@ -35,14 +36,14 @@ namespace Modbus.Net
///
protected BaseUtility(byte slaveAddress, byte masterAddress) : base(slaveAddress, masterAddress)
{
-
}
}
///
- /// 基础Api入口
+ /// 基础Api入口
///
- public abstract class BaseUtility : IUtilityProperty, IUtilityMethodData where TProtocalUnit : ProtocalUnit
+ public abstract class BaseUtility : IUtilityProperty, IUtilityMethodData
+ where TProtocalUnit : ProtocalUnit
{
///
/// 协议收发主体
@@ -68,37 +69,12 @@ namespace Modbus.Net
/// 从站号
///
public byte SlaveAddress { get; set; }
+
///
/// 主站号
///
public byte MasterAddress { get; set; }
- ///
- /// 协议是否遵循小端格式
- ///
- public abstract Endian Endian { get; }
-
- ///
- /// 设备是否已经连接
- ///
- public bool IsConnected => Wrapper?.ProtocalLinker != null && Wrapper.ProtocalLinker.IsConnected;
-
- ///
- /// 标识设备的连接关键字
- ///
- public string ConnectionToken => Wrapper?.ProtocalLinker == null ? ConnectionString : Wrapper.ProtocalLinker.ConnectionToken;
-
- ///
- /// 地址翻译器
- ///
- public AddressTranslator AddressTranslator { get; set; }
-
- ///
- /// 设置连接类型
- ///
- /// 连接类型
- public abstract void SetConnectionType(int connectionType);
-
///
/// 获取数据
///
@@ -144,17 +120,16 @@ namespace Modbus.Net
var typeName = getTypeAndCount.Key.FullName;
var bCount = BigEndianValueHelper.Instance.ByteLength[typeName];
var getReturnValue = await GetDatasAsync(startAddress,
- (int) Math.Ceiling(bCount*getTypeAndCount.Value));
+ (int) Math.Ceiling(bCount * getTypeAndCount.Value));
var getBytes = getReturnValue;
return ValueHelper.GetInstance(Endian).ByteArrayToObjectArray(getBytes, getTypeAndCount);
-
}
catch (Exception)
{
return null;
}
}
-
+
///
/// 获取数据
///
@@ -181,7 +156,7 @@ namespace Modbus.Net
try
{
var getBytes = await GetDatasAsync(startAddress,
- new KeyValuePair(typeof (T), getByteCount));
+ new KeyValuePair(typeof(T), getByteCount));
return ValueHelper.GetInstance(Endian).ObjectArrayToDestinationArray(getBytes);
}
catch (Exception)
@@ -203,7 +178,7 @@ namespace Modbus.Net
AsyncHelper.RunSync(() => GetDatasAsync(startAddress, getTypeAndCountList));
}
- /// GetEndian
+ ///
/// 获取数据
///
/// 开始地址
@@ -219,7 +194,7 @@ namespace Modbus.Net
from getTypeAndCount in translateTypeAndCount
let typeName = getTypeAndCount.Key.FullName
let bCount = BigEndianValueHelper.Instance.ByteLength[typeName]
- select (int) Math.Ceiling(bCount*getTypeAndCount.Value)).Sum();
+ select (int) Math.Ceiling(bCount * getTypeAndCount.Value)).Sum();
var getReturnValue = await GetDatasAsync(startAddress, bAllCount);
var getBytes = getReturnValue;
return ValueHelper.GetInstance(Endian).ByteArrayToObjectArray(getBytes, translateTypeAndCount);
@@ -249,6 +224,27 @@ namespace Modbus.Net
/// 是否设置成功
public abstract Task SetDatasAsync(string startAddress, object[] setContents);
+ ///
+ /// 协议是否遵循小端格式
+ ///
+ public abstract Endian Endian { get; }
+
+ ///
+ /// 设备是否已经连接
+ ///
+ public bool IsConnected => Wrapper?.ProtocalLinker != null && Wrapper.ProtocalLinker.IsConnected;
+
+ ///
+ /// 标识设备的连接关键字
+ ///
+ public string ConnectionToken
+ => Wrapper?.ProtocalLinker == null ? ConnectionString : Wrapper.ProtocalLinker.ConnectionToken;
+
+ ///
+ /// 地址翻译器
+ ///
+ public AddressTranslator AddressTranslator { get; set; }
+
///
/// 连接设备
///
@@ -289,13 +285,19 @@ namespace Modbus.Net
{
if (this is TUtilityMethod)
{
- Type t = typeof(TUtilityMethod);
- object returnValue = t.GetRuntimeMethod(methodName, parameters.Select(p => p.GetType()).ToArray(), false)
+ var t = typeof(TUtilityMethod);
+ var returnValue = t.GetRuntimeMethod(methodName, parameters.Select(p => p.GetType()).ToArray(), false)
.Invoke(this, parameters);
- return (TReturnType)returnValue;
+ return (TReturnType) returnValue;
}
throw new InvalidCastException($"Utility未实现{typeof(TUtilityMethod).Name}的接口");
}
+
+ ///
+ /// 设置连接类型
+ ///
+ /// 连接类型
+ public abstract void SetConnectionType(int connectionType);
}
///
@@ -312,6 +314,7 @@ namespace Modbus.Net
/// 设备是否已经连接
///
bool IsConnected { get; }
+
///
/// 标识设备的连接关键字
///
diff --git a/Modbus.Net/src/Base.Common/CRC16.cs b/Modbus.Net/src/Base.Common/CRC16.cs
index 5303dba..478d6e2 100644
--- a/Modbus.Net/src/Base.Common/CRC16.cs
+++ b/Modbus.Net/src/Base.Common/CRC16.cs
@@ -14,16 +14,15 @@ namespace Modbus.Net
{
private static Crc16 _crc16;
- private Crc16()
- {
-
- }
-
///
/// CRC验证表
///
private byte[] crc_table = new byte[512];
+ private Crc16()
+ {
+ }
+
///
/// 获取校验工具实例
///
@@ -31,9 +30,7 @@ namespace Modbus.Net
public static Crc16 GetInstance()
{
if (_crc16 == null)
- {
_crc16 = new Crc16();
- }
return _crc16;
}
@@ -51,7 +48,9 @@ namespace Modbus.Net
CRC = 0xFFFF;
//set all 1
if (Len <= 0)
+ {
CRC = 0;
+ }
else
{
Len--;
@@ -59,13 +58,10 @@ namespace Modbus.Net
{
CRC = CRC ^ message[IX];
for (IY = 0; IY <= 7; IY++)
- {
if ((CRC & 1) != 0)
CRC = (CRC >> 1) ^ 0xA001;
else
CRC = CRC >> 1;
- //
- }
}
}
Rcvbuf[1] = (byte) ((CRC & 0xff00) >> 8); //高位置
@@ -91,9 +87,7 @@ namespace Modbus.Net
Array.Copy(byteframe, 0, byteArr, 0, byteArr.Length);
GetCRC(byteArr, ref recvbuff);
if (recvbuff[0] == byteframe[byteframe.Length - 2] && recvbuff[1] == byteframe[byteframe.Length - 1])
- {
return true;
- }
return false;
}
@@ -121,7 +115,7 @@ namespace Modbus.Net
for (var t = 0; t <= hexArray.GetUpperBound(0); t++)
{
- if ((hexArray[t] >= 48) && (hexArray[t] <= 57))
+ if (hexArray[t] >= 48 && hexArray[t] <= 57)
decNum = hexArray[t] - 48;
@@ -130,7 +124,7 @@ namespace Modbus.Net
if (msb)
{
- decNumMSB = decNum*16;
+ decNumMSB = decNum * 16;
msb = false;
}
else
@@ -154,12 +148,11 @@ namespace Modbus.Net
for (i = 0; decByteTotal > 0; i++)
{
//b = Convert.ToInt32(System.Math.Pow(16.0, i));
- var a = decByteTotal%16;
+ var a = decByteTotal % 16;
decByteTotal /= 16;
if (a <= 9)
hexByte = a.ToString();
else
- {
switch (a)
{
case 10:
@@ -181,7 +174,6 @@ namespace Modbus.Net
hexByte = "F";
break;
}
- }
hexTotal = string.Concat(hexByte, hexTotal);
}
return hexTotal == checkString;
@@ -200,15 +192,12 @@ namespace Modbus.Net
{
byte sum = 0;
foreach (var b in code)
- {
sum += b;
- }
- sum = (byte)(~sum + 1); //取反+1
+ sum = (byte) (~sum + 1); //取反+1
var lrc = sum.ToString("X2");
return lrc;
}
#endregion
-
}
}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/IMachineMethod.cs b/Modbus.Net/src/Base.Common/IMachineMethod.cs
index c5fc50b..31f23ab 100644
--- a/Modbus.Net/src/Base.Common/IMachineMethod.cs
+++ b/Modbus.Net/src/Base.Common/IMachineMethod.cs
@@ -1,7 +1,4 @@
-using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using System.Threading.Tasks;
namespace Modbus.Net
@@ -11,7 +8,6 @@ namespace Modbus.Net
///
public interface IMachineMethod
{
-
}
///
diff --git a/Modbus.Net/src/Base.Common/IProtocal.cs b/Modbus.Net/src/Base.Common/IProtocal.cs
index b2b4fae..2bb48bd 100644
--- a/Modbus.Net/src/Base.Common/IProtocal.cs
+++ b/Modbus.Net/src/Base.Common/IProtocal.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Threading.Tasks;
namespace Modbus.Net
{
@@ -12,7 +8,8 @@ namespace Modbus.Net
/// 向Connector传入的类型
/// 从Connector返回的类型
/// 协议单元的类型
- public interface IProtocal where TProtocalUnit : IProtocalFormatting
+ public interface IProtocal
+ where TProtocalUnit : IProtocalFormatting
{
///
/// 发送协议内容并接收,一般方法
@@ -44,4 +41,4 @@ namespace Modbus.Net
/// 输出信息的结构化描述
Task SendReceiveAsync(TProtocalUnit unit, IInputStruct content);
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/IProtocalFormatting.cs b/Modbus.Net/src/Base.Common/IProtocalFormatting.cs
index d494e8c..b9ff233 100644
--- a/Modbus.Net/src/Base.Common/IProtocalFormatting.cs
+++ b/Modbus.Net/src/Base.Common/IProtocalFormatting.cs
@@ -5,7 +5,6 @@
///
public interface IProtocalFormatting : IProtocalFormatting
{
-
}
///
@@ -38,12 +37,12 @@
IOutputStruct Unformat(TParamOut messageBytes, ref int pos);
///
- /// 把仪器返回的内容填充到输出结构中
- ///
- /// 返回数据的字节流
- /// 转换标记位
- /// IOutputStruct的具体类型
- /// 结构化的输出数据
+ /// 把仪器返回的内容填充到输出结构中
+ ///
+ /// 返回数据的字节流
+ /// 转换标记位
+ /// IOutputStruct的具体类型
+ /// 结构化的输出数据
T Unformat(TParamOut messageBytes, ref int pos) where T : class, IOutputStruct;
}
}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/IProtocalLinker.cs b/Modbus.Net/src/Base.Common/IProtocalLinker.cs
index 94633ad..eb1091a 100644
--- a/Modbus.Net/src/Base.Common/IProtocalLinker.cs
+++ b/Modbus.Net/src/Base.Common/IProtocalLinker.cs
@@ -1,8 +1,4 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
+using System.Threading.Tasks;
namespace Modbus.Net
{
@@ -62,4 +58,4 @@ namespace Modbus.Net
/// 缩减后的协议内容
TParamOut BytesDecact(TParamOut content);
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/IProtocalLinkerBytesExtend.cs b/Modbus.Net/src/Base.Common/IProtocalLinkerBytesExtend.cs
index 77f168e..ef2af9d 100644
--- a/Modbus.Net/src/Base.Common/IProtocalLinkerBytesExtend.cs
+++ b/Modbus.Net/src/Base.Common/IProtocalLinkerBytesExtend.cs
@@ -5,7 +5,6 @@
///
public interface IProtocalLinkerBytesExtend : IProtocalLinkerBytesExtend
{
-
}
///
diff --git a/Modbus.Net/src/Base.Common/IUtilityMethod.cs b/Modbus.Net/src/Base.Common/IUtilityMethod.cs
index a6b9deb..ce526ee 100644
--- a/Modbus.Net/src/Base.Common/IUtilityMethod.cs
+++ b/Modbus.Net/src/Base.Common/IUtilityMethod.cs
@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using System.Threading.Tasks;
namespace Modbus.Net
@@ -11,7 +9,6 @@ namespace Modbus.Net
///
public interface IUtilityMethod
{
-
}
///
@@ -19,6 +16,14 @@ namespace Modbus.Net
///
public interface IUtilityMethodData : IUtilityMethod
{
+ ///
+ /// 获取数据
+ ///
+ /// 开始地址
+ /// 获取字节数个数
+ /// 接收到的byte数据
+ byte[] GetDatas(string startAddress, int getByteCount);
+
///
/// 获取数据
///
@@ -69,7 +74,7 @@ namespace Modbus.Net
/// 获取数据的对象数组,请强制转换成相应类型
object[] GetDatas(string startAddress, IEnumerable> getTypeAndCountList);
- /// GetEndian
+ ///
/// 获取数据
///
/// 开始地址
@@ -94,11 +99,10 @@ namespace Modbus.Net
}
///
- /// Utility的时间读写接口
+ /// Utility的时间读写接口
///
public interface IUtilityMethodTime : IUtilityMethod
{
-
///
/// 获取PLC时间
///
@@ -111,6 +115,5 @@ namespace Modbus.Net
/// 设置PLC时间
/// 设置是否成功
Task SetTimeAsync(DateTime setTime);
-
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/ProtocalLinker.cs b/Modbus.Net/src/Base.Common/ProtocalLinker.cs
index 3ec9995..bd7accd 100644
--- a/Modbus.Net/src/Base.Common/ProtocalLinker.cs
+++ b/Modbus.Net/src/Base.Common/ProtocalLinker.cs
@@ -45,7 +45,8 @@ namespace Modbus.Net
{
//自动查找相应的协议放缩类,命令规则为——当前的实际类名(注意是继承后的)+"BytesExtend"。
var bytesExtend =
- Activator.CreateInstance(GetType().GetTypeInfo().Assembly.GetType(GetType().FullName + "BytesExtend")) as
+ Activator.CreateInstance(GetType().GetTypeInfo().Assembly.GetType(GetType().FullName + "BytesExtend"))
+ as
IProtocalLinkerBytesExtend;
return bytesExtend?.BytesExtend(content);
}
@@ -59,7 +60,8 @@ namespace Modbus.Net
{
//自动查找相应的协议放缩类,命令规则为——当前的实际类名(注意是继承后的)+"BytesExtend"。
var bytesExtend =
- Activator.CreateInstance(GetType().GetTypeInfo().Assembly.GetType(GetType().FullName + "BytesExtend")) as
+ Activator.CreateInstance(GetType().GetTypeInfo().Assembly.GetType(GetType().FullName + "BytesExtend"))
+ as
IProtocalLinkerBytesExtend;
return bytesExtend?.BytesDecact(content);
}
@@ -85,33 +87,6 @@ namespace Modbus.Net
///
public bool IsConnected => BaseConnector != null && BaseConnector.IsConnected;
- ///
- /// 连接设备
- ///
- /// 设备是否连接成功
- public bool Connect()
- {
- return BaseConnector.Connect();
- }
-
- ///
- /// 连接设备
- ///
- /// 设备是否连接成功
- public async Task ConnectAsync()
- {
- return await BaseConnector.ConnectAsync();
- }
-
- ///
- /// 断开设备
- ///
- /// 设备是否断开成功
- public bool Disconnect()
- {
- return BaseConnector.Disconnect();
- }
-
///
/// 发送并接收数据
///
@@ -192,5 +167,32 @@ namespace Modbus.Net
{
throw new NotImplementedException();
}
+
+ ///
+ /// 连接设备
+ ///
+ /// 设备是否连接成功
+ public bool Connect()
+ {
+ return BaseConnector.Connect();
+ }
+
+ ///
+ /// 连接设备
+ ///
+ /// 设备是否连接成功
+ public async Task ConnectAsync()
+ {
+ return await BaseConnector.ConnectAsync();
+ }
+
+ ///
+ /// 断开设备
+ ///
+ /// 设备是否断开成功
+ public bool Disconnect()
+ {
+ return BaseConnector.Disconnect();
+ }
}
}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/ProtocalUnit.cs b/Modbus.Net/src/Base.Common/ProtocalUnit.cs
index f10c579..5360a73 100644
--- a/Modbus.Net/src/Base.Common/ProtocalUnit.cs
+++ b/Modbus.Net/src/Base.Common/ProtocalUnit.cs
@@ -7,7 +7,6 @@ namespace Modbus.Net
///
public abstract class ProtocalUnit : ProtocalUnit
{
-
}
///
@@ -20,12 +19,12 @@ namespace Modbus.Net
///
public Endian Endian { get; set; } = Endian.BigEndianLsb;
- ///
- /// 从输入结构格式化
- /// s
- /// 结构化的输入数据
- /// 格式化后的字节流
- public abstract TParamIn Format(IInputStruct message);
+ ///
+ /// 从输入结构格式化
+ ///
+ /// 结构化的输入数据
+ /// 格式化后的字节流
+ public abstract TParamIn Format(IInputStruct message);
///
/// 从对象的参数数组格式化
@@ -37,25 +36,25 @@ namespace Modbus.Net
return TranslateContent(Endian, message);
}
- ///
- /// 把仪器返回的内容填充到输出结构中
- ///
- /// 返回数据的字节流
- /// 转换标记位
- /// 结构化的输出数据
- public abstract IOutputStruct Unformat(TParamOut messageBytes, ref int pos);
+ ///
+ /// 把仪器返回的内容填充到输出结构中
+ ///
+ /// 返回数据的字节流
+ /// 转换标记位
+ /// 结构化的输出数据
+ public abstract IOutputStruct Unformat(TParamOut messageBytes, ref int pos);
- ///
- /// 把仪器返回的内容填充到输出结构中
- ///
- /// 返回数据的字节流
- /// 转换标记位
- /// IOutputStruct的具体类型
- /// 结构化的输出数据
- public T Unformat(TParamOut messageBytes, ref int pos) where T : class, IOutputStruct
- {
- return Unformat(messageBytes, ref pos) as T;
- }
+ ///
+ /// 把仪器返回的内容填充到输出结构中
+ ///
+ /// 返回数据的字节流
+ /// 转换标记位
+ /// IOutputStruct的具体类型
+ /// 结构化的输出数据
+ public T Unformat(TParamOut messageBytes, ref int pos) where T : class, IOutputStruct
+ {
+ return Unformat(messageBytes, ref pos) as T;
+ }
///
/// 转换静态方法,把对象数组转换为字节数组。
@@ -64,8 +63,8 @@ namespace Modbus.Net
/// 对象数组
/// 字节数组
public static byte[] TranslateContent(Endian endian, params object[] contents)
- {
- return ValueHelper.GetInstance(endian).ObjectArrayToByteArray(contents);
+ {
+ return ValueHelper.GetInstance(endian).ObjectArrayToByteArray(contents);
}
}
diff --git a/Modbus.Net/src/Base.Common/TaskManager.cs b/Modbus.Net/src/Base.Common/TaskManager.cs
index e73aa17..3169381 100644
--- a/Modbus.Net/src/Base.Common/TaskManager.cs
+++ b/Modbus.Net/src/Base.Common/TaskManager.cs
@@ -17,7 +17,6 @@ namespace Modbus.Net
///
public class DataReturnDef : DataReturnDef
{
-
}
///
@@ -29,6 +28,7 @@ namespace Modbus.Net
/// 设备的Id
///
public TMachineKey MachineId { get; set; }
+
///
/// 返回的数据值
///
@@ -141,7 +141,7 @@ namespace Modbus.Net
TryExecuteTask(item);
}
}
- // We're done processing items on the current thread
+ // We're done processing items on the current thread
finally
{
_currentThreadIsProcessingItems = false;
@@ -176,7 +176,10 @@ namespace Modbus.Net
///
protected sealed override bool TryDequeue(Task task)
{
- lock (_tasks) return _tasks.Remove(task);
+ lock (_tasks)
+ {
+ return _tasks.Remove(task);
+ }
}
///
@@ -213,7 +216,7 @@ namespace Modbus.Net
private readonly TaskFactory _tasks;
///
- /// 构造函数
+ /// 构造函数
///
/// 设备
/// 任务工厂
@@ -278,11 +281,9 @@ namespace Modbus.Net
/// 是否停止成功
public bool StopAllTimers()
{
- bool ans = true;
+ var ans = true;
foreach (var task in TasksWithTimer)
- {
ans = ans && StopTimer(task.Name);
- }
return ans;
}
@@ -308,11 +309,9 @@ namespace Modbus.Net
/// 是否暂停成功
public bool PauseAllTimers()
{
- bool ans = true;
+ var ans = true;
foreach (var task in TasksWithTimer)
- {
ans = ans && PauseTimer(task.Name);
- }
return ans;
}
@@ -338,11 +337,9 @@ namespace Modbus.Net
/// 是否恢复成功
public bool ContinueAllTimers()
{
- bool ans = true;
+ var ans = true;
foreach (var task in TasksWithTimer)
- {
ans = ans && ContinueTimer(task.Name);
- }
return ans;
}
@@ -427,7 +424,7 @@ namespace Modbus.Net
return new DataReturnDef
{
MachineId = machine.GetMachineIdString(),
- ReturnValues = ans,
+ ReturnValues = ans
};
};
Params = null;
@@ -436,7 +433,7 @@ namespace Modbus.Net
TimerTime = getCycle;
}
}
-
+
///
/// 写入数据的预定义任务
///
@@ -461,7 +458,7 @@ namespace Modbus.Net
MachineSetDataType.CommunicationTag).WithCancellation(cts.Token));
return ans;
};
- Params = new object[]{values};
+ Params = new object[] {values};
Return = returnFunc;
}
}
@@ -472,46 +469,51 @@ namespace Modbus.Net
/// 任务返回值的类型
public class TaskItem : ITaskItem, IEquatable>
{
- ///
- /// 名称
- ///
- public string Name { get; set; }
///
/// 定时器
///
private Timer Timer { get; set; }
+
///
/// 定时器的时间
///
public int TimerTime { get; set; }
+
///
/// 离线定时器
///
private Timer TimerDisconnected { get; set; }
+
///
/// 离线定时器的时间
///
public int TimerDisconnectedTime { get; set; }
+
///
/// 执行的任务
///
public Func> Invoke { get; set; }
+
///
/// 检测设备的在线状态
///
- internal Func DetectConnected { get; set; }
+ internal Func DetectConnected { get; set; }
+
///
/// 任务执行的参数
///
public object[] Params { get; set; }
+
///
/// 返回值的处理函数
///
public Action Return { get; set; }
+
///
/// 获取设备
///
internal Func GetMachine { get; set; }
+
///
/// 获取任务工厂
///
@@ -527,6 +529,11 @@ namespace Modbus.Net
return Name == other?.Name;
}
+ ///
+ /// 名称
+ ///
+ public string Name { get; set; }
+
///
/// 启动定时器
///
@@ -537,6 +544,17 @@ namespace Modbus.Net
return true;
}
+ ///
+ /// 停止定时器
+ ///
+ ///
+ public bool StopTimer()
+ {
+ DeactivateTimer();
+ DeactivateTimerDisconnected();
+ return true;
+ }
+
///
/// 激活定时器
///
@@ -545,7 +563,7 @@ namespace Modbus.Net
Timer = new Timer(async state =>
{
if (!DetectConnected()) TimerChangeToDisconnect();
- var ans = await Invoke(GetMachine(),GetTaskFactory(),Params);
+ var ans = await Invoke(GetMachine(), GetTaskFactory(), Params);
Return?.Invoke(ans);
}, null, 0, TimerTime);
}
@@ -601,17 +619,6 @@ namespace Modbus.Net
ActivateTimerDisconnected();
return true;
}
-
- ///
- /// 停止定时器
- ///
- ///
- public bool StopTimer()
- {
- DeactivateTimer();
- DeactivateTimerDisconnected();
- return true;
- }
}
///
@@ -719,16 +726,6 @@ namespace Modbus.Net
_tasks = new TaskFactory(_cts.Token, TaskCreationOptions.None, TaskContinuationOptions.None, _scheduler);
}
- ///
- /// 强制停止所有正在运行的任务
- ///
- public void TaskHalt()
- {
- _cts.Cancel();
- _cts = new CancellationTokenSource();
- _tasks = new TaskFactory(_cts.Token, TaskCreationOptions.None, TaskContinuationOptions.None, _scheduler);
- }
-
///
/// 保持连接
///
@@ -742,9 +739,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
machine.Machine.KeepConnect = _keepConnect;
- }
}
ContinueTimerAll();
}
@@ -791,6 +786,7 @@ namespace Modbus.Net
/// 设备读数据的关键字
///
public MachineGetDataType GetDataType { get; set; }
+
///
/// 设备写数据的关键字
///
@@ -810,6 +806,16 @@ namespace Modbus.Net
}
}
+ ///
+ /// 强制停止所有正在运行的任务
+ ///
+ public void TaskHalt()
+ {
+ _cts.Cancel();
+ _cts = new CancellationTokenSource();
+ _tasks = new TaskFactory(_cts.Token, TaskCreationOptions.None, TaskContinuationOptions.None, _scheduler);
+ }
+
///
/// 添加一台设备
///
@@ -834,9 +840,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in machines)
- {
AddMachine(machine);
- }
}
}
@@ -922,7 +926,7 @@ namespace Modbus.Net
{
lock (_machines)
{
- _machines.RemoveWhere(p=>p.Machine.Equals(machine));
+ _machines.RemoveWhere(p => p.Machine.Equals(machine));
}
}
@@ -938,9 +942,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
ans &= machine.InvokeTimer(item);
- }
}
return ans;
}
@@ -955,9 +957,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
ans &= machine.StopAllTimers();
- }
}
return ans;
}
@@ -973,9 +973,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
ans &= machine.StopTimer(taskItemName);
- }
}
return ans;
}
@@ -990,9 +988,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
ans &= machine.PauseAllTimers();
- }
}
return ans;
}
@@ -1008,9 +1004,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
ans &= machine.PauseTimer(taskItemName);
- }
}
return ans;
}
@@ -1025,9 +1019,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
ans &= machine.ContinueAllTimers();
- }
}
return ans;
}
@@ -1042,9 +1034,7 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
machine.ContinueTimer(taskItemName);
- }
}
return true;
}
@@ -1061,12 +1051,10 @@ namespace Modbus.Net
lock (_machines)
{
foreach (var machine in _machines)
- {
tasks.Add(machine.InvokeOnce(item));
- }
}
var ans = await Task.WhenAll(tasks);
- return ans.All(p=>p);
+ return ans.All(p => p);
}
///
@@ -1080,9 +1068,7 @@ namespace Modbus.Net
{
var machine = _machines.FirstOrDefault(p => p.Machine.Id.Equals(machineId));
if (machine != null)
- {
return await machine.InvokeOnce(item);
- }
return false;
}
@@ -1097,9 +1083,7 @@ namespace Modbus.Net
{
var machine = _machines.FirstOrDefault(p => p.Machine.Id.Equals(machineId));
if (machine != null)
- {
return machine.InvokeTimer(item);
- }
return false;
}
@@ -1113,9 +1097,7 @@ namespace Modbus.Net
{
var machine = _machines.FirstOrDefault(p => p.Machine.Id.Equals(machineId));
if (machine != null)
- {
return machine.StopTimer(taskItemName);
- }
return false;
}
@@ -1129,9 +1111,7 @@ namespace Modbus.Net
{
var machine = _machines.FirstOrDefault(p => p.Machine.Id.Equals(machineId));
if (machine != null)
- {
return machine.PauseTimer(taskItemName);
- }
return false;
}
@@ -1145,9 +1125,7 @@ namespace Modbus.Net
{
var machine = _machines.FirstOrDefault(p => p.Machine.Id.Equals(machineId));
if (machine != null)
- {
return machine.ContinueTimer(taskItemName);
- }
return false;
}
}
diff --git a/Modbus.Net/src/Base.Common/TcpConnector.cs b/Modbus.Net/src/Base.Common/TcpConnector.cs
index 2b354e3..8317870 100644
--- a/Modbus.Net/src/Base.Common/TcpConnector.cs
+++ b/Modbus.Net/src/Base.Common/TcpConnector.cs
@@ -74,9 +74,7 @@ namespace Modbus.Net
{
_timeoutTime = value;
if (_socketClient != null)
- {
_socketClient.ReceiveTimeout = _timeoutTime;
- }
}
}
@@ -144,9 +142,7 @@ namespace Modbus.Net
public override async Task ConnectAsync()
{
if (_socketClient != null)
- {
Disconnect();
- }
try
{
_socketClient = new TcpClient
@@ -187,9 +183,7 @@ namespace Modbus.Net
public override bool Disconnect()
{
if (_socketClient == null)
- {
return true;
- }
try
{
@@ -239,9 +233,7 @@ namespace Modbus.Net
try
{
if (!IsConnected)
- {
await ConnectAsync();
- }
var stream = _socketClient.GetStream();
await stream.WriteAsync(datagram, 0, datagram.Length);
@@ -280,9 +272,7 @@ namespace Modbus.Net
try
{
if (!IsConnected)
- {
await ConnectAsync();
- }
var stream = _socketClient.GetStream();
await stream.WriteAsync(datagram, 0, datagram.Length);
@@ -313,9 +303,7 @@ namespace Modbus.Net
stream.Flush();
// 异步接收回答
if (len > 0)
- {
return CheckReplyDatagram(len);
- }
return null;
}
catch (Exception err)
@@ -339,9 +327,7 @@ namespace Modbus.Net
RefreshReceiveCount();
if (len <= 0)
- {
RefreshErrorCount();
- }
return replyMessage;
}
diff --git a/Modbus.Net/src/Base.Common/TcpProtocalLinker.cs b/Modbus.Net/src/Base.Common/TcpProtocalLinker.cs
index b353cd8..6a86707 100644
--- a/Modbus.Net/src/Base.Common/TcpProtocalLinker.cs
+++ b/Modbus.Net/src/Base.Common/TcpProtocalLinker.cs
@@ -1,4 +1,5 @@
-#if NET40||NET45||NET451||NET452||NET46||NET461||NET462||NET47
+
+#if NET40||NET45||NET451||NET452||NET46||NET461||NET462||NET47
using System.Configuration;
#endif
diff --git a/Modbus.Net/src/Base.Common/TypeExtensions.cs b/Modbus.Net/src/Base.Common/TypeExtensions.cs
index fb8778d..b81436f 100644
--- a/Modbus.Net/src/Base.Common/TypeExtensions.cs
+++ b/Modbus.Net/src/Base.Common/TypeExtensions.cs
@@ -1,10 +1,7 @@
using System;
-using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
-using System.Text;
-using System.Threading.Tasks;
namespace Modbus.Net
{
@@ -16,21 +13,21 @@ namespace Modbus.Net
#region Public Methods
///
- /// Looks for the method in the type matching the name and arguments.
+ /// Looks for the method in the type matching the name and arguments.
///
///
///
- /// The name of the method to find.
+ /// The name of the method to find.
///
///
- /// The types of the method's arguments to match.
+ /// The types of the method's arguments to match.
///
///
- /// Is method Generic Method.
+ /// Is method Generic Method.
///
///
///
- /// Thrown if:
+ /// Thrown if:
/// - The name of the method is not specified.
///
public static MethodInfo GetRuntimeMethod(this Type type, string methodName, Type[] args, bool isGenericMethod)
@@ -42,26 +39,23 @@ namespace Modbus.Net
throw new ArgumentNullException("methodName", "The name of the method has not been specified.");
- var methods = type.GetRuntimeMethods().Where(methodInfo => string.Equals(methodInfo.Name, methodName, StringComparison.OrdinalIgnoreCase)).ToList();
+ var methods =
+ type.GetRuntimeMethods()
+ .Where(methodInfo => string.Equals(methodInfo.Name, methodName, StringComparison.OrdinalIgnoreCase))
+ .ToList();
if (!methods.Any())
- return null; // No methods have the specified name.
+ return null; // No methods have the specified name.
if (isGenericMethod)
- {
methods = methods.Where(method => method.IsGenericMethod).ToList();
- }
else
- {
methods = methods.Where(method => !method.IsGenericMethod).ToList();
- }
var ans = methods.Where(method => IsSignatureMatch(method, args));
if (ans.Count() <= 1)
- {
- return ans.Count() == 1 ? ans.Single() : null;
- }
+ return ans.Count() == 1 ? ans.Single() : null;
// Oh noes, don't make me go there.
throw new NotImplementedException("Resolving overloaded methods is not implemented as of now.");
@@ -72,7 +66,7 @@ namespace Modbus.Net
#region Private Methods
///
- /// Finds out if the provided arguments matches the specified method's signature.
+ /// Finds out if the provided arguments matches the specified method's signature.
///
///
///
@@ -83,11 +77,11 @@ namespace Modbus.Net
// Gets the parameters of the method to analyze.
- ParameterInfo[] parameters = methodInfo.GetParameters();
+ var parameters = methodInfo.GetParameters();
- int currentArgId = 0;
+ var currentArgId = 0;
- foreach (ParameterInfo parameterInfo in parameters)
+ foreach (var parameterInfo in parameters)
{
if (!ReferenceEquals(args, null) && currentArgId < args.Length)
{
@@ -102,7 +96,7 @@ namespace Modbus.Net
if (parameterInfo.ParameterType.IsGenericParameter)
{
// Gets the base type of the generic parameter.
- Type baseType = parameterInfo.ParameterType.GetTypeInfo().BaseType;
+ var baseType = parameterInfo.ParameterType.GetTypeInfo().BaseType;
// TODO: This is not good v and works with the most simple situation.
@@ -129,4 +123,4 @@ namespace Modbus.Net
#endregion
}
-}
+}
\ No newline at end of file
diff --git a/Modbus.Net/src/Base.Common/ValueHelper.cs b/Modbus.Net/src/Base.Common/ValueHelper.cs
index 01b34b3..01a2897 100644
--- a/Modbus.Net/src/Base.Common/ValueHelper.cs
+++ b/Modbus.Net/src/Base.Common/ValueHelper.cs
@@ -410,7 +410,7 @@ namespace Modbus.Net
var temp = data[pos];
for (var i = 0; i < 8; i++)
{
- t[i] = temp%2 > 0;
+ t[i] = temp % 2 > 0;
temp /= 2;
}
pos += 1;
@@ -427,11 +427,11 @@ namespace Modbus.Net
public bool GetBit(byte number, ref int pos, ref int subPos)
{
if (subPos < 0 && subPos >= 8) throw new IndexOutOfRangeException();
- var ans = number%2;
+ var ans = number % 2;
var i = 0;
while (i <= subPos)
{
- ans = number%2;
+ ans = number % 2;
number /= 2;
i++;
}
@@ -491,7 +491,7 @@ namespace Modbus.Net
b = true;
//自动将目标数组中内含的子数组展开,是所有包含在子数组拼接为一个数组
var contentArray =
- ArrayList.Adapter((Array) content).ToArray(typeof (object)).OfType