slik-dispenser/backend/Program.cs

110 lines
2.8 KiB
C#

using MQTTnet;
using MQTTnet.Client;
using backend.Application;
using backend.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(builder => {
builder.AllowAnyHeader();
builder.WithOrigins("http://localhost:5173");
builder.AllowCredentials();
builder.AllowAnyMethod();
});
//app.UseHttpsRedirection();
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);
await mqttClient.SubscribeAsync(
new MqttFactory()
.CreateSubscribeOptionsBuilder()
.WithTopicFilter(f => f.WithTopic("login_request"))
.WithTopicFilter(f => f.WithTopic("dispense_request"))
.Build(),
CancellationToken.None
);
ApplicationState.DbContext = new DispenserContext();
mqttClient.ApplicationMessageReceivedAsync += delegate(MqttApplicationMessageReceivedEventArgs args) {
var payload = System.Text.Encoding.Default.GetString(args.ApplicationMessage.PayloadSegment);
User? user;
MqttApplicationMessageBuilder message;
switch (args.ApplicationMessage.Topic) {
case "login_request":
user = ApplicationState.DbContext!.Users.FirstOrDefault(user => user.TouchCode == payload);
message = new MqttApplicationMessageBuilder()
.WithTopic("login");
if (user == null) {
message.WithPayload("error");
} else {
message.WithPayload(user.Id.ToString());
}
mqttClient.PublishAsync(message.Build());
break;
case "dispense_request":
user = ApplicationState.DbContext!.Users.FirstOrDefault(user => user.Id == int.Parse(payload));
if (user == null || (!user.IsParent && user.Dispenses <= 0)) {
// TODO error
break;
}
message = new MqttApplicationMessageBuilder()
.WithTopic("dispense")
.WithPayload("dispense");
mqttClient.PublishAsync(message.Build());
break;
}
return Task.CompletedTask;
};
ApplicationState.MqttClient = mqttClient;
Console.WriteLine("Connected");
app.Run();