-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRabbitService.cs
More file actions
184 lines (171 loc) · 8.33 KB
/
Copy pathRabbitService.cs
File metadata and controls
184 lines (171 loc) · 8.33 KB
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
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MQTTnet;
using MQTTnet.Formatter;
using System.Linq;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using TemperatureSensorArduinoReader.TopicStrategies;
namespace TemperatureSensorArduinoReader
{
public class RabbitService : IDisposable
{
private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
private IMqttClient? managedMqttClientPublisher;
private static readonly Random random = new();
private readonly IOptions<TemperatureAppSettings> temperatureAppSettings;
private readonly ILogger<RabbitService> logger;
private readonly TopicDispatcher topicDispatcher;
private TimeSpan mqttConnectionTimeout = TimeSpan.Zero;
private SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);
private readonly MqttClientTlsOptions tlsOptions;
public RabbitService(IOptions<TemperatureAppSettings> temperatureAppSettings, ILogger<RabbitService> logger, IHostApplicationLifetime hostApplicationLifetime, TopicDispatcher topicDispatcher)
{
this.temperatureAppSettings = temperatureAppSettings;
this.logger = logger;
this.topicDispatcher = topicDispatcher;
tlsOptions = new MqttClientTlsOptions
{
UseTls = true,
CertificateValidationHandler = ValidateCertificate
};
hostApplicationLifetime.ApplicationStopping.Register(Stop);
Connect(cancellationTokenSource.Token).Wait();
}
private bool ValidateCertificate(MqttClientCertificateValidationEventArgs context)
{
if (context.SslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
if (context.SslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors
&& context.Chain != null
&& context.Chain.ChainStatus.All(s => s.Status is X509ChainStatusFlags.NoError or X509ChainStatusFlags.RevocationStatusUnknown or X509ChainStatusFlags.OfflineRevocation))
{
logger.LogInformation("Accepting MQTT TLS certificate {subject}; revocation status could not be checked.", context.Certificate?.Subject);
return true;
}
logger.LogWarning("MQTT TLS certificate validation errors: {errors} for {subject}", context.SslPolicyErrors, context.Certificate?.Subject);
if (context.Chain != null)
{
var chainStatus = string.Join("; ", context.Chain.ChainStatus.Select(s => $"{s.Status}: {s.StatusInformation?.Trim()}"));
logger.LogWarning("MQTT TLS chain status: {chainStatus}", chainStatus);
foreach (var element in context.Chain.ChainElements)
{
var elementStatus = string.Join(", ", element.ChainElementStatus.Select(s => s.Status.ToString()));
logger.LogWarning("MQTT TLS chain element {subject}: {status}", element.Certificate.Subject, string.IsNullOrEmpty(elementStatus) ? "OK" : elementStatus);
}
}
return false;
}
private void Stop()
{
cancellationTokenSource.Cancel();
}
private async Task Connect(CancellationToken cancellationToken)
{
logger.LogInformation("Connecting to MQTT broker...");
var mqttFactory = new MqttClientFactory();
managedMqttClientPublisher = mqttFactory.CreateMqttClient();
managedMqttClientPublisher.ConnectedAsync += Connected;
managedMqttClientPublisher.ApplicationMessageReceivedAsync += MessageReceived;
managedMqttClientPublisher.DisconnectedAsync += Disconnected;
await semaphore.WaitAsync(cancellationToken);
try
{
if (!managedMqttClientPublisher.IsConnected)
{
await managedMqttClientPublisher.ConnectAsync(BuildMQTTOptions(), cancellationToken);
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error connecting to MQTT broker.");
}
finally
{
semaphore.Release();
}
}
private async Task Connected(MqttClientConnectedEventArgs e)
{
logger.LogInformation("Connected to MQTT broker.");
mqttConnectionTimeout = TimeSpan.Zero;
await managedMqttClientPublisher.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(MqttTopics.HomeAssistantStatus).Build(), cancellationTokenSource.Token);
await managedMqttClientPublisher.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(MqttTopics.HeaterOutTemp).Build(), cancellationTokenSource.Token);
await managedMqttClientPublisher.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(MqttTopics.GarageTemperature).Build(), cancellationTokenSource.Token);
}
private async Task Disconnected(MqttClientDisconnectedEventArgs e)
{
await semaphore.WaitAsync(cancellationTokenSource.Token);
logger.LogWarning("Disconnected from MQTT broker.");
if (managedMqttClientPublisher != null)
{
while (!managedMqttClientPublisher.IsConnected)
{
if (cancellationTokenSource.IsCancellationRequested)
{
break;
}
mqttConnectionTimeout = TimeSpan.FromMilliseconds(Math.Min(mqttConnectionTimeout.TotalMilliseconds * 2 + random.Next(0, 5000), 300000));
await Task.Delay((int)mqttConnectionTimeout.TotalMilliseconds, cancellationTokenSource.Token);
try
{
logger.LogInformation("Reconnecting to MQTT broker...");
await managedMqttClientPublisher.ConnectAsync(BuildMQTTOptions(), cancellationTokenSource.Token);
}
catch (Exception ex)
{
logger.LogError(ex, "Error reconnecting to MQTT broker.");
}
}
}
semaphore.Release();
}
private async Task MessageReceived(MqttApplicationMessageReceivedEventArgs e)
{
logger.LogInformation("Received MQTT message on topic {topic}", e.ApplicationMessage.Topic);
await topicDispatcher.Dispatch(e.ApplicationMessage.Topic, e.ApplicationMessage.Payload, cancellationTokenSource.Token);
}
public async Task Publish(object data, string topic, CancellationToken cancellationToken)
{
if (managedMqttClientPublisher != null && !managedMqttClientPublisher.IsConnected)
{
await Connect(cancellationToken);
}
try
{
if (managedMqttClientPublisher != null)
{
await managedMqttClientPublisher.PublishStringAsync(topic, data.ToString(), cancellationToken: cancellationToken);
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error publishing to MQTT broker.");
throw;
}
}
public void Dispose()
{
managedMqttClientPublisher?.DisconnectAsync(cancellationToken: cancellationTokenSource.Token).Wait();
managedMqttClientPublisher?.Dispose();
managedMqttClientPublisher = null;
cancellationTokenSource.Dispose();
semaphore.Dispose();
}
private MqttClientOptions BuildMQTTOptions()
{
var builder = new MqttClientOptionsBuilder()
.WithTcpServer(temperatureAppSettings.Value.MqttBroker, temperatureAppSettings.Value.MqttPort)
.WithProtocolVersion(MqttProtocolVersion.V311)
.WithTlsOptions(tlsOptions)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(60))
.WithCleanSession(true)
.WithCredentials(temperatureAppSettings.Value.MQTTUsername, Encoding.UTF8.GetBytes(temperatureAppSettings.Value.MQTTPassword));
return builder.Build();
}
}
}