-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathModbusPlc2Service.cs
More file actions
88 lines (76 loc) · 2.3 KB
/
ModbusPlc2Service.cs
File metadata and controls
88 lines (76 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using SimpleHmi.PlcService;
using System.Net.Sockets;
using Modbus.Device;
namespace SimpleHmi.Plc2Service
{
public class ModbusPlc2Service : IPlc2Service
{
private readonly System.Timers.Timer _timer;
private TcpClient _client;
private ModbusIpMaster _master;
private DateTime _lastScanTime;
public ConnectionStates ConnectionState { get; private set; }
public TimeSpan ScanTime { get; private set; }
public bool FirstOutput { get; private set; }
public event EventHandler ValuesRefreshed;
public ModbusPlc2Service()
{
_timer = new System.Timers.Timer();
_timer.Elapsed += OnTimerElapsed;
_timer.Interval = 100;
}
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
if (_master == null || (ConnectionState != ConnectionStates.Online))
{
return;
}
try
{
_timer.Stop();
ScanTime = DateTime.Now - _lastScanTime;
RefreshValues();
OnValuesRefreshed();
}
finally
{
_timer.Start();
}
_lastScanTime = DateTime.Now;
}
private void RefreshValues()
{
var coils = _master.ReadCoils(1, 0, 1);
FirstOutput = coils[0];
}
public void Connect()
{
ConnectionState = ConnectionStates.Connecting;
_client = new TcpClient("127.0.0.1", 502);
_master = ModbusIpMaster.CreateIp(_client);
ConnectionState = ConnectionStates.Online;
_timer.Start();
}
public void Disconnect()
{
_timer.Stop();
_master.Dispose();
_client.Close();
ConnectionState = ConnectionStates.Offline;
}
private void OnValuesRefreshed()
{
ValuesRefreshed?.Invoke(this, new EventArgs());
}
public Task WriteFirstOutput(bool value)
{
return _master.WriteSingleCoilAsync(1, 0, value);
}
}
}