slik-dispenser/backend/Program.cs

89 lines
2.3 KiB
C#
Raw Normal View History

using MQTTnet;
using MQTTnet.Client;
using backend.Application;
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 => {
2023-12-19 12:37:13 +00:00
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);
2023-12-20 21:42:42 +00:00
await mqttClient.SubscribeAsync(
new MqttFactory().CreateSubscribeOptionsBuilder().WithTopicFilter(f => f.WithTopic("login_request")).Build(),
CancellationToken.None
);
2023-12-05 22:43:02 +00:00
ApplicationState.DbContext = new DispenserContext();
2023-12-20 21:42:42 +00:00
mqttClient.ApplicationMessageReceivedAsync += delegate(MqttApplicationMessageReceivedEventArgs args) {
var payload = System.Text.Encoding.Default.GetString(args.ApplicationMessage.PayloadSegment);
switch (args.ApplicationMessage.Topic) {
case "login_request":
var user = ApplicationState.DbContext!.Users.FirstOrDefault(user => user.TouchCode == payload);
var message = new MqttApplicationMessageBuilder()
.WithTopic("login");
if (user == null) {
message.WithPayload("error");
} else {
message.WithPayload(user.Id.ToString());
}
mqttClient.PublishAsync(message.Build());
break;
}
return Task.CompletedTask;
};
ApplicationState.MqttClient = mqttClient;
Console.WriteLine("Connected");
app.Run();