-
Notifications
You must be signed in to change notification settings - Fork 4
/
MqttNode.cs
397 lines (314 loc) · 13.3 KB
/
MqttNode.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
using Godot;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Protocol;
using MQTTnet.Server;
using RoverControlApp.Core;
using RoverControlApp.Core.Settings;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.ServiceModel;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RoverControlApp.MVVM.Model;
public partial class MqttNode : Node
{
[Signal]
public delegate void ConnectionChangedEventHandler(ConnectionState state);
[Signal]
public delegate void MessageReceivedEventHandler(string topic, MqttNodeMessage message);
public delegate Task MessageReceivedAsyncEventHandler(string topic, MqttApplicationMessage? message);
public event MessageReceivedAsyncEventHandler? MessageReceivedAsync;
public CommunicationState ConnectionState
{
get => _connectionState;
private set
{
if (_connectionState == value) return;
_connectionState = value;
CallDeferred(MethodName.EmitSignal, SignalName.ConnectionChanged, (int)_connectionState);
EventLogger.LogMessageDebug("MqttNode", EventLogger.LogLevel.Verbose, $"Connection state changed to \"{value}\"");
}
}
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
public static MqttNode Singleton { get; private set; }
#pragma warning restore CS8618
/*
* Godot overrides
*/
public override void _Ready()
{
Singleton ??= this;
LocalSettings.Singleton.Connect(LocalSettings.SignalName.CategoryChanged, Callable.From<StringName>(OnSettingsCategoryChanged));
LocalSettings.Singleton.Connect(LocalSettings.SignalName.PropagatedPropertyChanged, Callable.From<StringName, StringName, Variant, Variant>(OnSettingsPropertyChanged));
LocalSettings.Singleton.Connect(LocalSettings.SignalName.PropagatedSubcategoryChanged, Callable.From<StringName, StringName, Variant, Variant>(OnSettingsSubcategoryChanged));
MqStart();
}
public override void _ExitTree()
{
LocalSettings.Singleton.Disconnect(LocalSettings.SignalName.CategoryChanged, Callable.From<StringName>(OnSettingsCategoryChanged));
LocalSettings.Singleton.Disconnect(LocalSettings.SignalName.PropagatedPropertyChanged, Callable.From<StringName, StringName, Variant, Variant>(OnSettingsPropertyChanged));
LocalSettings.Singleton.Disconnect(LocalSettings.SignalName.PropagatedSubcategoryChanged, Callable.From<StringName, StringName, Variant, Variant>(OnSettingsSubcategoryChanged));
MqStop();
RequestReady();
}
/*
* Settings handlers
*/
void OnSettingsCategoryChanged(StringName property)
{
if (property != nameof(LocalSettings.Mqtt)) return;
MqRestart();
}
void OnSettingsPropertyChanged(StringName category, StringName name, Variant oldValue, Variant newValue)
{
if (category != nameof(Mqtt)) return;
var (newTopic, newQos) =
(LocalSettings.Singleton.Mqtt.GetAllTopicsToSubscribe().Where(entry => entry.Item1 == newValue.AsString())).FirstOrDefault();
if (string.IsNullOrEmpty(newTopic))
return;
MqUnsubscribeTopic(oldValue.AsString());
MqSubscribeTopic(newTopic, newQos);
}
void OnSettingsSubcategoryChanged(StringName category, StringName name, Variant oldValue, Variant newValue)
{
if (category != nameof(Mqtt) || name != nameof(Mqtt.ClientSettings)) return;
MqRestart();
}
/*
* Helper methods
*/
public static string TopicFull(string subtopic)
{
return LocalSettings.Singleton.Mqtt.ClientSettings.TopicMain + "/" + subtopic;
}
/*
* Public methods Mqtt
*/
public async Task EnqueueMessageAsync(string subtopic, string? arg, MqttQualityOfServiceLevel qos = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
{
await _managedMqttClient.EnqueueAsync(TopicFull(subtopic),arg, qos, retain);
EventLogger.LogMessageDebug("MqttNode", EventLogger.LogLevel.Verbose, $"Message enqueued at subtopic: \"{subtopic}\" with:\n{arg}");
}
public void EnqueueMessage(string subtopic, string? arg, MqttQualityOfServiceLevel qos = MqttQualityOfServiceLevel.AtMostOnce, bool retain = false)
{
Task.Run(async () => await _managedMqttClient.EnqueueAsync(subtopic, arg, qos, retain));
EventLogger.LogMessageDebug("MqttNode", EventLogger.LogLevel.Verbose, $"Message enqueued at subtopic: \"{subtopic}\" with:\n{arg}");
}
public MqttApplicationMessage? GetReceivedMessageOnTopic(string? subtopic)
{
if (subtopic == null) return null;
MqttApplicationMessage? response = new();
var succ = _responses?.TryGetValue(subtopic, out response) ?? false;
return succ ? response : null;
}
public string? GetReceivedMessageOnTopicAsString(string? subtopic)
{
return GetReceivedMessageOnTopic(subtopic)?.ConvertPayloadToString();
}
/*
* Methods for Mqtt control
*/
private bool MqStart()
{
if (ConnectionState == CommunicationState.Created)
{
EventLogger.LogMessageDebug(LogSource, EventLogger.LogLevel.Warning, "Can't start, mqtt is already starting!");
return false;
}
if (ConnectionState != CommunicationState.Closed)
{
EventLogger.LogMessageDebug(LogSource, EventLogger.LogLevel.Warning, "Can't start, mqtt is not fully closed!");
return false;
}
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Verbose, "Starting mqtt");
ConnectionState = CommunicationState.Created;
_cts = new CancellationTokenSource();
_responses = new Dictionary<string, MqttApplicationMessage?>();
_mqttThread = new Thread(ThWork) { IsBackground = true, Name = "MqttThread", Priority = ThreadPriority.BelowNormal };
_mqttThread.Start();
return true;
}
private bool MqStop(bool awaitFullStop = false)
{
switch (ConnectionState)
{
case CommunicationState.Closed:
EventLogger.LogMessageDebug(LogSource, EventLogger.LogLevel.Warning, "Can't stop, mqtt is stopped!");
return false;
case CommunicationState.Closing:
EventLogger.LogMessageDebug(LogSource, EventLogger.LogLevel.Warning, "Can't stop, mqtt is already stopping!");
return false;
}
EventLogger.LogMessageDebug(LogSource, EventLogger.LogLevel.Verbose, "Requesting thread stop");
_cts!.Cancel();
if(awaitFullStop)
{
_mqttThread!.Join();
EventLogger.LogMessageDebug(LogSource, EventLogger.LogLevel.Verbose, "Thread stop confirmed!");
return true;
}
EventLogger.LogMessageDebug(LogSource, EventLogger.LogLevel.Verbose,
_mqttThread!.Join(200) ? "Thread stop confirmed!" : "Thread stop not confirmed. Proceeding");
return true;
}
private void MqRestart()
{
Task.Run(() => { MqStop(true); MqStart(); });
}
private async Task MqSubscribeTopicAsync(string subtopic, MqttQualityOfServiceLevel qos = MqttQualityOfServiceLevel.AtMostOnce)
{
if (string.IsNullOrEmpty(subtopic)) return;
var topic = TopicFull(subtopic);
EventLogger.LogMessage(LogSource,EventLogger.LogLevel.Verbose, $"Subscribing to topic: \"{topic}\"");
await _managedMqttClient.SubscribeAsync(topic, qos);
}
private void MqSubscribeTopic(string subtopic, MqttQualityOfServiceLevel qos = MqttQualityOfServiceLevel.AtMostOnce)
{
Task.Run(async () => await MqSubscribeTopicAsync(subtopic, qos));
}
private async Task MqUnsubscribeTopicAsync(string subtopic)
{
if (string.IsNullOrEmpty(subtopic)) return;
var topic = TopicFull(subtopic);
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Verbose, $"Unsubscribing from topic: \"{topic}\"");
await _managedMqttClient.UnsubscribeAsync(topic);
}
private void MqUnsubscribeTopic(string subtopic)
{
Task.Run(async () => await MqUnsubscribeTopicAsync(subtopic));
}
private async Task MqSubscribeAllAsync()
{
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Verbose, $"Subscribing to ALL topics.");
List<Task> subTasks = [];
foreach(var (topic, qos) in LocalSettings.Singleton.Mqtt.GetAllTopicsToSubscribe())
subTasks.Add(MqSubscribeTopicAsync(topic, qos));
await Task.WhenAll(subTasks);
}
/*
* Methods used only on thread
*/
private void ThWork()
{
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Verbose, "Thread started");
ConnectionState = CommunicationState.Opening;
//kind of worried about this one
ThClientConnect().Wait();
SpinWait.SpinUntil(() => _cts!.IsCancellationRequested);
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Verbose, "Thread stopping");
ConnectionState = CommunicationState.Closing;
//and this
ThClientDisconnect().Wait();
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Verbose, "Thread quit");
ConnectionState = CommunicationState.Closed;
}
private async Task ThClientConnect()
{
if (_managedMqttClient is not null)
return;
var mqttFactory = new MqttFactory();
_managedMqttClient = mqttFactory.CreateManagedMqttClient();
var mqttClientOptions = new MqttClientOptionsBuilder()
.WithTcpServer(LocalSettings.Singleton.Mqtt.ClientSettings.BrokerIp, LocalSettings.Singleton.Mqtt.ClientSettings.BrokerPort)
.WithKeepAlivePeriod(TimeSpan.FromSeconds(LocalSettings.Singleton.Mqtt.ClientSettings.PingInterval))
.WithWillTopic(TopicFull(LocalSettings.Singleton.Mqtt.TopicRoverStatus))
.WithWillPayload(JsonSerializer.Serialize(new MqttClasses.RoverStatus() { CommunicationState = CommunicationState.Faulted }))
.WithWillQualityOfServiceLevel(MqttQualityOfServiceLevel.ExactlyOnce)
.WithWillRetain()
.Build();
var managedMqttClientOptions = new ManagedMqttClientOptionsBuilder()
.WithClientOptions(mqttClientOptions)
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithMaxPendingMessages(99)
.WithPendingMessagesOverflowStrategy(MqttPendingMessagesOverflowStrategy.DropOldestQueuedMessage)
.Build();
_managedMqttClient.DisconnectedAsync += ThOnDisconnectedAsync;
_managedMqttClient.ConnectedAsync += ThOnConnectedAsync;
_managedMqttClient.SynchronizingSubscriptionsFailedAsync += ThOnSynchronizingSubscriptionsFailedAsync;
_managedMqttClient.ApplicationMessageReceivedAsync += ThOnApplicationMessageReceivedAsync;
await _managedMqttClient.StartAsync(managedMqttClientOptions);
await MqSubscribeAllAsync();
}
private async Task ThClientDisconnect()
{
if (_managedMqttClient is null)
return;
_managedMqttClient.DisconnectedAsync -= ThOnDisconnectedAsync;
_managedMqttClient.ConnectedAsync -= ThOnConnectedAsync;
_managedMqttClient.SynchronizingSubscriptionsFailedAsync -= ThOnSynchronizingSubscriptionsFailedAsync;
_managedMqttClient.ApplicationMessageReceivedAsync -= ThOnApplicationMessageReceivedAsync;
await _managedMqttClient.EnqueueAsync
(
TopicFull(LocalSettings.Singleton.Mqtt.TopicRoverControl),
JsonSerializer.Serialize(new MqttClasses.RoverControl())
);
await _managedMqttClient.EnqueueAsync
(
TopicFull(LocalSettings.Singleton.Mqtt.TopicManipulatorControl),
JsonSerializer.Serialize(new MqttClasses.ManipulatorControl())
);
await _managedMqttClient.EnqueueAsync
(
TopicFull(LocalSettings.Singleton.Mqtt.TopicRoverStatus),
JsonSerializer.Serialize(new MqttClasses.RoverStatus() { CommunicationState = CommunicationState.Closed }),
MqttQualityOfServiceLevel.ExactlyOnce,
true
);
await Task.Run(async Task? () =>
{
for (int i = 0; (_managedMqttClient.PendingApplicationMessagesCount > 0) && (i < 10); i++)
{
await Task.Delay(TimeSpan.FromMilliseconds(100));
}
});
await _managedMqttClient?.StopAsync(_managedMqttClient.PendingApplicationMessagesCount == 0)!;
SpinWait.SpinUntil(() => _managedMqttClient.IsConnected, 250);
_managedMqttClient.Dispose();
_managedMqttClient = null;
}
private Task ThOnConnectedAsync(MqttClientConnectedEventArgs arg)
{
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Info, "Mqtt is now Connected!");
ConnectionState = CommunicationState.Opened;
return Task.CompletedTask;
}
private Task ThOnDisconnectedAsync(MqttClientDisconnectedEventArgs arg)
{
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Info, "Mqtt is now Disconnected!");
ConnectionState = CommunicationState.Faulted;
return Task.CompletedTask;
}
private Task ThOnSynchronizingSubscriptionsFailedAsync(ManagedProcessFailedEventArgs arg)
{
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Error, $"Synchronizing subscriptions failed with: {arg}");
return Task.CompletedTask;
}
private Task ThOnApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
{
EventLogger.LogMessageDebug(LogSource, EventLogger.LogLevel.Verbose, $"Message received on topic {arg.ApplicationMessage.Topic} with:\n {arg.ApplicationMessage.ConvertPayloadToString()}");
if (_responses == null) return Task.CompletedTask;
var topic = arg.ApplicationMessage.Topic[(LocalSettings.Singleton.Mqtt.ClientSettings.TopicMain.Length + 1)..];
var payload = arg.ApplicationMessage;
if (_responses.ContainsKey(topic))
_responses[topic] = payload;
else if (!_responses.TryAdd(topic, payload))
EventLogger.LogMessage(LogSource, EventLogger.LogLevel.Error, $"Adding {payload} on topic {topic} to dictionary failed");
CallDeferred(MethodName.EmitSignal, SignalName.MessageReceived, topic, new MqttNodeMessage(payload));
MessageReceivedAsync?.Invoke(topic, payload);
return Task.CompletedTask;
}
/*
* Private members
*/
private IManagedMqttClient? _managedMqttClient;
private CancellationTokenSource? _cts;
private Thread? _mqttThread;
private Dictionary<string, MqttApplicationMessage?>? _responses;
private volatile CommunicationState _connectionState = CommunicationState.Closed;
const string LogSource = "MqttNode";
}