-
Notifications
You must be signed in to change notification settings - Fork 6
/
PlugIn.cs
564 lines (501 loc) · 20.9 KB
/
PlugIn.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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
using HomeSeerAPI;
using Hspi.DeviceData;
using Hspi.Pages;
using Hspi.Utils;
using Nito.AsyncEx;
using NullGuard;
using Scheduler.Classes;
using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using static System.FormattableString;
namespace Hspi
{
/// <summary>
/// Plugin class
/// </summary>
/// <seealso cref="Hspi.HspiBase" />
[NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)]
internal class PlugIn : HspiBase
{
public PlugIn()
: base(PlugInData.PlugInName, supportConfigDevice: true, supportConfigDeviceAll: true)
{
}
public override string ConfigDevice(int deviceId, [AllowNull] string user, int userRights, bool newDevice)
{
if (newDevice)
{
return string.Empty;
}
try
{
var deviceClass = (DeviceClass)HS.GetDeviceByRef(deviceId);
if (deviceClass.get_Interface(HS) == PlugInData.PlugInName)
{
var deviceIdentifier = DeviceIdentifier.Identify(deviceClass);
if (deviceIdentifier != null)
{
return configPage.GetDeviceImportTab(deviceIdentifier);
}
}
else
{
return configPage.GetDeviceHistoryTab(deviceId);
}
return string.Empty;
}
catch (Exception ex)
{
LogError(Invariant($"ConfigDevice for {deviceId} With {ex.Message}"));
return string.Empty;
}
}
public override Enums.ConfigDevicePostReturn ConfigDevicePost(int deviceId, [AllowNull] string data, [AllowNull] string user, int userRights)
{
try
{
return configPage.GetDeviceHistoryPost(Callback, deviceId, data);
}
catch (Exception ex)
{
LogError(Invariant($"ConfigDevicePost for {deviceId} With {ex.Message}"));
return Enums.ConfigDevicePostReturn.DoneAndCancelAndStay;
}
}
public override string GetPagePlugin(string page, [AllowNull]string user, int userRights, [AllowNull]string queryString)
{
if (page == ConfigPage.Name)
{
return configPage.GetWebPage(queryString);
}
return string.Empty;
}
public override void HSEvent(Enums.HSEvent eventType, [AllowNull]object[] parameters)
{
HSEventImpl(eventType, parameters).Wait(ShutdownCancellationToken);
}
public override string InitIO(string port)
{
string result = string.Empty;
try
{
pluginConfig = new PluginConfig(HS);
configPage = new ConfigPage(HS, pluginConfig);
Trace.TraceInformation("Starting Plugin");
LogConfiguration();
pluginConfig.ConfigChanged += PluginConfig_ConfigChanged;
RegisterConfigPage();
Callback.RegisterEventCB(Enums.HSEvent.VALUE_CHANGE, Name, string.Empty);
Callback.RegisterEventCB(Enums.HSEvent.STRING_CHANGE, Name, string.Empty);
RestartProcessing();
Trace.TraceInformation("Plugin Started");
}
catch (Exception ex)
{
result = Invariant($"Failed to initialize PlugIn with {ex.GetFullMessage()}");
Trace.TraceError(result);
}
return result;
}
public override void LogDebug(string message)
{
if ((pluginConfig != null) && pluginConfig.DebugLogging)
{
base.LogDebug(message);
}
}
public override IPlugInAPI.PollResultInfo PollDevice(int deviceId)
{
if (ImportDeviceFromDB(deviceId))
{
var pollResult = new IPlugInAPI.PollResultInfo
{
Result = IPlugInAPI.enumPollResult.OK,
Value = HS.DeviceValueEx(deviceId),
};
return pollResult;
}
else
{
return base.PollDevice(deviceId);
}
}
public override string PostBackProc(string page, string data, [AllowNull]string user, int userRights)
{
if (page == ConfigPage.Name)
{
return configPage.PostBackProc(data, user, userRights);
}
return string.Empty;
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (!disposedValue)
{
if (pluginConfig != null)
{
pluginConfig.ConfigChanged -= PluginConfig_ConfigChanged;
}
configPage?.Dispose();
Shutdown();
disposedValue = true;
}
base.Dispose(disposing);
}
private static async Task RecordDeviceValue(InfluxDBMeasurementsCollector collector,
IHSApplication HS,
DeviceClass device)
{
if (device != null)
{
int deviceRefId = device.get_Ref(HS);
bool notValid = HS.get_DeviceInvalidValue(deviceRefId);
if (!notValid)
{
double deviceValue = device.get_devValue(HS);
string deviceString = HS.DeviceString(deviceRefId);
if (string.IsNullOrWhiteSpace(deviceString))
{
deviceString = HS.DeviceVSP_GetStatus(deviceRefId, deviceValue, ePairStatusControl.Status);
}
Trace.WriteLine(Invariant($"Recording Device Ref Id: {deviceRefId} with [{deviceValue}] & [{deviceString}]"));
DateTime lastChange = device.get_Last_Change(HS);
RecordData recordData = new RecordData(deviceRefId,
deviceValue,
deviceString,
device.get_Name(HS),
device.get_Location(HS),
device.get_Location2(HS),
lastChange);
await collector.Record(recordData).ConfigureAwait(false);
}
else
{
Trace.TraceWarning(Invariant($"Not recording Device Ref Id: {deviceRefId} as it has invalid value."));
}
}
}
private async Task<InfluxDBMeasurementsCollector> GetInfluxDBMeasurementsCollector()
{
using (var sync = await influxDBMeasurementsCollectorLock.EnterAsync().ConfigureAwait(false))
{
return influxDBMeasurementsCollector;
}
}
private async Task HSEventImpl(Enums.HSEvent eventType, object[] parameters)
{
try
{
if ((eventType == Enums.HSEvent.VALUE_CHANGE) && (parameters.Length > 4))
{
int deviceRefId = Convert.ToInt32(parameters[4], CultureInfo.InvariantCulture);
await RecordDeviceValue(deviceRefId, TrackedType.Value).ConfigureAwait(false);
}
else if ((eventType == Enums.HSEvent.STRING_CHANGE) && (parameters.Length > 3))
{
int deviceRefId = Convert.ToInt32(parameters[3], CultureInfo.InvariantCulture);
await RecordDeviceValue(deviceRefId, TrackedType.String).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to process HSEvent {eventType} with {ex.GetFullMessage()}"));
}
}
private void LogConfiguration()
{
var dbConfig = pluginConfig.DBLoginInformation;
Trace.WriteLine(Invariant($"Url:{dbConfig.DBUri} User:{dbConfig.User} Database:{dbConfig.DB}"));
}
private void PluginConfig_ConfigChanged(object sender, EventArgs e)
{
RestartProcessing();
}
private async Task RecordDeviceValue(int deviceRefId, TrackedType trackedType)
{
var collector = await GetInfluxDBMeasurementsCollector().ConfigureAwait(false);
if ((collector != null) && collector.IsTracked(deviceRefId, trackedType))
{
var device = HS.GetDeviceByRef(deviceRefId) as DeviceClass;
await RecordDeviceValue(collector, HS, device).ConfigureAwait(false);
}
}
private async Task RecordTrackedDevices()
{
var collector = await GetInfluxDBMeasurementsCollector().ConfigureAwait(false);
if (collector != null)
{
var deviceEnumerator = HS.GetDeviceEnumerator() as clsDeviceEnumeration;
do
{
DeviceClass device = deviceEnumerator.GetNext();
if (device != null)
{
if (collector.IsTracked(device.get_Ref(HS), null))
{
await RecordDeviceValue(collector, HS, device).ConfigureAwait(false);
}
}
ShutdownCancellationToken.ThrowIfCancellationRequested();
}
while (!deviceEnumerator.Finished);
}
}
private void RegisterConfigPage()
{
string link = ConfigPage.Name;
HS.RegisterPage(link, Name, string.Empty);
var wpd = new HomeSeerAPI.WebPageDesc()
{
plugInName = Name,
link = link,
linktext = "Configuration",
page_title = Invariant($"{Name} Configuration"),
};
Callback.RegisterConfigLink(wpd);
Callback.RegisterLink(wpd);
}
private void RestartProcessing()
{
Utils.TaskHelper.StartAsyncWithErrorChecking("Measurements Collector", StartInfluxDBMeasurementsCollector, ShutdownCancellationToken);
Utils.TaskHelper.StartAsyncWithErrorChecking("Device Import", StartDeviceImport, ShutdownCancellationToken);
}
private void Shutdown()
{
using (var sync = influxDBMeasurementsCollectorLock.Enter())
{
influxDBMeasurementsCollector?.Dispose();
}
using (var sync = deviceRootDeviceManagerLock.Enter())
{
deviceRootDeviceManager?.Dispose();
}
}
private async Task StartDeviceImport()
{
using (var sync = await deviceRootDeviceManagerLock.EnterAsync(ShutdownCancellationToken))
{
deviceRootDeviceManager?.Dispose();
deviceRootDeviceManager = new DeviceRootDeviceManager(HS,
pluginConfig.DBLoginInformation,
pluginConfig.ImportDevicesData,
ShutdownCancellationToken);
}
}
private async Task StartInfluxDBMeasurementsCollector()
{
using (var sync = await influxDBMeasurementsCollectorLock.EnterAsync(ShutdownCancellationToken))
{
bool recreate = (influxDBMeasurementsCollector == null) ||
(!influxDBMeasurementsCollector.LoginInformation.Equals(pluginConfig.DBLoginInformation));
if (recreate)
{
if (pluginConfig.DBLoginInformation.IsValid)
{
influxDBMeasurementsCollector?.Dispose();
influxDBMeasurementsCollector = new InfluxDBMeasurementsCollector(pluginConfig.DBLoginInformation, ShutdownCancellationToken);
influxDBMeasurementsCollector.Start(pluginConfig.DevicePersistenceData.Values);
}
}
else
{
influxDBMeasurementsCollector.UpdatePeristenceData(pluginConfig.DevicePersistenceData.Values);
}
}
// do not leave thread to avoid leaving thread as it can delay startup
#pragma warning disable CA2007 // Consider calling ConfigureAwait on the awaited task
await RecordTrackedDevices();
#pragma warning restore CA2007 // Consider calling ConfigureAwait on the awaited task
}
#region "Action Override"
public override string ActionBuildUI([AllowNull]string uniqueControlId, IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
return configPage.GetRefreshActionUI(uniqueControlId ?? string.Empty, actionInfo);
default:
return base.ActionBuildUI(uniqueControlId, actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to give build Action UI with {ex.GetFullMessage()}"));
throw;
}
}
public override bool ActionConfigured(IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
if (actionInfo.DataIn != null)
{
RefreshDeviceAction refreshDeviceAction = ObjectSerialize.DeSerializeFromBytes(actionInfo.DataIn) as RefreshDeviceAction;
if ((refreshDeviceAction != null) && (refreshDeviceAction.DeviceRefId != 0))
{
return HS.GetDeviceByRef(refreshDeviceAction.DeviceRefId) != null;
}
}
return false;
default:
return base.ActionConfigured(actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to ActionConfigured with {ex.GetFullMessage()}"));
return false;
}
}
public override int ActionCount()
{
return 1;
}
public override string ActionFormatUI(IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
if (actionInfo.DataIn != null)
{
var refreshDeviceAction = ObjectSerialize.DeSerializeFromBytes(actionInfo.DataIn) as RefreshDeviceAction;
if ((refreshDeviceAction != null) && (refreshDeviceAction.DeviceRefId != 0))
{
HSHelper hSHelper = new HSHelper(HS);
return Invariant($"Refresh {hSHelper.GetName(refreshDeviceAction.DeviceRefId)} from Influx DB");
}
}
return Invariant($"{PlugInData.PlugInName} Unknown Device Import Refresh");
default:
return base.ActionFormatUI(actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to ActionFormatUI with {ex.GetFullMessage()}"));
throw;
}
}
public override IPlugInAPI.strMultiReturn ActionProcessPostUI([AllowNull] NameValueCollection postData, IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
return ConfigPage.GetRefreshActionPostUI(postData, actionInfo);
default:
return base.ActionProcessPostUI(postData, actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to ActionProcessPostUI with {ex.GetFullMessage()}"));
throw;
}
}
public override bool ActionReferencesDevice(IPlugInAPI.strTrigActInfo actionInfo, int deviceId)
{
try
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
if (actionInfo.DataIn != null)
{
var refreshDeviceAction = ObjectSerialize.DeSerializeFromBytes(actionInfo.DataIn) as RefreshDeviceAction;
return (refreshDeviceAction != null) && (refreshDeviceAction.DeviceRefId == deviceId);
}
return false;
default:
return false;
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to ActionReferencesDevice with {ex.GetFullMessage()}"));
return false;
}
}
public override string get_ActionName(int actionNumber)
{
try
{
switch (actionNumber)
{
case ActionRefreshTANumber:
return Invariant($"{Name}:Refresh From InfluxDB");
default:
return base.get_ActionName(actionNumber);
}
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to give Action Name with {ex.GetFullMessage()}"));
throw;
}
}
public override bool HandleAction(IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
if (actionInfo.DataIn != null)
{
var refreshDeviceAction = ObjectSerialize.DeSerializeFromBytes(actionInfo.DataIn) as RefreshDeviceAction;
if ((refreshDeviceAction != null) && (refreshDeviceAction.DeviceRefId != 0))
{
if (ImportDeviceFromDB(refreshDeviceAction.DeviceRefId))
{
return true;
}
}
}
Trace.TraceWarning(Invariant($"Failed to execute action with Device not Found"));
return false;
default:
return base.HandleAction(actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to execute action with {ex.GetFullMessage()}"));
return false;
}
}
private bool ImportDeviceFromDB(int deviceRefId)
{
DeviceRootDeviceManager deviceRootDeviceManagerCopy;
using (var sync = deviceRootDeviceManagerLock.Enter())
{
deviceRootDeviceManagerCopy = deviceRootDeviceManager;
}
return deviceRootDeviceManagerCopy.ImportDataForDevice(deviceRefId).ResultForSync();
}
#endregion "Action Override"
private const int ActionRefreshTANumber = 1;
private readonly AsyncMonitor deviceRootDeviceManagerLock = new AsyncMonitor();
private readonly AsyncMonitor influxDBMeasurementsCollectorLock = new AsyncMonitor();
private ConfigPage configPage;
private DeviceRootDeviceManager deviceRootDeviceManager;
private bool disposedValue;
private InfluxDBMeasurementsCollector influxDBMeasurementsCollector;
private PluginConfig pluginConfig;
}
}