Connect to MQTT server in backend and publish dispense message

This commit is contained in:
ReiMerc 2023-11-28 22:08:40 +01:00
parent c6621f2959
commit 472d0488e4
8 changed files with 60 additions and 19 deletions

1
backend/.gitignore vendored
View File

@ -1,3 +1,4 @@
obj/
bin/
appsettings.json

View File

@ -0,0 +1,9 @@
using MQTTnet.Client;
namespace backend.Application
{
public static class ApplicationState
{
public static IMqttClient? MqttClient { get; set; }
}
}

View File

@ -1,4 +1,6 @@
using Microsoft.AspNetCore.Mvc;
using MQTTnet;
using backend.Application;
namespace backend.Controllers;
@ -8,8 +10,14 @@ public class DispenserController : ControllerBase
[HttpPost("Dispense")]
public void Dispense()
{
// TODO send MQTT to arduino
Console.WriteLine("Dispensing..");
var message = new MqttApplicationMessageBuilder()
.WithTopic("dispense")
.WithPayload("dispense")
.Build();
ApplicationState.MqttClient!.PublishAsync(message, CancellationToken.None);
}
}

View File

@ -1,3 +1,7 @@
using MQTTnet;
using MQTTnet.Client;
using backend.Application;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
@ -24,4 +28,25 @@ app.UseAuthorization();
app.MapControllers();
var configuration = app.Services.GetRequiredService<IConfiguration>();
// Connect via MQTT
Console.WriteLine($"Connecting to MQTT server: {configuration["Mqtt:Host"]}:{configuration["Mqtt:Port"]}...");
var mqttClient = new MqttFactory().CreateMqttClient();
var options = new MqttClientOptionsBuilder()
.WithTcpServer(configuration["Mqtt:Host"], int.Parse(configuration["Mqtt:Port"]!))
.WithCredentials(configuration["Mqtt:Username"], configuration["Mqtt:Password"])
.WithTlsOptions(new MqttClientTlsOptionsBuilder().Build())
.Build();
await mqttClient.ConnectAsync(options, CancellationToken.None);
ApplicationState.MqttClient = mqttClient;
Console.WriteLine("Connected");
app.Run();

View File

@ -1,8 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -1,9 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

View File

@ -0,0 +1,15 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Mqtt": {
"Host": "example.hivemq.cloud",
"Port": 8883,
"Username": "user",
"Password": "password"
}
}

View File

@ -7,8 +7,8 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.8" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.13" />
<PackageReference Include="MQTTnet" Version="4.3.1.873" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>