Skip to content

Commit

Permalink
Refactoring, Examples and Warning cleanup (#95)
Browse files Browse the repository at this point in the history
  • Loading branch information
pglombardo authored Oct 9, 2023
1 parent 83b4560 commit fd220fa
Show file tree
Hide file tree
Showing 16 changed files with 108 additions and 40 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,15 @@ csharp_style_unused_value_expression_statement_preference = discard_variable:sug
dotnet_diagnostic.IDE0058.severity = suggestion
csharp_style_unused_value_assignment_preference = discard_variable:suggestion
dotnet_diagnostic.IDE0059.severity = suggestion
dotnet_diagnostic.IDE0002.severity = none
dotnet_diagnostic.IDE0010.severity = none
dotnet_diagnostic.IDE0021.severity = none
dotnet_diagnostic.IDE0028.severity = none
dotnet_diagnostic.IDE0049.severity = none
dotnet_diagnostic.IDE0053.severity = none
dotnet_diagnostic.IDE0090.severity = none
dotnet_diagnostic.IDE0290.severity = none
dotnet_diagnostic.SA1508.severity = none

##########################################
# Formatting Rules
Expand Down
2 changes: 2 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
],
"cSpell.words": [
"CONNACK",
"hivemq",
"hivemqtt",
"PUBACK",
"PUBCOMP",
"PUBREC",
Expand Down
2 changes: 1 addition & 1 deletion Examples/HiveMQtt-CLI/HiveMQtt-CLI/HiveMQtt-CLI.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<RootNamespace>HiveMQtt_CLI</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
Expand Down
2 changes: 1 addition & 1 deletion Examples/Reconnect/.vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/net7.0/Reconnect.dll",
"program": "${workspaceFolder}/bin/Debug/net6.0/Reconnect.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
Expand Down
40 changes: 40 additions & 0 deletions Examples/Reconnect/NLog.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>

<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>

<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->

<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
<target name="logfile" xsi:type="File" fileName="Reconnect.log" />
<target name="logconsole" xsi:type="Console" />
</targets>

<rules>
<!-- add your logging rules here -->

<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
<logger name="HiveMQtt.*" minlevel="Trace" writeTo="logconsole" />
</rules>
</nlog>
17 changes: 10 additions & 7 deletions Examples/Reconnect/Program.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
using HiveMQtt.Client;
using HiveMQtt.Client.Exceptions;
using HiveMQtt.Client.Options;
using System.Text.Json;
using System.Diagnostics;

var topic = "hivemqtt/waiting/game";

var options = new HiveMQClientOptions();
options.Host = "127.0.0.1";
options.Port = 1883;
var options = new HiveMQClientOptions
{
Host = "127.0.0.1",
Port = 1883,
};

var client = new HiveMQClient(options);

Expand Down Expand Up @@ -74,12 +78,12 @@
break;
}
}
catch (Exception ex)
catch (HiveMQttClientException ex)
{
Console.WriteLine($"--> Failed to connect: {ex.Message}");
Console.WriteLine($"--> Failed to reconnect: {ex.Message}");

// Double the delay with each failed retry to a maximum
delay = Math.Min(delay * 2, 10000);
delay = Math.Min(delay * 2, 15000);
Console.WriteLine($"--> Will delay for {delay / 1000} seconds until next try.");
}
}
Expand Down Expand Up @@ -123,7 +127,6 @@
})
).ConfigureAwait(false);


