2015-07-17 update 1

This commit is contained in:
parallelbgls
2015-07-17 16:20:33 +08:00
parent 8fef63bd3c
commit 8c9901b137
5 changed files with 40 additions and 73 deletions

View File

@@ -29,5 +29,17 @@ namespace ModBus.Net
.GetAwaiter() .GetAwaiter()
.GetResult(); .GetResult();
} }
public static Task WithCancellation(this Task task,
CancellationToken token)
{
return task.ContinueWith(t => t.GetAwaiter().GetResult(), token);
}
public static Task<T> WithCancellation<T>(this Task<T> task,
CancellationToken token)
{
return task.ContinueWith(t => t.GetAwaiter().GetResult(), token);
}
} }
} }

View File

@@ -64,7 +64,7 @@ namespace ModBus.Net
p => p.Area == communicateAddress.Area && p.Address == pos + communicateAddress.Address); p => p.Area == communicateAddress.Area && p.Address == pos + communicateAddress.Address);
if (address != null) if (address != null)
{ {
ans.Add(address.CommunicationTag, new ReturnUnit{PlcValue = Math.Round(Single.Parse(ValueHelper.Instance.GetValue(datas, ref pos, address.DataType).ToString()) * address.Zoom, address.DataType == typeof(System.Single) || address.DataType == typeof(System.Double) ? 3 : (Math.Log10(address.Zoom) > 0 ? 0 : (int)Math.Ceiling(-Math.Log10(address.Zoom)))).ToString(),UnitExtend = address.UnitExtend}); ans.Add(address.CommunicationTag, new ReturnUnit{PlcValue = Double.Parse(ValueHelper.Instance.GetValue(datas, ref pos, address.DataType).ToString()) * address.Zoom,UnitExtend = address.UnitExtend});
} }
else else
{ {
@@ -123,7 +123,7 @@ namespace ModBus.Net
public class ReturnUnit public class ReturnUnit
{ {
public string PlcValue { get; set; } public double PlcValue { get; set; }
public UnitExtend UnitExtend { get; set; } public UnitExtend UnitExtend { get; set; }
} }
@@ -140,6 +140,7 @@ namespace ModBus.Net
/// 放缩比例 /// 放缩比例
/// </summary> /// </summary>
public double Zoom { get; set; } public double Zoom { get; set; }
public int DecimalPos { get; set; }
/// <summary> /// <summary>
/// 通讯标识名称 /// 通讯标识名称
/// </summary> /// </summary>

View File

@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
[assembly: AssemblyConfiguration("")] [assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("杭州德联科技股份有限公司")] [assembly: AssemblyCompany("杭州德联科技股份有限公司")]
[assembly: AssemblyProduct("ModBus.Net")] [assembly: AssemblyProduct("ModBus.Net")]
[assembly: AssemblyCopyright("Copyright © Chris L. 2014 HangZhou Delin Technology")] [assembly: AssemblyCopyright("Copyright © Chris L. 2014 HangZhou Delian Technology")]
[assembly: AssemblyTrademark("")] [assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")] [assembly: AssemblyCulture("")]
@@ -35,5 +35,5 @@ using System.Runtime.InteropServices;
// 方法是按如下所示使用“*”: // 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")] // [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.2.0415")] [assembly: AssemblyVersion("0.2.5.0716")]
[assembly: AssemblyFileVersion("0.2.2.0415")] [assembly: AssemblyFileVersion("0.2.5.0716")]

View File

@@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Timer = System.Timers.Timer;
namespace ModBus.Net namespace ModBus.Net
@@ -170,6 +169,7 @@ namespace ModBus.Net
private TaskFactory<Dictionary<string,ReturnUnit>> _tasks; private TaskFactory<Dictionary<string,ReturnUnit>> _tasks;
private TaskScheduler _scheduler; private TaskScheduler _scheduler;
private CancellationTokenSource _cts; private CancellationTokenSource _cts;
private Timer _timer; private Timer _timer;
private bool _keepConnect; private bool _keepConnect;
@@ -205,27 +205,30 @@ namespace ModBus.Net
get { return _getCycle; } get { return _getCycle; }
set set
{ {
if (value == _getCycle) return;
if (value == Timeout.Infinite) if (value == Timeout.Infinite)
{ {
if (_timer != null) if (_timer != null)
{ {
_timer.Stop(); _timer.Change(Timeout.Infinite, Timeout.Infinite);
} }
} }
else if (value < 0) return;
else else
{ {
if (_timer != null)
{
_timer.Change(Timeout.Infinite, Timeout.Infinite);
_timer.Dispose();
_timer = null;
}
if (value > 0) if (value > 0)
{ {
_getCycle = value; _getCycle = value;
} }
if (_timer != null) _timer.Interval = _getCycle*1000; _timer = new Timer(MaintainTasks, null, 0, _getCycle * 1000);
else //MaintainTasks(null);
{
_timer = new Timer(_getCycle*1000);
_timer.Elapsed += MaintainTasks;
}
_timer.Start();
//MaintainTasks(null,null);
} }
} }
} }
@@ -293,7 +296,7 @@ namespace ModBus.Net
} }
private void MaintainTasks(object sender, System.Timers.ElapsedEventArgs e) private void MaintainTasks(object sender)
{ {
AsyncHelper.RunSync(MaintainTasksAsync); AsyncHelper.RunSync(MaintainTasksAsync);
} }
@@ -343,7 +346,9 @@ namespace ModBus.Net
try try
{ {
//var ans = machine.GetDatas(); //var ans = machine.GetDatas();
var ans = await _tasks.StartNew(machine.GetDatas); CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(_getCycle * 2));
var ans = await _tasks.StartNew(machine.GetDatas, cts.Token);
if (ReturnValues != null) if (ReturnValues != null)
{ {
ReturnValues(new KeyValuePair<int, Dictionary<string,ReturnUnit>>(machine.Id, ans)); ReturnValues(new KeyValuePair<int, Dictionary<string,ReturnUnit>>(machine.Id, ans));

View File

@@ -82,59 +82,7 @@ namespace ModBus.Net
return AsyncHelper.RunSync(ConnectAsync); return AsyncHelper.RunSync(ConnectAsync);
} }
private ManualResetEvent _timeoutObject = new ManualResetEvent(false);
private bool _isConnectionSuccessful;
public override async Task<bool> ConnectAsync() public override async Task<bool> ConnectAsync()
{
_timeoutObject.Reset();
_socketClient = new TcpClient();
_socketClient.BeginConnect(_host, _port, 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<bool> ConnectAsync()
{ {
if (_socketClient != null) if (_socketClient != null)
{ {
@@ -150,7 +98,9 @@ namespace ModBus.Net
try try
{ {
await _socketClient.ConnectAsync(_host, _port); CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TimeoutTime);
await _socketClient.ConnectAsync(_host, _port).WithCancellation(cts.Token);
} }
catch (Exception e) catch (Exception e)
{ {
@@ -158,7 +108,6 @@ namespace ModBus.Net
} }
if (_socketClient.Connected) if (_socketClient.Connected)
{ {
_stream = _socketClient.GetStream();
AddInfo("client connected."); AddInfo("client connected.");
return true; return true;
} }
@@ -170,7 +119,7 @@ namespace ModBus.Net
AddInfo("client connect exception: " + err.Message); AddInfo("client connect exception: " + err.Message);
return false; return false;
} }
}*/ }
public override bool Disconnect() public override bool Disconnect()
{ {