64 lines
2.7 KiB
C#
64 lines
2.7 KiB
C#
using System.IO.Ports;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using MoniteurBaie.DataModels;
|
|
using MoniteurBaie.Utils;
|
|
using StackExchange.Redis;
|
|
|
|
namespace MoniteurBaie.SerialCom;
|
|
|
|
public class Worker : BackgroundService
|
|
{
|
|
private readonly ILogger<Worker> _logger;
|
|
private readonly IConfiguration _configuration;
|
|
|
|
public Worker(ILogger<Worker> logger, IConfiguration configuration)
|
|
{
|
|
_logger = logger;
|
|
_configuration = configuration;
|
|
}
|
|
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
var config = _configuration.GetSection("MoniteurBaie");
|
|
var serialConfig = config.GetSection("Serial");
|
|
var redisConfig = config.GetSection("Redis");
|
|
|
|
using IBatteryController batteryController = config.GetValue<bool>("Mock")
|
|
? new MockBatteryController()
|
|
: new BatteryController(_logger, serialPort =>
|
|
{
|
|
serialPort.PortName = serialConfig.GetValue<string>("Path")!;
|
|
serialPort.BaudRate = serialConfig.GetValue<int>("BaudRate");
|
|
serialPort.Parity = serialConfig.GetValue<Parity>("Parity");
|
|
serialPort.DataBits = serialConfig.GetValue<int>("DataBits");
|
|
serialPort.StopBits = serialConfig.GetValue<StopBits>("StopBits");
|
|
serialPort.Handshake = serialConfig.GetValue<Handshake>("Handshake");
|
|
serialPort.Encoding = Encoding.GetEncoding(serialConfig.GetValue<string>("Encoding")!);
|
|
serialPort.NewLine = serialConfig.GetValue<string>("NewLine")!;
|
|
});
|
|
|
|
await batteryController.Open(stoppingToken);
|
|
|
|
using var redis = await ConnectionMultiplexer.ConnectAsync(redisConfig.GetValue<string>("Endpoint")!, opts =>
|
|
{
|
|
opts.ClientName = redisConfig.GetValue<string>("ClientName");
|
|
});
|
|
|
|
using var dataApi = new DataApi(_logger, config.GetSection("Api"));
|
|
|
|
var redisChannel = redisConfig.GetValue<string>("Channels:Packets")!;
|
|
batteryController.AddSerialObserver(Listener.Create((BatteryControllerPacket packet) =>
|
|
{
|
|
var dataPacket = JsonSerializer.Serialize(packet, BatteryControllerPacketContext.Default.BatteryControllerPacket);
|
|
redis.GetSubscriber().Publish(redisChannel, dataPacket, CommandFlags.FireAndForget);
|
|
dataApi.Send(packet);
|
|
}));
|
|
|
|
var mq = await redis.GetSubscriber().SubscribeAsync(redisConfig.GetValue<string>("Channels:Commands")!);
|
|
mq.OnMessage(channelMessage => batteryController.SendCommand(channelMessage.Message.ToString(), stoppingToken));
|
|
|
|
await Task.Delay(Timeout.Infinite, stoppingToken);
|
|
}
|
|
}
|