-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPLCController.cs
350 lines (319 loc) · 11.7 KB
/
PLCController.cs
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace mujinplccs
{
public sealed class PLCController
{
private PLCMemory memory = null;
private string heartbeatSignal = "";
private DateTime lastHeartbeatTimestamp = DateTime.MinValue;
private TimeSpan? maxHeartbeatInterval = null;
private Dictionary<string, object> state = new Dictionary<string, object>();
private BlockingCollection<IDictionary<string, object>> queue = new BlockingCollection<IDictionary<string, object>>(
new ConcurrentQueue<IDictionary<string, object>>()
);
/// <summary>
///
/// </summary>
/// <param name="memory"></param>
/// <param name="maxHeartbeatInterval">Max time allowed before declaring disconnection when heartbeat signal is not received.</param>
/// <param name="heartbeatSignal">Name of the heartbeat signal, default to empty which means any memory modification by anyone is considered as heartbeat.</param>
public PLCController(PLCMemory memory, TimeSpan? maxHeartbeatInterval = null, string heartbeatSignal = "")
{
this.memory = memory;
this.maxHeartbeatInterval = maxHeartbeatInterval;
this.heartbeatSignal = heartbeatSignal;
// register observer
this.memory.Modified += new PLCMemory.Observer(this._Enqueue);
// copy memory
lock (memory)
{
foreach (var pair in memory)
{
this.state[pair.Key] = pair.Value;
}
}
}
/// <summary>
/// Whether time since last heartbeat is within expectation indicating an active connection.
/// </summary>
public bool IsConnected
{
get
{
if (this.maxHeartbeatInterval.HasValue)
{
return DateTime.Now - this.lastHeartbeatTimestamp < this.maxHeartbeatInterval.Value;
}
return true;
}
}
private void _Enqueue(IDictionary<string, object> modifications)
{
if (this.heartbeatSignal == "" || modifications.ContainsKey(this.heartbeatSignal))
{
lock (this)
{
// timestamp of last activity
this.lastHeartbeatTimestamp = DateTime.Now;
}
}
queue.Add(modifications);
}
private void _DequeueAll()
{
IDictionary<string, object> modifications;
while (queue.TryTake(out modifications))
{
foreach (var pair in modifications)
{
this.state[pair.Key] = pair.Value;
}
}
}
private IDictionary<string, object> _Dequeue(TimeSpan? timeout = null, bool timeoutOnDisconnect = true)
{
var start = DateTime.Now;
IDictionary<string, object> modifications;
while (true)
{
// make sure timeout has not already been reached
if (timeout.HasValue && timeout.Value < TimeSpan.Zero)
{
throw new TimeoutException();
}
if (queue.TryTake(out modifications, TimeSpan.FromMilliseconds(50)))
{
// successfully took
break;
}
// see if we timed out
if (timeout.HasValue && (DateTime.Now - start) > timeout.Value)
{
throw new TimeoutException();
}
// if disconnection is detected, immediately timeout.
if (timeoutOnDisconnect && !this.IsConnected)
{
throw new TimeoutException();
}
}
// apply the modification to local state
foreach (var pair in modifications)
{
this.state[pair.Key] = pair.Value;
}
return modifications;
}
/// <summary>
/// Synchronize the local memory snapshot with what has happened already.
/// </summary>
public void Sync()
{
this._DequeueAll();
}
/// <summary>
/// Wait until IsConnected becomes true.
/// </summary>
/// <param name="timeout"></param>
public void WaitUntilConnected(TimeSpan? timeout = null)
{
while (!this.IsConnected)
{
var start = DateTime.Now;
this._Dequeue(timeout, false);
if (timeout.HasValue)
{
timeout = timeout.Value.Subtract(DateTime.Now - start);
}
}
}
/// <summary>
/// Wait for a key to change to a particular value.
/// Specifically, if the key is already at such value, wait until it changes to something else and then changes back.
/// If value is null, then wait for any change to the key.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="timeout"></param>
public void WaitFor(string key, object value, TimeSpan? timeout = null)
{
this.WaitFor(new Dictionary<string, object>()
{
{ key, value },
}, timeout);
}
/// <summary>
/// Wait for multiple keys, return as soon as any one key has the expected value.
/// If the passed in expected value of a key is null, then wait for any change to that key.
/// </summary>
/// <param name="signals"></param>
/// <param name="timeout"></param>
public void WaitFor(IDictionary<string, object> signals, TimeSpan? timeout = null)
{
while (true)
{
var start = DateTime.Now;
var modifications = this._Dequeue(timeout);
foreach (var pair in modifications)
{
if (signals.ContainsKey(pair.Key))
{
if (signals[pair.Key] == null || pair.Value.Equals(signals[pair.Key]))
{
return;
}
}
}
if (timeout.HasValue)
{
timeout = timeout.Value.Subtract(DateTime.Now - start);
}
}
}
/// <summary>
/// Wait until a key is at the expected value.
/// If the key is already at such value, return immediately.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="timeout"></param>
public void WaitUntil(string key, object value, TimeSpan? timeout = null)
{
this.WaitUntil(new Dictionary<string, object>()
{
{ key, value },
}, null, timeout);
}
/// <summary>
/// Wait until multiple keys are ALL at their expected value, OR ANY one key is at its exceptional value.
/// If all the keys are already satisfying the expectations, then return immediately.
/// If any of the exceptional conditions is met, then return immediately.
/// </summary>
/// <param name="expectations"></param>
/// <param name="exceptions"></param>
/// <param name="timeout"></param>
public void WaitUntil(IDictionary<string, object> expectations, IDictionary<string, object> exceptions = null, TimeSpan? timeout = null)
{
// combine all signals
var all = new Dictionary<string, object>(expectations);
if (exceptions != null)
{
foreach (var pair in exceptions)
{
all[pair.Key] = pair.Value;
}
}
// always clear the queue first
this._DequeueAll();
while (true)
{
// check if any exceptions is already met
if (exceptions != null)
{
foreach (var pair in exceptions)
{
if (this.state.ContainsKey(pair.Key) && this.state[pair.Key].Equals(pair.Value))
{
return;
}
}
}
// check if all expectations are already met
bool met = true;
foreach (var pair in expectations)
{
if (!this.state.ContainsKey(pair.Key) || !this.state[pair.Key].Equals(pair.Value))
{
met = false;
break;
}
}
if (met)
{
return;
}
// wait for it to change
var start = DateTime.Now;
this.WaitFor(all, timeout);
if (timeout.HasValue)
{
timeout = timeout.Value.Subtract(DateTime.Now - start);
}
}
}
/// <summary>
/// Get value of a key in the current state snapshot of the PLC memory.
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public T Get<T>(string key, T defaultValue)
{
if (this.state.ContainsKey(key))
{
return (T)Convert.ChangeType(this.state[key], typeof(T));
}
return defaultValue;
}
/// <summary>
/// Get value of a key in the current state snapshot of the PLC memory.
/// </summary>
/// <param name="key"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public T SyncAndGet<T>(string key, T defaultValue)
{
this.Sync();
return this.Get(key, defaultValue);
}
/// <summary>
/// Get multiple keys in the current state snapshot of the PLC memory.
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public IDictionary<string, object> Get(string[] keys)
{
Dictionary<string, object> values = new Dictionary<string, object>();
foreach (var key in keys)
{
if (this.state.ContainsKey(key))
{
values[key] = this.state[key];
}
}
return values;
}
/// <summary>
/// Get multiple keys in the current state snapshot of the PLC memory.
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public IDictionary<string, object> SyncAndGet(string[] keys)
{
this.Sync();
return this.Get(keys);
}
/// <summary>
/// Set key in PLC memory.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void Set(string key, object value)
{
this.memory.Write(new Dictionary<string, object>()
{
{ key, value },
});
}
/// <summary>
/// Set multiple keys in PLC memory.
/// </summary>
/// <param name="values"></param>
public void Set(IDictionary<string, object> values)
{
this.memory.Write(values);
}
}
}