Add support for esp

This commit is contained in:
2025-07-19 18:59:53 +02:00
parent 732d7c8295
commit 5c26b8f8dd
12 changed files with 255 additions and 230 deletions

View File

@@ -6,35 +6,28 @@ using Microsoft.AspNetCore.Mvc;
namespace HomeApi.Controllers;
[ApiController]
[Route("[controller]")]
[Route("home")]
public class HomeController(IMediator mediator) : ControllerBase
{
[HttpGet(Name = "GetHome")]
[HttpGet(Name = "getHome")]
public async Task<ActionResult<WeatherInformation>> Get()
{
return Ok(await mediator.Send(new Weather.Command()));
}
[HttpGet("default.bmp")]
[HttpGet("default.jpg")]
public async Task<IActionResult> GetImage()
{
return File(await mediator.Send(new ImageGeneration.Command()), "image/bmp");
return File(await mediator.Send(new ImageGeneration.Command()), "image/jpeg");
}
/*[HttpGet("screen/buffers")]
public async Task<IActionResult> GetCombinedBuffers()
[HttpGet("configuration")]
public async Task<ActionResult<MicroProcessorConfiguration>> GetCombinedBuffers()
{
var (black, red) = await mediator.Send(new ImageGeneration.Command());
return Ok(await mediator.Send(new Configuration.Command()));
}
// Combine buffers
byte[] combined = new byte[black.Length + red.Length];
Buffer.BlockCopy(black, 0, combined, 0, black.Length);
Buffer.BlockCopy(red, 0, combined, black.Length, red.Length);
return File(combined, "application/octet-stream");
}*/
[HttpGet("departureboard")]
[HttpGet("departure-board")]
public async Task<ActionResult<List<TimeTable>>> GetDepartureBoard()
{
return Ok(await mediator.Send(new DepartureBoard.Command()));

View File

@@ -0,0 +1,31 @@
using HomeApi.Models;
using HomeApi.Models.Configuration;
using MediatR;
using Microsoft.Extensions.Options;
namespace HomeApi.Handlers;
public static class Configuration
{
public record Command : IRequest<MicroProcessorConfiguration>;
public class Handler(IOptions<ApiConfiguration> configuration)
: IRequestHandler<Command, MicroProcessorConfiguration>
{
private readonly ApiConfiguration _apiConfiguration = configuration.Value;
public Task<MicroProcessorConfiguration> Handle(Command request, CancellationToken cancellationToken)
{
return Task.FromResult(new MicroProcessorConfiguration
{
InformationBoardImageUrl = _apiConfiguration.EspConfiguration.InformationBoardImageUrl,
UpdateIntervalMinutes = _apiConfiguration.EspConfiguration.UpdateIntervalMinutes,
BlackTextThreshold = _apiConfiguration.EspConfiguration.BlackTextThreshold,
ContrastStrength = _apiConfiguration.EspConfiguration.ContrastStrength,
DitheringStrength = _apiConfiguration.EspConfiguration.DitheringStrength,
EnableDithering = _apiConfiguration.EspConfiguration.EnableDithering,
EnhanceContrast = _apiConfiguration.EspConfiguration.EnhanceContrast
});
}
}
}

View File

@@ -8,18 +8,11 @@ public static class DepartureBoard
{
public record Command : IRequest<List<TimeTable>>;
public class Handler : IRequestHandler<Command, List<TimeTable>>
public class Handler(IDepartureBoardService departureBoardService) : IRequestHandler<Command, List<TimeTable>>
{
private readonly IDepartureBoardService _departureBoardService;
public Handler(IDepartureBoardService departureBoardService)
{
_departureBoardService = departureBoardService;
}
public async Task<List<TimeTable>> Handle(Command request, CancellationToken cancellationToken)
{
return await _departureBoardService.GetDepartureBoard() ?? new List<TimeTable>();
return await departureBoardService.GetDepartureBoard() ?? new List<TimeTable>();
}
}
}

View File

@@ -5,10 +5,6 @@ using MediatR;
using Microsoft.Extensions.Options;
using PuppeteerSharp;
using RazorLight;
using SixLabors.ImageSharp.Formats.Bmp;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using Image = SixLabors.ImageSharp.Image;
namespace HomeApi.Handlers;
@@ -16,24 +12,18 @@ public static class ImageGeneration
{
public record Command : IRequest<Stream>;
public class Handler : IRequestHandler<Command, Stream>
public class Handler(
IWebHostEnvironment env,
IMediator mediator,
IOptions<ApiConfiguration> apiConfiguration)
: IRequestHandler<Command, Stream>
{
private readonly ILogger<Handler> _logger;
private readonly IWebHostEnvironment _env;
private readonly IMediator _mediator;
public Handler(
IOptions<ApiConfiguration> apiConfiguration,
ILogger<Handler> logger, IWebHostEnvironment env, IMediator mediator)
{
_logger = logger;
_env = env;
_mediator = mediator;
}
private readonly ApiConfiguration _apiConfiguration = apiConfiguration.Value;
public async Task<Stream> Handle(Command request, CancellationToken cancellationToken)
{
var weather = await _mediator.Send(new Weather.Command(), cancellationToken);
var departureBoard = await _mediator.Send(new DepartureBoard.Command(), cancellationToken);
var weather = await mediator.Send(new Weather.Command(), cancellationToken);
var departureBoard = await mediator.Send(new DepartureBoard.Command(), cancellationToken);
var model = new Models.Image
{
@@ -50,13 +40,19 @@ public static class ImageGeneration
.UseMemoryCachingProvider()
.Build();
var path = Path.Combine(_env.WebRootPath, "index.cshtml");
var path = Path.Combine(env.WebRootPath, "index.cshtml");
var template = await File.ReadAllTextAsync(path, cancellationToken);
var result = await engine.CompileRenderStringAsync("templateKey", template, model, viewBag: new ExpandoObject());
dynamic viewBag = new ExpandoObject();
viewBag.IsHighContrast = _apiConfiguration.EspConfiguration.IsHighContrastMode;
var result = await engine.CompileRenderStringAsync("templateKey", template, model, viewBag: viewBag);
if (!string.IsNullOrEmpty(result))
return await CreateImage(result);
throw new Exception("Failed to generate HTML content for image.");
}
private static async Task<Stream> CreateImage(string htmlContent)
@@ -68,63 +64,16 @@ public static class ImageGeneration
Headless = true,
Args = ["--disable-gpu"]
});
var page = await browser.NewPageAsync();
await page.SetViewportAsync(new ViewPortOptions
{
Width = 800,
Height = 480
});
await page.SetContentAsync(htmlContent, new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } });
var stream = await page.ScreenshotStreamAsync(new ScreenshotOptions { Type = ScreenshotType.Png });
return await stream.ToBmpStream();
await page.SetContentAsync(htmlContent, new NavigationOptions { WaitUntil = [WaitUntilNavigation.Networkidle0] });
return await page.ScreenshotStreamAsync(new ScreenshotOptions { Type = ScreenshotType.Jpeg, Quality = 60 });
}
}
private static async Task<Stream> ToBmpStream(this Stream stream)
{
var image = await Image.LoadAsync<Rgba32>(stream);
// Resize or crop to 800x480 if necessary
image.Mutate(x => x.Resize(800, 480));
// Reduce to 3-color e-paper palette
image.ProcessPixelRows(accessor =>
{
for (var y = 0; y < accessor.Height; y++)
{
var row = accessor.GetRowSpan(y);
for (var x = 0; x < row.Length; x++)
{
var pixel = row[x];
// Compute perceived brightness (gray)
var brightness = 0.299f * pixel.R + 0.587f * pixel.G + 0.114f * pixel.B;
if (pixel.R > 150 && pixel.G < 80 && pixel.B < 80) // RED threshold
{
row[x] = new Rgba32(255, 0, 0); // Red
}
else if (brightness > 180)
{
row[x] = new Rgba32(255, 255, 255); // White
}
else
{
row[x] = new Rgba32(0, 0, 0); // Black
}
}
}
});
var bmpStream = new MemoryStream();
var bmpEncoder = new BmpEncoder
{
BitsPerPixel = BmpBitsPerPixel.Pixel24
};
await image.SaveAsync(bmpStream, bmpEncoder);
bmpStream.Position = 0;
return bmpStream;
}
}

