-
Notifications
You must be signed in to change notification settings - Fork 1
/
MPowerConnectorManager.cs
304 lines (267 loc) · 10.3 KB
/
MPowerConnectorManager.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
using HomeSeerAPI;
using Hspi.Connector.Model;
using Hspi.DeviceData;
using Hspi.Exceptions;
using Nito.AsyncEx;
using NullGuard;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using static System.FormattableString;
namespace Hspi.Connector
{
[NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)]
internal sealed class MPowerConnectorManager : IDisposable
{
public MPowerConnectorManager(IHSApplication HS, MPowerDevice device, CancellationToken shutdownToken)
{
this.HS = HS;
Device = device;
rootDeviceData = new DeviceRootDeviceManager(device.Name, device.Id, this.HS);
combinedCancellationSource = CancellationTokenSource.CreateLinkedTokenSource(shutdownToken);
Task.Factory.StartNew(ManageConnection,
Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Current);
Task.Factory.StartNew(ProcessDeviceUpdates,
Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Current);
}
public async Task HandleCommand(DeviceIdentifier deviceIdentifier, double value, ePairControlUse control)
{
if (deviceIdentifier.DeviceId != Device.Id)
{
throw new ArgumentException("Invalid Device Identifier");
}
// This function runs in separate thread than main run
MPowerConnector connectorCopy;
using (var sync = await rootDeviceDataLock.LockAsync(Token).ConfigureAwait(false))
{
connectorCopy = connector;
if (connectorCopy == null)
{
throw new HspiException(Invariant($"No connection to Device for {Device.DeviceIP}"));
}
await rootDeviceData.HandleCommand(deviceIdentifier, Token, connectorCopy, value, control).ConfigureAwait(false);
}
await connectorCopy.UpdateAllSensorData(Token).ConfigureAwait(false);
}
private async Task ManageConnection()
{
try
{
while (!Token.IsCancellationRequested)
{
// connect if needed
await Connect().ConfigureAwait(false);
// sleep for 30 seconds or Close
await SleepForIntervalOrClose().ConfigureAwait(false);
// Check for connection health
await CheckConnection().ConfigureAwait(false);
}
}
catch (Exception ex)
{
if (ex.IsCancelException())
{
throw;
}
Trace.TraceError(Invariant($"ManageConnection for {Device.DeviceIP} failed with {ex.GetFullMessage()}. Restarting ..."));
}
}
private async Task ProcessDeviceUpdates()
{
try
{
while (!Token.IsCancellationRequested)
{
var sensorData = await changedPorts.DequeueAsync(Token).ConfigureAwait(false);
using (var sync = await rootDeviceDataLock.LockAsync(Token).ConfigureAwait(false))
{
try
{
if (Device.EnabledPorts.Contains(sensorData.Port))
{
rootDeviceData.ProcessSensorData(Device, sensorData);
}
}
catch (Exception ex)
{
if (ex.IsCancelException())
{
throw;
}
Trace.TraceWarning(Invariant($"Failed to update Sensor Data for Port {sensorData.Port} on {Device.DeviceIP} with {ex.GetFullMessage()}"));
}
}
}
}
catch (Exception ex)
{
if (ex.IsCancelException())
{
throw;
}
Trace.TraceError(Invariant($"ProcessDeviceUpdates for {Device.DeviceIP} failed with {ex.GetFullMessage()}. Restarting ..."));
}
}
private async Task CheckConnection()
{
if (connector != null)
{
bool destroyConnection = ShouldDestroyConnection();
if (destroyConnection)
{
await DestroyConnection().ConfigureAwait(false);
}
else
{
try
{
await connector.UpdateAllSensorData(Token).ConfigureAwait(false);
}
catch (Exception ex)
{
if (ex.IsCancelException())
{
throw;
}
Trace.TraceWarning(Invariant($"Failed to Get Full Sensor Data from {Device.DeviceIP} with {ex.GetFullMessage()}"));
await DestroyConnection().ConfigureAwait(false);
}
}
}
}
private bool ShouldDestroyConnection()
{
if (connector.ConnectionClosed.IsCancellationRequested)
{
return true;
}
if (!connector.Connected)
{
Trace.TraceWarning(Invariant($"WebSocket Disconnected to {Device.DeviceIP}. Total Errors:{connector.TotalErrors}. Reconnecting..."));
return true;
}
int maxErrors = 10;
if (connector.TotalErrors > maxErrors)
{
Trace.TraceWarning(Invariant($"Too many errors in websocket connection to {Device.DeviceIP}. Total Errors:{connector.TotalErrors}. Reconnecting..."));
return true;
}
TimeSpan maxUpdateTime = TimeSpan.FromSeconds(240);
TimeSpan lastUpdate = connector.TimeSinceLastUpdate;
if (lastUpdate > maxUpdateTime)
{
Trace.TraceWarning(Invariant($"Did not receive update from {Device.DeviceIP} for {lastUpdate.Seconds} seconds. Reconnecting..."));
return true;
}
return false;
}
private async Task DestroyConnection()
{
try
{
await connector.LogOut(Token).ConfigureAwait(false);
}
catch (Exception) { }
DisposeConnector();
}
private void DisposeConnector()
{
if (connector != null)
{
connector.PortsChanged -= Connector_PortsChanged;
connector.Dispose();
connector = null;
}
}
private async Task SleepForIntervalOrClose()
{
TimeSpan delay = TimeSpan.FromSeconds(30);
if (connector != null)
{
using (var combinedSource = CancellationTokenSource.CreateLinkedTokenSource(Token, connector.ConnectionClosed))
{
await Task.Delay(delay, combinedSource.Token).ConfigureAwait(false);
}
}
else
{
await Task.Delay(delay, Token).ConfigureAwait(false);
}
Token.ThrowIfCancellationRequested();
}
private async Task Connect()
{
if (connector == null)
{
MPowerConnector newConnector = null;
try
{
newConnector = new MPowerConnector(Device.DeviceIP);
newConnector.PortsChanged += Connector_PortsChanged;
await newConnector.Connect(Device.Username, Device.Password, Token).ConfigureAwait(false);
connector = newConnector;
}
catch (Exception ex)
{
if (ex.IsCancelException())
{
throw;
}
Trace.TraceWarning(Invariant($"Failed to Connect to {Device.DeviceIP} with {ex.Message}"));
newConnector.PortsChanged -= Connector_PortsChanged;
newConnector?.Dispose();
}
}
}
private void Connector_PortsChanged(object sender, IList<SensorData> portsChanged)
{
if (sender == connector)
{
try
{
foreach (var data in portsChanged)
{
changedPorts.Enqueue(data, Token);
}
}
catch (OperationCanceledException)
{
}
}
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
public MPowerDevice Device { get; }
private void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
combinedCancellationSource.Cancel();
DisposeConnector();
combinedCancellationSource.Dispose();
}
disposedValue = true;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion IDisposable Support
private CancellationToken Token => combinedCancellationSource.Token;
private volatile MPowerConnector connector;
private readonly CancellationTokenSource combinedCancellationSource;
private readonly IHSApplication HS;
private readonly AsyncProducerConsumerQueue<SensorData> changedPorts = new AsyncProducerConsumerQueue<SensorData>();
private readonly DeviceRootDeviceManager rootDeviceData;
private readonly AsyncLock rootDeviceDataLock = new AsyncLock();
}
}