Add new properties and events for the managed client.

This commit is contained in:
Christian Kratky
2018-06-21 20:42:44 +02:00
parent 8b376874c0
commit e8d5bd7bfb
7 changed files with 58 additions and 33 deletions
+1 -1
View File
@@ -15,7 +15,7 @@
<copyright>Copyright Christian Kratky 2016-2018</copyright> <copyright>Copyright Christian Kratky 2016-2018</copyright>
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags> <tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags>
<dependencies> <dependencies>
<dependency id="MQTTnet" version="2.8.0-alpha5" /> <dependency id="MQTTnet" version="2.8.0" />
</dependencies> </dependencies>
</metadata> </metadata>
@@ -15,7 +15,7 @@
<copyright>Copyright Christian Kratky 2016-2018</copyright> <copyright>Copyright Christian Kratky 2016-2018</copyright>
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags> <tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags>
<dependencies> <dependencies>
<dependency id="MQTTnet" version="2.8.0-beta1" /> <dependency id="MQTTnet" version="2.8.0" />
</dependencies> </dependencies>
</metadata> </metadata>
+1 -1
View File
@@ -15,7 +15,7 @@
<copyright>Copyright Christian Kratky 2016-2018</copyright> <copyright>Copyright Christian Kratky 2016-2018</copyright>
<tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags> <tags>MQTT Message Queue Telemetry Transport MQTTClient MQTTServer Server MQTTBroker Broker NETStandard IoT InternetOfThings Messaging Hardware Arduino Sensor Actuator M2M ESP Smart Home Cities Automation Xamarin</tags>
<dependencies> <dependencies>
<dependency id="MQTTnet" version="2.8.0-beta1" /> <dependency id="MQTTnet" version="2.8.0" />
</dependencies> </dependencies>
</metadata> </metadata>
+3
View File
@@ -21,6 +21,9 @@
* [ManagedClient] The managed client is moved to a separate nuget package. * [ManagedClient] The managed client is moved to a separate nuget package.
* [ManagedClient] Added an own message format with extended properties like ID (BREAKING CHANGE). * [ManagedClient] Added an own message format with extended properties like ID (BREAKING CHANGE).
* [ManagedClient] Fixed a loading issue of stored application messages (thanks to @JTrotta). * [ManagedClient] Fixed a loading issue of stored application messages (thanks to @JTrotta).
* [ManagedClient] Added a new event which is fired when a synchronization of the subscriptions has failed.
* [ManagedClient] Added a new event which is fired when a connection attempt has failed.
* [ManagedClient] Exposed a new property which provides the count of not published messages (pending messages count).
* [Server] Added support for other WebSocket sub protocol formats like mqttv-3.1.1 (thanks to @israellot). * [Server] Added support for other WebSocket sub protocol formats like mqttv-3.1.1 (thanks to @israellot).
* [Server] The takeover of an existing client sessions is now treated as a _clean_ disconnect of the previous client. * [Server] The takeover of an existing client sessions is now treated as a _clean_ disconnect of the previous client.
* [Server] The pending messages queue per client is now limited to 250 messages. Overflow strategy and count can be changed via options (thanks to @VladimirAkopyan) * [Server] The pending messages queue per client is now limited to 250 messages. Overflow strategy and count can be changed via options (thanks to @VladimirAkopyan)
@@ -9,12 +9,16 @@ namespace MQTTnet.Extensions.ManagedClient
{ {
bool IsStarted { get; } bool IsStarted { get; }
bool IsConnected { get; } bool IsConnected { get; }
int PendingApplicationMessagesCount { get; }
event EventHandler<MqttClientConnectedEventArgs> Connected; event EventHandler<MqttClientConnectedEventArgs> Connected;
event EventHandler<MqttClientDisconnectedEventArgs> Disconnected; event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
event EventHandler<ApplicationMessageProcessedEventArgs> ApplicationMessageProcessed; event EventHandler<ApplicationMessageProcessedEventArgs> ApplicationMessageProcessed;
event EventHandler<MqttManagedProcessFailedEventArgs> ConnectingFailed;
event EventHandler<MqttManagedProcessFailedEventArgs> SynchronizingSubscriptionsFailed;
Task StartAsync(IManagedMqttClientOptions options); Task StartAsync(IManagedMqttClientOptions options);
Task StopAsync(); Task StopAsync();
@@ -14,8 +14,8 @@ namespace MQTTnet.Extensions.ManagedClient
public class ManagedMqttClient : IManagedMqttClient public class ManagedMqttClient : IManagedMqttClient
{ {
private readonly BlockingCollection<ManagedMqttApplicationMessage> _messageQueue = new BlockingCollection<ManagedMqttApplicationMessage>(); private readonly BlockingCollection<ManagedMqttApplicationMessage> _messageQueue = new BlockingCollection<ManagedMqttApplicationMessage>();
private readonly ConcurrentDictionary<string, MqttQualityOfServiceLevel> _subscriptions = new ConcurrentDictionary<string, MqttQualityOfServiceLevel>(); private readonly Dictionary<string, MqttQualityOfServiceLevel> _subscriptions = new Dictionary<string, MqttQualityOfServiceLevel>();
private readonly List<string> _unsubscriptions = new List<string>(); private readonly HashSet<string> _unsubscriptions = new HashSet<string>();
private readonly IMqttClient _mqttClient; private readonly IMqttClient _mqttClient;
private readonly IMqttNetChildLogger _logger; private readonly IMqttNetChildLogger _logger;
@@ -43,12 +43,16 @@ namespace MQTTnet.Extensions.ManagedClient
public bool IsConnected => _mqttClient.IsConnected; public bool IsConnected => _mqttClient.IsConnected;
public bool IsStarted => _connectionCancellationToken != null; public bool IsStarted => _connectionCancellationToken != null;
public int PendingApplicationMessagesCount => _messageQueue.Count;
public event EventHandler<MqttClientConnectedEventArgs> Connected; public event EventHandler<MqttClientConnectedEventArgs> Connected;
public event EventHandler<MqttClientDisconnectedEventArgs> Disconnected; public event EventHandler<MqttClientDisconnectedEventArgs> Disconnected;
public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived; public event EventHandler<MqttApplicationMessageReceivedEventArgs> ApplicationMessageReceived;
public event EventHandler<ApplicationMessageProcessedEventArgs> ApplicationMessageProcessed; public event EventHandler<ApplicationMessageProcessedEventArgs> ApplicationMessageProcessed;
public event EventHandler SynchronizingSubscriptionsFailed;
public event EventHandler<MqttManagedProcessFailedEventArgs> ConnectingFailed;
public event EventHandler<MqttManagedProcessFailedEventArgs> SynchronizingSubscriptionsFailed;
public async Task StartAsync(IManagedMqttClientOptions options) public async Task StartAsync(IManagedMqttClientOptions options)
{ {
@@ -120,10 +124,13 @@ namespace MQTTnet.Extensions.ManagedClient
{ {
if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters)); if (topicFilters == null) throw new ArgumentNullException(nameof(topicFilters));
foreach (var topicFilter in topicFilters) lock (_subscriptions)
{ {
_subscriptions[topicFilter.Topic] = topicFilter.QualityOfServiceLevel; foreach (var topicFilter in topicFilters)
_subscriptionsNotPushed = true; {
_subscriptions[topicFilter.Topic] = topicFilter.QualityOfServiceLevel;
_subscriptionsNotPushed = true;
}
} }
return Task.FromResult(0); return Task.FromResult(0);
@@ -131,12 +138,17 @@ namespace MQTTnet.Extensions.ManagedClient
public Task UnsubscribeAsync(IEnumerable<string> topics) public Task UnsubscribeAsync(IEnumerable<string> topics)
{ {
foreach (var topic in topics) if (topics == null) throw new ArgumentNullException(nameof(topics));
lock (_subscriptions)
{ {
if (_subscriptions.TryRemove(topic, out _)) foreach (var topic in topics)
{ {
_unsubscriptions.Add(topic); if (_subscriptions.Remove(topic))
_subscriptionsNotPushed = true; {
_unsubscriptions.Add(topic);
_subscriptionsNotPushed = true;
}
} }
} }
@@ -210,7 +222,7 @@ namespace MQTTnet.Extensions.ManagedClient
} }
} }
private async Task PublishQueuedMessagesAsync(CancellationToken cancellationToken) private void PublishQueuedMessages(CancellationToken cancellationToken)
{ {
try try
{ {
@@ -222,12 +234,9 @@ namespace MQTTnet.Extensions.ManagedClient
continue; continue;
} }
if (cancellationToken.IsCancellationRequested) cancellationToken.ThrowIfCancellationRequested();
{
continue;
}
await TryPublishQueuedMessageAsync(message).ConfigureAwait(false); TryPublishQueuedMessage(message);
} }
} }
catch (OperationCanceledException) catch (OperationCanceledException)
@@ -243,17 +252,13 @@ namespace MQTTnet.Extensions.ManagedClient
} }
} }
private async Task TryPublishQueuedMessageAsync(ManagedMqttApplicationMessage message) private void TryPublishQueuedMessage(ManagedMqttApplicationMessage message)
{ {
Exception transmitException = null; Exception transmitException = null;
try try
{ {
await _mqttClient.PublishAsync(message.ApplicationMessage).ConfigureAwait(false); _mqttClient.PublishAsync(message.ApplicationMessage).GetAwaiter().GetResult();
_storageManager?.RemoveAsync(message).GetAwaiter().GetResult();
if (_storageManager != null)
{
await _storageManager.RemoveAsync(message).ConfigureAwait(false);
}
} }
catch (MqttCommunicationException exception) catch (MqttCommunicationException exception)
{ {
@@ -282,13 +287,13 @@ namespace MQTTnet.Extensions.ManagedClient
_logger.Info(nameof(ManagedMqttClient), "Synchronizing subscriptions"); _logger.Info(nameof(ManagedMqttClient), "Synchronizing subscriptions");
List<TopicFilter> subscriptions; List<TopicFilter> subscriptions;
List<string> unsubscriptions; HashSet<string> unsubscriptions;
lock (_subscriptions) lock (_subscriptions)
{ {
subscriptions = _subscriptions.Select(i => new TopicFilter(i.Key, i.Value)).ToList(); subscriptions = _subscriptions.Select(i => new TopicFilter(i.Key, i.Value)).ToList();
unsubscriptions = new List<string>(_unsubscriptions); unsubscriptions = new HashSet<string>(_unsubscriptions);
_unsubscriptions.Clear(); _unsubscriptions.Clear();
_subscriptionsNotPushed = false; _subscriptionsNotPushed = false;
@@ -316,7 +321,7 @@ namespace MQTTnet.Extensions.ManagedClient
_logger.Warning(exception, "Synchronizing subscriptions failed."); _logger.Warning(exception, "Synchronizing subscriptions failed.");
_subscriptionsNotPushed = true; _subscriptionsNotPushed = true;
SynchronizingSubscriptionsFailed?.Invoke(this, EventArgs.Empty); SynchronizingSubscriptionsFailed?.Invoke(this, new MqttManagedProcessFailedEventArgs(exception));
} }
} }
@@ -332,8 +337,9 @@ namespace MQTTnet.Extensions.ManagedClient
await _mqttClient.ConnectAsync(_options.ClientOptions).ConfigureAwait(false); await _mqttClient.ConnectAsync(_options.ClientOptions).ConfigureAwait(false);
return ReconnectionResult.Reconnected; return ReconnectionResult.Reconnected;
} }
catch (Exception) catch (Exception exception)
{ {
ConnectingFailed?.Invoke(this, new MqttManagedProcessFailedEventArgs(exception));
return ReconnectionResult.NotConnected; return ReconnectionResult.NotConnected;
} }
} }
@@ -364,9 +370,7 @@ namespace MQTTnet.Extensions.ManagedClient
_publishingCancellationToken = cts; _publishingCancellationToken = cts;
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Factory.StartNew(() => PublishQueuedMessages(cts.Token), cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
Task.Run(() => PublishQueuedMessagesAsync(cts.Token), cts.Token);
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
} }
private void StopPublishing() private void StopPublishing()
@@ -0,0 +1,14 @@
using System;
namespace MQTTnet.Extensions.ManagedClient
{
public class MqttManagedProcessFailedEventArgs : EventArgs
{
public MqttManagedProcessFailedEventArgs(Exception exception)
{
Exception = exception;
}
public Exception Exception { get; }
}
}