diff --git a/Modbus.Net/ModBus.Net/BaseMachine.cs b/Modbus.Net/ModBus.Net/BaseMachine.cs index 02c57b0..8506694 100644 --- a/Modbus.Net/ModBus.Net/BaseMachine.cs +++ b/Modbus.Net/ModBus.Net/BaseMachine.cs @@ -55,6 +55,7 @@ namespace ModBus.Net foreach (var communicateAddress in CommunicateAddresses) { var datas = BaseUtility.GetDatas(2, 0, AddressFormater.FormatAddress(communicateAddress.Area,communicateAddress.Address), communicateAddress.GetCount); + if (datas == null) return null; int pos = 0; while (pos < communicateAddress.GetCount) { diff --git a/Modbus.Net/ModBus.Net/BaseUtility.cs b/Modbus.Net/ModBus.Net/BaseUtility.cs index dbbaecf..108ac5b 100644 --- a/Modbus.Net/ModBus.Net/BaseUtility.cs +++ b/Modbus.Net/ModBus.Net/BaseUtility.cs @@ -49,31 +49,55 @@ namespace ModBus.Net public virtual object[] GetDatas(byte belongAddress, byte masterAddress, string startAddress, KeyValuePair getTypeAndCount) { - string typeName = getTypeAndCount.Key.FullName; - double bCount = ValueHelper.Instance.ByteLength[typeName]; - byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress, (int)Math.Ceiling(bCount * getTypeAndCount.Value)); - return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount); + try + { + string typeName = getTypeAndCount.Key.FullName; + double bCount = ValueHelper.Instance.ByteLength[typeName]; + byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress, + (int) Math.Ceiling(bCount*getTypeAndCount.Value)); + return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCount); + } + catch (Exception) + { + return null; + } } public virtual T[] GetDatas(byte belongAddress, byte masterAddress, string startAddress, int getByteCount) { - var getBytes = GetDatas(belongAddress, masterAddress, startAddress, new KeyValuePair(typeof(T), getByteCount)); - return ValueHelper.Instance.ObjectArrayToDestinationArray(getBytes); + try + { + var getBytes = GetDatas(belongAddress, masterAddress, startAddress, + new KeyValuePair(typeof (T), getByteCount)); + return ValueHelper.Instance.ObjectArrayToDestinationArray(getBytes); + } + catch (Exception) + { + return null; + } } public virtual object[] GetDatas(byte belongAddress, byte masterAddress, string startAddress, IEnumerable> getTypeAndCountList) { - int bAllCount = 0; - foreach (var getTypeAndCount in getTypeAndCountList) + try { - string typeName = getTypeAndCount.Key.FullName; - double bCount = ValueHelper.Instance.ByteLength[typeName]; - bAllCount += (int)Math.Ceiling(bCount*getTypeAndCount.Value); + int bAllCount = 0; + foreach (var getTypeAndCount in getTypeAndCountList) + { + string typeName = getTypeAndCount.Key.FullName; + double bCount = ValueHelper.Instance.ByteLength[typeName]; + bAllCount += (int)Math.Ceiling(bCount * getTypeAndCount.Value); + } + byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress, bAllCount); + return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList); } - byte[] getBytes = GetDatas(belongAddress, masterAddress, startAddress, bAllCount); - return ValueHelper.Instance.ByteArrayToObjectArray(getBytes, getTypeAndCountList); + catch (Exception) + { + return null; + } + } /// /// 设置数据 diff --git a/Modbus.Net/ModBus.Net/TaskManager.cs b/Modbus.Net/ModBus.Net/TaskManager.cs index e710ccd..c1e3113 100644 --- a/Modbus.Net/ModBus.Net/TaskManager.cs +++ b/Modbus.Net/ModBus.Net/TaskManager.cs @@ -225,7 +225,7 @@ namespace ModBus.Net _timer.Elapsed += MaintainTasks; } _timer.Start(); - MaintainTasks(null,null); + //MaintainTasks(null,null); } } } @@ -259,9 +259,12 @@ namespace ModBus.Net public void AddMachines(IEnumerable machines) { - foreach (var machine in machines) + lock (_machines) { - AddMachine(machine); + foreach (var machine in machines) + { + AddMachine(machine); + } } } @@ -289,14 +292,22 @@ namespace ModBus.Net } } + private void MaintainTasks(object sender, System.Timers.ElapsedEventArgs e) { + AsyncHelper.RunSync(MaintainTasksAsync); + } + + private async Task MaintainTasksAsync() + { + HashSet saveMachines = new HashSet(); lock (_machines) { - foreach (var machine in _machines) - { - RunTask(machine); - } + saveMachines.UnionWith(_machines); + } + foreach (var machine in saveMachines) + { + await RunTask(machine); } } @@ -327,12 +338,12 @@ namespace ModBus.Net } } - private void RunTask(BaseMachine machine) + private async Task RunTask(BaseMachine machine) { try { //var ans = machine.GetDatas(); - var ans = _tasks.StartNew(machine.GetDatas).Result; + var ans = await _tasks.StartNew(machine.GetDatas); if (ReturnValues != null) { ReturnValues(new KeyValuePair>(machine.Id, ans)); diff --git a/Modbus.Net/ModBus.Net/TcpConnector.cs b/Modbus.Net/ModBus.Net/TcpConnector.cs index d971036..cec9e35 100644 --- a/Modbus.Net/ModBus.Net/TcpConnector.cs +++ b/Modbus.Net/ModBus.Net/TcpConnector.cs @@ -1,5 +1,7 @@ using System; +using System.Net; using System.Net.Sockets; +using System.Threading; using System.Threading.Tasks; namespace ModBus.Net @@ -61,7 +63,10 @@ namespace ModBus.Net public override bool IsConnected { - get { return _socketClient != null && _socketClient.Connected; } + get + { + return _socketClient != null && _socketClient.Client != null && _socketClient.Connected; + } } public void Dispose() @@ -78,7 +83,59 @@ namespace ModBus.Net return AsyncHelper.RunSync(ConnectAsync); } + private ManualResetEvent _timeoutObject = new ManualResetEvent(false); + private bool _isConnectionSuccessful; public override async Task ConnectAsync() + { + _timeoutObject.Reset(); + _socketClient = new TcpClient(); + _socketClient.BeginConnect(_host, _port, new AsyncCallback(CallBackMethod), _socketClient); + if (_timeoutObject.WaitOne(TimeoutTime, false)) + { + if (_isConnectionSuccessful) + { + AddInfo("client connected."); + return true; + } + else + { + AddInfo("connect failed."); + _socketClient = null; + return false; + } + } + else + { + _socketClient.Close(); + AddInfo("connect failed."); + _socketClient = null; + return false; + } + } + + private void CallBackMethod(IAsyncResult asyncresult) + { + try + { + _isConnectionSuccessful = false; + TcpClient tcpclient = asyncresult.AsyncState as TcpClient; + if (tcpclient != null && tcpclient.Client != null) + { + _isConnectionSuccessful = true; + } + } + catch (Exception ex) + { + AddInfo("client connected exception: " + ex.Message); + _isConnectionSuccessful = false; + } + finally + { + _timeoutObject.Set(); + } + } + + /*public override async Task ConnectAsync() { if (_socketClient != null) { @@ -88,7 +145,8 @@ namespace ModBus.Net { _socketClient = new TcpClient { - ReceiveTimeout = TimeoutTime + SendTimeout = TimeoutTime, + ReceiveTimeout = TimeoutTime }; try @@ -113,7 +171,7 @@ namespace ModBus.Net AddInfo("client connect exception: " + err.Message); return false; } - } + }*/ public override bool Disconnect() {