-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathPluginConfig.cs
390 lines (343 loc) · 15.2 KB
/
PluginConfig.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
using HomeSeerAPI;
using Hspi.Utils;
using Nito.AsyncEx;
using NullGuard;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using static System.FormattableString;
namespace Hspi
{
/// <summary>
/// Class to store PlugIn Configuration
/// </summary>
internal class PluginConfig
{
/// <summary>
/// Initializes a new instance of the <see cref="PluginConfig"/> class.
/// </summary>
/// <param name="HS">The homeseer application.</param>
public PluginConfig(IHSApplication HS)
{
this.HS = HS;
LoadDBSettings();
LoadPersistenceSettings();
LoadImportDeviceSettings();
debugLogging = GetValue(DebugLoggingKey, false);
}
public event EventHandler<EventArgs> ConfigChanged;
public InfluxDBLoginInformation DBLoginInformation
{
get
{
using (var sync = configLock.ReaderLock())
{
return influxDBLoginInformation;
}
}
set
{
using (var sync = configLock.WriterLock())
{
influxDBLoginInformation = value;
SetValue(InfluxDBUriKey, value.DBUri);
SetValue(InfluxDBUsernameKey, value.User);
SetValue(InfluxDBPasswordKey, HS.EncryptString(value.Password, string.Empty));
SetValue(InfluxDBDBKey, value.DB);
SetValue(RetentionKey, value.Retention);
}
}
}
/// <summary>
/// Gets or sets a value indicating whether debug logging is enabled.
/// </summary>
/// <value>
/// <c>true</c> if [debug logging]; otherwise, <c>false</c>.
/// </value>
public bool DebugLogging
{
get
{
using (var sync = configLock.ReaderLock())
{
return debugLogging;
}
}
set
{
using (var sync = configLock.WriterLock())
{
SetValue(DebugLoggingKey, value, ref debugLogging);
}
}
}
public IImmutableDictionary<string, DevicePersistenceData> DevicePersistenceData
{
get
{
using (var sync = configLock.ReaderLock())
{
return devicePersistenceData.ToImmutableDictionary();
}
}
}
public IImmutableDictionary<string, ImportDeviceData> ImportDevicesData
{
get
{
using (var sync = configLock.ReaderLock())
{
return importDevicesData.ToImmutableDictionary();
}
}
}
public static string CheckEmptyOrWhitespace([AllowNull]string value)
{
return string.IsNullOrWhiteSpace(value) ? null : value;
}
public void AddDevicePersistenceData(in DevicePersistenceData device)
{
using (var sync = configLock.WriterLock())
{
var newdevicePersistenceData = new Dictionary<string, DevicePersistenceData>(devicePersistenceData);
newdevicePersistenceData[device.Id] = device;
devicePersistenceData = newdevicePersistenceData;
SetValue(DeviceRefIdKey, device.DeviceRefId, device.Id);
SetValue(MeasurementKey, device.Measurement, device.Id);
SetValue(FieldKey, device.Field ?? string.Empty, device.Id);
SetValue(FieldStringKey, device.FieldString ?? string.Empty, device.Id);
SetValue(TagsKey, ObjectSerialize.SerializeToString(device.Tags) ?? string.Empty, device.Id);
SetValue(PersistenceIdsKey, devicePersistenceData.Keys.Aggregate((x, y) => x + PersistenceIdsSeparator + y));
SetValue(MaxValidValueKey, device.MaxValidValue, device.Id);
SetValue(MinValidValueKey, device.MinValidValue, device.Id);
SetValue(TrackedTypeKey, device.TrackedType, device.Id);
}
}
public void AddImportDeviceData(in ImportDeviceData device)
{
using (var sync = configLock.WriterLock())
{
var newImportDeviceData = new Dictionary<string, ImportDeviceData>(importDevicesData);
newImportDeviceData[device.Id] = device;
importDevicesData = newImportDeviceData;
SetValue(NameKey, device.Name, device.Id);
SetValue(SqlKey, device.Sql, device.Id);
SetValue(IntervalKey, device.Interval.TotalSeconds, device.Id);
SetValue(UnitKey, device.Unit, device.Id);
SetValue(ImportDevicesIdsKey, importDevicesData.Keys.Aggregate((x, y) => x + ImportDevicesIdsSeparator + y));
}
}
/// <summary>
/// Fires event that configuration changed.
/// </summary>
public void FireConfigChanged()
{
if (ConfigChanged != null)
{
var ConfigChangedCopy = ConfigChanged;
ConfigChangedCopy(this, EventArgs.Empty);
}
}
public void RemoveDevicePersistenceData(string id)
{
using (var sync = configLock.WriterLock())
{
var newdevicePersistenceData = new Dictionary<string, DevicePersistenceData>(devicePersistenceData);
newdevicePersistenceData.Remove(id);
devicePersistenceData = newdevicePersistenceData;
if (devicePersistenceData.Count > 0)
{
SetValue(PersistenceIdsKey, devicePersistenceData.Keys.Aggregate((x, y) => x + PersistenceIdsSeparator + y));
}
else
{
SetValue(PersistenceIdsKey, string.Empty);
}
HS.ClearINISection(id, FileName);
}
}
public void RemoveImportDeviceData(string id)
{
using (var sync = configLock.WriterLock())
{
var newImportDeviceData = new Dictionary<string, ImportDeviceData>(importDevicesData);
newImportDeviceData.Remove(id);
importDevicesData = newImportDeviceData;
if (importDevicesData.Count > 0)
{
SetValue(ImportDevicesIdsKey, devicePersistenceData.Keys.Aggregate((x, y) => x + ImportDevicesIdsSeparator + y));
}
else
{
SetValue(ImportDevicesIdsKey, string.Empty);
}
HS.ClearINISection(id, FileName);
}
}
private T GetValue<T>(string key, T defaultValue)
{
return GetValue(key, defaultValue, DefaultSection);
}
private T GetValue<T>(string key, T defaultValue, string section)
{
string stringValue = HS.GetINISetting(section, key, null, FileName);
if (stringValue != null)
{
try
{
T result = (T)System.Convert.ChangeType(stringValue, typeof(T), CultureInfo.InvariantCulture);
return result;
}
catch (Exception)
{
return defaultValue;
}
}
return defaultValue;
}
private void LoadDBSettings()
{
// read db uri
string influxDBUriString = GetValue(InfluxDBUriKey, string.Empty);
Uri.TryCreate(influxDBUriString, UriKind.Absolute, out Uri influxDBUri);
this.influxDBLoginInformation = new InfluxDBLoginInformation(
influxDBUri,
CheckEmptyOrWhitespace(GetValue(InfluxDBUsernameKey, string.Empty)),
CheckEmptyOrWhitespace(HS.DecryptString(GetValue(InfluxDBPasswordKey, string.Empty), string.Empty)),
CheckEmptyOrWhitespace(GetValue(InfluxDBDBKey, string.Empty)),
CheckEmptyOrWhitespace(GetValue(RetentionKey, string.Empty))
);
}
private void LoadImportDeviceSettings()
{
string importDevicesConcatString = GetValue(ImportDevicesIdsKey, string.Empty);
var ids = importDevicesConcatString.Split(ImportDevicesIdsSeparator);
importDevicesData = new Dictionary<string, ImportDeviceData>();
foreach (var id in ids)
{
string name = GetValue(NameKey, string.Empty, id);
string sql = GetValue(SqlKey, string.Empty, id);
string time = GetValue(IntervalKey, string.Empty, id);
string unit = GetValue(UnitKey, string.Empty, id);
if (!int.TryParse(time, out int timeSeconds))
{
continue;
}
var data = new ImportDeviceData(id, name, sql, TimeSpan.FromSeconds(timeSeconds), unit);
this.importDevicesData.Add(id, data);
}
}
private void LoadPersistenceSettings()
{
string deviceIdsConcatString = GetValue(PersistenceIdsKey, string.Empty);
var persistenceIds = deviceIdsConcatString.Split(PersistenceIdsSeparator);
devicePersistenceData = new Dictionary<string, DevicePersistenceData>();
foreach (var persistenceId in persistenceIds)
{
string deviceRefIdString = GetValue(DeviceRefIdKey, string.Empty, persistenceId);
if (!int.TryParse(deviceRefIdString, out int deviceRefId))
{
continue;
}
string measurement = GetValue(MeasurementKey, string.Empty, persistenceId);
string field = GetValue(FieldKey, string.Empty, persistenceId);
string fieldString = GetValue(FieldStringKey, string.Empty, persistenceId);
string maxValidValueString = GetValue(MaxValidValueKey, string.Empty, persistenceId);
string minValidValueString = GetValue(MinValidValueKey, string.Empty, persistenceId);
string trackedTypeString = GetValue(TrackedTypeKey, string.Empty, persistenceId);
var tagString = GetValue(TagsKey, string.Empty, persistenceId);
Dictionary<string, string> tags = null;
try
{
tags = ObjectSerialize.DeSerializeToObject(tagString) as Dictionary<string, string>;
}
catch (Exception ex)
{
Trace.TraceWarning(Invariant($"Failed to load tags for {deviceRefIdString} with {ex.GetFullMessage()}"));
}
double? maxValidValue = null;
double? minValidValue = null;
TrackedType? trackedType = null;
if (double.TryParse(maxValidValueString, out var value))
{
maxValidValue = value;
}
if (double.TryParse(minValidValueString, out value))
{
minValidValue = value;
}
if (Enum.TryParse<TrackedType>(trackedTypeString, out var trackedTypeValue))
{
trackedType = trackedTypeValue;
}
var data = new DevicePersistenceData(persistenceId, deviceRefId, measurement, field, fieldString, tags,
maxValidValue, minValidValue, trackedType);
this.devicePersistenceData.Add(persistenceId, data);
}
}
private void SetValue<T>(string key, T value, string section = DefaultSection)
{
string stringValue = System.Convert.ToString(value, CultureInfo.InvariantCulture);
HS.SaveINISetting(section, key, stringValue, FileName);
}
private void SetValue<T>(string key, Nullable<T> value, string section = DefaultSection) where T : struct
{
string stringValue = value.HasValue ? System.Convert.ToString(value.Value, CultureInfo.InvariantCulture) : string.Empty;
HS.SaveINISetting(section, key, stringValue, FileName);
}
private void SetValue<T>(string key, T value, ref T oldValue)
{
SetValue<T>(key, value, ref oldValue, DefaultSection);
}
private void SetValue<T>(string key, T value, ref T oldValue, string section)
{
if (!value.Equals(oldValue))
{
string stringValue = System.Convert.ToString(value, CultureInfo.InvariantCulture);
HS.SaveINISetting(section, key, stringValue, FileName);
oldValue = value;
}
}
public const string DefaultFieldValueString = "value";
public const string DeviceLocation1Tag = "location1";
public const string DeviceLocation2Tag = "location2";
public const string DeviceNameTag = "name";
public const string DeviceRefIdTag = "refid";
public const string DeviceStringValueDefaultField = "valueString";
public const string DeviceValueDefaultField = "value";
private const string DebugLoggingKey = "DebugLogging";
private const string DefaultSection = "Settings";
private const string DeviceRefIdKey = "DeviceRefId";
private const string FieldKey = "Field";
private const string FieldStringKey = "FieldString";
private const string ImportDevicesIdsKey = "ImportDeviceIds";
private const char ImportDevicesIdsSeparator = ',';
private const string InfluxDBDBKey = "InfluxDBDB";
private const string InfluxDBPasswordKey = "InfluxDBPassword";
private const string InfluxDBUriKey = "InfluxDBUri";
private const string InfluxDBUsernameKey = "InfluxDBUsername";
private const string IntervalKey = "IntervalSeconds";
private const string MaxValidValueKey = "MaxValidValue";
private const string MeasurementKey = "Measurement";
private const string MinValidValueKey = "MinValidValue";
private const string TrackedTypeKey = "TrackedTyp";
private const string NameKey = "Name";
private const string PersistenceIdsKey = "PersistenceIds";
private const char PersistenceIdsSeparator = ',';
private const string RetentionKey = "Retention";
private const string SqlKey = "Sql";
private const string TagsKey = "Tags";
private const string UnitKey = "Unit";
private readonly static string FileName = Invariant($"{Path.GetFileName(System.Reflection.Assembly.GetEntryAssembly().Location)}.ini");
private readonly AsyncReaderWriterLock configLock = new AsyncReaderWriterLock();
private readonly IHSApplication HS;
private bool debugLogging;
private Dictionary<string, DevicePersistenceData> devicePersistenceData;
private Dictionary<string, ImportDeviceData> importDevicesData;
private InfluxDBLoginInformation influxDBLoginInformation;
};
}