Skip to content

Commit

Permalink
WiP
Browse files Browse the repository at this point in the history
  • Loading branch information
scottt732 committed Dec 18, 2023
1 parent e5beb36 commit 3334bac
Show file tree
Hide file tree
Showing 96 changed files with 1,664 additions and 1,248 deletions.
6 changes: 3 additions & 3 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"name": "Sample (console)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/Samples/Mqtt.Sample/bin/Debug/net7.0/Mqtt.Sample.dll",
"preLaunchTask": "build",
"program": "${workspaceFolder}/Samples/Mqtt.Sample/bin/Debug/net8.0/Mqtt.Sample.dll",
"args": [],
"cwd": "${workspaceFolder}/Samples/Mqtt.Sample",
"console": "integratedTerminal",
Expand All @@ -18,4 +18,4 @@
"request": "attach"
}
]
}
}
6 changes: 3 additions & 3 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<Import Project="$(ParentDirectoryBuildProps)" Condition="Exists('$(ParentDirectoryBuildProps)')"/>

<PropertyGroup Label="Build">
<TargetFramework>net7.0</TargetFramework>
<TargetFramework>net8.0</TargetFramework>
<LangVersion>latest</LangVersion>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<AnalysisLevel>latest</AnalysisLevel>
Expand Down Expand Up @@ -41,8 +41,8 @@
</ItemGroup>

<ItemGroup Label="Package References">
<PackageReference Include="JetBrains.Annotations" PrivateAssets="All" Version="2023.2.0" />
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" PrivateAssets="All" Version="17.7.30" />
<PackageReference Include="JetBrains.Annotations" PrivateAssets="All" Version="2023.3.0" />
<PackageReference Include="Microsoft.VisualStudio.Threading.Analyzers" PrivateAssets="All" Version="[17.8.14,)" />
<PackageReference Include="MinVer" PrivateAssets="All" Version="4.3.0" />
<PackageReference Include="StyleCop.Analyzers" PrivateAssets="All" Version="1.1.118" />
</ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion Samples/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
</PropertyGroup>

<ItemGroup Label="Package References">
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="1.0.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="8.0.0" />
</ItemGroup>

<ItemGroup Label="Files">
Expand Down
4 changes: 2 additions & 2 deletions Samples/Mqtt.Sample/Controllers/TestController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ public TestController(ILogger<TestController> logger)
[Topic("run/+user/+count")]
public Task<bool> RunAsync(
string user,
int count,
float count,
CancellationToken cancellationToken)
{
Logger.LogInformation("Running {User}: {Count} {Payload}", user, count, Encoding.ASCII.GetString(Request.Payload));
Logger.LogInformation("Running {User}: {Count} {Payload}", user, count, Encoding.UTF8.GetString(Request.Payload));
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(true);
}
Expand Down
3 changes: 2 additions & 1 deletion Samples/Mqtt.Sample/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Global using directives

global using JetBrains.Annotations;
global using JetBrains.Annotations;
global using Sholo.Mqtt;
5 changes: 2 additions & 3 deletions Samples/Mqtt.Sample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@
using Mqtt.Sample.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Sholo.Mqtt;
using Sholo.Mqtt.Application.Builder;
using Sholo.Mqtt.Hosting;
using Sholo.Mqtt.Routing;
using Sholo.Mqtt.TypeConverters.NewtonsoftJson;

