-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMQTTControl.cs
More file actions
298 lines (264 loc) · 10.5 KB
/
MQTTControl.cs
File metadata and controls
298 lines (264 loc) · 10.5 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
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
#nullable enable
using System;
using System.Buffers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Packets; // for v5 subscribe options if needed
using MQTTnet.Protocol; // QoS enums
using InstDotNet;
public class MQTTControl
{
public const string DEFAULT_CLIENT_ID = "clientId-UwbManager-001";
private static string _clientId = string.Empty;
private static string _serverAddress = string.Empty;
private static string _usernname = string.Empty;
private static string _password = string.Empty;
private static int _port;
private static string _receiveMessageTopic = string.Empty;
private static string _sendMessageTopic = string.Empty;
private static int _timeoutInSeconds;
private static int _keepAlivePeriodSeconds;
public static System.Action<string>? OnMessageReceived;
private static IMqttClient? client;
private static CancellationTokenSource? _cts;
// Return Task so callers can await completion and observe exceptions
public static async Task Initialise(CancellationTokenSource cts, AppConfig? config = null)
{
_cts = cts ?? new CancellationTokenSource();
if (config != null)
{
_serverAddress = config.MQTT.ServerAddress;
_port = config.MQTT.Port;
_usernname = config.MQTT.Username;
_password = config.MQTT.Password;
_receiveMessageTopic = config.MQTT.ReceiveTopic;
_sendMessageTopic = config.MQTT.SendTopic;
_timeoutInSeconds = config.MQTT.TimeoutSeconds;
_keepAlivePeriodSeconds = config.MQTT.KeepAlivePeriodSeconds;
// Use configured client ID, or generate from hardware ID if empty
if (string.IsNullOrWhiteSpace(config.MQTT.ClientId))
{
var baseClientId = HardwareId.GetMqttClientId("UwbManager");
var processId = System.Diagnostics.Process.GetCurrentProcess().Id;
_clientId = $"{baseClientId}-pid{processId}";
Console.WriteLine($"Using hardware-based MQTT client ID: {_clientId} (PID: {processId})");
}
else
{
_clientId = config.MQTT.ClientId;
}
}
else
{
// Fallback to defaults if no config provided
_serverAddress = "mqtt.dynamicdevices.co.uk";
_port = 1883;
_usernname = "";
_password = "";
_receiveMessageTopic = "DotnetMQTT/Test/in";
_sendMessageTopic = "DotnetMQTT/Test/out";
_timeoutInSeconds = 10;
_keepAlivePeriodSeconds = 60;
var baseClientId = HardwareId.GetMqttClientId("UwbManager");
var processId = System.Diagnostics.Process.GetCurrentProcess().Id;
_clientId = $"{baseClientId}-pid{processId}";
}
var factory = new MqttClientFactory();
client = factory.CreateMqttClient();
// Setup handlers
client.ApplicationMessageReceivedAsync += e =>
{
try
{
var sequence = e.ApplicationMessage.Payload;
var bytes = sequence.IsEmpty ? Array.Empty<byte>() : sequence.ToArray();
var payload = bytes.Length == 0 ? string.Empty : Encoding.UTF8.GetString(bytes);
Console.WriteLine($"MSG [{e.ApplicationMessage.Topic}]: {payload}");
// forward to any subscriber in the app
OnMessageReceived?.Invoke(payload);
}
catch (Exception ex)
{
Console.WriteLine($"Error processing incoming message: {ex.Message}");
}
return Task.CompletedTask;
};
client.ConnectedAsync += async e =>
{
Console.WriteLine("MQTT: Connected.");
// Publish version information to version subtopic
await PublishVersionInfo().ConfigureAwait(false);
return;
};
client.DisconnectedAsync += e =>
{
Console.WriteLine($"MQTT: Disconnected. Reason: {e?.Exception?.Message ?? "none"}");
return Task.CompletedTask;
};
var builder = new MqttClientOptionsBuilder()
.WithClientId(_clientId)
.WithTcpServer(_serverAddress, _port)
.WithCleanSession()
.WithTimeout(TimeSpan.FromSeconds(_timeoutInSeconds))
.WithKeepAlivePeriod(TimeSpan.FromSeconds(_keepAlivePeriodSeconds));
// Add credentials only if provided
if (!string.IsNullOrWhiteSpace(_usernname) && !string.IsNullOrWhiteSpace(_password))
{
builder = builder.WithCredentials(_usernname, _password);
}
var options = builder.Build();
try
{
Console.WriteLine($"MQTT: Connecting to {_serverAddress}:{_port} ...");
await client.ConnectAsync(options, _cts.Token).ConfigureAwait(false);
// Subscribe (MQTT v5 supports more options; QoS shown here)
await client.SubscribeAsync(new MqttTopicFilterBuilder()
.WithTopic(_receiveMessageTopic)
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
.Build(), _cts.Token).ConfigureAwait(false);
await Publish($"Connected to {_serverAddress}. Subscribed to {_receiveMessageTopic}. Publishing to {_sendMessageTopic}.");
Console.WriteLine($"Connected to {_serverAddress}");
Console.WriteLine($"MQTT: Subscribed to {_receiveMessageTopic}");
}
catch (Exception ex)
{
Console.WriteLine($"MQTT: Connect/Subscribe failed: {ex.GetType().Name}: {ex.Message}");
// rethrow so caller can observe if they awaited Initialise
throw;
}
}
public static async Task DisconnectAsync()
{
if (client == null)
{
return;
}
try
{
if (client.IsConnected)
{
await client.DisconnectAsync().ConfigureAwait(false);
Console.WriteLine("MQTT: Disconnect complete.");
}
}
catch (Exception ex)
{
Console.WriteLine($"MQTT: Error during disconnect: {ex.Message}");
}
}
public static async Task PublishDebugMessage(string message)
{
await Publish(message, "debug");
}
public static async Task Publish(string message, string channel = "")
{
if (client == null)
{
Console.WriteLine("MQTT: Publish skipped - client is null.");
return;
}
if (!client.IsConnected)
{
Console.WriteLine("MQTT: Publish skipped - client not connected.");
return;
}
string sendTopic = _sendMessageTopic;
if (channel != "")
{
sendTopic += "/" + channel;
}
var messageOut = new MqttApplicationMessageBuilder()
.WithTopic(sendTopic)
.WithPayload(message)
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
.Build();
try
{
if (_cts != null)
{
await client.PublishAsync(messageOut, _cts.Token).ConfigureAwait(false);
}
else
{
await client.PublishAsync(messageOut).ConfigureAwait(false);
}
Console.WriteLine("MQTT: Published.");
}
catch (Exception ex)
{
Console.WriteLine($"MQTT: Publish error: {ex.Message}");
}
}
/// <summary>
/// Publishes version and build information as JSON to the version subtopic
/// </summary>
private static async Task PublishVersionInfo()
{
if (client == null || !client.IsConnected)
{
Console.WriteLine("MQTT: Version info publish skipped - client not connected.");
return;
}
try
{
// Create version info object
var versionInfo = new
{
version = VersionInfo.Version,
assemblyVersion = VersionInfo.AssemblyVersion,
fileVersion = VersionInfo.FileVersion,
informationalVersion = VersionInfo.InformationalVersion,
buildDate = VersionInfo.BuildDate,
gitCommitHash = VersionInfo.GitCommitHash,
fullVersion = VersionInfo.FullVersion,
clientId = _clientId,
timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
};
// Serialize to JSON
var jsonOptions = new JsonSerializerOptions
{
WriteIndented = false,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var jsonPayload = JsonSerializer.Serialize(versionInfo, jsonOptions);
// Construct version topic as subtopic of SendTopic
var versionTopic = string.IsNullOrEmpty(_sendMessageTopic)
? "version"
: $"{_sendMessageTopic}/version";
var messageOut = new MqttApplicationMessageBuilder()
.WithTopic(versionTopic)
.WithPayload(jsonPayload)
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
.WithRetainFlag(true)
.Build();
if (_cts != null)
{
await client.PublishAsync(messageOut, _cts.Token).ConfigureAwait(false);
}
else
{
await client.PublishAsync(messageOut).ConfigureAwait(false);
}
Console.WriteLine($"MQTT: Published version info to {versionTopic}");
}
catch (Exception ex)
{
Console.WriteLine($"MQTT: Version info publish error: {ex.Message}");
}
}
public static void ReceiveMessage(string message)
{
Console.WriteLine($"Received message");
OnMessageReceived?.Invoke(message);
}
/// <summary>
/// Check if MQTT client is connected
/// </summary>
public static bool IsConnected()
{
return client != null && client.IsConnected;
}
}