while (true)
{
await Task.Delay(2000).ConfigureAwait(false);
Expand Down
12 changes: 10 additions & 2 deletions Examples/Reconnect/Reconnect.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
Expand All @@ -13,8 +13,16 @@
</PropertyGroup>

<!-- Update the version to match -->
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="HiveMQtt" Version="0.4.1" />
<PackageReference Include="HiveMQtt" Version="0.4.2" />
</ItemGroup>

<ItemGroup>
<None Update="NLog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
1 change: 1 addition & 0 deletions Source/HiveMQtt/Client/HiveMQClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public HiveMQClient(HiveMQClientOptions? options = null)
{
options ??= new HiveMQClientOptions();
this.Options = options;
this.cancellationSource = new CancellationTokenSource();
}

/// <inheritdoc />
Expand Down
1 change: 0 additions & 1 deletion Source/HiveMQtt/Client/HiveMQClientEvents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
namespace HiveMQtt.Client;

using System;
using System.Diagnostics;
using HiveMQtt.Client.Events;
using HiveMQtt.Client.Options;
using HiveMQtt.Client.Results;
Expand Down
3 changes: 1 addition & 2 deletions Source/HiveMQtt/Client/HiveMQClientSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ namespace HiveMQtt.Client;
/// <inheritdoc />
public partial class HiveMQClient : IDisposable, IHiveMQClient
{
private readonly CancellationTokenSource cancellationSource;
private Socket? socket;
private Stream? stream;
private PipeReader? reader;
private PipeWriter? writer;
private CancellationTokenSource cancellationSource;
private CancellationToken outFlowCancellationToken;
private CancellationToken infoFlowCancellationToken;

Expand Down Expand Up @@ -131,7 +131,6 @@ internal async Task<bool> ConnectSocketAsync()
this.writer = PipeWriter.Create(this.stream);

// Setup the cancellation tokens
this.cancellationSource = new CancellationTokenSource();
this.outFlowCancellationToken = this.cancellationSource.Token;
this.infoFlowCancellationToken = this.cancellationSource.Token;

Expand Down
31 changes: 16 additions & 15 deletions Source/HiveMQtt/Client/HiveMQClientTrafficProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ private Task<bool> TrafficInflowProcessorAsync(CancellationToken cancellationTok
if (readResult.IsCompleted)
{
// This is an unexpected exit and may be due to a network failure.
Logger.Trace("TrafficInflowProcessor IsCompleted: end of the streamx");
Logger.Trace("TrafficInflowProcessor IsCompleted: end of the stream");

if (this.connectState == ConnectState.Connected)
{
Expand All @@ -220,6 +220,7 @@ private Task<bool> TrafficInflowProcessorAsync(CancellationToken cancellationTok
this.cancellationSource.Cancel();
return false;
}

return true;
}

Expand Down Expand Up @@ -308,7 +309,7 @@ private Task<bool> TrafficInflowProcessorAsync(CancellationToken cancellationTok
/// <summary>
/// Handle an incoming Publish packet.
/// </summary>
/// <param name="publishPacket"></param>
/// <param name="publishPacket">The received publish packet.</param>
internal void HandleIncomingPublishPacket(PublishPacket publishPacket)
{
Logger.Trace("<-- Publish");
Expand Down Expand Up @@ -339,8 +340,8 @@ internal void HandleIncomingPublishPacket(PublishPacket publishPacket)
/// <summary>
/// Handle an incoming ConnAck packet.
/// </summary>
/// <param name="pubAckPacket"></param>
/// <exception cref="HiveMQttClientException"></exception>
/// <param name="pubAckPacket">The received PubAck packet.</param>
/// <exception cref="HiveMQttClientException">Raised if the packet identifier is unknown.</exception>
internal void HandleIncomingPubAckPacket(PubAckPacket pubAckPacket)
{
Logger.Trace("<-- PubAck");
Expand All @@ -362,7 +363,7 @@ internal void HandleIncomingPubAckPacket(PubAckPacket pubAckPacket)
/// <summary>
/// Handle an incoming PubRec packet.
/// </summary>
/// <param name="pubRecPacket"></param>
/// <param name="pubRecPacket">The received PubRec packet.</param>
internal void HandleIncomingPubRecPacket(PubRecPacket pubRecPacket)
{
Logger.Trace("<-- PubRec");
Expand Down Expand Up @@ -394,7 +395,7 @@ internal void HandleIncomingPubRecPacket(PubRecPacket pubRecPacket)
/// <summary>
/// Handle an incoming PubRel packet.
/// </summary>
/// <param name="pubRelPacket"></param>
/// <param name="pubRelPacket">The received PubRel packet.</param>
internal void HandleIncomingPubRelPacket(PubRelPacket pubRelPacket)
{
Logger.Trace("<-- PubRel");
Expand All @@ -417,8 +418,8 @@ internal void HandleIncomingPubRelPacket(PubRelPacket pubRelPacket)
/// <summary>
/// Handle an incoming PubComp packet.
/// </summary>
/// <param name="pubCompPacket"></param>
/// <exception cref="HiveMQttClientException"></exception>
/// <param name="pubCompPacket">The received PubComp packet.</param>
/// <exception cref="HiveMQttClientException">Raised if the packet identifier is unknown.</exception>
internal void HandleIncomingPubCompPacket(PubCompPacket pubCompPacket)
{
Logger.Trace("<-- PubComp");
Expand All @@ -433,10 +434,10 @@ internal void HandleIncomingPubCompPacket(PubCompPacket pubCompPacket)
/// <summary>
/// Write a buffer to the stream.
/// </summary>
/// <param name="source"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="HiveMQttClientException"></exception>
/// <param name="source">The buffer to write.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A FlushResult wrapped in a ValueTask.</returns>
/// <exception cref="HiveMQttClientException">Raised if the writer is null.</exception>
internal ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default)
{
if (this.writer is null)
Expand All @@ -450,9 +451,9 @@ internal ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, Cancella
/// <summary>
/// Read a buffer from the stream.
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
/// <exception cref="HiveMQttClientException"></exception>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>A ReadResult wrapped in a ValueTask.</returns>
/// <exception cref="HiveMQttClientException">Raised if the reader is null.</exception>
internal ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default)
{
if (this.reader is null)
Expand Down
4 changes: 2 additions & 2 deletions Source/HiveMQtt/Client/HiveMQClientUtil.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ namespace HiveMQtt.Client;
/// <inheritdoc />
public partial class HiveMQClient : IDisposable, IHiveMQClient
{
private bool disposed = false;
private int lastPacketId = 0;
private bool disposed;
private int lastPacketId;

/// <summary>
/// https://learn.microsoft.com/en-us/dotnet/api/system.idisposable?view=net-6.0.
Expand Down
1 change: 0 additions & 1 deletion Source/HiveMQtt/Client/Results/UnsubscribeResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ namespace HiveMQtt.Client.Results;

public class UnsubscribeResult
{
// FIXME: List of subscriptions with their unsubscribe reason codes
public UnsubscribeResult()
{
this.Subscriptions = new List<Subscription>();
Expand Down
6 changes: 6 additions & 0 deletions Source/HiveMQtt/HiveMQtt.sln
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HiveMQtt", "HiveMQtt.csproj
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HiveMQtt-CLI", "..\..\Examples\HiveMQtt-CLI\HiveMQtt-CLI\HiveMQtt-CLI.csproj", "{B7404198-178C-43C5-9136-4BF25D23EC7E}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Reconnect", "..\..\Examples\Reconnect\Reconnect.csproj", "{FE0AD218-169C-4DE6-ADBE-0B55695620B4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -21,6 +23,10 @@ Global
{B7404198-178C-43C5-9136-4BF25D23EC7E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B7404198-178C-43C5-9136-4BF25D23EC7E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B7404198-178C-43C5-9136-4BF25D23EC7E}.Release|Any CPU.Build.0 = Release|Any CPU
{FE0AD218-169C-4DE6-ADBE-0B55695620B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FE0AD218-169C-4DE6-ADBE-0B55695620B4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FE0AD218-169C-4DE6-ADBE-0B55695620B4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FE0AD218-169C-4DE6-ADBE-0B55695620B4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
2 changes: 1 addition & 1 deletion Source/HiveMQtt/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using System.Runtime.CompilerServices;

[assembly:InternalsVisibleTo("HiveMQtt.Test")]
[assembly: InternalsVisibleTo("HiveMQtt.Test")]

[assembly: CLSCompliant(true)]
15 changes: 8 additions & 7 deletions Tests/HiveMQtt.Test/HiveMQClient/HiveMQClientConnectTest.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace HiveMQtt.Test.HiveMQClient;

using System.Globalization;
using System.Threading.Tasks;
using HiveMQtt.Client;
using HiveMQtt.Client.Events;
Expand Down Expand Up @@ -161,7 +162,7 @@ public async Task Test_AfterDisconnectEvent_Async()
// Assert that all Events were called
Assert.True(client.LocalStore.ContainsKey("AfterDisconnectHandlerCalled"));
Assert.True(client.LocalStore.ContainsKey("AfterDisconnectHandlerCalledCount"));
Assert.Equal(client.LocalStore["AfterDisconnectHandlerCalledCount"], "1");
Assert.Equal("1", client.LocalStore["AfterDisconnectHandlerCalledCount"]);

// Remove event handlers
client.AfterDisconnect -= AfterDisconnectHandler;
Expand Down Expand Up @@ -232,11 +233,11 @@ private static void AfterDisconnectHandler(object? sender, AfterDisconnectEventA
{
var client = (HiveMQClient)sender;

if (client.LocalStore.ContainsKey("AfterDisconnectHandlerCalled"))
if (client.LocalStore.TryGetValue("AfterDisconnectHandlerCalled", out var value))
{
var count = Convert.ToInt16(client.LocalStore["AfterDisconnectHandlerCalledCount"]);
var count = Convert.ToInt16(value, CultureInfo.InvariantCulture);
count++;
client.LocalStore.Add("AfterDisconnectHandlerCalledCount", count.ToString());
client.LocalStore.Add("AfterDisconnectHandlerCalledCount", count.ToString(CultureInfo.InvariantCulture));
}
else
{
Expand All @@ -253,11 +254,11 @@ private static void OnDisconnectSentHandler(object? sender, OnDisconnectSentEven
{
var client = (HiveMQClient)sender;

if (client.LocalStore.ContainsKey("OnDisconnectSentHandlerCalled"))
if (client.LocalStore.TryGetValue("OnDisconnectSentHandlerCalled", out var value))
{
var count = Convert.ToInt16(client.LocalStore["OnDisconnectSentHandlerCalledCount"]);
var count = Convert.ToInt16(value, CultureInfo.InvariantCulture);
count++;
client.LocalStore.Add("OnDisconnectSentHandlerCalledCount", count.ToString());
client.LocalStore.Add("OnDisconnectSentHandlerCalledCount", count.ToString(CultureInfo.InvariantCulture));
}
else
{
Expand Down

0 comments on commit fd220fa

Please sign in to comment.