namespace Mqtt.Sample;
Expand Down Expand Up @@ -38,7 +37,7 @@ await Host.CreateDefaultBuilder(args)
};
});
services.AddHostedService<FakeClientService>();
services.AddHostedService<ClientService>();
})
.ConfigureMqttHost(app =>
{
Expand Down
121 changes: 121 additions & 0 deletions Samples/Mqtt.Sample/Services/ClientService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Extensions.ManagedClient;
using MQTTnet.Protocol;

namespace Mqtt.Sample.Services;

internal sealed class ClientService : BackgroundService
{
private SortedDictionary<char, MenuItem> Items { get; }
private IManagedMqttClient MqttClient { get; }
private ILogger Logger { get; }

public ClientService(
IManagedMqttClient mqttClient,
ILogger<ClientService> logger
)
{
MqttClient = mqttClient;
Logger = logger;

Items = new SortedDictionary<char, MenuItem>(Comparer<char>.Create((a, b) => char.ToLowerInvariant(a).CompareTo(char.ToLowerInvariant(b))))
{
['0'] = new("Send a message", ct => SendMessage(
b => b
.WithTopic("test/run/scott/26.2")
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
.WithPayload("this is a test")
.WithRetainFlag(false),
ct
)),
['1'] = new("Send a message", ct => SendMessage(
b => b
.WithTopic("test/run/scott/25/2")
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtMostOnce)
.WithPayload("{\"hello\":\"world\",\"test\":\"123\"}"u8.ToArray())
.WithRetainFlag(false),
ct
)),
};
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);

async Task Quit(CancellationTokenSource c)
{
await c.CancelAsync();
}

await WriteMenu(false);

var cancellationToken = cts.Token;
while (!cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Choose an option (? for menu, q to quit):");
var c = Console.ReadKey(true);
var lc = char.ToLowerInvariant(c.KeyChar);

var task = lc switch
{
'?' => WriteMenu(false),
'q' => Quit(cts),
_ => Items.TryGetValue(lc, out var item) ? item.Action.Invoke(cancellationToken) : WriteMenu(true)
};

await task;
}
}

private async Task SendMessage(Action<MqttApplicationMessageBuilder> configuration, CancellationToken cancellationToken)
{
Logger.LogInformation("Sending a message");

var mqttApplicationMessageBuilder = new MqttApplicationMessageBuilder();

configuration.Invoke(mqttApplicationMessageBuilder);

var mqttApplicationMessage = mqttApplicationMessageBuilder.Build();

await MqttClient.InternalClient.PublishAsync(mqttApplicationMessage, cancellationToken);
}

private Task WriteMenu(bool showErrorMessage)
{
if (showErrorMessage)
{
Console.WriteLine("Invalid option");
Console.WriteLine();
}

foreach (var (c, item) in Items)
{
if (c is '?' or 'q')
{
throw new InvalidOperationException("? and q are reserved");
}

Console.WriteLine($" {c} {item.Description}");
}

Console.WriteLine(" ? Help");
Console.WriteLine(" q Quit");

return Task.CompletedTask;
}

private sealed class MenuItem
{
public string Description { get; }
public Func<CancellationToken, Task> Action { get; }

public MenuItem(string description, Func<CancellationToken, Task> action)
{
Description = description;
Action = action;
}
}
}
71 changes: 0 additions & 71 deletions Samples/Mqtt.Sample/Services/FakeClientService.cs

This file was deleted.

2 changes: 1 addition & 1 deletion Samples/Mqtt.Sample/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"mqtt": {
"host": "mosquitto",
"host": "localhost",
"port": 1883
}
}
2 changes: 1 addition & 1 deletion Source/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
</ItemGroup>

<ItemGroup Label="Package References">
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="1.1.1" />
<PackageReference Include="Microsoft.SourceLink.GitHub" PrivateAssets="All" Version="8.0.0" />
</ItemGroup>

<ItemGroup Label="Files">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public MqttTopicPatternPropertyConfigurationBuilder(string initialParameterName,
ParameterName = initialParameterName;
ValueSetter = valueSetter;

if (DefaultTypeConverters.TryGetStringTypeConverter(parameterType, out var typeConverter))
if (DefaultTypeConverter.TryGetStringTypeConverter(parameterType, out var typeConverter))
{
TypeConverter = typeConverter!;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ ILogger<NewtonsoftJsonPayloadTypeConverter> logger
Serializer = JsonSerializer.Create(options.Value.SerializerSettings);
}

public bool TryConvertPayload(ArraySegment<byte> payloadData, Type targetType, out object result) => TryConvert(payloadData, targetType, out result);
public bool TryConvertPayload(ArraySegment<byte> payload, Type targetType, out object result) => TryConvert(payload, targetType, out result);

private bool TryConvert(ArraySegment<byte> data, Type targetType, out object result)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Sholo.Mqtt.Internal;
Expand Down Expand Up @@ -50,7 +49,7 @@ public IMqttApplication Build()

var routeProvider = ApplicationServices.GetRequiredService<IRouteProvider>();

var topicFilters = routeProvider.Endpoints.Select(x => x.TopicFilter);
var topicFilters = routeProvider.TopicFilters;

return new MqttApplication(topicFilters, app);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public IMqttApplication? Current
get => _current;
private set
{
var previous = _current ?? throw new InvalidOperationException();
var previous = _current;
_current = value;

OnApplicationChanged(previous, _current!);
Expand Down
Loading

0 comments on commit 3334bac

Please sign in to comment.