forked from equinor/flotilla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MqttService.cs
314 lines (279 loc) · 12.4 KB
/
MqttService.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
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Api.Mqtt.Events;
using Api.Mqtt.MessageModels;
using Api.Utilities;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Packets;
namespace Api.Mqtt
{
public class MqttService : BackgroundService
{
private readonly ILogger<MqttService> _logger;
private readonly int _maxRetryAttempts;
private readonly IManagedMqttClient _mqttClient;
private readonly ManagedMqttClientOptions _options;
private readonly TimeSpan _reconnectDelay = TimeSpan.FromSeconds(5);
//private readonly bool _notProduction;
private readonly string _serverHost;
private readonly int _serverPort;
private readonly bool _shouldFailOnMaxRetries;
private CancellationToken _cancellationToken;
private int _reconnectAttempts;
public MqttService(ILogger<MqttService> logger, IConfiguration config)
{
_reconnectAttempts = 0;
_logger = logger;
var mqttFactory = new MqttFactory();
_mqttClient = mqttFactory.CreateManagedMqttClient();
/*_notProduction = !(
config.GetValue<string?>("ASPNETCORE_ENVIRONMENT") ?? "Production"
).Equals("Production", StringComparison.OrdinalIgnoreCase);*/
var mqttConfig = config.GetSection("Mqtt");
string password = mqttConfig.GetValue<string>("Password") ?? "";
string username = mqttConfig.GetValue<string>("Username") ?? "";
_serverHost = mqttConfig.GetValue<string>("Host") ?? "";
_serverPort = mqttConfig.GetValue<int>("Port");
_maxRetryAttempts = mqttConfig.GetValue<int>("MaxRetryAttempts");
_shouldFailOnMaxRetries = mqttConfig.GetValue<bool>("ShouldFailOnMaxRetries");
var tlsOptions = new MqttClientTlsOptions
{
UseTls = true,
/* Currently disabled to use self-signed certificate in the internal broker communication */
//if (_notProduction)
IgnoreCertificateChainErrors = true
};
var builder = new MqttClientOptionsBuilder()
.WithTcpServer(_serverHost, _serverPort)
.WithTlsOptions(tlsOptions)
.WithCredentials(username, password);
_options = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(_reconnectDelay)
.WithClientOptions(builder.Build())
.Build();
RegisterCallbacks();
var topics = mqttConfig.GetSection("Topics").Get<List<string>>() ?? new List<string>();
SubscribeToTopics(topics);
}
public static event EventHandler<MqttReceivedArgs>? MqttIsarRobotStatusReceived;
public static event EventHandler<MqttReceivedArgs>? MqttIsarRobotInfoReceived;
public static event EventHandler<MqttReceivedArgs>? MqttIsarRobotHeartbeatReceived;
public static event EventHandler<MqttReceivedArgs>? MqttIsarMissionReceived;
public static event EventHandler<MqttReceivedArgs>? MqttIsarTaskReceived;
public static event EventHandler<MqttReceivedArgs>? MqttIsarStepReceived;
public static event EventHandler<MqttReceivedArgs>? MqttIsarBatteryReceived;
public static event EventHandler<MqttReceivedArgs>? MqttIsarPressureReceived;
public static event EventHandler<MqttReceivedArgs>? MqttIsarPoseReceived;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_cancellationToken = stoppingToken;
_logger.LogInformation("MQTT client STARTED");
await _mqttClient.StartAsync(_options);
await _cancellationToken;
await _mqttClient.StopAsync();
_logger.LogInformation("MQTT client STOPPED");
}
/// <summary>
/// The callback function for when a subscribed topic publishes a message
/// </summary>
/// <param name="messageReceivedEvent"> The event information for the MQTT message </param>
private Task OnMessageReceived(MqttApplicationMessageReceivedEventArgs messageReceivedEvent)
{
string content = messageReceivedEvent.ApplicationMessage.ConvertPayloadToString();
string topic = messageReceivedEvent.ApplicationMessage.Topic;
var messageType = MqttTopics.TopicsToMessages.GetItemByTopic(topic);
if (messageType is null)
{
_logger.LogError("No message class defined for topic '{topicName}'", topic);
return Task.CompletedTask;
}
_logger.LogDebug("Topic: {topic} - Message received: \n{payload}", topic, content);
switch (messageType)
{
case Type type when type == typeof(IsarRobotStatusMessage):
OnIsarTopicReceived<IsarRobotStatusMessage>(content);
break;
case Type type when type == typeof(IsarRobotInfoMessage):
OnIsarTopicReceived<IsarRobotInfoMessage>(content);
break;
case Type type when type == typeof(IsarRobotHeartbeatMessage):
OnIsarTopicReceived<IsarRobotHeartbeatMessage>(content);
break;
case Type type when type == typeof(IsarMissionMessage):
OnIsarTopicReceived<IsarMissionMessage>(content);
break;
case Type type when type == typeof(IsarTaskMessage):
OnIsarTopicReceived<IsarTaskMessage>(content);
break;
case Type type when type == typeof(IsarStepMessage):
OnIsarTopicReceived<IsarStepMessage>(content);
break;
case Type type when type == typeof(IsarBatteryMessage):
OnIsarTopicReceived<IsarBatteryMessage>(content);
break;
case Type type when type == typeof(IsarPressureMessage):
OnIsarTopicReceived<IsarPressureMessage>(content);
break;
case Type type when type == typeof(IsarPoseMessage):
OnIsarTopicReceived<IsarPoseMessage>(content);
break;
default:
_logger.LogWarning(
"No callback defined for MQTT message type '{type}'",
messageType.Name
);
break;
}
return Task.CompletedTask;
}
private Task OnConnected(MqttClientConnectedEventArgs obj)
{
_logger.LogInformation(
"Successfully connected to broker at {host}:{port}.",
_serverHost,
_serverPort
);
_reconnectAttempts = 0;
return Task.CompletedTask;
}
private Task OnConnectingFailed(ConnectingFailedEventArgs obj)
{
if (_reconnectAttempts == -1)
{
return Task.CompletedTask;
}
string errorMsg =
"Failed to connect to MQTT broker. Exception: " + obj.Exception.Message;
if (_reconnectAttempts >= _maxRetryAttempts)
{
_logger.LogError("{errorMsg}\n Exceeded max reconnect attempts.", errorMsg);
if (_shouldFailOnMaxRetries)
{
_logger.LogError("Stopping MQTT client due to critical failure");
StopAsync(_cancellationToken);
return Task.CompletedTask;
}
_reconnectAttempts = -1;
return Task.CompletedTask;
}
_reconnectAttempts++;
_logger.LogWarning(
"{errorMsg}\n Retrying in {time}s ({attempt}/{maxAttempts})",
errorMsg,
_reconnectDelay.Seconds,
_reconnectAttempts,
_maxRetryAttempts
);
return Task.CompletedTask;
}
private Task OnDisconnected(MqttClientDisconnectedEventArgs obj)
{
// Only log a disconnect if previously connected (not on reconnect attempt)
if (obj.ClientWasConnected)
{
if (obj.Reason is MqttClientDisconnectReason.NormalDisconnection)
{
_logger.LogInformation(
"Successfully disconnected from broker at {host}:{port}",
_serverHost,
_serverPort
);
}
else
{
_logger.LogWarning(
"Lost connection to broker at {host}:{port}",
_serverHost,
_serverPort
);
}
}
return Task.CompletedTask;
}
private void RegisterCallbacks()
{
_mqttClient.ConnectedAsync += OnConnected;
_mqttClient.DisconnectedAsync += OnDisconnected;
_mqttClient.ConnectingFailedAsync += OnConnectingFailed;
_mqttClient.ApplicationMessageReceivedAsync += OnMessageReceived;
}
public void SubscribeToTopics(List<string> topics)
{
List<MqttTopicFilter> topicFilters = new();
StringBuilder sb = new();
sb.AppendLine("Mqtt service subscribing to the following topics:");
topics.ForEach(
topic =>
{
topicFilters.Add(new MqttTopicFilter
{
Topic = topic
});
sb.AppendLine(topic);
}
);
_logger.LogInformation("{topicContent}", sb.ToString());
_mqttClient.SubscribeAsync(topicFilters).Wait();
}
private void OnIsarTopicReceived<T>(string content) where T : MqttMessage
{
T? message;
try
{
var options = new JsonSerializerOptions
{
Converters =
{
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
}
};
message = JsonSerializer.Deserialize<T>(content, options);
if (message is null)
{
throw new JsonException();
}
}
catch (Exception ex)
when (ex is JsonException or NotSupportedException or ArgumentException)
{
_logger.LogError(
"Could not create '{className}' object from MQTT message json",
typeof(T).Name
);
return;
}
var type = typeof(T);
try
{
var raiseEvent = type switch
{
_ when type == typeof(IsarRobotStatusMessage) => MqttIsarRobotStatusReceived,
_ when type == typeof(IsarRobotInfoMessage) => MqttIsarRobotInfoReceived,
_ when type == typeof(IsarRobotHeartbeatMessage) => MqttIsarRobotHeartbeatReceived,
_ when type == typeof(IsarMissionMessage) => MqttIsarMissionReceived,
_ when type == typeof(IsarTaskMessage) => MqttIsarTaskReceived,
_ when type == typeof(IsarStepMessage) => MqttIsarStepReceived,
_ when type == typeof(IsarBatteryMessage) => MqttIsarBatteryReceived,
_ when type == typeof(IsarPressureMessage) => MqttIsarPressureReceived,
_ when type == typeof(IsarPoseMessage) => MqttIsarPoseReceived,
_
=> throw new NotImplementedException(
$"No event defined for message type '{typeof(T).Name}'"
)
};
// Event will be null if there are no subscribers
if (raiseEvent is not null)
{
raiseEvent(this, new MqttReceivedArgs(message));
}
}
catch (NotImplementedException e)
{
_logger.LogWarning("{msg}", e.Message);
}
}
}
}