Enable nullable

This commit is contained in:
christian
2025-10-20 11:29:24 +02:00
parent 5ebc5fcb7e
commit 37631730e0
116 changed files with 497 additions and 463 deletions
+1
View File
@@ -15,6 +15,7 @@
<NuGetAudit>true</NuGetAudit>
<NuGetAuditLevel>low</NuGetAuditLevel>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<LangVersion>default</LangVersion>
</PropertyGroup>
<ItemGroup>
@@ -39,6 +39,8 @@
<NuGetAuditLevel>low</NuGetAuditLevel>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<IsAotCompatible>true</IsAotCompatible>
<LangVersion>default</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
@@ -12,7 +12,12 @@ namespace MQTTnet.Extensions.Rpc;
public interface IMqttRpcClient : IDisposable
{
Task<byte[]> ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string,object> parameters = null);
Task<byte[]> ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string, object>? parameters = null);
Task<byte[]> ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string, object> parameters = null, CancellationToken cancellationToken = default);
Task<byte[]> ExecuteAsync(
string methodName,
byte[] payload,
MqttQualityOfServiceLevel qualityOfServiceLevel,
IDictionary<string, object>? parameters = null,
CancellationToken cancellationToken = default);
}
@@ -37,6 +37,8 @@
<NuGetAuditLevel>low</NuGetAuditLevel>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<IsAotCompatible>true</IsAotCompatible>
<LangVersion>default</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
+18 -9
View File
@@ -20,7 +20,7 @@ public sealed class MqttRpcClient : IMqttRpcClient
readonly IMqttClient _mqttClient;
readonly MqttRpcClientOptions _options;
readonly ConcurrentDictionary<string, AsyncTaskCompletionSource<byte[]>> _waitingCalls = new ConcurrentDictionary<string, AsyncTaskCompletionSource<byte[]>>();
readonly ConcurrentDictionary<string, AsyncTaskCompletionSource<byte[]>> _waitingCalls = new();
public MqttRpcClient(IMqttClient mqttClient, MqttRpcClientOptions options)
{
@@ -42,7 +42,12 @@ public sealed class MqttRpcClient : IMqttRpcClient
_waitingCalls.Clear();
}
public async Task<byte[]> ExecuteAsync(TimeSpan timeout, string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string, object> parameters = null)
public async Task<byte[]> ExecuteAsync(
TimeSpan timeout,
string methodName,
byte[] payload,
MqttQualityOfServiceLevel qualityOfServiceLevel,
IDictionary<string, object>? parameters = null)
{
using var timeoutToken = new CancellationTokenSource(timeout);
try
@@ -60,7 +65,12 @@ public sealed class MqttRpcClient : IMqttRpcClient
}
}
public async Task<byte[]> ExecuteAsync(string methodName, byte[] payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string, object> parameters = null, CancellationToken cancellationToken = default)
public async Task<byte[]> ExecuteAsync(
string methodName,
byte[] payload,
MqttQualityOfServiceLevel qualityOfServiceLevel,
IDictionary<string, object>? parameters = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(methodName);
@@ -82,7 +92,7 @@ public sealed class MqttRpcClient : IMqttRpcClient
var requestMessageBuilder = new MqttApplicationMessageBuilder().WithTopic(requestTopic).WithPayload(payload).WithQualityOfServiceLevel(qualityOfServiceLevel);
if (_mqttClient.Options.ProtocolVersion == MqttProtocolVersion.V500)
if (_mqttClient.Options!.ProtocolVersion == MqttProtocolVersion.V500)
{
requestMessageBuilder.WithResponseTopic(responseTopic);
}
@@ -103,11 +113,10 @@ public sealed class MqttRpcClient : IMqttRpcClient
await _mqttClient.SubscribeAsync(subscribeOptions, cancellationToken).ConfigureAwait(false);
await _mqttClient.PublishAsync(requestMessage, cancellationToken).ConfigureAwait(false);
using (cancellationToken.Register(
() =>
{
awaitable.TrySetCanceled();
}))
using (cancellationToken.Register(() =>
{
awaitable.TrySetCanceled();
}))
{
return await awaitable.Task.ConfigureAwait(false);
}
@@ -12,7 +12,7 @@ namespace MQTTnet.Extensions.Rpc;
public static class MqttRpcClientExtensions
{
public static Task<byte[]> ExecuteAsync(this IMqttRpcClient client, TimeSpan timeout, string methodName, string payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string,object> parameters = null)
public static Task<byte[]> ExecuteAsync(this IMqttRpcClient client, TimeSpan timeout, string methodName, string payload, MqttQualityOfServiceLevel qualityOfServiceLevel, IDictionary<string,object>? parameters = null)
{
if (client == null) throw new ArgumentNullException(nameof(client));
@@ -6,7 +6,7 @@ namespace MQTTnet.Extensions.Rpc;
public sealed class MqttRpcTopicPair
{
public string RequestTopic { get; set; }
public required string RequestTopic { get; init; }
public string ResponseTopic { get; set; }
public required string ResponseTopic { get; init; }
}
@@ -10,8 +10,12 @@ namespace MQTTnet.Extensions.Rpc;
public sealed class TopicGenerationContext
{
public TopicGenerationContext(IMqttClient mqttClient, MqttRpcClientOptions options, string methodName,
IDictionary<string, object> parameters, MqttQualityOfServiceLevel qualityOfServiceLevel)
public TopicGenerationContext(
IMqttClient mqttClient,
MqttRpcClientOptions options,
string methodName,
IDictionary<string, object>? parameters,
MqttQualityOfServiceLevel qualityOfServiceLevel)
{
MethodName = methodName ?? throw new ArgumentNullException(nameof(methodName));
Parameters = parameters;
@@ -22,12 +26,12 @@ public sealed class TopicGenerationContext
public string MethodName { get; }
public IDictionary<string, object> Parameters { get; }
public IMqttClient MqttClient { get; }
public MqttRpcClientOptions Options { get; }
public IDictionary<string, object>? Parameters { get; }
/// <summary>
/// Gets or sets the quality of service level.
/// The Quality of Service (QoS) level is an agreement between the sender of a message and the receiver of a message
@@ -33,6 +33,8 @@
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>1591;NETSDK1138</NoWarn>
<IsAotCompatible>true</IsAotCompatible>
<LangVersion>default</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
@@ -8,9 +8,9 @@ namespace MQTTnet.Server.EnhancedAuthentication;
public sealed class ExchangeEnhancedAuthenticationOptions
{
public byte[] AuthenticationData { get; set; }
public byte[]? AuthenticationData { get; set; }
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
}
@@ -4,9 +4,9 @@ namespace MQTTnet.Server.EnhancedAuthentication;
public sealed class ExchangeEnhancedAuthenticationResult
{
public string ReasonString { get; set; }
public string? ReasonString { get; init; }
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; init; }
public byte[] AuthenticationData { get; set; }
public byte[]? AuthenticationData { get; init; }
}
@@ -22,15 +22,15 @@ public sealed class ClientConnectedEventArgs : EventArgs
SessionItems = sessionItems ?? throw new ArgumentNullException(nameof(sessionItems));
}
public byte[] AuthenticationData => _connectPacket.AuthenticationData;
public byte[]? AuthenticationData => _connectPacket.AuthenticationData;
public string AuthenticationMethod => _connectPacket.AuthenticationMethod;
public string? AuthenticationMethod => _connectPacket.AuthenticationMethod;
/// <summary>
/// Gets the client identifier of the connected client.
/// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues.
/// </summary>
public string ClientId => _connectPacket.ClientId;
public string ClientId => _connectPacket.ClientId!;
/// <summary>
/// Gets the endpoint of the connected client.
@@ -38,7 +38,7 @@ public sealed class ClientConnectedEventArgs : EventArgs
public EndPoint RemoteEndPoint { get; }
[Obsolete("Use RemoteEndPoint instead.")]
public string Endpoint => RemoteEndPoint?.ToString();
public string? Endpoint => RemoteEndPoint?.ToString();
/// <summary>
/// Gets the protocol version which is used by the connected client.
@@ -53,16 +53,16 @@ public sealed class ClientConnectedEventArgs : EventArgs
/// <summary>
/// Gets the user name of the connected client.
/// </summary>
public string UserName => _connectPacket.Username;
public string? UserName => _connectPacket.Username;
/// <summary>
/// Gets the password of the connected client.
/// </summary>
public string Password => Encoding.UTF8.GetString(_connectPacket.Password.AsSpan());
public string? Password => Encoding.UTF8.GetString(_connectPacket.Password.AsSpan());
/// <summary>
/// Gets the user properties sent by the client.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public List<MqttUserProperty> UserProperties => _connectPacket?.UserProperties;
public List<MqttUserProperty>? UserProperties => _connectPacket?.UserProperties;
}
@@ -35,24 +35,24 @@ public sealed class ClientDisconnectedEventArgs : EventArgs
/// Gets the client identifier.
/// Hint: This identifier needs to be unique over all used clients / devices on the broker to avoid connection issues.
/// </summary>
public string ClientId => _connectPacket.ClientId;
public string ClientId => _connectPacket.ClientId!;
/// <summary>
/// Gets the user name of the client.
/// </summary>
public string UserName => _connectPacket.Username;
public string? UserName => _connectPacket.Username;
/// <summary>
/// Gets the password of the client.
/// </summary>
public string Password => Encoding.UTF8.GetString(_connectPacket.Password.AsSpan());
public string? Password => Encoding.UTF8.GetString(_connectPacket.Password.AsSpan());
public MqttClientDisconnectType DisconnectType { get; }
public EndPoint RemoteEndPoint { get; }
[Obsolete("Use RemoteEndPoint instead.")]
public string Endpoint => RemoteEndPoint?.ToString();
public string? Endpoint => RemoteEndPoint?.ToString();
/// <summary>
/// Gets the reason code sent by the client.
@@ -66,7 +66,7 @@ public sealed class ClientDisconnectedEventArgs : EventArgs
/// Only available for clean disconnects.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public string ReasonString => _disconnectPacket?.ReasonString;
public string? ReasonString => _disconnectPacket?.ReasonString;
/// <summary>
/// Gets the session expiry interval sent by the client.
@@ -85,5 +85,5 @@ public sealed class ClientDisconnectedEventArgs : EventArgs
/// Only available for clean disconnects.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public List<MqttUserProperty> UserProperties => _disconnectPacket?.UserProperties;
public List<MqttUserProperty>? UserProperties => _disconnectPacket?.UserProperties;
}
@@ -12,7 +12,7 @@ namespace MQTTnet.Server.Internal.Adapter;
public sealed class MqttTcpServerAdapter : IMqttServerAdapter
{
readonly List<MqttTcpServerListener> _listeners = new List<MqttTcpServerListener>();
readonly List<MqttTcpServerListener> _listeners = new();
CancellationTokenSource _cancellationTokenSource;
@@ -165,8 +165,8 @@ public sealed class MqttTcpServerListener : IDisposable
async Task TryHandleClientConnectionAsync(CrossPlatformSocket clientSocket)
{
Stream stream = null;
EndPoint remoteEndPoint = null;
Stream? stream = null;
EndPoint? remoteEndPoint = null;
try
{
@@ -667,7 +667,7 @@ public sealed class MqttClientSessionsManager : ISubscriptionChangedNotification
}
}
async Task<MqttConnectPacket> ReceiveConnectPacket(IMqttChannelAdapter channelAdapter, CancellationToken cancellationToken)
async Task<MqttConnectPacket?> ReceiveConnectPacket(IMqttChannelAdapter channelAdapter, CancellationToken cancellationToken)
{
try
{
+2 -1
View File
@@ -35,9 +35,10 @@
<NuGetAudit>true</NuGetAudit>
<NuGetAuditLevel>low</NuGetAuditLevel>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>disable</Nullable>
<Nullable>enable</Nullable>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<IsAotCompatible>true</IsAotCompatible>
<LangVersion>default</LangVersion>
</PropertyGroup>
<ItemGroup>
@@ -21,7 +21,7 @@ public static class MqttServerExtensions
public static Task InjectApplicationMessage(
this MqttServer server,
string topic,
string payload = null,
string? payload = null,
MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
bool retain = false)
{
@@ -20,7 +20,7 @@ public class MqttServerOptionsBuilder
return _options;
}
public MqttServerOptionsBuilder WithClientCertificate(RemoteCertificateValidationCallback validationCallback = null, bool checkCertificateRevocation = false)
public MqttServerOptionsBuilder WithClientCertificate(RemoteCertificateValidationCallback? validationCallback = null, bool checkCertificateRevocation = false)
{
_options.TlsEndpointOptions.ClientCertificateRequired = true;
_options.TlsEndpointOptions.CheckCertificateRevocation = checkCertificateRevocation;
@@ -183,7 +183,7 @@ public class MqttServerOptionsBuilder
return this;
}
public MqttServerOptionsBuilder WithEncryptionCertificate(byte[] value, IMqttServerCertificateCredentials credentials = null)
public MqttServerOptionsBuilder WithEncryptionCertificate(byte[] value, IMqttServerCertificateCredentials? credentials = null)
{
ArgumentNullException.ThrowIfNull(value);
+2 -2
View File
@@ -16,7 +16,7 @@ public sealed class SubscribeResponse
/// </summary>
public MqttSubscribeReasonCode ReasonCode { get; set; }
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
public List<MqttUserProperty> UserProperties { get; } = [];
public List<MqttUserProperty>? UserProperties { get; set; } = [];
}
+2 -2
View File
@@ -15,7 +15,7 @@ public sealed class UnsubscribeResponse
/// </summary>
public MqttUnsubscribeReasonCode ReasonCode { get; set; }
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
public List<MqttUserProperty> UserProperties { get; } = [];
public List<MqttUserProperty>? UserProperties { get; } = [];
}
@@ -14,6 +14,8 @@
<NuGetAudit>true</NuGetAudit>
<NuGetAuditLevel>low</NuGetAuditLevel>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<LangVersion>default</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
@@ -14,6 +14,8 @@
<NuGetAudit>true</NuGetAudit>
<NuGetAuditLevel>low</NuGetAuditLevel>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<LangVersion>default</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
@@ -18,9 +18,9 @@ public interface IMqttChannelAdapter : IDisposable
long BytesSent { get; }
X509Certificate2 ClientCertificate { get; }
X509Certificate2? ClientCertificate { get; }
EndPoint RemoteEndPoint { get; }
EndPoint? RemoteEndPoint { get; }
bool IsSecureConnection { get; }
@@ -30,7 +30,7 @@ public interface IMqttChannelAdapter : IDisposable
Task DisconnectAsync(CancellationToken cancellationToken);
Task<MqttPacket> ReceivePacketAsync(CancellationToken cancellationToken);
Task<MqttPacket?> ReceivePacketAsync(CancellationToken cancellationToken);
void ResetStatistics();
@@ -8,5 +8,5 @@ namespace MQTTnet.Adapter;
public interface IMqttClientAdapterFactory
{
IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector packetInspector, IMqttNetLogger logger);
IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector? packetInspector, IMqttNetLogger logger);
}
+5 -5
View File
@@ -50,15 +50,15 @@ public sealed class MqttChannelAdapter : Disposable, IMqttChannelAdapter
public long BytesSent => Volatile.Read(ref _statistics._bytesSent);
public X509Certificate2 ClientCertificate => _channel.ClientCertificate;
public X509Certificate2? ClientCertificate => _channel.ClientCertificate;
public EndPoint RemoteEndPoint => _channel.RemoteEndPoint;
public EndPoint? RemoteEndPoint => _channel.RemoteEndPoint;
public bool IsSecureConnection => _channel.IsSecureConnection;
public MqttPacketFormatterAdapter PacketFormatterAdapter { get; }
public MqttPacketInspector PacketInspector { get; set; }
public MqttPacketInspector? PacketInspector { get; set; }
public async Task ConnectAsync(CancellationToken cancellationToken)
{
@@ -73,7 +73,7 @@ public sealed class MqttChannelAdapter : Disposable, IMqttChannelAdapter
* block forever. Even a cancellation token is not supported properly.
*/
var timeout = new TaskCompletionSource<object>();
var timeout = new TaskCompletionSource<object?>();
await using (cancellationToken.Register(() => timeout.TrySetResult(null)))
{
var connectTask = Task.Run(
@@ -133,7 +133,7 @@ public sealed class MqttChannelAdapter : Disposable, IMqttChannelAdapter
}
}
public async Task<MqttPacket> ReceivePacketAsync(CancellationToken cancellationToken)
public async Task<MqttPacket?> ReceivePacketAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
@@ -17,7 +17,7 @@ public sealed class MqttPacketInspector
readonly AsyncEvent<InspectMqttPacketEventArgs> _asyncEvent;
readonly MqttNetSourceLogger _logger;
MemoryStream _receivedPacketBuffer;
MemoryStream? _receivedPacketBuffer;
public MqttPacketInspector(AsyncEvent<InspectMqttPacketEventArgs> asyncEvent, IMqttNetLogger logger)
{
@@ -61,7 +61,7 @@ public sealed class MqttPacketInspector
return CompletedTask.Instance;
}
var buffer = _receivedPacketBuffer.ToArray();
var buffer = _receivedPacketBuffer!.ToArray();
_receivedPacketBuffer.SetLength(0);
return InspectPacket(buffer, MqttPacketFlowDirection.Inbound);
@@ -11,7 +11,7 @@ public class BlobCertificateProvider(byte[] blob) : ICertificateProvider
{
public byte[] Blob { get; } = blob ?? throw new ArgumentNullException(nameof(blob));
public string Password { get; set; }
public string? Password { get; set; }
public X509Certificate2 GetCertificate()
{
+3 -2
View File
@@ -13,8 +13,9 @@ namespace MQTTnet.Channel;
public interface IMqttChannel : IDisposable
{
X509Certificate2 ClientCertificate { get; }
EndPoint RemoteEndPoint { get; }
X509Certificate2? ClientCertificate { get; }
EndPoint? RemoteEndPoint { get; }
bool IsSecureConnection { get; }
@@ -14,19 +14,19 @@ public sealed class MqttClientConnectResult
/// Gets the client identifier which was chosen by the server.
/// MQTTv5 only.
/// </summary>
public string AssignedClientIdentifier { get; init; }
public string? AssignedClientIdentifier { get; init; }
/// <summary>
/// Gets the authentication data.
/// MQTTv5 only.
/// </summary>
public byte[] AuthenticationData { get; init; }
public byte[]? AuthenticationData { get; init; }
/// <summary>
/// Gets the authentication method.
/// MQTTv5 only.
/// </summary>
public string AuthenticationMethod { get; init; }
public string? AuthenticationMethod { get; init; }
/// <summary>
/// Gets a value indicating whether a session was already available or not.
@@ -45,7 +45,7 @@ public sealed class MqttClientConnectResult
/// Gets the reason string.
/// MQTTv5 only.
/// </summary>
public string ReasonString { get; init; }
public string? ReasonString { get; init; }
public ushort? ReceiveMaximum { get; init; }
@@ -53,7 +53,7 @@ public sealed class MqttClientConnectResult
/// Gets the response information.
/// MQTTv5 only.
/// </summary>
public string ResponseInformation { get; init; }
public string? ResponseInformation { get; init; }
/// <summary>
/// Gets the result code.
@@ -78,7 +78,7 @@ public sealed class MqttClientConnectResult
/// Gets an alternate server which should be used instead of the current one.
/// MQTTv5 only.
/// </summary>
public string ServerReference { get; init; }
public string? ServerReference { get; init; }
public uint? SessionExpiryInterval { get; init; }
@@ -109,7 +109,7 @@ public sealed class MqttClientConnectResult
/// The feature is very similar to the HTTP header concept.
/// MQTTv5 only.
/// </summary>
public List<MqttUserProperty> UserProperties { get; init; }
public List<MqttUserProperty>? UserProperties { get; init; }
/// <summary>
/// Gets a value indicating whether wildcards can be used in subscriptions at the current server.
@@ -10,5 +10,5 @@ public interface IMqttNetLogger
{
bool IsEnabled { get; }
void Publish(MqttNetLogLevel level, string source, string message, object[] parameters, Exception exception);
void Publish(MqttNetLogLevel level, string source, string message, object?[]? parameters, Exception? exception);
}
@@ -9,17 +9,17 @@ namespace MQTTnet.Diagnostics.Logger;
/// <summary>
/// This logger fires an event when a new message was published.
/// </summary>
public sealed class MqttNetEventLogger(string logId = null) : IMqttNetLogger
public sealed class MqttNetEventLogger(string? logId = null) : IMqttNetLogger
{
public event EventHandler<MqttNetLogMessagePublishedEventArgs> LogMessagePublished;
public event EventHandler<MqttNetLogMessagePublishedEventArgs>? LogMessagePublished;
public bool IsEnabled => LogMessagePublished != null;
public string LogId { get; } = logId;
public string? LogId { get; } = logId;
public IFormatProvider FormatProvider { get; set; }
public IFormatProvider? FormatProvider { get; set; }
public void Publish(MqttNetLogLevel level, string source, string message, object[] parameters, Exception exception)
public void Publish(MqttNetLogLevel level, string source, string message, object?[]? parameters, Exception? exception)
{
var eventHandler = LogMessagePublished;
if (eventHandler == null)
@@ -30,7 +30,7 @@ public sealed class MqttNetEventLogger(string logId = null) : IMqttNetLogger
return;
}
if (parameters?.Length > 0 && message?.Length > 0)
if (parameters?.Length > 0 && message.Length > 0)
{
try
{
@@ -8,19 +8,19 @@ namespace MQTTnet.Diagnostics.Logger;
public sealed class MqttNetLogMessage
{
public string LogId { get; set; }
public string? LogId { get; set; }
public DateTime Timestamp { get; set; }
public int ThreadId { get; set; }
public string Source { get; set; }
public string? Source { get; set; }
public MqttNetLogLevel Level { get; set; }
public string Message { get; set; }
public string? Message { get; set; }
public Exception Exception { get; set; }
public Exception? Exception { get; set; }
public override string ToString()
{
@@ -15,7 +15,7 @@ public sealed class MqttNetNullLogger : IMqttNetLogger
public bool IsEnabled { get; }
public void Publish(MqttNetLogLevel level, string source, string message, object[] parameters, Exception exception)
public void Publish(MqttNetLogLevel level, string source, string message, object?[]? parameters, Exception? exception)
{
}
}
@@ -12,7 +12,7 @@ public sealed class MqttNetSourceLogger(IMqttNetLogger logger, string source)
public bool IsEnabled => _logger.IsEnabled;
public void Publish(MqttNetLogLevel logLevel, string message, object[] parameters, Exception exception)
public void Publish(MqttNetLogLevel logLevel, string message, object?[]? parameters, Exception? exception)
{
_logger.Publish(logLevel, source, message, parameters, exception);
}
@@ -19,7 +19,7 @@ public sealed class MqttClientDisconnectOptions
/// Gets or sets the reason string.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
/// <summary>
/// Gets or sets the session expiry interval.
@@ -31,5 +31,5 @@ public sealed class MqttClientDisconnectOptions
/// Gets or sets the user properties.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
}
@@ -10,9 +10,9 @@ namespace MQTTnet;
public sealed class MqttClientDisconnectOptionsBuilder
{
MqttClientDisconnectOptionsReason _reason = MqttClientDisconnectOptionsReason.NormalDisconnection;
string _reasonString;
string? _reasonString;
uint _sessionExpiryInterval;
List<MqttUserProperty> _userProperties;
List<MqttUserProperty>? _userProperties;
public MqttClientDisconnectOptions Build()
{
@@ -12,11 +12,11 @@ public sealed class MqttClientDisconnectedEventArgs : EventArgs
{
public MqttClientDisconnectedEventArgs(
bool clientWasConnected,
MqttClientConnectResult connectResult,
MqttClientConnectResult? connectResult,
MqttClientDisconnectReason reason,
string reasonString,
List<MqttUserProperty> userProperties,
Exception exception)
string? reasonString,
List<MqttUserProperty>? userProperties,
Exception? exception)
{
ClientWasConnected = clientWasConnected;
ConnectResult = connectResult;
@@ -32,9 +32,9 @@ public sealed class MqttClientDisconnectedEventArgs : EventArgs
/// Gets the authentication result.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public MqttClientConnectResult ConnectResult { get; }
public MqttClientConnectResult? ConnectResult { get; }
public Exception Exception { get; }
public Exception? Exception { get; }
/// <summary>
/// Gets or sets the reason.
@@ -42,7 +42,7 @@ public sealed class MqttClientDisconnectedEventArgs : EventArgs
/// </summary>
public MqttClientDisconnectReason Reason { get; }
public string ReasonString { get; }
public string? ReasonString { get; }
public List<MqttUserProperty> UserProperties { get; }
public List<MqttUserProperty>? UserProperties { get; }
}
@@ -9,17 +9,17 @@ using MQTTnet.Protocol;
namespace MQTTnet.Exceptions;
public sealed class MqttClientUnexpectedDisconnectReceivedException(MqttDisconnectPacket disconnectPacket, Exception innerException = null) : MqttCommunicationException(
public sealed class MqttClientUnexpectedDisconnectReceivedException(MqttDisconnectPacket disconnectPacket, Exception? innerException = null) : MqttCommunicationException(
$"Unexpected DISCONNECT (Reason code={disconnectPacket.ReasonCode}) received.",
innerException)
{
public MqttDisconnectReasonCode? ReasonCode { get; } = disconnectPacket.ReasonCode;
public string ReasonString { get; } = disconnectPacket.ReasonString;
public string? ReasonString { get; } = disconnectPacket.ReasonString;
public string ServerReference { get; } = disconnectPacket.ServerReference;
public string? ServerReference { get; } = disconnectPacket.ServerReference;
public uint? SessionExpiryInterval { get; } = disconnectPacket.SessionExpiryInterval;
public List<MqttUserProperty> UserProperties { get; } = disconnectPacket.UserProperties;
public List<MqttUserProperty>? UserProperties { get; } = disconnectPacket.UserProperties;
}
@@ -8,12 +8,12 @@ namespace MQTTnet.Exceptions;
public class MqttCommunicationException : Exception
{
public MqttCommunicationException(Exception innerException)
public MqttCommunicationException(Exception? innerException)
: base(innerException?.Message ?? "MQTT communication failed.", innerException)
{
}
public MqttCommunicationException(string message, Exception innerException = null)
public MqttCommunicationException(string message, Exception? innerException = null)
: base(message, innerException)
{
}
@@ -9,7 +9,7 @@ namespace MQTTnet.Formatter;
public interface IMqttPacketFormatter
{
MqttPacket Decode(ReceivedMqttPacket receivedPacket);
MqttPacket? Decode(ReceivedMqttPacket receivedPacket);
MqttPacketBuffer Encode(MqttPacket packet);
}
+1 -1
View File
@@ -131,7 +131,7 @@ public sealed class MqttBufferReader
public void SetBuffer(ArraySegment<byte> buffer)
{
SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
SetBuffer(buffer.Array!, buffer.Offset, buffer.Count);
}
public void SetBuffer(byte[] buffer, int offset, int length)
+2 -2
View File
@@ -110,7 +110,7 @@ public sealed class MqttBufferWriter
WriteBinary(propertyWriter._buffer, 0, propertyWriter.Length);
}
public void WriteBinary(byte[] value)
public void WriteBinary(byte[]? value)
{
if (value == null || value.Length == 0)
{
@@ -158,7 +158,7 @@ public sealed class MqttBufferWriter
IncreasePosition(1);
}
public void WriteString(string value)
public void WriteString(string? value)
{
if (string.IsNullOrEmpty(value))
{
+1 -1
View File
@@ -40,7 +40,7 @@ public readonly struct MqttPacketBuffer
}
var buffer = GC.AllocateUninitializedArray<byte>(Length);
MqttMemoryHelper.Copy(Packet.Array, Packet.Offset, buffer, 0, Packet.Count);
MqttMemoryHelper.Copy(Packet.Array!, Packet.Offset, buffer, 0, Packet.Count);
MqttMemoryHelper.Copy(Payload, 0, buffer, Packet.Count, (int)Payload.Length);
return buffer;
@@ -17,7 +17,7 @@ public sealed class MqttPacketFormatterAdapter
readonly MqttBufferReader _bufferReader = new();
readonly MqttBufferWriter _bufferWriter;
IMqttPacketFormatter _formatter;
IMqttPacketFormatter? _formatter;
public MqttPacketFormatterAdapter(MqttBufferWriter mqttBufferWriter)
{
@@ -37,10 +37,10 @@ public sealed class MqttPacketFormatterAdapter
_bufferWriter.Cleanup();
}
public MqttPacket Decode(ReceivedMqttPacket receivedMqttPacket)
public MqttPacket? Decode(ReceivedMqttPacket receivedMqttPacket)
{
ThrowIfFormatterNotSet();
return _formatter.Decode(receivedMqttPacket);
return _formatter!.Decode(receivedMqttPacket);
}
public void DetectProtocolVersion(ReceivedMqttPacket receivedMqttPacket)
@@ -52,7 +52,7 @@ public sealed class MqttPacketFormatterAdapter
public MqttPacketBuffer Encode(MqttPacket packet)
{
ThrowIfFormatterNotSet();
return _formatter.Encode(packet);
return _formatter!.Encode(packet);
}
public static IMqttPacketFormatter GetMqttPacketFormatter(MqttProtocolVersion protocolVersion, MqttBufferWriter bufferWriter)
@@ -80,7 +80,7 @@ public sealed class MqttPacketFormatterAdapter
throw new MqttProtocolViolationException("CONNECT packet must have at least 7 bytes.");
}
_bufferReader.SetBuffer(receivedMqttPacket.Body.Array, receivedMqttPacket.Body.Offset, receivedMqttPacket.Body.Count);
_bufferReader.SetBuffer(receivedMqttPacket.Body.Array!, receivedMqttPacket.Body.Offset, receivedMqttPacket.Body.Count);
var protocolName = _bufferReader.ReadString();
var protocolLevel = _bufferReader.ReadByte();
@@ -18,10 +18,7 @@ public static class MqttUnsubscribePacketFactory
UserProperties = clientUnsubscribeOptions.UserProperties
};
if (clientUnsubscribeOptions.TopicFilters != null)
{
packet.TopicFilters.AddRange(clientUnsubscribeOptions.TopicFilters);
}
packet.TopicFilters!.AddRange(clientUnsubscribeOptions.TopicFilters);
return packet;
}
@@ -29,7 +29,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
_mqttProtocolVersion = mqttProtocolVersion;
}
public MqttPacket Decode(ReceivedMqttPacket receivedPacket)
public MqttPacket? Decode(ReceivedMqttPacket receivedPacket)
{
if (receivedPacket.TotalLength == 0)
{
@@ -126,7 +126,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttConnAckPacket();
@@ -140,7 +140,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttConnAckPacket();
@@ -156,7 +156,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var protocolName = _bufferReader.ReadString();
var protocolVersion = _bufferReader.ReadByte();
@@ -224,7 +224,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
return new MqttPubAckPacket
{
@@ -236,7 +236,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
return new MqttPubCompPacket
{
@@ -248,7 +248,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(receivedMqttPacket.Body);
_bufferReader.SetBuffer(receivedMqttPacket.Body.Array, receivedMqttPacket.Body.Offset, receivedMqttPacket.Body.Count);
_bufferReader.SetBuffer(receivedMqttPacket.Body.Array!, receivedMqttPacket.Body.Offset, receivedMqttPacket.Body.Count);
var retain = (receivedMqttPacket.FixedHeader & 0x1) > 0;
var qualityOfServiceLevel = (MqttQualityOfServiceLevel)((receivedMqttPacket.FixedHeader >> 1) & 0x3);
@@ -283,7 +283,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
return new MqttPubRecPacket
{
@@ -295,7 +295,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
return new MqttPubRelPacket
{
@@ -307,7 +307,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttSubAckPacket
{
@@ -327,7 +327,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttSubscribePacket
{
@@ -352,7 +352,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
return new MqttUnsubAckPacket
{
@@ -364,7 +364,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttUnsubscribePacket
{
@@ -373,7 +373,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
while (!_bufferReader.EndOfStream)
{
packet.TopicFilters.Add(_bufferReader.ReadString());
packet.TopicFilters!.Add(_bufferReader.ReadString());
}
return packet;
@@ -694,9 +694,9 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
bufferWriter.WriteTwoByteInteger(packet.PacketIdentifier);
if (packet.ReasonCodes.Count != 0)
if (packet.ReasonCodes?.Count > 0)
{
foreach (var packetSubscribeReturnCode in packet.ReasonCodes)
foreach (var packetSubscribeReturnCode in packet.ReasonCodes!)
{
if (packetSubscribeReturnCode == MqttSubscribeReasonCode.GrantedQoS0)
{
@@ -759,7 +759,7 @@ public sealed class MqttV3PacketFormatter : IMqttPacketFormatter
static byte EncodeUnsubscribePacket(MqttUnsubscribePacket packet, MqttBufferWriter bufferWriter)
{
if (packet.TopicFilters.Count == 0)
if (packet.TopicFilters?.Count == 0)
{
throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.10.3-2].");
}
@@ -15,7 +15,7 @@ public sealed class MqttV5PacketDecoder
{
readonly MqttBufferReader _bufferReader = new();
public MqttPacket Decode(ReceivedMqttPacket receivedMqttPacket)
public MqttPacket? Decode(ReceivedMqttPacket receivedMqttPacket)
{
if (receivedMqttPacket.TotalLength == 0)
{
@@ -51,7 +51,7 @@ public sealed class MqttV5PacketDecoder
MqttAuthPacket DecodeAuthPacket(ArraySegment<byte> body)
{
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttAuthPacket();
@@ -95,7 +95,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var acknowledgeFlags = _bufferReader.ReadByte();
@@ -198,7 +198,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttConnectPacket
{
@@ -346,7 +346,7 @@ public sealed class MqttV5PacketDecoder
};
}
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttDisconnectPacket
{
@@ -383,7 +383,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttPubAckPacket
{
@@ -420,7 +420,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttPubCompPacket
{
@@ -458,7 +458,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var retain = (header & 1) > 0;
var qos = (MqttQualityOfServiceLevel)((header >> 1) & 3);
@@ -533,7 +533,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttPubRecPacket
{
@@ -570,7 +570,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttPubRelPacket
{
@@ -607,7 +607,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttSubAckPacket
{
@@ -643,7 +643,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttSubscribePacket
{
@@ -693,7 +693,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttUnsubAckPacket
{
@@ -730,7 +730,7 @@ public sealed class MqttV5PacketDecoder
{
ThrowIfBodyIsEmpty(body);
_bufferReader.SetBuffer(body.Array, body.Offset, body.Count);
_bufferReader.SetBuffer(body.Array!, body.Offset, body.Count);
var packet = new MqttUnsubscribePacket
{
@@ -747,7 +747,7 @@ public sealed class MqttV5PacketDecoder
while (!_bufferReader.EndOfStream)
{
packet.TopicFilters.Add(_bufferReader.ReadString());
packet.TopicFilters!.Add(_bufferReader.ReadString());
}
return packet;
@@ -30,7 +30,9 @@ public sealed class MqttV5PacketEncoder(MqttBufferWriter bufferWriter)
var fixedHeader = EncodePacket(packet);
var remainingLength = (uint)_bufferWriter.Length - reservedHeaderSize;
if (packet is MqttPublishPacket publishPacket)
var publishPacket = packet as MqttPublishPacket;
if (publishPacket != null)
{
var payload = publishPacket.Payload;
remainingLength += (uint)payload.Length;
@@ -405,7 +407,7 @@ public sealed class MqttV5PacketEncoder(MqttBufferWriter bufferWriter)
_propertiesWriter.WriteTo(_bufferWriter);
_propertiesWriter.Reset();
foreach (var reasonCode in packet.ReasonCodes)
foreach (var reasonCode in packet.ReasonCodes!)
{
_bufferWriter.WriteByte((byte)reasonCode);
}
@@ -476,7 +478,7 @@ public sealed class MqttV5PacketEncoder(MqttBufferWriter bufferWriter)
_propertiesWriter.WriteTo(_bufferWriter);
_propertiesWriter.Reset();
foreach (var reasonCode in packet.ReasonCodes)
foreach (var reasonCode in packet.ReasonCodes!)
{
_bufferWriter.WriteByte((byte)reasonCode);
}
@@ -500,7 +502,7 @@ public sealed class MqttV5PacketEncoder(MqttBufferWriter bufferWriter)
_propertiesWriter.WriteTo(_bufferWriter);
_propertiesWriter.Reset();
foreach (var topicFilter in packet.TopicFilters)
foreach (var topicFilter in packet.TopicFilters!)
{
_bufferWriter.WriteString(topicFilter);
}
@@ -18,7 +18,7 @@ public sealed class MqttV5PacketFormatter : IMqttPacketFormatter
_encoder = new MqttV5PacketEncoder(bufferWriter);
}
public MqttPacket Decode(ReceivedMqttPacket receivedPacket)
public MqttPacket? Decode(ReceivedMqttPacket receivedPacket)
{
return _decoder.Decode(receivedPacket);
}
@@ -35,7 +35,7 @@ public struct MqttV5PropertiesReader
CurrentPropertyId = MqttPropertyId.None;
}
public List<MqttUserProperty> CollectedUserProperties { get; private set; }
public List<MqttUserProperty>? CollectedUserProperties { get; private set; }
public MqttPropertyId CurrentPropertyId { get; private set; }
@@ -9,14 +9,9 @@ using MQTTnet.Protocol;
namespace MQTTnet.Formatter.V5;
public sealed class MqttV5PropertiesWriter
public sealed class MqttV5PropertiesWriter(MqttBufferWriter bufferWriter)
{
readonly MqttBufferWriter _bufferWriter;
public MqttV5PropertiesWriter(MqttBufferWriter bufferWriter)
{
_bufferWriter = bufferWriter ?? throw new ArgumentNullException(nameof(bufferWriter));
}
readonly MqttBufferWriter _bufferWriter = bufferWriter ?? throw new ArgumentNullException(nameof(bufferWriter));
public int Length => _bufferWriter.Length;
@@ -26,27 +21,27 @@ public sealed class MqttV5PropertiesWriter
_bufferWriter.Cleanup();
}
public void WriteAssignedClientIdentifier(string value)
public void WriteAssignedClientIdentifier(string? value)
{
Write(MqttPropertyId.AssignedClientIdentifier, value);
}
public void WriteAuthenticationData(byte[] value)
public void WriteAuthenticationData(byte[]? value)
{
Write(MqttPropertyId.AuthenticationData, value);
}
public void WriteAuthenticationMethod(string value)
public void WriteAuthenticationMethod(string? value)
{
Write(MqttPropertyId.AuthenticationMethod, value);
}
public void WriteContentType(string value)
public void WriteContentType(string? value)
{
Write(MqttPropertyId.ContentType, value);
}
public void WriteCorrelationData(byte[] value)
public void WriteCorrelationData(byte[]? value)
{
Write(MqttPropertyId.CorrelationData, value);
}
@@ -96,7 +91,7 @@ public sealed class MqttV5PropertiesWriter
Write(MqttPropertyId.PayloadFormatIndicator, (byte)value);
}
public void WriteReasonString(string value)
public void WriteReasonString(string? value)
{
Write(MqttPropertyId.ReasonString, value);
}
@@ -134,12 +129,12 @@ public sealed class MqttV5PropertiesWriter
Write(MqttPropertyId.RequestResponseInformation, true);
}
public void WriteResponseInformation(string value)
public void WriteResponseInformation(string? value)
{
Write(MqttPropertyId.ResponseInformation, value);
}
public void WriteResponseTopic(string value)
public void WriteResponseTopic(string? value)
{
Write(MqttPropertyId.ResponseTopic, value);
}
@@ -165,7 +160,7 @@ public sealed class MqttV5PropertiesWriter
Write(MqttPropertyId.ServerKeepAlive, value);
}
public void WriteServerReference(string value)
public void WriteServerReference(string? value)
{
Write(MqttPropertyId.ServerReference, value);
}
@@ -197,7 +192,7 @@ public sealed class MqttV5PropertiesWriter
WriteAsVariableByteInteger(MqttPropertyId.SubscriptionIdentifier, value);
}
public void WriteSubscriptionIdentifiers(ICollection<uint> value)
public void WriteSubscriptionIdentifiers(ICollection<uint>? value)
{
if (value == null)
{
@@ -251,7 +246,7 @@ public sealed class MqttV5PropertiesWriter
Write(MqttPropertyId.TopicAliasMaximum, value);
}
public void WriteUserProperties(List<MqttUserProperty> userProperties)
public void WriteUserProperties(List<MqttUserProperty>? userProperties)
{
if (userProperties == null || userProperties.Count == 0)
{
@@ -306,7 +301,7 @@ public sealed class MqttV5PropertiesWriter
_bufferWriter.WriteTwoByteInteger(value);
}
void Write(MqttPropertyId id, string value)
void Write(MqttPropertyId id, string? value)
{
if (string.IsNullOrEmpty(value))
{
@@ -317,7 +312,7 @@ public sealed class MqttV5PropertiesWriter
_bufferWriter.WriteString(value);
}
void Write(MqttPropertyId id, byte[] value)
void Write(MqttPropertyId id, byte[]? value)
{
if (value == null)
{
+1 -1
View File
@@ -19,7 +19,7 @@ public interface IMqttClient : IDisposable
bool IsConnected { get; }
MqttClientOptions Options { get; }
MqttClientOptions? Options { get; }
Task<MqttClientConnectResult> ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken = default);
@@ -16,7 +16,7 @@ public sealed class CrossPlatformSocket : IDisposable
{
readonly Socket _socket;
NetworkStream _networkStream;
NetworkStream? _networkStream;
public CrossPlatformSocket(AddressFamily addressFamily, ProtocolType protocolType)
{
@@ -50,13 +50,13 @@ public sealed class CrossPlatformSocket : IDisposable
set => _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, value ? 1 : 0);
}
public LingerOption LingerState
public LingerOption? LingerState
{
get => _socket.LingerState;
set => _socket.LingerState = value;
set => _socket.LingerState = value!;
}
public EndPoint LocalEndPoint => _socket.LocalEndPoint;
public EndPoint? LocalEndPoint => _socket.LocalEndPoint;
public bool NoDelay
{
@@ -70,7 +70,7 @@ public sealed class CrossPlatformSocket : IDisposable
set => _socket.ReceiveBufferSize = value;
}
public EndPoint RemoteEndPoint => _socket.RemoteEndPoint;
public EndPoint? RemoteEndPoint => _socket.RemoteEndPoint;
public bool ReuseAddress
{
@@ -108,7 +108,7 @@ public sealed class CrossPlatformSocket : IDisposable
set => _socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, value);
}
public async Task<CrossPlatformSocket> AcceptAsync(CancellationToken cancellationToken)
public async Task<CrossPlatformSocket?> AcceptAsync(CancellationToken cancellationToken)
{
try
{
@@ -12,7 +12,7 @@ namespace MQTTnet.Implementations;
public sealed class MqttClientAdapterFactory : IMqttClientAdapterFactory
{
public IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector packetInspector, IMqttNetLogger logger)
public IMqttChannelAdapter CreateClientAdapter(MqttClientOptions options, MqttPacketInspector? packetInspector, IMqttNetLogger logger)
{
ArgumentNullException.ThrowIfNull(options);
@@ -20,10 +20,10 @@ namespace MQTTnet.Implementations;
public sealed class MqttTcpChannel : IMqttChannel
{
readonly MqttClientOptions _clientOptions;
readonly MqttClientTcpOptions _tcpOptions;
readonly MqttClientOptions? _clientOptions;
readonly MqttClientTcpOptions? _tcpOptions;
Stream _stream;
Stream? _stream;
public MqttTcpChannel()
{
@@ -32,7 +32,7 @@ public sealed class MqttTcpChannel : IMqttChannel
public MqttTcpChannel(MqttClientOptions clientOptions) : this()
{
_clientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
_tcpOptions = (MqttClientTcpOptions)clientOptions.ChannelOptions;
_tcpOptions = (MqttClientTcpOptions)clientOptions.ChannelOptions!;
IsSecureConnection = clientOptions.ChannelOptions?.TlsOptions?.UseTls == true;
}
@@ -47,18 +47,18 @@ public sealed class MqttTcpChannel : IMqttChannel
ClientCertificate = clientCertificate;
}
public X509Certificate2 ClientCertificate { get; }
public X509Certificate2? ClientCertificate { get; }
public EndPoint RemoteEndPoint { get; private set; }
public EndPoint? RemoteEndPoint { get; private set; }
public bool IsSecureConnection { get; }
public async Task ConnectAsync(CancellationToken cancellationToken)
{
CrossPlatformSocket socket = null;
CrossPlatformSocket? socket = null;
try
{
if (_tcpOptions.AddressFamily == AddressFamily.Unspecified)
if (_tcpOptions!.AddressFamily == AddressFamily.Unspecified)
{
socket = new CrossPlatformSocket(_tcpOptions.ProtocolType);
}
@@ -74,7 +74,7 @@ public sealed class MqttTcpChannel : IMqttChannel
socket.ReceiveBufferSize = _tcpOptions.BufferSize;
socket.SendBufferSize = _tcpOptions.BufferSize;
socket.SendTimeout = (int)_clientOptions.Timeout.TotalMilliseconds;
socket.SendTimeout = (int)_clientOptions!.Timeout.TotalMilliseconds;
if (_tcpOptions.ProtocolType == ProtocolType.Tcp)
{
@@ -87,7 +87,7 @@ public sealed class MqttTcpChannel : IMqttChannel
socket.LingerState = _tcpOptions.LingerState;
}
if (_tcpOptions.DualMode.HasValue)
if (_tcpOptions.DualMode != null)
{
// It is important to avoid setting the flag if no specific value is set by the user
// because on IPv4 only networks the setter will always throw an exception. Regardless
@@ -95,7 +95,7 @@ public sealed class MqttTcpChannel : IMqttChannel
socket.DualMode = _tcpOptions.DualMode.Value;
}
await socket.ConnectAsync(_tcpOptions.RemoteEndpoint, cancellationToken).ConfigureAwait(false);
await socket.ConnectAsync(_tcpOptions.RemoteEndpoint!, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
@@ -285,13 +285,13 @@ public sealed class MqttTcpChannel : IMqttChannel
object sender,
string targetHost,
X509CertificateCollection localCertificates,
X509Certificate remoteCertificate,
X509Certificate? remoteCertificate,
string[] acceptableIssuers)
{
var certificateSelectionHandler = _tcpOptions?.TlsOptions?.CertificateSelectionHandler;
if (certificateSelectionHandler != null)
{
var eventArgs = new MqttClientCertificateSelectionEventArgs(targetHost, localCertificates, remoteCertificate, acceptableIssuers, _tcpOptions);
var eventArgs = new MqttClientCertificateSelectionEventArgs(targetHost, localCertificates, remoteCertificate, acceptableIssuers, _tcpOptions!);
return certificateSelectionHandler(eventArgs);
}
@@ -300,15 +300,15 @@ public sealed class MqttTcpChannel : IMqttChannel
return localCertificates[0];
}
return null;
return null!;
}
bool InternalUserCertificateValidationCallback(object sender, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
bool InternalUserCertificateValidationCallback(object? sender, X509Certificate? x509Certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors)
{
var certificateValidationHandler = _tcpOptions?.TlsOptions?.CertificateValidationHandler;
if (certificateValidationHandler != null)
{
var eventArgs = new MqttClientCertificateValidationEventArgs(x509Certificate, chain, sslPolicyErrors, _tcpOptions);
var eventArgs = new MqttClientCertificateValidationEventArgs(x509Certificate, chain, sslPolicyErrors, _tcpOptions!);
return certificateValidationHandler(eventArgs);
}
@@ -320,8 +320,8 @@ public sealed class MqttTcpChannel : IMqttChannel
return sslPolicyErrors == SslPolicyErrors.None;
}
X509CertificateCollection LoadCertificates()
X509CertificateCollection? LoadCertificates()
{
return _tcpOptions.TlsOptions.ClientCertificatesProvider?.GetCertificates();
return _tcpOptions!.TlsOptions.ClientCertificatesProvider?.GetCertificates();
}
}
@@ -16,17 +16,17 @@ namespace MQTTnet.Implementations;
public sealed class MqttWebSocketChannel : IMqttChannel
{
readonly MqttClientWebSocketOptions _options;
readonly MqttClientWebSocketOptions? _options;
AsyncLock _sendLock = new();
WebSocket _webSocket;
AsyncLock? _sendLock = new();
WebSocket? _webSocket;
public MqttWebSocketChannel(MqttClientWebSocketOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
public MqttWebSocketChannel(WebSocket webSocket, EndPoint remoteEndPoint, bool isSecureConnection, X509Certificate2 clientCertificate)
public MqttWebSocketChannel(WebSocket webSocket, EndPoint? remoteEndPoint, bool isSecureConnection, X509Certificate2 clientCertificate)
{
_webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket));
@@ -35,15 +35,15 @@ public sealed class MqttWebSocketChannel : IMqttChannel
ClientCertificate = clientCertificate;
}
public X509Certificate2 ClientCertificate { get; }
public X509Certificate2? ClientCertificate { get; }
public EndPoint RemoteEndPoint { get; }
public EndPoint? RemoteEndPoint { get; }
public bool IsSecureConnection { get; private set; }
public async Task ConnectAsync(CancellationToken cancellationToken)
{
var uri = _options.Uri;
var uri = _options!.Uri;
if (!uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase) && !uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase))
{
if (_options.TlsOptions?.UseTls == true)
@@ -96,7 +96,7 @@ public sealed class MqttWebSocketChannel : IMqttChannel
public async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
var response = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), cancellationToken).ConfigureAwait(false);
var response = await _webSocket!.ReceiveAsync(new ArraySegment<byte>(buffer, offset, count), cancellationToken).ConfigureAwait(false);
return response.Count;
}
@@ -111,7 +111,7 @@ public sealed class MqttWebSocketChannel : IMqttChannel
{
length -= segment.Length;
bool endOfPacket = isEndOfPacket && length == 0;
await _webSocket.SendAsync(segment, WebSocketMessageType.Binary, endOfPacket, cancellationToken).ConfigureAwait(false);
await _webSocket!.SendAsync(segment, WebSocketMessageType.Binary, endOfPacket, cancellationToken).ConfigureAwait(false);
}
}
@@ -133,9 +133,9 @@ public sealed class MqttWebSocketChannel : IMqttChannel
}
}
WebProxy CreateProxy()
WebProxy? CreateProxy()
{
if (string.IsNullOrEmpty(_options.ProxyOptions?.Address))
if (string.IsNullOrEmpty(_options!.ProxyOptions?.Address))
{
return null;
}
@@ -165,7 +165,7 @@ public sealed class MqttWebSocketChannel : IMqttChannel
void SetupClientWebSocket(ClientWebSocket clientWebSocket)
{
if (_options.ProxyOptions != null)
if (_options!.ProxyOptions != null)
{
clientWebSocket.Options.Proxy = CreateProxy();
}
@@ -9,10 +9,10 @@ namespace MQTTnet.Internal;
public readonly struct AsyncEventInvocator<TEventArgs>
{
readonly Action<TEventArgs> _handler;
readonly Func<TEventArgs, Task> _asyncHandler;
readonly Action<TEventArgs>? _handler;
readonly Func<TEventArgs, Task>? _asyncHandler;
public AsyncEventInvocator(Action<TEventArgs> handler, Func<TEventArgs, Task> asyncHandler)
public AsyncEventInvocator(Action<TEventArgs>? handler, Func<TEventArgs, Task>? asyncHandler)
{
_handler = handler;
_asyncHandler = asyncHandler;
+1 -1
View File
@@ -70,7 +70,7 @@ public sealed class AsyncQueue<TItem> : IDisposable
{
try
{
Task task = null;
Task? task = null;
lock (_syncRoot)
{
if (_isDisposed)
@@ -6,7 +6,7 @@ namespace MQTTnet.Internal;
public sealed class AsyncQueueDequeueResult<TItem>(bool isSuccess, TItem item)
{
public static readonly AsyncQueueDequeueResult<TItem> NonSuccess = new(false, default);
public static readonly AsyncQueueDequeueResult<TItem> NonSuccess = new(false, default!);
public bool IsSuccess { get; } = isSuccess;
+1 -1
View File
@@ -14,7 +14,7 @@ public sealed class AsyncSignal : IDisposable
bool _isDisposed;
bool _isSignaled;
AsyncSignalWaiter _waiter;
AsyncSignalWaiter? _waiter;
public void Dispose()
{
+1 -1
View File
@@ -15,7 +15,7 @@ public sealed class BlockingQueue<TItem> : IDisposable
readonly LinkedList<TItem> _items = [];
readonly object _syncRoot = new();
ManualResetEventSlim _gate = new(false);
ManualResetEventSlim? _gate = new(false);
public int Count
{
+1 -1
View File
@@ -104,7 +104,7 @@ public sealed class MqttPacketBus : IDisposable
_signal.Dispose();
}
public MqttPacketBusItem DropFirstItem(MqttPacketBusPartition partition)
public MqttPacketBusItem? DropFirstItem(MqttPacketBusPartition partition)
{
lock (_syncRoot)
{
+3 -8
View File
@@ -8,18 +8,13 @@ using MQTTnet.Packets;
namespace MQTTnet.Internal;
public sealed class MqttPacketBusItem
public sealed class MqttPacketBusItem(MqttPacket packet)
{
readonly AsyncTaskCompletionSource<MqttPacket> _promise = new();
public MqttPacketBusItem(MqttPacket packet)
{
Packet = packet ?? throw new ArgumentNullException(nameof(packet));
}
public event EventHandler? Completed;
public event EventHandler Completed;
public MqttPacket Packet { get; }
public MqttPacket Packet { get; } = packet ?? throw new ArgumentNullException(nameof(packet));
public void Cancel()
{
+3 -3
View File
@@ -10,19 +10,19 @@ namespace MQTTnet.Internal;
public static class TaskExtensions
{
public static void RunInBackground(this Task task, MqttNetSourceLogger logger = null)
public static void RunInBackground(this Task? task, MqttNetSourceLogger? logger = null)
{
task?.ContinueWith(
t =>
{
// Consume the exception first so that we get no exception regarding the not observed exception.
var exception = t.Exception;
logger?.Error(exception, "Unhandled exception in background task.");
logger?.Error(exception!, "Unhandled exception in background task.");
},
TaskContinuationOptions.OnlyOnFaulted);
}
public static async Task WaitAsync(this Task task, Task sender, MqttNetSourceLogger logger)
public static async Task WaitAsync(this Task? task, Task? sender, MqttNetSourceLogger logger)
{
ArgumentNullException.ThrowIfNull(logger);
@@ -21,7 +21,7 @@ public sealed class LowLevelMqttClient : ILowLevelMqttClient
readonly MqttNetSourceLogger _logger;
readonly IMqttNetLogger _rootLogger;
IMqttChannelAdapter _adapter;
IMqttChannelAdapter? _adapter;
public LowLevelMqttClient(IMqttClientAdapterFactory clientAdapterFactory, IMqttNetLogger logger)
{
@@ -48,7 +48,7 @@ public sealed class LowLevelMqttClient : ILowLevelMqttClient
throw new InvalidOperationException("Low level MQTT client is already connected. Disconnect first before connecting again.");
}
MqttPacketInspector packetInspector = null;
MqttPacketInspector? packetInspector = null;
if (_inspectPacketEvent.HasHandlers)
{
packetInspector = new MqttPacketInspector(_inspectPacketEvent, _rootLogger);
+2
View File
@@ -46,6 +46,8 @@
<NuGetAuditLevel>low</NuGetAuditLevel>
<AnalysisLevel>latest-Recommended</AnalysisLevel>
<IsAotCompatible>true</IsAotCompatible>
<LangVersion>default</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)'=='Debug'">
+6 -6
View File
@@ -18,7 +18,7 @@ public sealed class MqttApplicationMessage
/// The content type must be a UTF-8 encoded string. The content type value identifies the kind of UTF-8 encoded
/// payload.
/// </summary>
public string ContentType { get; set; }
public string? ContentType { get; set; }
/// <summary>
/// Gets or sets the correlation data.
@@ -26,7 +26,7 @@ public sealed class MqttApplicationMessage
/// published message.
/// Hint: MQTT 5 feature only.
/// </summary>
public byte[] CorrelationData { get; set; }
public byte[]? CorrelationData { get; set; }
/// <summary>
/// If the DUP flag is set to 0, it indicates that this is the first occasion that the Client or Server has attempted
@@ -94,7 +94,7 @@ public sealed class MqttApplicationMessage
/// the request/response pattern between clients that is common in web applications.
/// Hint: MQTT 5 feature only.
/// </summary>
public string ResponseTopic { get; set; }
public string? ResponseTopic { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the message should be retained or not.
@@ -112,7 +112,7 @@ public sealed class MqttApplicationMessage
/// the client when need to forward PUBLISH packets matching this subscription to this client.
/// Hint: MQTT 5 feature only.
/// </summary>
public List<uint> SubscriptionIdentifiers { get; set; }
public List<uint>? SubscriptionIdentifiers { get; set; }
/// <summary>
/// Gets or sets the MQTT topic.
@@ -121,7 +121,7 @@ public sealed class MqttApplicationMessage
/// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level
/// separator).
/// </summary>
public string Topic { get; set; }
public required string Topic { get; set; }
/// <summary>
/// Gets or sets the topic alias.
@@ -141,5 +141,5 @@ public sealed class MqttApplicationMessage
/// The feature is very similar to the HTTP header concept.
/// Hint: MQTT 5 feature only.
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
}
+12 -12
View File
@@ -18,19 +18,19 @@ namespace MQTTnet;
public sealed class MqttApplicationMessageBuilder
{
string _contentType;
byte[] _correlationData;
string? _contentType;
byte[]? _correlationData;
uint _messageExpiryInterval;
MqttPayloadFormatIndicator _payloadFormatIndicator;
ReadOnlySequence<byte> _payload;
MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
string _responseTopic;
string? _responseTopic;
bool _retain;
List<uint> _subscriptionIdentifiers;
string _topic;
List<uint>? _subscriptionIdentifiers;
string? _topic;
ushort _topicAlias;
List<MqttUserProperty> _userProperties;
List<MqttUserProperty>? _userProperties;
public MqttApplicationMessage Build()
{
@@ -41,7 +41,7 @@ public sealed class MqttApplicationMessageBuilder
var applicationMessage = new MqttApplicationMessage
{
Topic = _topic,
Topic = _topic!,
Payload = _payload,
QualityOfServiceLevel = _qualityOfServiceLevel,
Retain = _retain,
@@ -88,7 +88,7 @@ public sealed class MqttApplicationMessageBuilder
return this;
}
public MqttApplicationMessageBuilder WithPayload(byte[] payload)
public MqttApplicationMessageBuilder WithPayload(byte[]? payload)
{
_payload = payload == null || payload.Length == 0 ? EmptyBuffer.ReadOnlySequence : new ReadOnlySequence<byte>(payload);
return this;
@@ -100,7 +100,7 @@ public sealed class MqttApplicationMessageBuilder
return this;
}
public MqttApplicationMessageBuilder WithPayload(IEnumerable<byte> payload)
public MqttApplicationMessageBuilder WithPayload(IEnumerable<byte>? payload)
{
if (payload == null)
{
@@ -120,12 +120,12 @@ public sealed class MqttApplicationMessageBuilder
return WithPayload(payload.ToArray());
}
public MqttApplicationMessageBuilder WithPayload(Stream payload)
public MqttApplicationMessageBuilder WithPayload(Stream? payload)
{
return payload == null ? WithPayload(default(byte[])) : WithPayload(payload, payload.Length - payload.Position);
}
public MqttApplicationMessageBuilder WithPayload(Stream payload, long length)
public MqttApplicationMessageBuilder WithPayload(Stream? payload, long length)
{
if (payload == null || length == 0)
{
@@ -148,7 +148,7 @@ public sealed class MqttApplicationMessageBuilder
return WithPayload(payloadBuffer);
}
public MqttApplicationMessageBuilder WithPayload(string payload)
public MqttApplicationMessageBuilder WithPayload(string? payload)
{
if (string.IsNullOrEmpty(payload))
{
@@ -9,7 +9,7 @@ namespace MQTTnet;
public static class MqttApplicationMessageExtensions
{
public static string ConvertPayloadToString(this MqttApplicationMessage applicationMessage)
public static string? ConvertPayloadToString(this MqttApplicationMessage applicationMessage)
{
ArgumentNullException.ThrowIfNull(applicationMessage);
+47 -47
View File
@@ -29,7 +29,7 @@ public sealed class MqttClient : Disposable, IMqttClient
readonly MqttPacketIdentifierProvider _packetIdentifierProvider = new();
readonly IMqttNetLogger _rootLogger;
IMqttChannelAdapter _adapter;
IMqttChannelAdapter? _adapter;
bool _cleanDisconnectInitiated;
volatile int _connectionStatus;
@@ -37,18 +37,18 @@ public sealed class MqttClient : Disposable, IMqttClient
// The value for this field can be set from two different enums.
// They contain the same values but the set is reduced in one case.
int _disconnectReason;
string _disconnectReasonString;
List<MqttUserProperty> _disconnectUserProperties;
string? _disconnectReasonString;
List<MqttUserProperty>? _disconnectUserProperties;
Task _keepAlivePacketsSenderTask;
Task? _keepAlivePacketsSenderTask;
DateTime _lastPacketSentTimestamp;
CancellationTokenSource _mqttClientAlive;
MqttPacketDispatcher _packetDispatcher;
Task _packetReceiverTask;
AsyncQueue<MqttPublishPacket> _publishPacketReceiverQueue;
Task _publishPacketReceiverTask;
MqttDisconnectPacket _unexpectedDisconnectPacket;
CancellationTokenSource? _mqttClientAlive;
MqttPacketDispatcher? _packetDispatcher;
Task? _packetReceiverTask;
AsyncQueue<MqttPublishPacket>? _publishPacketReceiverQueue;
Task? _publishPacketReceiverTask;
MqttDisconnectPacket? _unexpectedDisconnectPacket;
public MqttClient(IMqttClientAdapterFactory channelFactory, IMqttNetLogger logger)
{
@@ -89,7 +89,7 @@ public sealed class MqttClient : Disposable, IMqttClient
public bool IsConnected => (MqttClientConnectionStatus)_connectionStatus == MqttClientConnectionStatus.Connected;
public MqttClientOptions Options { get; private set; }
public MqttClientOptions? Options { get; private set; }
public async Task<MqttClientConnectResult> ConnectAsync(MqttClientOptions options, CancellationToken cancellationToken = default)
{
@@ -102,7 +102,7 @@ public sealed class MqttClient : Disposable, IMqttClient
throw new InvalidOperationException("Not allowed to connect while connect/disconnect is pending.");
}
MqttClientConnectResult connectResult = null;
MqttClientConnectResult? connectResult = null;
try
{
@@ -202,9 +202,9 @@ public sealed class MqttClient : Disposable, IMqttClient
_disconnectReason = (int)options.Reason;
_cleanDisconnectInitiated = true;
if (Options.ValidateFeatures)
if (Options!.ValidateFeatures)
{
MqttClientDisconnectOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion);
MqttClientDisconnectOptionsValidator.ThrowIfNotSupported(options, _adapter!.PacketFormatterAdapter.ProtocolVersion);
}
// Sending the DISCONNECT may fail due to connection issues. The resulting exception
@@ -240,7 +240,7 @@ public sealed class MqttClient : Disposable, IMqttClient
}
else
{
using var timeout = new CancellationTokenSource(Options.Timeout);
using var timeout = new CancellationTokenSource(Options!.Timeout);
await Request<MqttPingRespPacket>(MqttPingReqPacket.Instance, timeout.Token).ConfigureAwait(false);
}
}
@@ -254,9 +254,9 @@ public sealed class MqttClient : Disposable, IMqttClient
ThrowIfDisposed();
ThrowIfNotConnected();
if (Options.ValidateFeatures)
if (Options!.ValidateFeatures)
{
MqttApplicationMessageValidator.ThrowIfNotSupported(applicationMessage, _adapter.PacketFormatterAdapter.ProtocolVersion);
MqttApplicationMessageValidator.ThrowIfNotSupported(applicationMessage, _adapter!.PacketFormatterAdapter.ProtocolVersion);
}
var publishPacket = MqttPublishPacketFactory.Create(applicationMessage);
@@ -292,7 +292,7 @@ public sealed class MqttClient : Disposable, IMqttClient
var authPacket = new MqttAuthPacket
{
// This must always be equal to the value from the CONNECT packet. So we use it here to ensure that.
AuthenticationMethod = Options.AuthenticationMethod,
AuthenticationMethod = Options!.AuthenticationMethod,
AuthenticationData = data.AuthenticationData,
ReasonString = data.ReasonString,
ReasonCode = data.ReasonCode,
@@ -314,9 +314,9 @@ public sealed class MqttClient : Disposable, IMqttClient
ThrowIfDisposed();
ThrowIfNotConnected();
if (Options.ValidateFeatures)
if (Options!.ValidateFeatures)
{
MqttClientSubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion);
MqttClientSubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter!.PacketFormatterAdapter.ProtocolVersion);
}
var subscribePacket = MqttSubscribePacketFactory.Create(options);
@@ -348,9 +348,9 @@ public sealed class MqttClient : Disposable, IMqttClient
ThrowIfDisposed();
ThrowIfNotConnected();
if (Options.ValidateFeatures)
if (Options!.ValidateFeatures)
{
MqttClientUnsubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion);
MqttClientUnsubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter!.PacketFormatterAdapter.ProtocolVersion);
}
var unsubscribePacket = MqttUnsubscribePacketFactory.Create(options);
@@ -465,8 +465,8 @@ public sealed class MqttClient : Disposable, IMqttClient
Task HandleEnhancedAuthentication(MqttAuthPacket authPacket, CancellationToken cancellationToken)
{
var eventArgs = new MqttEnhancedAuthenticationEventArgs(authPacket, _adapter, cancellationToken);
return Options.EnhancedAuthenticationHandler.HandleEnhancedAuthenticationAsync(eventArgs);
var eventArgs = new MqttEnhancedAuthenticationEventArgs(authPacket, _adapter!, cancellationToken);
return Options!.EnhancedAuthenticationHandler!.HandleEnhancedAuthenticationAsync(eventArgs);
}
void Cleanup()
@@ -498,10 +498,10 @@ public sealed class MqttClient : Disposable, IMqttClient
async Task<MqttClientConnectResult> ConnectInternal(IMqttChannelAdapter channelAdapter, CancellationToken cancellationToken)
{
var backgroundCancellationToken = _mqttClientAlive.Token;
var backgroundCancellationToken = _mqttClientAlive!.Token;
using var effectiveCancellationToken = CancellationTokenSource.CreateLinkedTokenSource(backgroundCancellationToken, cancellationToken);
_logger.Verbose("Trying to connect with server '{0}'", Options.ChannelOptions);
_logger.Verbose("Trying to connect with server '{0}'", Options!.ChannelOptions);
await channelAdapter.ConnectAsync(effectiveCancellationToken.Token).ConfigureAwait(false);
_logger.Verbose("Connection with server established");
@@ -520,7 +520,7 @@ public sealed class MqttClient : Disposable, IMqttClient
return connectResult;
}
async Task DisconnectCore(Task sender, Exception exception, MqttClientConnectResult connectResult, bool clientWasConnected)
async Task DisconnectCore(Task? sender, Exception? exception, MqttClientConnectResult? connectResult, bool clientWasConnected)
{
TryInitiateDisconnect();
@@ -528,7 +528,7 @@ public sealed class MqttClient : Disposable, IMqttClient
{
if (_adapter != null)
{
_logger.Verbose("Disconnecting [Timeout={0}]", Options.Timeout);
_logger.Verbose("Disconnecting [Timeout={0}]", Options!.Timeout);
using var timeout = new CancellationTokenSource(Options.Timeout);
await _adapter.DisconnectAsync(timeout.Token).ConfigureAwait(false);
@@ -543,7 +543,7 @@ public sealed class MqttClient : Disposable, IMqttClient
try
{
_packetDispatcher?.Dispose(new MqttClientDisconnectedException(exception));
_packetDispatcher?.Dispose(new MqttClientDisconnectedException(exception!));
var receiverTask = _packetReceiverTask.WaitAsync(sender, _logger);
var publishPacketReceiverTask = _publishPacketReceiverTask.WaitAsync(sender, _logger);
@@ -577,7 +577,7 @@ public sealed class MqttClient : Disposable, IMqttClient
}
}
Task DisconnectInternal(Task sender, Exception exception, MqttClientConnectResult connectResult)
Task DisconnectInternal(Task? sender, Exception? exception, MqttClientConnectResult? connectResult)
{
var clientWasConnected = IsConnected;
@@ -615,7 +615,7 @@ public sealed class MqttClient : Disposable, IMqttClient
{
try
{
_publishPacketReceiverQueue.Enqueue(publishPacket);
_publishPacketReceiverQueue!.Enqueue(publishPacket);
}
catch (Exception exception)
{
@@ -626,7 +626,7 @@ public sealed class MqttClient : Disposable, IMqttClient
async Task<MqttApplicationMessageReceivedEventArgs> HandleReceivedApplicationMessage(MqttPublishPacket publishPacket)
{
var applicationMessage = MqttApplicationMessageFactory.Create(publishPacket);
var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options.ClientId, applicationMessage, publishPacket, AcknowledgeReceivedPublishPacket);
var eventArgs = new MqttApplicationMessageReceivedEventArgs(Options!.ClientId, applicationMessage, publishPacket, AcknowledgeReceivedPublishPacket);
await _events.ApplicationMessageReceivedEvent.InvokeAsync(eventArgs).ConfigureAwait(false);
return eventArgs;
@@ -645,7 +645,7 @@ public sealed class MqttClient : Disposable, IMqttClient
Task ProcessReceivedAuthPacket(MqttAuthPacket authPacket, CancellationToken cancellationToken)
{
if (Options.EnhancedAuthenticationHandler == null)
if (Options!.EnhancedAuthenticationHandler == null)
{
// From RFC: If the re-authentication fails, the Client or Server SHOULD send DISCONNECT with an appropriate Reason Code
// as described in section 4.13, and MUST close the Network Connection [MQTT-4.12.1-2].
@@ -661,7 +661,7 @@ public sealed class MqttClient : Disposable, IMqttClient
return CompletedTask.Instance;
}
var eventArgs = new MqttEnhancedAuthenticationEventArgs(authPacket, _adapter, cancellationToken);
var eventArgs = new MqttEnhancedAuthenticationEventArgs(authPacket, _adapter!, cancellationToken);
return Options.EnhancedAuthenticationHandler.HandleEnhancedAuthenticationAsync(eventArgs);
}
@@ -673,7 +673,7 @@ public sealed class MqttClient : Disposable, IMqttClient
_unexpectedDisconnectPacket = disconnectPacket;
// Also dispatch disconnect to waiting threads to generate a proper exception.
_packetDispatcher.Dispose(new MqttClientUnexpectedDisconnectReceivedException(disconnectPacket));
_packetDispatcher!.Dispose(new MqttClientUnexpectedDisconnectReceivedException(disconnectPacket));
return DisconnectInternal(_packetReceiverTask, null, null);
}
@@ -684,7 +684,7 @@ public sealed class MqttClient : Disposable, IMqttClient
{
try
{
var publishPacketDequeueResult = await _publishPacketReceiverQueue.TryDequeueAsync(cancellationToken).ConfigureAwait(false);
var publishPacketDequeueResult = await _publishPacketReceiverQueue!.TryDequeueAsync(cancellationToken).ConfigureAwait(false);
if (!publishPacketDequeueResult.IsSuccess)
{
return;
@@ -713,7 +713,7 @@ public sealed class MqttClient : Disposable, IMqttClient
Task ProcessReceivedPubRecPacket(MqttPubRecPacket pubRecPacket, CancellationToken cancellationToken)
{
if (_packetDispatcher.TryDispatch(pubRecPacket))
if (_packetDispatcher!.TryDispatch(pubRecPacket))
{
return CompletedTask.Instance;
}
@@ -776,11 +776,11 @@ public sealed class MqttClient : Disposable, IMqttClient
return MqttClientPublishResultFactory.Create(pubRecPacket, pubCompPacket);
}
async Task<MqttPacket> Receive(CancellationToken cancellationToken)
async Task<MqttPacket?> Receive(CancellationToken cancellationToken)
{
var packetTask = _adapter.ReceivePacketAsync(cancellationToken);
var packetTask = _adapter!.ReceivePacketAsync(cancellationToken);
MqttPacket packet;
MqttPacket? packet;
if (packetTask.IsCompleted)
{
packet = packetTask.Result;
@@ -863,7 +863,7 @@ public sealed class MqttClient : Disposable, IMqttClient
packetIdentifier = packetWithIdentifier.PacketIdentifier;
}
using var packetAwaitable = _packetDispatcher.AddAwaitable<TResponsePacket>(packetIdentifier);
using var packetAwaitable = _packetDispatcher?.AddAwaitable<TResponsePacket>(packetIdentifier);
try
{
await Send(requestPacket, cancellationToken).ConfigureAwait(false);
@@ -871,12 +871,12 @@ public sealed class MqttClient : Disposable, IMqttClient
catch (Exception exception)
{
_logger.Warning(exception, "Error when sending {0} request packet", requestPacket.GetType().Name);
packetAwaitable.Fail(exception);
packetAwaitable?.Fail(exception);
}
try
{
return await packetAwaitable.WaitOneAsync(cancellationToken).ConfigureAwait(false);
return await packetAwaitable!.WaitOneAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception exception)
{
@@ -895,7 +895,7 @@ public sealed class MqttClient : Disposable, IMqttClient
_lastPacketSentTimestamp = DateTime.UtcNow;
return _adapter.SendPacketAsync(packet, cancellationToken);
return _adapter!.SendPacketAsync(packet, cancellationToken);
}
void ThrowIfConnected(string message)
@@ -971,13 +971,13 @@ public sealed class MqttClient : Disposable, IMqttClient
await ProcessReceivedAuthPacket(authPacket, cancellationToken).ConfigureAwait(false);
break;
case MqttPingRespPacket _:
_packetDispatcher.TryDispatch(packet);
_packetDispatcher!.TryDispatch(packet);
break;
case MqttPingReqPacket _:
throw new MqttProtocolViolationException("The PINGREQ Packet is sent from a client to the server only.");
default:
{
if (!_packetDispatcher.TryDispatch(packet))
if (!_packetDispatcher!.TryDispatch(packet))
{
throw new MqttProtocolViolationException($"Received packet '{packet}' at an unexpected time.");
}
@@ -1018,7 +1018,7 @@ public sealed class MqttClient : Disposable, IMqttClient
{
_logger.Verbose("Start sending keep alive packets");
var keepAlivePeriod = Options.KeepAlivePeriod;
var keepAlivePeriod = Options!.KeepAlivePeriod;
while (!cancellationToken.IsCancellationRequested)
{
+5 -5
View File
@@ -18,9 +18,9 @@ public static class MqttClientExtensions
public static Task DisconnectAsync(
this IMqttClient client,
MqttClientDisconnectOptionsReason reason = MqttClientDisconnectOptionsReason.NormalDisconnection,
string reasonString = null,
string? reasonString = null,
uint sessionExpiryInterval = 0,
List<MqttUserProperty> userProperties = null,
List<MqttUserProperty>? userProperties = null,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(client);
@@ -39,7 +39,7 @@ public static class MqttClientExtensions
public static Task<MqttClientPublishResult> PublishBinaryAsync(
this IMqttClient mqttClient,
string topic,
IEnumerable<byte> payload = null,
IEnumerable<byte>? payload = null,
MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
bool retain = false,
CancellationToken cancellationToken = default)
@@ -79,7 +79,7 @@ public static class MqttClientExtensions
public static Task<MqttClientPublishResult> PublishStringAsync(
this IMqttClient mqttClient,
string topic,
string payload = null,
string? payload = null,
MqttQualityOfServiceLevel qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce,
bool retain = false,
CancellationToken cancellationToken = default)
@@ -133,7 +133,7 @@ public static class MqttClientExtensions
public static async Task<bool> TryDisconnectAsync(
this IMqttClient client,
MqttClientDisconnectOptionsReason reason = MqttClientDisconnectOptionsReason.NormalDisconnection,
string reasonString = null)
string? reasonString = null)
{
ArgumentNullException.ThrowIfNull(client);
+1 -1
View File
@@ -25,7 +25,7 @@ public sealed class MqttTopicFilterBuilder
/// In MQTT, the word topic refers to an UTF-8 string that the broker uses to filter messages for each connected client.
/// The topic consists of one or more topic levels. Each topic level is separated by a forward slash (topic level separator).
/// </summary>
string _topic;
string? _topic;
bool _noLocal;
bool _retainAsPublished;
MqttRetainHandling _retainHandling = MqttRetainHandling.SendAtSubscribe;
@@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
@@ -9,18 +10,17 @@ namespace MQTTnet;
public sealed class DefaultMqttCertificatesProvider : IMqttClientCertificatesProvider
{
readonly X509Certificate2Collection _certificates;
readonly X509Certificate2Collection _certificates = new();
public DefaultMqttCertificatesProvider(X509Certificate2Collection certificates)
{
_certificates = certificates;
_certificates = certificates ?? throw new ArgumentNullException(nameof(certificates));
}
public DefaultMqttCertificatesProvider(IEnumerable<X509Certificate> certificates)
public DefaultMqttCertificatesProvider(IEnumerable<X509Certificate>? certificates)
{
if (certificates != null)
{
_certificates = [];
foreach (var certificate in certificates)
{
_certificates.Add(certificate);
@@ -6,5 +6,5 @@ namespace MQTTnet;
public interface IMqttClientChannelOptions
{
MqttClientTlsOptions TlsOptions { get; }
MqttClientTlsOptions? TlsOptions { get; }
}
@@ -6,6 +6,6 @@ namespace MQTTnet;
public interface IMqttClientCredentialsProvider
{
byte[] GetPassword(MqttClientOptions clientOptions);
byte[]? GetPassword(MqttClientOptions clientOptions);
string GetUserName(MqttClientOptions clientOptions);
}
@@ -11,23 +11,26 @@ public sealed class MqttClientCertificateSelectionEventArgs : EventArgs
{
public MqttClientCertificateSelectionEventArgs(
string targetHost,
X509CertificateCollection localCertificates,
X509Certificate remoteCertificate,
X509CertificateCollection? localCertificates,
X509Certificate? remoteCertificate,
string[] acceptableIssuers,
MqttClientTcpOptions tcpOptions)
{
TargetHost = targetHost;
LocalCertificates = localCertificates;
RemoveCertificate = remoteCertificate;
RemoteCertificate = remoteCertificate;
AcceptableIssuers = acceptableIssuers;
TcpOptions = tcpOptions ?? throw new ArgumentNullException(nameof(tcpOptions));
}
public string[] AcceptableIssuers { get; }
public X509CertificateCollection LocalCertificates { get; }
public X509CertificateCollection? LocalCertificates { get; }
public X509Certificate RemoveCertificate { get; }
[Obsolete("Typo! Use RemoteCertificate instead!")]
public X509Certificate? RemoveCertificate => RemoteCertificate;
public X509Certificate? RemoteCertificate { get; }
public string TargetHost { get; }
@@ -10,7 +10,7 @@ namespace MQTTnet;
public sealed class MqttClientCertificateValidationEventArgs : EventArgs
{
public MqttClientCertificateValidationEventArgs(X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors, IMqttClientChannelOptions clientOptions)
public MqttClientCertificateValidationEventArgs(X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors, IMqttClientChannelOptions clientOptions)
{
Certificate = certificate;
Chain = chain;
@@ -18,9 +18,9 @@ public sealed class MqttClientCertificateValidationEventArgs : EventArgs
ClientOptions = clientOptions ?? throw new ArgumentNullException(nameof(clientOptions));
}
public X509Certificate Certificate { get; }
public X509Certificate? Certificate { get; }
public X509Chain Chain { get; }
public X509Chain? Chain { get; }
public IMqttClientChannelOptions ClientOptions { get; }
@@ -6,16 +6,16 @@ namespace MQTTnet;
public sealed class MqttClientCredentials : IMqttClientCredentialsProvider
{
readonly byte[] _password;
readonly byte[]? _password;
readonly string _userName;
public MqttClientCredentials(string userName, byte[] password = null)
public MqttClientCredentials(string userName, byte[]? password = null)
{
_userName = userName;
_password = password;
}
public byte[] GetPassword(MqttClientOptions clientOptions)
public byte[]? GetPassword(MqttClientOptions clientOptions)
{
return _password;
}
@@ -17,7 +17,7 @@ public sealed class MqttClientDefaultCertificateValidationHandler
return true;
}
if (eventArgs.Chain.ChainStatus.Any(
if (eventArgs.Chain!.ChainStatus.Any(
c => c.Status is X509ChainStatusFlags.RevocationStatusUnknown or X509ChainStatusFlags.Revoked or X509ChainStatusFlags.OfflineRevocation))
{
if (eventArgs.ClientOptions?.TlsOptions?.IgnoreCertificateRevocationErrors != true)
+12 -12
View File
@@ -24,15 +24,15 @@ public sealed class MqttClientOptions
/// Gets or sets the authentication data.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public byte[] AuthenticationData { get; set; }
public byte[]? AuthenticationData { get; set; }
/// <summary>
/// Gets or sets the authentication method.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public string AuthenticationMethod { get; set; }
public string? AuthenticationMethod { get; set; }
public IMqttClientChannelOptions ChannelOptions { get; set; }
public IMqttClientChannelOptions? ChannelOptions { get; set; }
/// <summary>
/// Gets or sets a value indicating whether clean sessions are used or not.
@@ -52,14 +52,14 @@ public sealed class MqttClientOptions
/// </summary>
public string ClientId { get; set; } = Guid.NewGuid().ToString("N");
public IMqttClientCredentialsProvider Credentials { get; set; }
public IMqttClientCredentialsProvider? Credentials { get; set; }
/// <summary>
/// Gets or sets the handler for AUTH packets.
/// This can happen when connecting or at any time while being already connected.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public IMqttEnhancedAuthenticationHandler EnhancedAuthenticationHandler { get; set; }
public IMqttEnhancedAuthenticationHandler? EnhancedAuthenticationHandler { get; set; }
/// <summary>
/// Gets or sets the keep alive period.
@@ -143,7 +143,7 @@ public sealed class MqttClientOptions
/// The feature is very similar to the HTTP header concept.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
/// <summary>
/// When this feature is enabled the client will check if used properties are supported in the selected protocol
@@ -158,13 +158,13 @@ public sealed class MqttClientOptions
/// Gets or sets the content type of the will message.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public string WillContentType { get; set; }
public string? WillContentType { get; set; }
/// <summary>
/// Gets or sets the correlation data of the will message.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public byte[] WillCorrelationData { get; set; }
public byte[]? WillCorrelationData { get; set; }
/// <summary>
/// Gets or sets the will delay interval.
@@ -182,7 +182,7 @@ public sealed class MqttClientOptions
/// <summary>
/// Gets or sets the payload of the will message.
/// </summary>
public byte[] WillPayload { get; set; }
public byte[]? WillPayload { get; set; }
/// <summary>
/// Gets or sets the payload format indicator of the will message.
@@ -199,7 +199,7 @@ public sealed class MqttClientOptions
/// Gets or sets the response topic of the will message.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public string WillResponseTopic { get; set; }
public string? WillResponseTopic { get; set; }
/// <summary>
/// Gets or sets the retain flag of the will message.
@@ -209,13 +209,13 @@ public sealed class MqttClientOptions
/// <summary>
/// Gets or sets the topic of the will message.
/// </summary>
public string WillTopic { get; set; }
public string? WillTopic { get; set; }
/// <summary>
/// Gets or sets the user properties of the will message.
/// <remarks>MQTT 5.0.0+ feature.</remarks>
/// </summary>
public List<MqttUserProperty> WillUserProperties { get; set; }
public List<MqttUserProperty>? WillUserProperties { get; set; }
/// <summary>
/// Gets or sets the default and initial size of the packet write buffer.
@@ -18,10 +18,10 @@ public sealed class MqttClientOptionsBuilder
readonly MqttClientOptions _options = new();
int? _port;
EndPoint _remoteEndPoint;
MqttClientTcpOptions _tcpOptions;
MqttClientTlsOptions _tlsOptions;
MqttClientWebSocketOptions _webSocketOptions;
EndPoint? _remoteEndPoint;
MqttClientTcpOptions? _tcpOptions;
MqttClientTlsOptions? _tlsOptions;
MqttClientWebSocketOptions? _webSocketOptions;
public MqttClientOptions Build()
{
@@ -38,7 +38,7 @@ public sealed class MqttClientOptionsBuilder
if (_tcpOptions != null)
{
_tcpOptions.TlsOptions = tlsOptions;
_tcpOptions.TlsOptions = tlsOptions!;
if (_remoteEndPoint == null)
{
@@ -49,7 +49,7 @@ public sealed class MqttClientOptionsBuilder
{
if (dns.Port == 0)
{
if (_port.HasValue)
if (_port != null)
{
_remoteEndPoint = new DnsEndPoint(dns.Host, _port.Value, dns.AddressFamily);
}
@@ -64,7 +64,7 @@ public sealed class MqttClientOptionsBuilder
{
if (ip.Port == 0)
{
if (_port.HasValue)
if (_port != null)
{
_remoteEndPoint = new IPEndPoint(ip.Address, _port.Value);
}
@@ -82,10 +82,10 @@ public sealed class MqttClientOptionsBuilder
}
else if (_webSocketOptions != null)
{
_webSocketOptions.TlsOptions = tlsOptions;
_webSocketOptions.TlsOptions = tlsOptions!;
}
_options.ChannelOptions = (IMqttClientChannelOptions)_tcpOptions ?? _webSocketOptions;
_options.ChannelOptions = (IMqttClientChannelOptions?)_tcpOptions ?? _webSocketOptions;
MqttClientOptionsValidator.ThrowIfNotSupported(_options);
@@ -94,7 +94,7 @@ public sealed class MqttClientOptionsBuilder
public MqttClientOptionsBuilder WithAddressFamily(AddressFamily addressFamily)
{
_tcpOptions.AddressFamily = addressFamily;
_tcpOptions!.AddressFamily = addressFamily;
return this;
}
@@ -174,9 +174,9 @@ public sealed class MqttClientOptionsBuilder
return WithConnectionUri(new Uri(uri, UriKind.Absolute));
}
public MqttClientOptionsBuilder WithCredentials(string username, string password)
public MqttClientOptionsBuilder WithCredentials(string username, string? password)
{
byte[] passwordBuffer = null;
byte[]? passwordBuffer = null;
if (password != null)
{
@@ -186,7 +186,7 @@ public sealed class MqttClientOptionsBuilder
return WithCredentials(username, passwordBuffer);
}
public MqttClientOptionsBuilder WithCredentials(string username, byte[] password = null)
public MqttClientOptionsBuilder WithCredentials(string username, byte[]? password = null)
{
return WithCredentials(new MqttClientCredentials(username, password));
}
@@ -205,7 +205,7 @@ public sealed class MqttClientOptionsBuilder
return this;
}
public MqttClientOptionsBuilder WithEnhancedAuthentication(string method, byte[] data = null)
public MqttClientOptionsBuilder WithEnhancedAuthentication(string method, byte[]? data = null)
{
_options.AuthenticationMethod = method;
_options.AuthenticationData = data;
@@ -249,7 +249,7 @@ public sealed class MqttClientOptionsBuilder
public MqttClientOptionsBuilder WithProtocolType(ProtocolType protocolType)
{
_tcpOptions.ProtocolType = protocolType;
_tcpOptions!.ProtocolType = protocolType;
return this;
}
@@ -405,7 +405,7 @@ public sealed class MqttClientOptionsBuilder
return this;
}
public MqttClientOptionsBuilder WithWillPayload(byte[] willPayload)
public MqttClientOptionsBuilder WithWillPayload(byte[]? willPayload)
{
_options.WillPayload = willPayload;
return this;
@@ -423,11 +423,11 @@ public sealed class MqttClientOptionsBuilder
return this;
}
public MqttClientOptionsBuilder WithWillPayload(string willPayload)
public MqttClientOptionsBuilder WithWillPayload(string? willPayload)
{
if (string.IsNullOrEmpty(willPayload))
{
return WithWillPayload((byte[])null);
return WithWillPayload((byte[]?)null);
}
_options.WillPayload = Encoding.UTF8.GetBytes(willPayload);
@@ -26,7 +26,7 @@ public sealed class MqttClientTcpOptions : IMqttClientChannelOptions
/// Gets the local endpoint (network card) which is used by the client.
/// Set it to _null_ to let the OS select the network card.
/// </summary>
public EndPoint LocalEndpoint { get; set; }
public EndPoint? LocalEndpoint { get; set; }
/// <summary>
/// Enables or disables the Nagle algorithm for the socket.
@@ -42,7 +42,7 @@ public sealed class MqttClientTcpOptions : IMqttClientChannelOptions
/// </summary>
public ProtocolType ProtocolType { get; set; } = ProtocolType.Tcp;
public EndPoint RemoteEndpoint { get; set; }
public EndPoint? RemoteEndpoint { get; set; }
public MqttClientTlsOptions TlsOptions { get; set; } = new();
@@ -12,9 +12,9 @@ namespace MQTTnet;
public sealed class MqttClientTlsOptions
{
public Func<MqttClientCertificateValidationEventArgs, bool> CertificateValidationHandler { get; set; }
public Func<MqttClientCertificateValidationEventArgs, bool>? CertificateValidationHandler { get; set; }
public Func<MqttClientCertificateSelectionEventArgs, X509Certificate> CertificateSelectionHandler { get; set; }
public Func<MqttClientCertificateSelectionEventArgs, X509Certificate>? CertificateSelectionHandler { get; set; }
public bool UseTls { get; set; }
@@ -32,11 +32,11 @@ public sealed class MqttClientTlsOptions
/// with the server and requires certificates for authentication.
/// The implementation may return different certificates each time.
/// </summary>
public IMqttClientCertificatesProvider ClientCertificatesProvider { get; set; }
public IMqttClientCertificatesProvider? ClientCertificatesProvider { get; set; }
public List<SslApplicationProtocol> ApplicationProtocols { get; set; }
public List<SslApplicationProtocol>? ApplicationProtocols { get; set; }
public CipherSuitesPolicy CipherSuitesPolicy { get; set; }
public CipherSuitesPolicy? CipherSuitesPolicy { get; set; }
public EncryptionPolicy EncryptionPolicy { get; set; } = EncryptionPolicy.RequireEncryption;
@@ -46,9 +46,9 @@ public sealed class MqttClientTlsOptions
/// Gets or sets the target host.
/// If the value is null or empty the same host as the TCP socket host will be used.
/// </summary>
public string TargetHost { get; set; }
public string? TargetHost { get; set; }
public SslProtocols SslProtocol { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls13;
public X509Certificate2Collection TrustChain { get; set; }
public X509Certificate2Collection? TrustChain { get; set; }
}
@@ -11,11 +11,11 @@ namespace MQTTnet;
public sealed class MqttClientWebSocketOptions : IMqttClientChannelOptions
{
public CookieContainer CookieContainer { get; set; }
public CookieContainer? CookieContainer { get; set; }
public WebSocketDeflateOptions DangerousDeflateOptions { get; set; }
public WebSocketDeflateOptions? DangerousDeflateOptions { get; set; }
public ICredentials Credentials { get; set; }
public ICredentials? Credentials { get; set; }
/// <summary>
/// Gets or sets the keep alive interval for the Web Socket connection.
@@ -23,15 +23,15 @@ public sealed class MqttClientWebSocketOptions : IMqttClientChannelOptions
/// </summary>
public TimeSpan KeepAliveInterval { get; set; } = WebSocket.DefaultKeepAliveInterval;
public MqttClientWebSocketProxyOptions ProxyOptions { get; set; }
public MqttClientWebSocketProxyOptions? ProxyOptions { get; set; }
public IDictionary<string, string> RequestHeaders { get; set; }
public IDictionary<string, string>? RequestHeaders { get; set; }
public ICollection<string> SubProtocols { get; set; } = ["mqtt"];
public ICollection<string>? SubProtocols { get; set; } = ["mqtt"];
public MqttClientTlsOptions TlsOptions { get; set; } = new();
public string Uri { get; set; }
public required string Uri { get; set; }
/// <summary>
/// Gets or sets whether the default (system) credentials should be used when connecting via Web Socket connection.
@@ -41,6 +41,6 @@ public sealed class MqttClientWebSocketOptions : IMqttClientChannelOptions
public override string ToString()
{
return Uri;
return Uri ?? string.Empty;
}
}
@@ -11,10 +11,19 @@ namespace MQTTnet;
public sealed class MqttClientWebSocketOptionsBuilder
{
readonly MqttClientWebSocketOptions _webSocketOptions = new();
readonly MqttClientWebSocketOptions _webSocketOptions = new()
{
Uri = string.Empty
};
public MqttClientWebSocketOptions Build()
{
if (string.IsNullOrEmpty(_webSocketOptions.Uri))
{
throw new InvalidOperationException("The URI is not set.");
}
return _webSocketOptions;
}
@@ -6,17 +6,17 @@ namespace MQTTnet;
public sealed class MqttClientWebSocketProxyOptions
{
public string Address { get; set; }
public string? Address { get; set; }
public string[] BypassList { get; set; }
public string[]? BypassList { get; set; }
public bool BypassOnLocal { get; set; }
public string Domain { get; set; }
public string? Domain { get; set; }
public string Password { get; set; }
public string? Password { get; set; }
public bool UseDefaultCredentials { get; set; }
public string Username { get; set; }
public string? Username { get; set; }
}
@@ -30,13 +30,13 @@ public class MqttEnhancedAuthenticationEventArgs : EventArgs
/// Gets the authentication data.
/// Hint: MQTT 5 feature only.
/// </summary>
public byte[] AuthenticationData => _initialAuthPacket.AuthenticationData;
public byte[]? AuthenticationData => _initialAuthPacket.AuthenticationData;
/// <summary>
/// Gets the authentication method.
/// Hint: MQTT 5 feature only.
/// </summary>
public string AuthenticationMethod => _initialAuthPacket.AuthenticationMethod;
public string AuthenticationMethod => _initialAuthPacket.AuthenticationMethod!;
public CancellationToken CancellationToken { get; }
@@ -50,7 +50,7 @@ public class MqttEnhancedAuthenticationEventArgs : EventArgs
/// Gets the reason string.
/// Hint: MQTT 5 feature only.
/// </summary>
public string ReasonString => _initialAuthPacket.ReasonString;
public string? ReasonString => _initialAuthPacket.ReasonString;
/// <summary>
/// Gets the user properties.
@@ -61,7 +61,7 @@ public class MqttEnhancedAuthenticationEventArgs : EventArgs
/// The feature is very similar to the HTTP header concept.
/// Hint: MQTT 5 feature only.
/// </summary>
public List<MqttUserProperty> UserProperties => _initialAuthPacket.UserProperties;
public List<MqttUserProperty>? UserProperties => _initialAuthPacket.UserProperties;
public async Task<ReceiveMqttEnhancedAuthenticationDataResult> ReceiveAsync(CancellationToken cancellationToken = default)
{
@@ -18,7 +18,7 @@ public class MqttEnhancedAuthenticationExchangeData
/// method.
/// Hint: MQTT 5 feature only.
/// </summary>
public byte[] AuthenticationData { get; set; }
public byte[]? AuthenticationData { get; set; }
/// <summary>
/// Gets or sets the reason code.
@@ -30,7 +30,7 @@ public class MqttEnhancedAuthenticationExchangeData
/// Gets or sets the reason string.
/// Hint: MQTT 5 feature only.
/// </summary>
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
/// <summary>
/// Gets or sets the user properties.
@@ -41,5 +41,5 @@ public class MqttEnhancedAuthenticationExchangeData
/// The feature is very similar to the HTTP header concept.
/// Hint: MQTT 5 feature only.
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
}
@@ -10,13 +10,13 @@ namespace MQTTnet;
public sealed class ReceiveMqttEnhancedAuthenticationDataResult
{
public byte[] AuthenticationData { get; init; }
public byte[]? AuthenticationData { get; init; }
public string AuthenticationMethod { get; init; }
public string? AuthenticationMethod { get; init; }
public MqttAuthenticateReasonCode ReasonCode { get; init; }
public string ReasonString { get; init; }
public string? ReasonString { get; init; }
public List<MqttUserProperty> UserProperties { get; init; }
public List<MqttUserProperty>? UserProperties { get; init; }
}
@@ -9,9 +9,9 @@ namespace MQTTnet;
public sealed class SendMqttEnhancedAuthenticationDataOptions
{
public byte[] Data { get; init; }
public byte[]? Data { get; init; }
public string ReasonString { get; init; }
public string? ReasonString { get; init; }
public List<MqttUserProperty> UserProperties { get; init; }
public List<MqttUserProperty>? UserProperties { get; init; }
}
@@ -8,7 +8,7 @@ namespace MQTTnet.PacketDispatcher;
public sealed class MqttPacketAwaitableFilter
{
public Type Type { get; set; }
public required Type Type { get; init; }
public ushort Identifier { get; set; }
public ushort Identifier { get; init; }
}
+4 -4
View File
@@ -10,13 +10,13 @@ namespace MQTTnet.Packets;
/// <summary>Added in MQTTv5.0.0.</summary>
public sealed class MqttAuthPacket : MqttPacket
{
public byte[] AuthenticationData { get; set; }
public byte[]? AuthenticationData { get; set; }
public string AuthenticationMethod { get; set; }
public string? AuthenticationMethod { get; set; }
public MqttAuthenticateReasonCode ReasonCode { get; set; }
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
}
+7 -7
View File
@@ -12,11 +12,11 @@ public sealed class MqttConnAckPacket : MqttPacket
/// <summary>
/// Added in MQTTv5.
/// </summary>
public string AssignedClientIdentifier { get; set; }
public string? AssignedClientIdentifier { get; set; }
public byte[] AuthenticationData { get; set; }
public byte[]? AuthenticationData { get; set; }
public string AuthenticationMethod { get; set; }
public string? AuthenticationMethod { get; set; }
/// <summary>
/// Added in MQTTv3.1.1.
@@ -32,11 +32,11 @@ public sealed class MqttConnAckPacket : MqttPacket
/// </summary>
public MqttConnectReasonCode ReasonCode { get; set; }
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
public ushort ReceiveMaximum { get; set; }
public string ResponseInformation { get; set; }
public string? ResponseInformation { get; set; }
public bool RetainAvailable { get; set; }
@@ -44,7 +44,7 @@ public sealed class MqttConnAckPacket : MqttPacket
public ushort ServerKeepAlive { get; set; }
public string ServerReference { get; set; }
public string? ServerReference { get; set; }
public uint SessionExpiryInterval { get; set; }
@@ -54,7 +54,7 @@ public sealed class MqttConnAckPacket : MqttPacket
public ushort TopicAliasMaximum { get; set; }
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
public bool WildcardSubscriptionAvailable { get; set; }
+12 -12
View File
@@ -9,24 +9,24 @@ namespace MQTTnet.Packets;
public sealed class MqttConnectPacket : MqttPacket
{
public byte[] AuthenticationData { get; set; }
public byte[]? AuthenticationData { get; set; }
public string AuthenticationMethod { get; set; }
public string? AuthenticationMethod { get; set; }
/// <summary>
/// Also called "Clean Start" in MQTTv5.
/// </summary>
public bool CleanSession { get; set; }
public string ClientId { get; set; }
public string? ClientId { get; set; }
public byte[] WillCorrelationData { get; set; }
public byte[]? WillCorrelationData { get; set; }
public ushort KeepAlivePeriod { get; set; }
public uint MaximumPacketSize { get; set; }
public byte[] Password { get; set; }
public byte[]? Password { get; set; }
public ushort ReceiveMaximum { get; set; }
@@ -34,23 +34,23 @@ public sealed class MqttConnectPacket : MqttPacket
public bool RequestResponseInformation { get; set; }
public string WillResponseTopic { get; set; }
public string? WillResponseTopic { get; set; }
public uint SessionExpiryInterval { get; set; }
public ushort TopicAliasMaximum { get; set; }
public string Username { get; set; }
public string? Username { get; set; }
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
public string WillContentType { get; set; }
public string? WillContentType { get; set; }
public uint WillDelayInterval { get; set; }
public bool WillFlag { get; set; }
public byte[] WillMessage { get; set; }
public byte[]? WillMessage { get; set; }
public uint WillMessageExpiryInterval { get; set; }
@@ -60,9 +60,9 @@ public sealed class MqttConnectPacket : MqttPacket
public bool WillRetain { get; set; }
public string WillTopic { get; set; }
public string? WillTopic { get; set; }
public List<MqttUserProperty> WillUserProperties { get; set; }
public List<MqttUserProperty>? WillUserProperties { get; set; }
public bool TryPrivate { get; set; }
@@ -17,12 +17,12 @@ public sealed class MqttDisconnectPacket : MqttPacket
/// <summary>
/// Added in MQTTv5.
/// </summary>
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
/// <summary>
/// Added in MQTTv5.
/// </summary>
public string ServerReference { get; set; }
public string? ServerReference { get; set; }
/// <summary>
/// Added in MQTTv5.
@@ -32,7 +32,7 @@ public sealed class MqttDisconnectPacket : MqttPacket
/// <summary>
/// Added in MQTTv5.
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
public override string ToString()
{
+2 -2
View File
@@ -17,12 +17,12 @@ public sealed class MqttPubAckPacket : MqttPacketWithIdentifier
/// <summary>
/// Added in MQTTv5.
/// </summary>
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
/// <summary>
/// Added in MQTTv5.
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
public override string ToString()
{
+2 -2
View File
@@ -17,12 +17,12 @@ public sealed class MqttPubCompPacket : MqttPacketWithIdentifier
/// <summary>
/// Added in MQTTv5.
/// </summary>
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
/// <summary>
/// Added in MQTTv5.
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
public override string ToString()
{
+2 -2
View File
@@ -17,12 +17,12 @@ public sealed class MqttPubRecPacket : MqttPacketWithIdentifier
/// <summary>
/// Added in MQTTv5.
/// </summary>
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
/// <summary>
/// Added in MQTTv5.
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
public override string ToString()
{
+2 -2
View File
@@ -17,12 +17,12 @@ public sealed class MqttPubRelPacket : MqttPacketWithIdentifier
/// <summary>
/// Added in MQTTv5.
/// </summary>
public string ReasonString { get; set; }
public string? ReasonString { get; set; }
/// <summary>
/// Added in MQTTv5.
/// </summary>
public List<MqttUserProperty> UserProperties { get; set; }
public List<MqttUserProperty>? UserProperties { get; set; }
public override string ToString()
{

Some files were not shown because too many files have changed in this diff Show More