This repository has been archived by the owner on Dec 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathWUWeatherPlugin.cs
572 lines (496 loc) · 21.4 KB
/
WUWeatherPlugin.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
565
566
567
568
569
570
571
572
using HomeSeerAPI;
using Hspi.Exceptions;
using Hspi.WUWeather;
using NullGuard;
using Scheduler.Classes;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
namespace Hspi
{
using System.Diagnostics;
using static System.FormattableString;
/// <summary>
/// Plugin class for Weather Underground
/// </summary>
/// <seealso cref="Hspi.HspiBase" />
[NullGuard(ValidationFlags.Arguments | ValidationFlags.NonPublic)]
internal class WUWeatherPlugin : HspiBase
{
public WUWeatherPlugin()
: base(WUWeatherData.PlugInName)
{
}
public override string InitIO(string port)
{
string result = string.Empty;
try
{
pluginConfig = new PluginConfig(HS);
configPage = new ConfigPage(HS, pluginConfig);
Trace.TraceInformation("Starting Plugin");
#if DEBUG
pluginConfig.DebugLogging = true;
#endif
LogConfiguration();
pluginConfig.ConfigChanged += PluginConfig_ConfigChanged;
RegisterConfigPage();
RestartPeriodicTask();
Trace.TraceInformation("Plugin Started");
}
catch (Exception ex)
{
result = Invariant($"Failed to initialize PlugIn With {ex.GetFullMessage()}");
Trace.TraceError(result);
}
return result;
}
private void LogConfiguration()
{
Trace.WriteLine(Invariant($"APIKey:{pluginConfig.APIKey} Refresh Interval:{pluginConfig.RefreshIntervalMinutes} Minutes Station:{pluginConfig.StationId}"));
}
private void PluginConfig_ConfigChanged(object sender, EventArgs e)
{
// Wait for 5 seconds before fetching the data to avoid sending too many requests
// when user is doing a bunch of changes in config.
RestartPeriodicTask(TimeSpan.FromSeconds(5));
}
public override void LogDebug(string message)
{
if ((pluginConfig != null) && pluginConfig.DebugLogging)
{
base.LogDebug(message);
}
}
private static string CreateChildAddress(string parentAddress, string childAddress)
{
return Invariant($"{parentAddress}.{childAddress}");
}
/// <summary>
/// Creates the HS device.
/// </summary>
/// <param name="parent">The data for parent of device.</param>
/// <param name="rootDeviceData">The root device data.</param>
/// <param name="deviceData">The device data.</param>
/// <returns>New Device</returns>
private DeviceClass CreateDevice([AllowNull]DeviceClass parent, [AllowNull]RootDeviceData rootDeviceData, DeviceDataBase deviceData)
{
if (rootDeviceData != null)
{
Trace.TraceInformation(Invariant($"Creating {deviceData.Name} under {rootDeviceData.Name}"));
}
else
{
Trace.TraceInformation(Invariant($"Creating Root {deviceData.Name}"));
}
DeviceClass device = null;
int refId = HS.NewDeviceRef(rootDeviceData != null ? Invariant($"{rootDeviceData.Name} {deviceData.Name}") : deviceData.Name);
if (refId > 0)
{
device = (DeviceClass)HS.GetDeviceByRef(refId);
string address = rootDeviceData != null ? CreateChildAddress(rootDeviceData.Name, deviceData.Name) : deviceData.Name;
device.set_Address(HS, address);
device.set_Device_Type_String(HS, deviceData.HSDeviceTypeString);
var deviceType = new DeviceTypeInfo_m.DeviceTypeInfo();
deviceType.Device_API = DeviceTypeInfo_m.DeviceTypeInfo.eDeviceAPI.Plug_In;
deviceType.Device_Type = deviceData.HSDeviceType;
device.set_DeviceType_Set(HS, deviceType);
device.set_Interface(HS, Name);
device.set_InterfaceInstance(HS, string.Empty);
device.set_Last_Change(HS, DateTime.Now);
device.set_Location(HS, Name);
var pairs = deviceData.StatusPairs;
foreach (var pair in pairs)
{
HS.DeviceVSP_AddPair(refId, pair);
}
var gPairs = deviceData.GraphicsPairs;
foreach (var gpair in gPairs)
{
HS.DeviceVGP_AddPair(refId, gpair);
}
device.MISC_Set(HS, Enums.dvMISC.STATUS_ONLY);
device.MISC_Set(HS, Enums.dvMISC.SHOW_VALUES);
device.MISC_Clear(HS, Enums.dvMISC.AUTO_VOICE_COMMAND);
device.MISC_Clear(HS, Enums.dvMISC.SET_DOES_NOT_CHANGE_LAST_CHANGE);
device.set_Status_Support(HS, false);
if (parent != null)
{
parent.set_Relationship(HS, Enums.eRelationship.Parent_Root);
device.set_Relationship(HS, Enums.eRelationship.Child);
device.AssociatedDevice_Add(HS, parent.get_Ref(HS));
parent.AssociatedDevice_Add(HS, device.get_Ref(HS));
}
deviceData.SetInitialData(HS, device);
}
return device;
}
/// <summary>
/// Creates the devices based on configuration.
/// </summary>
/// <param name="currentDevices">The current HS devices.</param>
/// <param name="token">The token.</param>
private void CreateDevices(IDictionary<string, DeviceClass> currentDevices, CancellationToken token)
{
try
{
foreach (var deviceDefinition in WUWeatherData.DeviceDefinitions)
{
token.ThrowIfCancellationRequested();
currentDevices.TryGetValue(deviceDefinition.Name, out DeviceClass parentDevice);
foreach (var childDeviceDefinition in deviceDefinition.Children)
{
token.ThrowIfCancellationRequested();
if (!pluginConfig.GetDeviceEnabled(deviceDefinition, childDeviceDefinition))
{
continue;
}
// lazy creation of parent device when child is created
if (parentDevice == null)
{
parentDevice = CreateDevice(null, null, deviceDefinition);
currentDevices.Add(parentDevice.get_Address(HS), parentDevice);
}
string childAddress = CreateChildAddress(parentDevice.get_Address(HS), childDeviceDefinition.Name);
if (!currentDevices.ContainsKey(childAddress))
{
var childDevice = CreateDevice(parentDevice, deviceDefinition, childDeviceDefinition);
currentDevices.Add(childDevice.get_Address(HS), childDevice);
}
}
}
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to Create Devices For PlugIn With {ex.GetFullMessage()}"));
}
}
/// <summary>
/// Gets the current devices for plugin from Homeseer
/// </summary>
/// <returns>Current devices for plugin</returns>
/// <exception cref="HspiException"></exception>
private IDictionary<string, DeviceClass> GetCurrentDevices(CancellationToken token)
{
var deviceEnumerator = HS.GetDeviceEnumerator() as clsDeviceEnumeration;
if (deviceEnumerator == null)
{
throw new HspiException(Invariant($"{Name} failed to get a device enumerator from HomeSeer."));
}
var currentDevices = new Dictionary<string, DeviceClass>();
do
{
token.ThrowIfCancellationRequested();
DeviceClass device = deviceEnumerator.GetNext();
if ((device != null) &&
(device.get_Interface(HS) != null) &&
(device.get_Interface(HS).Trim() == Name))
{
string address = device.get_Address(HS);
currentDevices.Add(address, device);
}
} while (!deviceEnumerator.Finished);
return currentDevices;
}
public override string GetPagePlugin(string page, [AllowNull]string user, int userRights, [AllowNull]string queryString)
{
if (page == ConfigPage.Name)
{
return configPage.GetWebPage();
}
return string.Empty;
}
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;
}
#region "Script Override"
public override object PluginFunction([AllowNull]string functionName, [AllowNull] object[] parameters)
{
try
{
switch (functionName)
{
case null:
return null;
case "Refresh":
RestartPeriodicTask();
break;
}
return null;
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to execute function with {ex.GetFullMessage()}"));
return null;
}
}
#endregion "Script Override"
#region "Action Override"
public override int ActionCount()
{
return 1;
}
public override string get_ActionName(int actionNumber)
{
switch (actionNumber)
{
case ActionRefreshTANumber:
return Invariant($"{Name}:Refresh");
default:
return base.get_ActionName(actionNumber);
}
}
public override string ActionBuildUI([AllowNull]string uniqueControlId, IPlugInAPI.strTrigActInfo actionInfo)
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
return string.Empty;
default:
return base.ActionBuildUI(uniqueControlId, actionInfo);
}
}
public override string ActionFormatUI(IPlugInAPI.strTrigActInfo actionInfo)
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
return Invariant($"{WUWeatherData.PlugInName} Refreshes Data");
default:
return base.ActionFormatUI(actionInfo);
}
}
public override bool HandleAction(IPlugInAPI.strTrigActInfo actionInfo)
{
try
{
switch (actionInfo.TANumber)
{
case ActionRefreshTANumber:
RestartPeriodicTask();
return true;
default:
return base.HandleAction(actionInfo);
}
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to execute action with {ex.GetFullMessage()}"));
return false;
}
}
#endregion "Action Override"
/// <summary>
/// Restarts the periodic task to fetch data from server
/// </summary>
/// <param name="initialDelay">The initial one time delay.</param>
private void RestartPeriodicTask(TimeSpan? initialDelay = null)
{
lock (periodicTaskLock)
{
StopPeriodicTask(false);
cancellationTokenSourceForUpdateDevice = new CancellationTokenSource();
periodicTask = CreateAndUpdateDevices(initialDelay); // dont wait
}
}
private void StopPeriodicTask(bool ignoreExceptions)
{
if (periodicTask != null)
{
cancellationTokenSourceForUpdateDevice.Cancel();
try
{
periodicTask.Wait();
}
catch (AggregateException ex)
{
ex.Handle((exception) =>
{
if ((exception is OperationCanceledException) ||
(exception is TaskCanceledException))
{
return true;
}
return ignoreExceptions;
});
}
cancellationTokenSourceForUpdateDevice.Dispose();
}
}
/// <summary>
/// Creates the and update devices.
/// </summary>
/// <param name="initialDelay">The initial one time delay.</param>
/// <returns></returns>
private async Task CreateAndUpdateDevices(TimeSpan? initialDelay)
{
using (var combinedToken = CancellationTokenSource.CreateLinkedTokenSource(ShutdownCancellationToken,
cancellationTokenSourceForUpdateDevice.Token))
{
var currentDevices = GetCurrentDevices(combinedToken.Token);
while (!combinedToken.IsCancellationRequested)
{
try
{
if (initialDelay.HasValue)
{
await Task.Delay(initialDelay.Value, combinedToken.Token).ConfigureAwait(false);
initialDelay = null;
}
CreateDevices(currentDevices, combinedToken.Token);
await FetchAndUpdateDevices(currentDevices, combinedToken.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to Fetch Data with {ex.GetFullMessage()}"));
}
// Set it to run after RefreshIntervalMinutes minutes or next 12.00 am
TimeSpan nextRun = TimeSpan.FromMinutes(pluginConfig.RefreshIntervalMinutes);
TimeSpan nextDay = DateTimeOffset.Now.Date.AddDays(1) - DateTimeOffset.Now;
await Task.Delay(nextRun < nextDay ? nextRun : nextDay, combinedToken.Token).ConfigureAwait(false);
}
}
}
/// <summary>
/// Fetches the WU Data and update devices.
/// </summary>
/// <param name="existingDevices">The existing devices in HS.</param>
/// <param name="token">The token.</param>
/// <returns>Task</returns>
private async Task FetchAndUpdateDevices(IDictionary<string, DeviceClass> existingDevices, CancellationToken token)
{
if (string.IsNullOrWhiteSpace(pluginConfig.APIKey) || string.IsNullOrWhiteSpace(pluginConfig.StationId))
{
Trace.TraceWarning("Configuration not setup to fetch weather data");
return;
}
Trace.TraceInformation(Invariant($"Starting data fetch from WU Weather from station:{pluginConfig.StationId}"));
LogConfiguration();
WUWeatherService service = new WUWeatherService(pluginConfig.APIKey);
XmlDocument rootXmlDocument = await service.GetDataForStationAsync(pluginConfig.StationId, token).ConfigureAwait(false);
XPathNavigator rootNavigator = rootXmlDocument.CreateNavigator();
foreach (var deviceDefinition in WUWeatherData.DeviceDefinitions)
{
token.ThrowIfCancellationRequested();
existingDevices.TryGetValue(deviceDefinition.Name, out var rootDevice);
if (rootDevice == null)
{
// no root device exists yet so children won't exist
continue;
}
Unit currentUnit = pluginConfig.Unit;
XPathExpression childExpression = deviceDefinition.PathData.GetPath(currentUnit);
XPathNodeIterator childNodeIter = rootNavigator.Select(childExpression);
if (childNodeIter != null && childNodeIter.MoveNext())
{
XmlElement childElement = childNodeIter.Current.UnderlyingObject as XmlElement;
if (childElement == null)
{
Trace.TraceWarning(Invariant($"{deviceDefinition.Name} has invalid type in xml document."));
continue;
}
deviceDefinition.UpdateDeviceData(HS, rootDevice, childElement);
var childNavigator = childElement.CreateNavigator();
DateTimeOffset? lastUpdate = deviceDefinition.LastUpdateTime;
foreach (var childDeviceDefinition in deviceDefinition.Children)
{
string childAddress = CreateChildAddress(deviceDefinition.Name, childDeviceDefinition.Name);
existingDevices.TryGetValue(childAddress, out var childDevice);
if (childDevice != null)
{
token.ThrowIfCancellationRequested();
try
{
XPathExpression subExpression = childDeviceDefinition.PathData.GetPath(this.pluginConfig.Unit);
XPathNodeIterator elements = childNavigator.Select(subExpression);
childDeviceDefinition.UpdateDeviceData(HS, childDevice, elements);
if (lastUpdate.HasValue)
{
childDevice.set_Last_Change(HS, lastUpdate.Value.DateTime);
}
var scaledNumberDeviceData = childDeviceDefinition as ScaledNumberDeviceData;
if (scaledNumberDeviceData != null)
{
childDevice.set_ScaleText(HS, scaledNumberDeviceData.GetDeviceSuffix(currentUnit));
}
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
Trace.TraceError(Invariant($"Failed to update [{childAddress}] with {ex.GetFullMessage()}"));
}
}
}
}
}
Trace.TraceInformation(Invariant($"Finished Processing update from station:{pluginConfig.StationId}"));
}
private void RegisterConfigPage()
{
string link = ConfigPage.Name;
HS.RegisterPage(link, Name, string.Empty);
HomeSeerAPI.WebPageDesc wpd = new HomeSeerAPI.WebPageDesc()
{
plugInName = Name,
link = link,
linktext = "Configuration",
page_title = Invariant($"{Name} Configuration"),
};
Callback.RegisterConfigLink(wpd);
Callback.RegisterLink(wpd);
}
/// <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)
{
lock (periodicTaskLock)
{
StopPeriodicTask(true);
}
if (pluginConfig != null)
{
pluginConfig.ConfigChanged -= PluginConfig_ConfigChanged;
}
if (configPage != null)
{
configPage.Dispose();
}
if (pluginConfig != null)
{
pluginConfig.Dispose();
}
disposedValue = true;
}
base.Dispose(disposing);
}
private CancellationTokenSource cancellationTokenSourceForUpdateDevice = new CancellationTokenSource();
private Task periodicTask;
private readonly object periodicTaskLock = new object();
private ConfigPage configPage;
private PluginConfig pluginConfig;
private const int ActionRefreshTANumber = 1;
private bool disposedValue = false;
}
}