-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMockOpcSubscription.cs
More file actions
83 lines (70 loc) · 2.05 KB
/
MockOpcSubscription.cs
File metadata and controls
83 lines (70 loc) · 2.05 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
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Website: https://www.blazor.zone or https://argozhang.github.io/
namespace BootstrapBlazor.OpcDa;
sealed class MockOpcDaSubscription : IOpcSubscription, IDisposable
{
private readonly int _updateRate;
private readonly bool _active;
private readonly List<string> _items = [];
private CancellationTokenSource? _cts;
public MockOpcDaSubscription(string name, int updateRate = 1000, bool active = true)
{
Name = name;
_updateRate = updateRate;
_active = active;
_cts = new CancellationTokenSource();
_ = Task.Run(() => DoTask(_cts.Token));
}
public string Name { get; }
public bool KeepLastValue { get; set; }
public Action<List<OpcReadItem>>? DataChanged { get; set; }
public void AddItems(IEnumerable<string> items)
{
_items.AddRange(items);
}
private void UpdateValues()
{
if (DataChanged != null)
{
var values = _items.Select(i => new OpcReadItem(i, Quality.Good, DateTime.Now, Random.Shared.Next(1000, 2000))).ToList();
DataChanged.Invoke(values);
}
}
private async Task DoTask(CancellationToken token)
{
do
{
try
{
if (_active)
{
UpdateValues();
}
await Task.Delay(_updateRate, token);
}
catch (OperationCanceledException)
{
// ignored
}
}
while (!token.IsCancellationRequested);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_cts != null)
{
_cts.Cancel();
_cts.Dispose();
_cts = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}