mirror of
https://github.com/ckaczor/HomeMonitor.git
synced 2026-01-14 01:25:38 -05:00
Upgrade DeviceStatus service to .NET 8 and add OpenTelemetry
This commit is contained in:
@@ -1,21 +1,14 @@
|
|||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
namespace Service.Controllers
|
namespace ChrisKaczor.HomeMonitor.DeviceStatus.Service.Controllers;
|
||||||
{
|
|
||||||
[Route("[controller]")]
|
[Route("[controller]")]
|
||||||
[ApiController]
|
[ApiController]
|
||||||
public class StatusController : ControllerBase
|
public class StatusController(DeviceRepository deviceRepository) : ControllerBase
|
||||||
{
|
{
|
||||||
private readonly DeviceRepository _deviceRepository;
|
|
||||||
public StatusController(DeviceRepository deviceRepository)
|
|
||||||
{
|
|
||||||
_deviceRepository = deviceRepository;
|
|
||||||
}
|
|
||||||
|
|
||||||
[HttpGet("recent")]
|
[HttpGet("recent")]
|
||||||
public ActionResult<IEnumerable<Device>> GetRecent()
|
public ActionResult<IEnumerable<Device>> GetRecent()
|
||||||
{
|
{
|
||||||
return _deviceRepository.Values;
|
return deviceRepository.Values;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,22 +1,22 @@
|
|||||||
using System.Text.Json.Serialization;
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
namespace Service;
|
namespace ChrisKaczor.HomeMonitor.DeviceStatus.Service;
|
||||||
|
|
||||||
public class Device
|
public class Device
|
||||||
{
|
{
|
||||||
[JsonPropertyName("name")]
|
|
||||||
public string Name { get; }
|
|
||||||
|
|
||||||
[JsonPropertyName("status")]
|
|
||||||
public bool Status { get; private set; }
|
|
||||||
|
|
||||||
public Device(string name, string statusString)
|
public Device(string name, string statusString)
|
||||||
{
|
{
|
||||||
Name = name;
|
Name = name;
|
||||||
Update(statusString);
|
Update(statusString);
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Update(string statusString)
|
[JsonPropertyName("name")]
|
||||||
|
public string Name { get; }
|
||||||
|
|
||||||
|
[JsonPropertyName("status")]
|
||||||
|
public bool Status { get; private set; }
|
||||||
|
|
||||||
|
private void Update(string statusString)
|
||||||
{
|
{
|
||||||
Status = statusString == "1";
|
Status = statusString == "1";
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
namespace Service;
|
namespace ChrisKaczor.HomeMonitor.DeviceStatus.Service;
|
||||||
|
|
||||||
public class DeviceRepository : Dictionary<string, Device> { }
|
public class DeviceRepository : Dictionary<string, Device>;
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
FROM mcr.microsoft.com/dotnet/aspnet:6.0-alpine AS base
|
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine AS base
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
EXPOSE 80
|
EXPOSE 8080
|
||||||
|
|
||||||
FROM mcr.microsoft.com/dotnet/sdk:6.0-alpine AS build
|
FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build
|
||||||
WORKDIR /src
|
WORKDIR /src
|
||||||
COPY ["./Service.csproj", "./"]
|
COPY ["./Service.csproj", "./"]
|
||||||
RUN dotnet restore "Service.csproj"
|
RUN dotnet restore "Service.csproj"
|
||||||
|
|||||||
@@ -1,20 +1,13 @@
|
|||||||
using RestSharp;
|
using RestSharp;
|
||||||
|
|
||||||
namespace Service;
|
namespace ChrisKaczor.HomeMonitor.DeviceStatus.Service;
|
||||||
|
|
||||||
public class LaundryMonitor
|
public class LaundryMonitor(IConfiguration configuration)
|
||||||
{
|
{
|
||||||
|
private readonly string _botToken = configuration["Telegram:BotToken"]!;
|
||||||
|
private readonly string _chatId = configuration["Telegram:ChatId"]!;
|
||||||
private readonly RestClient _restClient = new();
|
private readonly RestClient _restClient = new();
|
||||||
|
|
||||||
private readonly string _botToken;
|
|
||||||
private readonly string _chatId;
|
|
||||||
|
|
||||||
public LaundryMonitor(IConfiguration configuration)
|
|
||||||
{
|
|
||||||
_botToken = configuration["Telegram:BotToken"];
|
|
||||||
_chatId = configuration["Telegram:ChatId"];
|
|
||||||
}
|
|
||||||
|
|
||||||
public async Task HandleDeviceMessage(Device device)
|
public async Task HandleDeviceMessage(Device device)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
|
|||||||
@@ -3,33 +3,34 @@ using MQTTnet;
|
|||||||
using MQTTnet.Client;
|
using MQTTnet.Client;
|
||||||
using System.Text.Json;
|
using System.Text.Json;
|
||||||
|
|
||||||
namespace Service;
|
namespace ChrisKaczor.HomeMonitor.DeviceStatus.Service;
|
||||||
|
|
||||||
public class MessageHandler : IHostedService
|
public class MessageHandler : IHostedService
|
||||||
{
|
{
|
||||||
private IMqttClient? _mqttClient;
|
|
||||||
private HubConnection? _hubConnection;
|
|
||||||
|
|
||||||
private readonly IConfiguration _configuration;
|
private readonly IConfiguration _configuration;
|
||||||
private readonly DeviceRepository _deviceRepository;
|
private readonly ILogger _logger;
|
||||||
private readonly LaundryMonitor _laundryMonitor;
|
|
||||||
private readonly Dictionary<string, Timer> _deviceTimers = new();
|
|
||||||
private readonly TimeSpan _deviceDelayTime;
|
private readonly TimeSpan _deviceDelayTime;
|
||||||
|
private readonly DeviceRepository _deviceRepository;
|
||||||
|
private readonly Dictionary<string, Timer> _deviceTimers = new();
|
||||||
|
private readonly LaundryMonitor _laundryMonitor;
|
||||||
|
private HubConnection? _hubConnection;
|
||||||
|
private IMqttClient? _mqttClient;
|
||||||
|
|
||||||
public MessageHandler(IConfiguration configuration, DeviceRepository deviceRepository, LaundryMonitor laundryMonitor)
|
public MessageHandler(IConfiguration configuration, DeviceRepository deviceRepository, LaundryMonitor laundryMonitor, ILogger<MessageHandler> logger)
|
||||||
{
|
{
|
||||||
_configuration = configuration;
|
_configuration = configuration;
|
||||||
|
_logger = logger;
|
||||||
_deviceRepository = deviceRepository;
|
_deviceRepository = deviceRepository;
|
||||||
_laundryMonitor = laundryMonitor;
|
_laundryMonitor = laundryMonitor;
|
||||||
|
|
||||||
_deviceDelayTime = TimeSpan.Parse(_configuration["DeviceStatus:DelayTime"]);
|
_deviceDelayTime = TimeSpan.Parse(_configuration["DeviceStatus:DelayTime"]!);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task StartAsync(CancellationToken cancellationToken)
|
public async Task StartAsync(CancellationToken cancellationToken)
|
||||||
{
|
{
|
||||||
if (!string.IsNullOrEmpty(_configuration["Hub:DeviceStatus"]))
|
if (!string.IsNullOrEmpty(_configuration["Hub:DeviceStatus"]))
|
||||||
{
|
{
|
||||||
_hubConnection = new HubConnectionBuilder().WithUrl(_configuration["Hub:DeviceStatus"]).Build();
|
_hubConnection = new HubConnectionBuilder().WithUrl(_configuration["Hub:DeviceStatus"]!).Build();
|
||||||
_hubConnection.On("RequestLatestStatus", async () => await RequestLatestStatus());
|
_hubConnection.On("RequestLatestStatus", async () => await RequestLatestStatus());
|
||||||
|
|
||||||
await _hubConnection.StartAsync(cancellationToken);
|
await _hubConnection.StartAsync(cancellationToken);
|
||||||
@@ -45,16 +46,21 @@ public class MessageHandler : IHostedService
|
|||||||
await _mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
await _mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
||||||
|
|
||||||
var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
|
var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
|
||||||
.WithTopicFilter(
|
.WithTopicFilter(f => f.WithTopic("device-status/#"))
|
||||||
f =>
|
|
||||||
{
|
|
||||||
f.WithTopic("device-status/#");
|
|
||||||
})
|
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
await _mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
|
await _mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task StopAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
if (_hubConnection != null)
|
||||||
|
await _hubConnection.StopAsync(cancellationToken);
|
||||||
|
|
||||||
|
if (_mqttClient != null)
|
||||||
|
await _mqttClient.DisconnectAsync(new MqttClientDisconnectOptionsBuilder().Build(), CancellationToken.None);
|
||||||
|
}
|
||||||
|
|
||||||
private async Task OnApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
|
private async Task OnApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
|
||||||
{
|
{
|
||||||
var topic = arg.ApplicationMessage.Topic;
|
var topic = arg.ApplicationMessage.Topic;
|
||||||
@@ -65,8 +71,8 @@ public class MessageHandler : IHostedService
|
|||||||
|
|
||||||
var newDevice = new Device(deviceName, payload);
|
var newDevice = new Device(deviceName, payload);
|
||||||
|
|
||||||
if (_deviceTimers.ContainsKey(newDevice.Name))
|
if (_deviceTimers.TryGetValue(newDevice.Name, out var deviceTimer))
|
||||||
await _deviceTimers[newDevice.Name].DisposeAsync();
|
await deviceTimer.DisposeAsync();
|
||||||
|
|
||||||
if (!_deviceRepository.ContainsKey(newDevice.Name) || newDevice.Status)
|
if (!_deviceRepository.ContainsKey(newDevice.Name) || newDevice.Status)
|
||||||
{
|
{
|
||||||
@@ -141,17 +147,8 @@ public class MessageHandler : IHostedService
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task StopAsync(CancellationToken cancellationToken)
|
private void WriteLog(string message)
|
||||||
{
|
{
|
||||||
if (_hubConnection != null)
|
_logger.LogInformation(message);
|
||||||
await _hubConnection.StopAsync(cancellationToken);
|
|
||||||
|
|
||||||
if (_mqttClient != null)
|
|
||||||
await _mqttClient.DisconnectAsync(new MqttClientDisconnectOptionsBuilder().Build(), CancellationToken.None);
|
|
||||||
}
|
|
||||||
|
|
||||||
private static void WriteLog(string message)
|
|
||||||
{
|
|
||||||
Console.WriteLine(message);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,8 +1,17 @@
|
|||||||
using Service;
|
using ChrisKaczor.Common.OpenTelemetry;
|
||||||
|
using System.Reflection;
|
||||||
|
|
||||||
|
namespace ChrisKaczor.HomeMonitor.DeviceStatus.Service;
|
||||||
|
|
||||||
|
public static class Program
|
||||||
|
{
|
||||||
|
public static void Main(string[] args)
|
||||||
|
{
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
|
||||||
builder.Host.ConfigureAppConfiguration((_, config) => config.AddEnvironmentVariables());
|
builder.Configuration.AddEnvironmentVariables();
|
||||||
|
|
||||||
|
builder.Services.AddCommonOpenTelemetry(Assembly.GetExecutingAssembly().GetName().Name, builder.Configuration["Telemetry:Endpoint"], nameof(MessageHandler));
|
||||||
|
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
|
|
||||||
@@ -27,3 +36,5 @@ app.UseAuthorization();
|
|||||||
app.MapControllers();
|
app.MapControllers();
|
||||||
|
|
||||||
app.Run();
|
app.Run();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +1,19 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
<PropertyGroup>
|
<PropertyGroup>
|
||||||
<TargetFramework>net6.0</TargetFramework>
|
<TargetFramework>net8.0</TargetFramework>
|
||||||
<Nullable>enable</Nullable>
|
<Nullable>enable</Nullable>
|
||||||
<ImplicitUsings>enable</ImplicitUsings>
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
<AssemblyName>ChrisKaczor.HomeMonitor.DeviceStatus.Service</AssemblyName>
|
<AssemblyName>ChrisKaczor.HomeMonitor.DeviceStatus.Service</AssemblyName>
|
||||||
|
<RootNamespace>ChrisKaczor.HomeMonitor.DeviceStatus.Service</RootNamespace>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<PackageReference Include="JetBrains.Annotations" Version="2022.1.0" />
|
<PackageReference Include="ChrisKaczor.Common.OpenTelemetry" Version="1.0.1" />
|
||||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="6.0.8" />
|
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.1" />
|
||||||
<PackageReference Include="MQTTnet" Version="4.1.0.247" />
|
<PackageReference Include="MQTTnet" Version="4.3.3.952" />
|
||||||
<PackageReference Include="MQTTnet.AspNetCore" Version="4.1.0.247" />
|
<PackageReference Include="RestSharp" Version="110.2.0" />
|
||||||
<PackageReference Include="RestSharp" Version="108.0.1" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
|
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
{
|
{
|
||||||
"Logging": {
|
"Logging": {
|
||||||
"LogLevel": {
|
"LogLevel": {
|
||||||
"Default": "Information",
|
"Default": "Warning",
|
||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft": "Information"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
@@ -18,5 +18,8 @@
|
|||||||
},
|
},
|
||||||
"Mqtt": {
|
"Mqtt": {
|
||||||
"Server": "mosquitto"
|
"Server": "mosquitto"
|
||||||
|
},
|
||||||
|
"Telemetry": {
|
||||||
|
"Endpoint": "http://signoz-otel-collector.platform:4317/"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,7 +51,7 @@ metadata:
|
|||||||
spec:
|
spec:
|
||||||
ports:
|
ports:
|
||||||
- name: client
|
- name: client
|
||||||
port: 80
|
port: 8080
|
||||||
selector:
|
selector:
|
||||||
app: device-status-service
|
app: device-status-service
|
||||||
type: ClusterIP
|
type: ClusterIP
|
||||||
@@ -75,7 +75,7 @@ spec:
|
|||||||
- kind: Service
|
- kind: Service
|
||||||
name: device-status-service
|
name: device-status-service
|
||||||
namespace: home-monitor
|
namespace: home-monitor
|
||||||
port: 80
|
port: 8080
|
||||||
---
|
---
|
||||||
apiVersion: traefik.containo.us/v1alpha1
|
apiVersion: traefik.containo.us/v1alpha1
|
||||||
kind: Middleware
|
kind: Middleware
|
||||||
|
|||||||
Reference in New Issue
Block a user