View File

@@ -17,7 +17,6 @@
<PackageReference Include="RazorLight" Version="2.3.1" />
<PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" />
<PackageReference Include="Scalar.AspNetCore" Version="2.5.6" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.10" />
</ItemGroup>
<ItemGroup>

View File

@@ -11,7 +11,15 @@ public interface IAuroraService
public class AuroraService(IAuroraClient auroraApi) : IAuroraService
{
public Task<AuroraForecastApiResponse> GetAuroraForecastAsync(string lat, string lon)
{
try
{
return auroraApi.GetForecastAsync(latitude: lat, longitude: lon);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}

View File

@@ -6,6 +6,7 @@ public class ApiConfiguration
public BaseUrls BaseUrls { get; set; } = new();
public string DefaultCity { get; set; } = "Vega stockholms lan";
public string DefaultStation { get; set; } = "Vega station";
public EspConfig EspConfiguration { get; set; } = new();
}
public class BaseUrls
@@ -23,3 +24,15 @@ public class Keys
public string Aurora { get; set; } = string.Empty;
public string ResRobot { get; set; } = string.Empty;
}
public class EspConfig
{
public string InformationBoardImageUrl { get; set; } = string.Empty;
public int UpdateIntervalMinutes { get; set; } = 2;
public int BlackTextThreshold { get; set; } = 190; // (0-255)
public bool EnableDithering { get; set; } = true;
public int DitheringStrength { get; set; } = 8; // (8-32)
public bool EnhanceContrast { get; set; } = true;
public int ContrastStrength { get; set; } = 10; // (0-100)
public bool IsHighContrastMode { get; set; } = true;
}

