-
Notifications
You must be signed in to change notification settings - Fork 0
/
WorkerDataGenerator.cs
325 lines (262 loc) · 14.1 KB
/
WorkerDataGenerator.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
using HassSensorConfiguration;
using HomeAssistantDataGenerator.Configuration;
using HomeAssistantDataGenerator.Generators;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MQTTnet;
using MQTTnet.Client.Options;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Protocol;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace HomeAssistantDataGenerator
{
public interface IWorkerDataGenerator
{
Task PublishAsync(string topic, string payload, MqttQualityOfServiceLevel mqttQosLevel);
Task PublishAsync(string configurationTopic, string configurationPayload, MqttQualityOfServiceLevel mqttQosLevel, bool retain);
}
public class WorkerDataGenerator : BackgroundService, IWorkerDataGenerator
{
protected ILogger<WorkerDataGenerator> Logger { get; }
protected ProgramConfiguration ProgramConfiguration { get; }
protected MqttConfiguration MqttConfiguration { get; }
public IManagedMqttClient MqttClient { get; }
protected List<IHassComponent> ComponentList { get; } = new List<IHassComponent>();
protected List<Task> GeneratorTasks { get; set; } = new();
public WorkerDataGenerator(ILogger<WorkerDataGenerator> logger, IOptions<ProgramConfiguration> programConfiguration, IOptions<MqttConfiguration> mqttConfiguration)
{
Logger = logger;
ProgramConfiguration = programConfiguration.Value;
MqttConfiguration = mqttConfiguration.Value;
MqttClient = new MqttFactory().CreateManagedMqttClient();
}
private static IDataGenerator GeneratorFactory(PresetGenerator presetGenerator)
{
switch (presetGenerator.GeneratorType)
{
case GeneratorType.File:
var gen1 = typeof(FileGenerator<>);
Type[] typeArgs1 = { GetValuesType(presetGenerator.ValuesType) };
var makeme1 = gen1.MakeGenericType(typeArgs1);
return (IDataGenerator)Activator.CreateInstance(makeme1, presetGenerator);
case GeneratorType.Wave:
var gen2 = typeof(WaveGenerator<>);
Type[] typeArgs2 = { GetValuesType(presetGenerator.ValuesType) };
var makeme2 = gen2.MakeGenericType(typeArgs2);
return (IDataGenerator)Activator.CreateInstance(makeme2, presetGenerator);
case GeneratorType.BinaryRandom:
return new BinaryRandomGenerator(presetGenerator);
default: return null;
}
}
private static Type GetValuesType(ValuesType valuesType) =>
valuesType switch
{
ValuesType.Integer => typeof(Int32),
ValuesType.Double => typeof(Double),
ValuesType.String => typeof(String),
_ => throw new ArgumentException($"Invalud type! {valuesType}"),
};
public async Task PublishAsync(string topic, string payload, MqttQualityOfServiceLevel mqttQosLevel) =>
await MqttClient.PublishAsync(topic, payload, mqttQosLevel);
public async Task PublishAsync(string topic, string payload, MqttQualityOfServiceLevel mqttQosLevel, bool retain) =>
await MqttClient.PublishAsync(topic, payload, mqttQosLevel, retain);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
var task = ConnectToMqtt(stoppingToken);
CreateComponents();
CreateGeneratorTasks(stoppingToken);
await task;
// send device configuration with retain flag
await SendDeviceConfiguration();
Logger.LogInformation("Sent devices configuration at: {time}", DateTimeOffset.Now);
//await PostSendConfigurationAsync(stoppingToken);
Logger.LogInformation("Running at: {time}", DateTimeOffset.Now);
try
{
while (!stoppingToken.IsCancellationRequested)
await Task.Delay(30000, stoppingToken);
// wait to all work tasks finished
Task.WaitAll(GeneratorTasks.ToArray(), 5000, stoppingToken);
}
catch (TaskCanceledException) { }
Logger.LogInformation("Stopping at: {time}", DateTimeOffset.Now);
}
catch (Exception ex)
{
Logger.LogError(ex, "Error at {time}", DateTimeOffset.Now);
}
}
private async Task ConnectToMqtt(CancellationToken stoppingToken)
{
Logger.LogInformation("Creating MqttClient at: {time}. Uri:{mqttUri}", DateTimeOffset.Now, MqttConfiguration.MqttUri);
var messageBuilder = new MqttClientOptionsBuilder()
.WithClientId(MqttConfiguration.ClientId.Replace("-", "").Replace(" ", ""))
.WithCredentials(MqttConfiguration.MqttUser, MqttConfiguration.MqttUserPassword)
.WithTcpServer(MqttConfiguration.MqttUri, MqttConfiguration.MqttPort)
.WithCleanSession();
var options = MqttConfiguration.MqttSecure ?
messageBuilder.WithTls().Build() :
messageBuilder.Build();
var managedOptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(options)
.Build();
await MqttClient.StartAsync(managedOptions);
// wait for connection
while (!MqttClient.IsConnected && !stoppingToken.IsCancellationRequested)
{
Logger.LogTrace("MqttClient not connected... Go to sleep for a second...");
Thread.Sleep(1000);
}
Logger.LogInformation("Creating MqttClient done at: {time}", DateTimeOffset.Now);
}
private void CreateComponents()
{
foreach (var virtualDevice in ProgramConfiguration.Devices)
{
var device = new Device
{
Name = virtualDevice.DeviceDescription.Name,
Model = virtualDevice.DeviceDescription.Model,
Manufacturer = virtualDevice.DeviceDescription.Manufacturer,
Identifiers = new List<string> { virtualDevice.DeviceDescription.Identifier },
DataFormat = virtualDevice.DeviceDescription.DataFormat
};
var deviceDescription = GetDeviceClassDescriptionValue(virtualDevice.DeviceDescription.DeviceType);
var componentFactory = deviceDescription.ComponentFactory;
var sensorDescription = componentFactory.CreateSensorDescription();
sensorDescription.DeviceClassDescription = deviceDescription;
sensorDescription.Device = device;
ComponentList.Add(componentFactory.CreateComponent(sensorDescription));
}
}
protected static DeviceClassDescription GetDeviceClassDescriptionValue(string deviceClass) =>
deviceClass switch
{
"Temperature" => DeviceClassDescription.Temperature,
"Voltage" => DeviceClassDescription.Voltage,
"PressureHpa" => DeviceClassDescription.PressureHpa,
"Current" => DeviceClassDescription.Current,
"FrequencyHz" => DeviceClassDescription.FrequencyHz,
"Humidity" => DeviceClassDescription.Humidity,
"Plug" => DeviceClassDescription.Plug,
_ => DeviceClassDescription.None,
};
public void CreateGeneratorTasks(CancellationToken cancellationToken)
{
Logger.LogInformation("Creating Generators at: {time}", DateTimeOffset.Now);
foreach (var device in ProgramConfiguration.Devices)
{
var generatorExt = GeneratorFactory(device.PresetGenerator);
var task = new Task(() =>
{
var component = ComponentList.First(e => e.Device.Identifiers[0] == device.DeviceDescription.Identifier);
var generator = generatorExt;
var ct = cancellationToken;
while (!ct.IsCancellationRequested)
{
try
{
if (generator.GetValue(DateTime.Now, out var value))
{
object payload = "";
string topic = "";
switch (component.Device.DataFormat)
{
case DataFormat.Correct:
var payloadJObj1 = JObject.FromObject(new
{
Id = component.Device.Identifiers[0],
name = $"{component.Device.Identifiers[0]}"
});
payloadJObj1.Add(new JProperty(component.DeviceClassDescription.ValueName, value.ToString()));
payload = payloadJObj1;
topic = component.StateTopic.Replace("+/+", $"{MqttConfiguration.MqttHomeDeviceTopic}/{ProgramConfiguration.ServiceName}");
break;
case DataFormat.Invalid1: // Other topic and custom value
var payloadJObj2 = JObject.FromObject(new
{
Sensor = component.Device.Identifiers[0]
});
payloadJObj2.Add("value", value.ToString());
payload = payloadJObj2;
topic = $"Device{component.Device.Identifiers[0]}";
break;
case DataFormat.Invalid2: // binary
if (value is double @double) // integer, last two digits - after comma
payload = ((int)Math.Truncate(@double * 100)).ToString("X");
else if (value is int @int)
payload = @int.ToString("X");
else if (value is bool boolean)
payload = boolean ? 1 : 0;
else throw new ArgumentException("Invalid Argument", nameof(DataFormat));
topic = $"Binary-{component.Device.Identifiers[0]}-Sensor";
break;
case DataFormat.Invalid3: // xml
payload = $"<sensor><data><name>{component.DeviceClassDescription.ValueName}</name><value>{value}</value></data>";
topic = $"XmlSensor_{component.Device.Identifiers[0]}";
break;
case DataFormat.Invalid4: // csv
payload = $"{component.DeviceClassDescription.ValueName};{value}";
topic = $"CSV-{component.Device.Identifiers[0]}";
break;
case DataFormat.Invalid5: //simple
payload = value.ToString();
topic = $"Sensor{component.Device.Identifiers[0]}";
break;
}
// send message
var t = MqttClient.PublishAsync(topic, payload.ToString(), MqttConfiguration.MqttQosLevel);
t.Wait();
Logger.LogInformation("WorkerDataGenerator send message: '{payload}' at {time}", payload, DateTimeOffset.Now);
}
}
catch (Exception e)
{
Logger.LogError(e, "WorkerDataGenerator send message error at {time}", DateTimeOffset.Now);
}
ct.WaitHandle.WaitOne(1000);
}
}, cancellationToken);
task.Start();
GeneratorTasks.Add(task);
}
Logger.LogInformation("Generators created at: {time}", DateTimeOffset.Now);
}
/// <summary>
/// publish configuration message with retain flag to HomeAssistant
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
protected async Task SendDeviceConfiguration()
{
try
{
foreach (var component in ComponentList.Where(e => e.Device.DataFormat == DataFormat.Correct))
{
await MqttClient.PublishAsync(
string.Format(MqttConfiguration.ConfigurationTopic,
component.GetType().GetHassComponentTypeString(), component.UniqueId),
JsonConvert.SerializeObject(component),
MqttConfiguration.MqttQosLevel,
true);
Logger.LogInformation("Send configuration for component {uniqueId} at: {time}", component.UniqueId, DateTimeOffset.Now);
}
}
catch (Exception ex)
{
Logger.LogError(ex, "Error at {time}", DateTimeOffset.Now);
}
}
}
}