You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hass-workstation-service/Worker.cs

63 lines
2.3 KiB

4 years ago
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using hass_workstation_service.Communication;
using hass_workstation_service.Data;
using hass_workstation_service.Domain.Sensors;
4 years ago
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MQTTnet.Client;
4 years ago
namespace hass_workstation_service
4 years ago
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private readonly ConfiguredSensorsService _configuredSensorsService;
private readonly MqttPublisher _mqttPublisher;
4 years ago
public Worker(ILogger<Worker> logger,
ConfiguredSensorsService configuredSensorsService,
MqttPublisher mqttPublisher)
4 years ago
{
_logger = logger;
this._configuredSensorsService = configuredSensorsService;
this._mqttPublisher = mqttPublisher;
4 years ago
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!_mqttPublisher.IsConnected)
{
_logger.LogInformation("Connecting to MQTT broker...");
await Task.Delay(2000);
}
_logger.LogInformation("Connected. Sending auto discovery messages.");
foreach (AbstractSensor sensor in _configuredSensorsService.ConfiguredSensors)
{
await sensor.PublishAutoDiscoveryConfigAsync();
}
4 years ago
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogDebug("Worker running at: {time}", DateTimeOffset.Now);
foreach (AbstractSensor sensor in _configuredSensorsService.ConfiguredSensors)
{
await sensor.PublishStateAsync();
}
// announce autodiscovery every 30 seconds
if (_mqttPublisher.LastConfigAnnounce < DateTime.UtcNow.AddSeconds(-30))
{
foreach (AbstractSensor sensor in _configuredSensorsService.ConfiguredSensors)
{
await sensor.PublishAutoDiscoveryConfigAsync();
}
}
4 years ago
await Task.Delay(1000, stoppingToken);
}
}
}
}