-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathDeviceUpdateTrigger.cs
More file actions
198 lines (161 loc) · 5.86 KB
/
DeviceUpdateTrigger.cs
File metadata and controls
198 lines (161 loc) · 5.86 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
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
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace RGB.NET.Core;
/// <summary>
/// Represents an update-trigger used to update devices with a maximum update-rate.
/// </summary>
public class DeviceUpdateTrigger : AbstractUpdateTrigger, IDeviceUpdateTrigger
{
#region Properties & Fields
/// <summary>
/// Gets or sets the timeout used by the blocking wait for data availability.
/// </summary>
public int Timeout { get; set; } = 100;
/// <summary>
/// Gets the update frequency used by the trigger if not limited by data shortage.
/// </summary>
public double UpdateFrequency { get; private set; }
private double _maxUpdateRate;
/// <summary>
/// Gets or sets the maximum update rate of this trigger (is overwriten if the <see cref="UpdateRateHardLimit"/> is smaller).
/// <= 0 removes the limit.
/// </summary>
public double MaxUpdateRate
{
get => _maxUpdateRate;
set
{
_maxUpdateRate = value;
UpdateUpdateFrequency();
}
}
private double _updateRateHardLimit;
/// <summary>
/// Gets the hard limit of the update rate of this trigger. Updates will never perform faster then then this value if it's set.
/// <= 0 removes the limit.
/// </summary>
public double UpdateRateHardLimit
{
get => _updateRateHardLimit;
protected set
{
_updateRateHardLimit = value;
UpdateUpdateFrequency();
}
}
/// <summary>
/// Gets or sets the time in ms after which a refresh-request is sent even if no changes are made in the meantime to prevent the target from timing out or similar problems.
/// To disable heartbeats leave it at 0.
/// </summary>
public int HeartbeatTimer { get; set; }
/// <inheritdoc />
public override double LastUpdateTime { get; protected set; }
/// <summary>
/// Gets or sets the timestamp of the last update.
/// </summary>
protected long LastUpdateTimestamp { get; set; }
/// <summary>
/// Gets or sets the event to trigger when new data is available (<see cref="TriggerHasData"/>).
/// </summary>
protected AutoResetEvent HasDataEvent { get; set; } = new(false);
/// <summary>
/// Gets or sets a bool indicating if the trigger is currently updating.
/// </summary>
protected bool IsRunning { get; set; }
/// <summary>
/// Gets or sets the update loop of this trigger.
/// </summary>
protected Task? UpdateTask { get; set; }
/// <summary>
/// Gets or sets the cancellation token source used to create the cancellation token checked by the <see cref="UpdateTask"/>.
/// </summary>
protected CancellationTokenSource? UpdateTokenSource { get; set; }
/// <summary>
/// Gets or sets the cancellation token checked by the <see cref="UpdateTask"/>.
/// </summary>
protected CancellationToken UpdateToken { get; set; }
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="DeviceUpdateTrigger"/> class.
/// </summary>
public DeviceUpdateTrigger()
{ }
/// <summary>
/// Initializes a new instance of the <see cref="DeviceUpdateTrigger"/> class.
/// </summary>
/// <param name="updateRateHardLimit">The hard limit of the update rate of this trigger.</param>
public DeviceUpdateTrigger(double updateRateHardLimit)
{
this.UpdateRateHardLimit = updateRateHardLimit;
}
#endregion
#region Methods
/// <summary>
/// Starts the trigger.
/// </summary>
public override void Start()
{
if (IsRunning) return;
IsRunning = true;
UpdateTokenSource?.Dispose();
UpdateTokenSource = new CancellationTokenSource();
UpdateTask = Task.Factory.StartNew(UpdateLoop, (UpdateToken = UpdateTokenSource.Token), TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
/// <summary>
/// Stops the trigger.
/// </summary>
public virtual async void Stop()
{
if (!IsRunning) return;
IsRunning = false;
UpdateTokenSource?.Cancel();
if (UpdateTask != null)
try
{
await UpdateTask.ConfigureAwait(false);
UpdateTask?.Dispose();
}
catch (TaskCanceledException) { }
catch (OperationCanceledException) { }
catch (InvalidOperationException) { }
UpdateTask = null;
}
/// <summary>
/// The update loop called by the <see cref="UpdateTask"/>.
/// </summary>
protected virtual void UpdateLoop()
{
OnStartup();
using (TimerHelper.RequestHighResolutionTimer())
while (!UpdateToken.IsCancellationRequested)
if (HasDataEvent.WaitOne(Timeout))
LastUpdateTime = TimerHelper.Execute(TimerExecute, UpdateFrequency * 1000);
else if ((HeartbeatTimer > 0) && (LastUpdateTimestamp > 0) && (TimerHelper.GetElapsedTime(LastUpdateTimestamp) > HeartbeatTimer))
OnUpdate(new CustomUpdateData().Heartbeat());
}
private void TimerExecute() => OnUpdate();
protected override void OnUpdate(CustomUpdateData? updateData = null)
{
base.OnUpdate(updateData);
LastUpdateTimestamp = Stopwatch.GetTimestamp();
}
/// <inheritdoc />
public void TriggerHasData() => HasDataEvent.Set();
private void UpdateUpdateFrequency()
{
UpdateFrequency = MaxUpdateRate;
if ((UpdateFrequency <= 0) || ((UpdateRateHardLimit > 0) && (UpdateRateHardLimit < UpdateFrequency)))
UpdateFrequency = UpdateRateHardLimit;
}
/// <inheritdoc />
public override void Dispose()
{
Stop();
GC.SuppressFinalize(this);
}
#endregion
}