mirror of
https://github.com/ckaczor/HomeMonitor.git
synced 2026-01-13 17:22:54 -05:00
Update Weather to .NET 8 and add telemetry
This commit is contained in:
@@ -1,27 +1,26 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using System;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Weather.SerialReader.Controllers
|
||||
namespace ChrisKaczor.HomeMonitor.Weather.SerialReader.Controllers;
|
||||
|
||||
[Route("[controller]")]
|
||||
[ApiController]
|
||||
public class HealthController : ControllerBase
|
||||
{
|
||||
[Route("[controller]")]
|
||||
[ApiController]
|
||||
public class HealthController : ControllerBase
|
||||
private readonly TimeSpan _checkTimeSpan = TimeSpan.FromSeconds(5);
|
||||
|
||||
[HttpGet("ready")]
|
||||
public IActionResult Ready()
|
||||
{
|
||||
private readonly TimeSpan _checkTimeSpan = TimeSpan.FromSeconds(5);
|
||||
|
||||
[HttpGet("ready")]
|
||||
public IActionResult Ready()
|
||||
{
|
||||
return SerialReader.BoardStarted ? Ok() : Conflict();
|
||||
}
|
||||
|
||||
[HttpGet("health")]
|
||||
public IActionResult Health()
|
||||
{
|
||||
var lastReading = SerialReader.LastReading;
|
||||
var timeSinceLastReading = DateTimeOffset.UtcNow - lastReading;
|
||||
|
||||
return SerialReader.BoardStarted && timeSinceLastReading <= _checkTimeSpan ? Ok(lastReading) : BadRequest(lastReading);
|
||||
}
|
||||
return SerialReader.BoardStarted ? Ok() : Conflict();
|
||||
}
|
||||
}
|
||||
|
||||
[HttpGet("health")]
|
||||
public IActionResult Health()
|
||||
{
|
||||
var lastReading = SerialReader.LastReading;
|
||||
var timeSinceLastReading = DateTimeOffset.UtcNow - lastReading;
|
||||
|
||||
return SerialReader.BoardStarted && timeSinceLastReading <= _checkTimeSpan ? Ok(lastReading) : BadRequest(lastReading);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:5.0-focal-arm32v7 AS base
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0-jammy-arm32v7 AS base
|
||||
WORKDIR /app
|
||||
EXPOSE 80
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:5.0-focal AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0-jammy AS build
|
||||
WORKDIR /src
|
||||
COPY ["./SerialReader.csproj", "./"]
|
||||
RUN dotnet restore -r linux-arm "SerialReader.csproj"
|
||||
|
||||
@@ -1,20 +1,116 @@
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.ResponseCompression;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenTelemetry.Exporter;
|
||||
using OpenTelemetry.Logs;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
using System;
|
||||
using System.IO.Compression;
|
||||
using System.Reflection;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Weather.SerialReader
|
||||
namespace ChrisKaczor.HomeMonitor.Weather.SerialReader;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static class Program
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
CreateHostBuilder(args).Build().Run();
|
||||
}
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
private static IHostBuilder CreateHostBuilder(string[] args) =>
|
||||
Host.CreateDefaultBuilder(args)
|
||||
.ConfigureWebHostDefaults(webBuilder =>
|
||||
builder.Configuration.AddEnvironmentVariables();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// ---
|
||||
|
||||
var openTelemetry = builder.Services.AddOpenTelemetry();
|
||||
|
||||
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
|
||||
|
||||
var serviceName = Assembly.GetExecutingAssembly().GetName().Name;
|
||||
|
||||
openTelemetry.ConfigureResource(resource => resource.AddService(serviceName!));
|
||||
|
||||
openTelemetry.WithMetrics(meterProviderBuilder => meterProviderBuilder
|
||||
.AddAspNetCoreInstrumentation()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddProcessInstrumentation()
|
||||
.AddMeter("Microsoft.AspNetCore.Hosting")
|
||||
.AddMeter("Microsoft.AspNetCore.Server.Kestrel"));
|
||||
|
||||
openTelemetry.WithTracing(tracerProviderBuilder =>
|
||||
{
|
||||
tracerProviderBuilder.AddAspNetCoreInstrumentation(instrumentationOptions => instrumentationOptions.RecordException = true);
|
||||
|
||||
tracerProviderBuilder.AddHttpClientInstrumentation(instrumentationOptions => instrumentationOptions.RecordException = true);
|
||||
|
||||
tracerProviderBuilder.AddSqlClientInstrumentation(o =>
|
||||
{
|
||||
o.RecordException = true;
|
||||
o.SetDbStatementForText = true;
|
||||
});
|
||||
|
||||
tracerProviderBuilder.AddSource(nameof(SerialReader));
|
||||
|
||||
tracerProviderBuilder.SetErrorStatusOnException();
|
||||
|
||||
tracerProviderBuilder.AddOtlpExporter(exporterOptions =>
|
||||
{
|
||||
exporterOptions.Endpoint = new Uri(builder.Configuration["Telemetry:Endpoint"]!);
|
||||
exporterOptions.Protocol = OtlpExportProtocol.Grpc;
|
||||
});
|
||||
});
|
||||
|
||||
builder.Services.AddLogging(loggingBuilder =>
|
||||
{
|
||||
loggingBuilder.SetMinimumLevel(LogLevel.Information);
|
||||
loggingBuilder.AddOpenTelemetry(options =>
|
||||
{
|
||||
webBuilder.UseStartup<Startup>();
|
||||
});
|
||||
options.AddOtlpExporter(exporterOptions =>
|
||||
{
|
||||
exporterOptions.Endpoint = new Uri(builder.Configuration["Telemetry:Endpoint"]!);
|
||||
exporterOptions.Protocol = OtlpExportProtocol.Grpc;
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
builder.Services.AddHostedService<SerialReader>();
|
||||
|
||||
builder.Services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);
|
||||
|
||||
builder.Services.AddResponseCompression(options =>
|
||||
{
|
||||
options.Providers.Add<GzipCompressionProvider>();
|
||||
options.EnableForHttps = true;
|
||||
});
|
||||
|
||||
builder.Services.AddCors(o => o.AddPolicy("CorsPolicy", corsPolicyBuilder => corsPolicyBuilder.AllowAnyMethod().AllowAnyHeader().AllowCredentials().WithOrigins("http://localhost:4200")));
|
||||
|
||||
builder.Services.AddMvc().AddJsonOptions(configure => { configure.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); });
|
||||
|
||||
// ---
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (builder.Environment.IsDevelopment())
|
||||
app.UseDeveloperExceptionPage();
|
||||
|
||||
app.UseCors("CorsPolicy");
|
||||
|
||||
app.UseResponseCompression();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,163 +8,158 @@ using System.IO.Ports;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Weather.SerialReader
|
||||
namespace ChrisKaczor.HomeMonitor.Weather.SerialReader;
|
||||
|
||||
public class SerialReader(IConfiguration configuration, ILogger<SerialReader> logger) : IHostedService
|
||||
{
|
||||
public class SerialReader : IHostedService
|
||||
public static bool BoardStarted { get; private set; }
|
||||
public static DateTimeOffset LastReading { get; private set; }
|
||||
|
||||
private CancellationToken _cancellationToken;
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
_cancellationToken = cancellationToken;
|
||||
|
||||
public static bool BoardStarted { get; private set; }
|
||||
public static DateTimeOffset LastReading { get; private set; }
|
||||
Task.Run(Execute, cancellationToken);
|
||||
|
||||
private CancellationToken _cancellationToken;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public SerialReader(IConfiguration configuration)
|
||||
private void Execute()
|
||||
{
|
||||
var baudRate = configuration.GetValue<int>("Weather:Port:BaudRate");
|
||||
|
||||
while (!_cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_cancellationToken = cancellationToken;
|
||||
|
||||
Task.Run(Execute, cancellationToken);
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void Execute()
|
||||
{
|
||||
var baudRate = int.Parse(_configuration["Weather:Port:BaudRate"]);
|
||||
|
||||
while (!_cancellationToken.IsCancellationRequested)
|
||||
try
|
||||
{
|
||||
try
|
||||
{
|
||||
WriteLog("Starting main loop");
|
||||
|
||||
Thread.Sleep(1000);
|
||||
|
||||
var port = GetPort();
|
||||
|
||||
if (port == null)
|
||||
continue;
|
||||
|
||||
using var serialPort = new SerialPort(port, baudRate) { NewLine = "\r\n" };
|
||||
|
||||
WriteLog("Opening serial port");
|
||||
|
||||
serialPort.Open();
|
||||
|
||||
BoardStarted = false;
|
||||
|
||||
var factory = new ConnectionFactory
|
||||
{
|
||||
HostName = _configuration["Weather:Queue:Host"],
|
||||
UserName = _configuration["Weather:Queue:User"],
|
||||
Password = _configuration["Weather:Queue:Password"]
|
||||
};
|
||||
|
||||
WriteLog("Connecting to queue server");
|
||||
|
||||
using var connection = factory.CreateConnection();
|
||||
using var model = connection.CreateModel();
|
||||
|
||||
WriteLog("Declaring queue");
|
||||
|
||||
model.QueueDeclare(_configuration["Weather:Queue:Name"], true, false, false, null);
|
||||
|
||||
WriteLog("Starting serial read loop");
|
||||
|
||||
ReadSerial(serialPort, model);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WriteLog($"Exception: {exception}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ReadSerial(SerialPort serialPort, IModel model)
|
||||
{
|
||||
while (!_cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = serialPort.ReadLine();
|
||||
|
||||
if (!BoardStarted)
|
||||
{
|
||||
BoardStarted = message.Contains("Board starting");
|
||||
|
||||
if (BoardStarted)
|
||||
WriteLog("Board started");
|
||||
}
|
||||
|
||||
if (!BoardStarted)
|
||||
{
|
||||
WriteLog($"Message received but board not started: {message}");
|
||||
continue;
|
||||
}
|
||||
|
||||
LastReading = DateTimeOffset.UtcNow;
|
||||
|
||||
WriteLog($"Message received: {message}");
|
||||
|
||||
var weatherMessage = WeatherMessage.Parse(message);
|
||||
|
||||
var messageString = JsonConvert.SerializeObject(weatherMessage);
|
||||
|
||||
var body = Encoding.UTF8.GetBytes(messageString);
|
||||
|
||||
var properties = model.CreateBasicProperties();
|
||||
|
||||
properties.Persistent = true;
|
||||
|
||||
model.BasicPublish(string.Empty, _configuration["Weather:Queue:Name"], properties, body);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
WriteLog("Serial port read timeout");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string GetPort()
|
||||
{
|
||||
var portPrefix = _configuration["Weather:Port:Prefix"];
|
||||
|
||||
while (!_cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
WriteLog($"Checking for port starting with: {portPrefix}");
|
||||
|
||||
var ports = SerialPort.GetPortNames();
|
||||
|
||||
var port = Array.Find(ports, p => p.StartsWith(portPrefix));
|
||||
|
||||
if (port != null)
|
||||
{
|
||||
WriteLog($"Port found: {port}");
|
||||
return port;
|
||||
}
|
||||
|
||||
WriteLog("Port not found - waiting");
|
||||
WriteLog("Starting main loop");
|
||||
|
||||
Thread.Sleep(1000);
|
||||
|
||||
var port = GetPort();
|
||||
|
||||
if (port == null)
|
||||
continue;
|
||||
|
||||
using var serialPort = new SerialPort(port, baudRate);
|
||||
|
||||
serialPort.NewLine = "\r\n";
|
||||
|
||||
WriteLog("Opening serial port");
|
||||
|
||||
serialPort.Open();
|
||||
|
||||
BoardStarted = false;
|
||||
|
||||
var factory = new ConnectionFactory
|
||||
{
|
||||
HostName = configuration["Weather:Queue:Host"],
|
||||
UserName = configuration["Weather:Queue:User"],
|
||||
Password = configuration["Weather:Queue:Password"]
|
||||
};
|
||||
|
||||
WriteLog("Connecting to queue server");
|
||||
|
||||
using var connection = factory.CreateConnection();
|
||||
using var model = connection.CreateModel();
|
||||
|
||||
WriteLog("Declaring queue");
|
||||
|
||||
model.QueueDeclare(configuration["Weather:Queue:Name"], true, false, false, null);
|
||||
|
||||
WriteLog("Starting serial read loop");
|
||||
|
||||
ReadSerial(serialPort, model);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WriteLog($"Exception: {exception}");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void WriteLog(string message)
|
||||
{
|
||||
Console.WriteLine(message);
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ReadSerial(SerialPort serialPort, IModel model)
|
||||
{
|
||||
while (!_cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
var message = serialPort.ReadLine();
|
||||
|
||||
if (!BoardStarted)
|
||||
{
|
||||
BoardStarted = message.Contains("Board starting");
|
||||
|
||||
if (BoardStarted)
|
||||
WriteLog("Board started");
|
||||
}
|
||||
|
||||
if (!BoardStarted)
|
||||
{
|
||||
WriteLog($"Message received but board not started: {message}");
|
||||
continue;
|
||||
}
|
||||
|
||||
LastReading = DateTimeOffset.UtcNow;
|
||||
|
||||
WriteLog($"Message received: {message}");
|
||||
|
||||
var weatherMessage = WeatherMessage.Parse(message);
|
||||
|
||||
var messageString = JsonConvert.SerializeObject(weatherMessage);
|
||||
|
||||
var body = Encoding.UTF8.GetBytes(messageString);
|
||||
|
||||
var properties = model.CreateBasicProperties();
|
||||
|
||||
properties.Persistent = true;
|
||||
|
||||
model.BasicPublish(string.Empty, configuration["Weather:Queue:Name"], properties, body);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
WriteLog("Serial port read timeout");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private string GetPort()
|
||||
{
|
||||
var portPrefix = configuration["Weather:Port:Prefix"]!;
|
||||
|
||||
while (!_cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
WriteLog($"Checking for port starting with: {portPrefix}");
|
||||
|
||||
var ports = SerialPort.GetPortNames();
|
||||
|
||||
var port = Array.Find(ports, p => p.StartsWith(portPrefix));
|
||||
|
||||
if (port != null)
|
||||
{
|
||||
WriteLog($"Port found: {port}");
|
||||
return port;
|
||||
}
|
||||
|
||||
WriteLog("Port not found - waiting");
|
||||
|
||||
Thread.Sleep(1000);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void WriteLog(string message)
|
||||
{
|
||||
logger.LogInformation(message);
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<CodeAnalysisRuleSet>../../ChrisKaczor.ruleset</CodeAnalysisRuleSet>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -13,13 +12,16 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ChrisKaczor.HomeMonitor.Weather.Models" Version="1.1.6" />
|
||||
<PackageReference Include="JetBrains.Annotations" Version="2021.1.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration" Version="5.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="5.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="5.0.0" />
|
||||
<PackageReference Include="RabbitMQ.Client" Version="6.2.1" />
|
||||
<PackageReference Include="System.IO.Ports" Version="5.0.1" />
|
||||
<PackageReference Include="ChrisKaczor.HomeMonitor.Weather.Models" Version="1.1.8" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="RabbitMQ.Client" Version="6.8.1" />
|
||||
<PackageReference Include="System.IO.Ports" Version="8.0.0" />
|
||||
<PackageReference Include="OpenTelemetry.AutoInstrumentation" Version="1.3.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.7.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.7.0" />
|
||||
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.7.0" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.7.0" />
|
||||
<PackageReference Include="System.Security.Cryptography.Xml" Version="8.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,34 +0,0 @@
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Weather.SerialReader
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddControllers();
|
||||
|
||||
services.AddHostedService<SerialReader>();
|
||||
}
|
||||
|
||||
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
|
||||
{
|
||||
if (env.IsDevelopment())
|
||||
{
|
||||
app.UseDeveloperExceptionPage();
|
||||
}
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.UseEndpoints(endpoints =>
|
||||
{
|
||||
endpoints.MapControllers();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,5 +7,8 @@
|
||||
"Queue": {
|
||||
"Name": "weather"
|
||||
}
|
||||
},
|
||||
"Telemetry": {
|
||||
"Endpoint": "http://signoz-otel-collector.platform:4317/"
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ spec:
|
||||
livenessProbe:
|
||||
httpGet:
|
||||
path: health/health
|
||||
port: 80
|
||||
port: 8080
|
||||
env:
|
||||
- name: Weather__Queue__Host
|
||||
value: weather-queue
|
||||
|
||||
Reference in New Issue
Block a user