-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPLCMemory.cs
72 lines (64 loc) · 2.32 KB
/
PLCMemory.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
using System;
using System.Collections.Generic;
namespace mujinplccs
{
/// <summary>
/// PLCMemory is a key-value store that supports locked PLC memory read write operations.
/// </summary>
public sealed class PLCMemory : Dictionary<string, object>
{
public delegate void Observer(IDictionary<string, object> modifications);
//private DateTime lastHeartbeatTimestamp = DateTime.MinValue;
public event Observer Modified = null;
public PLCMemory() : base()
{
}
/// <summary>
/// Atomically read PLC memory.
/// </summary>
/// <param name="keys">An array of strings representing the named memory addresses.</param>
/// <returns>A dictionary containing the mapping between requested memory addresses and their stored values. If a requested address does not exist in the memory, it will be omitted here.</returns>
public Dictionary<string, object> Read(string[] keys)
{
var data = new Dictionary<string, object>();
lock (this)
{
foreach (string key in keys)
{
if (this.ContainsKey(key))
{
data[key] = this[key];
}
}
}
return data;
}
/// <summary>
/// Atomically write PLC memory.
/// </summary>
/// <param name="data">A dictionary containing the mapping between named memory addresses and their desired values.</param>
public void Write(IDictionary<string, object> data)
{
var modifications = new Dictionary<string, object>();
lock (this)
{
foreach (var pair in data)
{
if (!this.ContainsKey(pair.Key) || !this[pair.Key].Equals(pair.Value))
{
modifications[pair.Key] = pair.Value;
}
this[pair.Key] = pair.Value;
}
}
// notify observers of the modifications
if (modifications.Count > 0)
{
if (this.Modified != null)
{
this.Modified.Invoke(modifications);
}
}
}
}
}