View File

@@ -0,0 +1,12 @@
namespace HomeApi.Models;
public class MicroProcessorConfiguration
{
public string InformationBoardImageUrl { get; set; } = string.Empty;
public int UpdateIntervalMinutes { get; set; } = 2;
public int BlackTextThreshold { get; set; } = 190; // (0-255)
public bool EnableDithering { get; set; } = true;
public int DitheringStrength { get; set; } = 8; // (8-32)
public bool EnhanceContrast { get; set; } = true;
public int ContrastStrength { get; set; } = 10; // (0-100)
}

View File

@@ -13,11 +13,8 @@ var app = builder.Build();
app.UseStaticFiles();
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
app.MapOpenApi();
app.MapScalarApiReference();
app.UseHttpsRedirection();

View File

@@ -13,6 +13,16 @@
}
},
"ApiConfiguration": {
"EspConfiguration": {
"InformationBoardImageUrl": "http://192.168.101.178:5000/home/default.jpg",
"UpdateIntervalMinutes": 2,
"BlackTextThreshold": 190,
"EnableDithering": true,
"DitheringStrength": 8,
"EnhanceContrast": true,
"ContrastStrength": 10,
"IsHighContrastMode": true
},
"Keys": {
"Weather": "NOT COMMITED",
"ResRobot": "NOT COMMITED"

View File

@@ -13,6 +13,16 @@
}
},
"ApiConfiguration": {
"EspConfiguration": {
"InformationBoardImageUrl": "http://192.168.101.178:5000/home/default.jpg",
"UpdateIntervalMinutes": 2,
"BlackTextThreshold": 190,
"EnableDithering": true,
"DitheringStrength": 8,
"EnhanceContrast": true,
"ContrastStrength": 10,
"IsHighContrastMode": true
},
"Keys": {
"Weather": "NOT COMMITED",
"ResRobot": "NOT COMMITED"

View File

@@ -122,6 +122,11 @@
return map.TryGetValue(code, out var value) ? value : "fa-question-circle";
}
private static string UseHighContrast(bool isHighContrast)
{
return isHighContrast ? "high-contrast" : string.Empty;
}
}
<!DOCTYPE html>
@@ -143,6 +148,11 @@
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}
.high-contrast * {
color: hsl(0 0% 0%) !important;
border-color: hsl(0 0% 0%) !important;
}
/* Color Variables */
:root {
/* Base colors - Grayscale */
@@ -205,7 +215,7 @@
}
.location-icon {
color: hsl(0 85% 60%);
color: hsl(0 85% 60%) !important;
font-size: 14px;
}
@@ -256,24 +266,24 @@
}
.cloud-icon {
color: hsl(var(--weather-cloudy));
color: hsl(var(--weather-cloudy)) !important;
}
.wind-icon, .activity-icon {
color: hsl(0 85% 60%);
color: hsl(0 85% 60%) !important;
}
.aurora-icon {
color: hsl(var(--weather-aurora));
color: hsl(var(--weather-aurora)) !important;
}
.air-quality-badge {
background: hsl(var(--air-good));
color: white;
color: hsl(0, 0%, 100%) !important;
padding: 8px 16px;
border-radius: 20px;
font-size: 12px;
font-weight: 500;
font-weight: bolder;
text-align: center;
}
@@ -317,7 +327,7 @@
display: flex;
justify-content: center;
margin: 4px 0;
color: hsl(var(--weather));
color: hsl(var(--weather)) !important;
}
.forecast-condition {
@@ -383,11 +393,11 @@
}
.sunrise-icon, .sunset-icon {
color: hsl(0 85% 60%);
color: hsl(0 85% 60%) !important;
}
.moon-icon {
color: hsl(0 85% 60%);
color: hsl(0 85% 60%) !important;
}
/* Right Column - Transport */
@@ -425,7 +435,7 @@
}
.transport-color {
color: hsl(var(--transport-color));
color: hsl(var(--transport-color)) !important;
}
.transport-info {
@@ -472,7 +482,7 @@
</style>
</head>
<body>
<div class="weather-card">
<div class="weather-card @UseHighContrast(ViewBag.IsHighContrast)">
<!-- Left Column - Current Weather -->
<div class="current-weather">
<div class="location">
@@ -534,7 +544,7 @@
<div class="forecast-card">
<div class="forecast-date">@GetDayStatus(day.Date)</div>
<div class="forecast-icon">
<i class="fas fa-cloud @GetWeatherIcon(day.IconCode)"></i>
<i class="fas fa-cloud forecast-icon @GetWeatherIcon(day.IconCode)"></i>
</div>
<div class="forecast-condition">@(day.Day?.ConditionText ?? "Unspecified")</div>
<div class="forecast-temp">@day.MinTempC°/@day.MaxTempC°</div>
@@ -609,7 +619,7 @@
<div class="update-text">Last updated: <span id="current-time"></span></div>
</div>
</div>
</div>
</div>
<script>
// Update current time