-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMqttMessageQueue.cs
More file actions
191 lines (162 loc) · 6.48 KB
/
MqttMessageQueue.cs
File metadata and controls
191 lines (162 loc) · 6.48 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
using System;
using System.Threading;
using System.Threading.Tasks;
using Birko.MessageQueue.Serialization;
using Birko.Time;
using MQTTnet;
using MQTTnet.Client;
namespace Birko.MessageQueue.Mqtt
{
/// <summary>
/// MQTT message queue implementation using MQTTnet.
/// Supports QoS 0/1/2, persistent sessions, topic wildcards,
/// retained messages, Last Will, TLS, and automatic reconnection.
/// </summary>
public class MqttMessageQueue : IMessageQueue
{
private readonly MqttSettings _options;
private readonly IMqttClient _client;
private readonly MqttProducer _producer;
private readonly MqttConsumer _consumer;
private CancellationTokenSource? _reconnectCts;
private bool _disposed;
public IMessageProducer Producer => _producer;
public IMessageConsumer Consumer => _consumer;
public bool IsConnected => _client.IsConnected;
/// <summary>
/// Fired when the client connects or reconnects to the broker.
/// </summary>
public event Func<Task>? Connected;
/// <summary>
/// Fired when the client disconnects from the broker.
/// </summary>
public event Func<Task>? Disconnected;
/// <summary>
/// Creates a new MQTT message queue.
/// </summary>
/// <param name="options">MQTT connection options.</param>
/// <param name="serializer">Message serializer. Defaults to JsonMessageSerializer.</param>
/// <param name="clock">Date/time provider. Defaults to SystemDateTimeProvider.</param>
public MqttMessageQueue(MqttSettings options, IMessageSerializer? serializer = null, IDateTimeProvider? clock = null)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
var ser = serializer ?? new JsonMessageSerializer();
var factory = new MqttFactory();
_client = factory.CreateMqttClient();
_producer = new MqttProducer(_client, ser, _options);
_consumer = new MqttConsumer(_client, ser, _options, clock);
_client.DisconnectedAsync += OnDisconnectedAsync;
_client.ConnectedAsync += OnConnectedAsync;
}
public async Task ConnectAsync(CancellationToken cancellationToken = default)
{
ObjectDisposedException.ThrowIf(_disposed, this);
var optionsBuilder = new MqttClientOptionsBuilder()
.WithTcpServer(_options.Location, _options.Port)
.WithClientId(_options.ClientId ?? $"birko-{Guid.NewGuid():N}")
.WithCleanSession(_options.CleanSession)
.WithKeepAlivePeriod(_options.KeepAlive)
.WithTimeout(_options.ConnectionTimeout);
if (!string.IsNullOrEmpty(_options.UserName))
{
optionsBuilder.WithCredentials(_options.UserName, _options.Password);
}
if (_options.UseSecure)
{
optionsBuilder.WithTlsOptions(tls =>
{
tls.UseTls(true);
if (_options.AllowUntrustedCertificates)
{
tls.WithAllowUntrustedCertificates(true);
}
if (_options.ClientCertificate != null)
{
tls.WithClientCertificates(new[] { _options.ClientCertificate });
}
});
}
if (_options.LastWill != null)
{
optionsBuilder
.WithWillTopic(_options.LastWill.Topic)
.WithWillPayload(_options.LastWill.Payload)
.WithWillQualityOfServiceLevel(MqttProducer.ToMqttQos(_options.LastWill.QualityOfService))
.WithWillRetain(_options.LastWill.Retain);
}
await _client.ConnectAsync(optionsBuilder.Build(), cancellationToken).ConfigureAwait(false);
}
public async Task DisconnectAsync(CancellationToken cancellationToken = default)
{
_reconnectCts?.Cancel();
_reconnectCts = null;
if (_client.IsConnected)
{
var disconnectOptions = new MqttClientDisconnectOptionsBuilder()
.WithReason(MqttClientDisconnectOptionsReason.NormalDisconnection)
.Build();
await _client.DisconnectAsync(disconnectOptions, cancellationToken).ConfigureAwait(false);
}
}
private async Task OnConnectedAsync(MqttClientConnectedEventArgs args)
{
if (Connected != null)
{
await Connected.Invoke().ConfigureAwait(false);
}
}
private async Task OnDisconnectedAsync(MqttClientDisconnectedEventArgs args)
{
if (Disconnected != null)
{
await Disconnected.Invoke().ConfigureAwait(false);
}
if (_disposed || !_options.AutoReconnect)
{
return;
}
_reconnectCts?.Cancel();
_reconnectCts = new CancellationTokenSource();
var ct = _reconnectCts.Token;
_ = Task.Run(async () =>
{
var attempts = 0;
while (!ct.IsCancellationRequested && !_client.IsConnected)
{
if (_options.MaxReconnectAttempts > 0 && attempts >= _options.MaxReconnectAttempts)
{
break;
}
try
{
await Task.Delay(_options.ReconnectDelay, ct).ConfigureAwait(false);
await ConnectAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
catch
{
attempts++;
}
}
}, ct);
}
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_reconnectCts?.Cancel();
_reconnectCts?.Dispose();
_client.DisconnectedAsync -= OnDisconnectedAsync;
_client.ConnectedAsync -= OnConnectedAsync;
_producer.Dispose();
_consumer.Dispose();
_client.Dispose();
}
}
}