Compare commits
25 Commits
add-image-
...
v0.0.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 58858700d9 | |||
| 2c86c7741d | |||
| fc52024d5a | |||
| d768b8ae3f | |||
| acd428ed9c | |||
| 3c6205c44d | |||
| acd16f3b5d | |||
| 65257303a8 | |||
| 5a6c715fd8 | |||
| 202c6fad1b | |||
| 337be8e534 | |||
| 44821fb465 | |||
| 58d50ecee2 | |||
| 98fb59a97b | |||
| 91cc89ac02 | |||
| dbf0d93d00 | |||
| c8e4a85296 | |||
| 6fd653b45d | |||
| 07c618d55d | |||
| 6077a6e14b | |||
| ba47856fbc | |||
| e21601234a | |||
| e9d145455e | |||
| c987a0bd58 | |||
| c0536d789b |
230
.github/workflows/build.yml
vendored
Normal file
230
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,230 @@
|
||||
name: Build and Deploy
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master # Change to your default branch if different
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
environment:
|
||||
description: 'Environment to deploy to'
|
||||
required: true
|
||||
default: 'prod'
|
||||
type: choice
|
||||
options:
|
||||
- prod
|
||||
- dev
|
||||
- test
|
||||
restart_iis:
|
||||
description: 'Restart IIS after deployment'
|
||||
required: true
|
||||
default: true
|
||||
type: boolean
|
||||
create_release:
|
||||
description: 'Create release'
|
||||
required: true
|
||||
default: true
|
||||
type: boolean
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: self-hosted # Ensure your self-hosted runner is configured
|
||||
environment: ${{ github.event.inputs.environment || 'prod' }}
|
||||
steps:
|
||||
- name: Get Current User
|
||||
run: |
|
||||
$env:USERNAME
|
||||
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0 # Fetches all history and tags for versioning
|
||||
|
||||
- name: Set up .NET
|
||||
uses: actions/setup-dotnet@v2
|
||||
with:
|
||||
dotnet-version: '9.0' # Change to your required .NET version
|
||||
|
||||
- name: Restore .NET Dependencies
|
||||
run: dotnet restore ./HomeApi.sln
|
||||
|
||||
- name: Build .NET Project
|
||||
run: dotnet build --configuration Release ./HomeApi/HomeApi.csproj
|
||||
|
||||
- name: Publish .NET Project
|
||||
run: |
|
||||
dotnet publish ./HomeApi/HomeApi.csproj --configuration Release --output ./output/dotnet --self-contained false --no-restore /p:PublishTrimmed=false /p:CopyOutputSymbolsToPublishDirectory=false
|
||||
|
||||
# Verify wwwroot was published
|
||||
if (Test-Path -Path "./output/dotnet/wwwroot") {
|
||||
Write-Host "wwwroot folder was published successfully"
|
||||
} else {
|
||||
Write-Host "WARNING: wwwroot folder was not found in published output!"
|
||||
}
|
||||
|
||||
# Check for Chrome-related files
|
||||
if (Test-Path -Path "./output/dotnet/Chrome") {
|
||||
Write-Host "Chrome folder was published successfully"
|
||||
} else {
|
||||
Write-Host "Chrome folder not found in published output"
|
||||
}
|
||||
|
||||
if (Test-Path -Path "./output/dotnet/ChromeHeadlessShell") {
|
||||
Write-Host "ChromeHeadlessShell was published successfully"
|
||||
} else {
|
||||
Write-Host "ChromeHeadlessShell not found in published output"
|
||||
}
|
||||
|
||||
- name: Generate SemVer version
|
||||
if: ${{ github.event.inputs.create_release != 'false' }}
|
||||
id: semver
|
||||
uses: ietf-tools/semver-action@v1
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
branch: master
|
||||
patchAll: true # Always increment patch number
|
||||
|
||||
- name: Create GitHub Release
|
||||
if: ${{ github.event.inputs.create_release != 'false' }}
|
||||
uses: actions/create-release@v1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
tag_name: ${{ steps.semver.outputs.next }}
|
||||
release_name: Release ${{ steps.semver.outputs.next }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
|
||||
- name: Generate appsettings.json
|
||||
run: |
|
||||
$appSettings = @{
|
||||
Logging = @{
|
||||
LogLevel = @{
|
||||
Default = "Information"
|
||||
"Microsoft.AspNetCore" = "Warning"
|
||||
}
|
||||
}
|
||||
ApiConfiguration = @{
|
||||
EspConfiguration = @{
|
||||
InformationBoardImageUrl = "${{ vars.ESP_IMAGE_URL }}"
|
||||
UpdateIntervalMinutes = [int]"${{ vars.ESP_UPDATE_INTERVAL }}"
|
||||
BlackTextThreshold = [int]"${{ vars.ESP_BLACK_TEXT_THRESHOLD }}"
|
||||
EnableDithering = [System.Convert]::ToBoolean("${{ vars.ESP_ENABLE_DITHERING }}")
|
||||
DitheringStrength = [int]"${{ vars.ESP_DITHERING_STRENGTH }}"
|
||||
EnhanceContrast = [System.Convert]::ToBoolean("${{ vars.ESP_ENHANCE_CONTRAST }}")
|
||||
ContrastStrength = [int]"${{ vars.ESP_CONTRAST_STRENGTH }}"
|
||||
IsHighContrastMode = [System.Convert]::ToBoolean("${{ vars.ESP_HIGH_CONTRAST_MODE }}")
|
||||
}
|
||||
Keys = @{
|
||||
Weather = "${{ secrets.WEATHER_API_KEY }}"
|
||||
ResRobot = "${{ secrets.RES_ROBOT_API_KEY }}"
|
||||
}
|
||||
BaseUrls = @{
|
||||
Nominatim = "${{ vars.NOMINATIM_URL }}"
|
||||
Aurora = "${{ vars.AURORA_URL }}"
|
||||
Weather = "${{ vars.WEATHER_URL }}"
|
||||
ResRobot = "${{ vars.RES_ROBOT_URL }}"
|
||||
}
|
||||
DefaultCity = "${{ vars.DEFAULT_CITY }}"
|
||||
DefaultStation = "${{ vars.DEFAULT_STATION }}"
|
||||
}
|
||||
AllowedHosts = "*"
|
||||
}
|
||||
|
||||
$appSettings | ConvertTo-Json -Depth 10 | Set-Content -Path "./output/dotnet/appsettings.json"
|
||||
Write-Host "Generated appsettings.json successfully"
|
||||
|
||||
# Check wwwroot and manually copy if missing
|
||||
- name: Ensure wwwroot is Included
|
||||
run: |
|
||||
if (-not (Test-Path -Path "./output/dotnet/wwwroot")) {
|
||||
Write-Host "wwwroot folder not found in published output, manually copying..."
|
||||
|
||||
# Check if wwwroot exists in project directory
|
||||
$sourceWwwroot = "./HomeApi/wwwroot"
|
||||
|
||||
if (Test-Path -Path $sourceWwwroot) {
|
||||
Write-Host "Found wwwroot directory in source, copying..."
|
||||
New-Item -ItemType Directory -Path "./output/dotnet/wwwroot" -Force
|
||||
Copy-Item -Path "$sourceWwwroot/*" -Destination "./output/dotnet/wwwroot" -Recurse -Force
|
||||
} else {
|
||||
Write-Host "WARNING: Could not find wwwroot in source directory!"
|
||||
}
|
||||
}
|
||||
|
||||
- name: Upload Artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dotnet-artifacts
|
||||
path: ./output/dotnet
|
||||
|
||||
deploy:
|
||||
runs-on: self-hosted # Ensure your self-hosted runner is configured
|
||||
needs: build
|
||||
environment: ${{ github.event.inputs.environment || 'prod' }}
|
||||
|
||||
steps:
|
||||
- name: Download .NET Artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: dotnet-artifacts
|
||||
path: ./output/dotnet
|
||||
|
||||
- name: Stop IIS Application Pool
|
||||
run: |
|
||||
Import-Module WebAdministration
|
||||
$appPoolName = "${{ vars.IIS_APP_POOL_NAME }}"
|
||||
if ([string]::IsNullOrEmpty($appPoolName)) {
|
||||
$appPoolName = "HomeApi"
|
||||
}
|
||||
|
||||
Write-Host "Stopping application pool: $appPoolName"
|
||||
|
||||
# Check if app pool exists
|
||||
if (Test-Path "IIS:\AppPools\$appPoolName") {
|
||||
# Stop app pool
|
||||
if ((Get-WebAppPoolState -Name $appPoolName).Value -ne "Stopped") {
|
||||
Stop-WebAppPool -Name $appPoolName
|
||||
Start-Sleep -Seconds 5 # Give it time to fully stop
|
||||
Write-Host "Application pool stopped successfully"
|
||||
} else {
|
||||
Write-Host "Application pool was already stopped"
|
||||
}
|
||||
} else {
|
||||
Write-Host "Warning: Application pool '$appPoolName' not found. Will attempt to copy files anyway."
|
||||
}
|
||||
|
||||
- name: Copy .NET Publish Files to IIS Server
|
||||
run: |
|
||||
# Ensure destination directory exists
|
||||
if (-not (Test-Path "C:\inetpub\applications\HomeApi")) {
|
||||
New-Item -ItemType Directory -Path "C:\inetpub\applications\HomeApi" -Force
|
||||
Write-Host "Created destination directory"
|
||||
}
|
||||
|
||||
# Copy files
|
||||
Write-Host "Copying files to destination..."
|
||||
Copy-Item -Path ".\output\dotnet\*" -Destination "C:\inetpub\applications\HomeApi" -Recurse -Force
|
||||
Write-Host "Files copied successfully"
|
||||
|
||||
- name: Restart IIS Application Pool
|
||||
if: ${{ github.event.inputs.restart_iis != 'false' }}
|
||||
run: |
|
||||
Import-Module WebAdministration
|
||||
$appPoolName = "${{ vars.IIS_APP_POOL_NAME }}"
|
||||
if ([string]::IsNullOrEmpty($appPoolName)) {
|
||||
$appPoolName = "HomeApi"
|
||||
}
|
||||
|
||||
Write-Host "Starting application pool: $appPoolName"
|
||||
|
||||
# Check if app pool exists
|
||||
if (Test-Path "IIS:\AppPools\$appPoolName") {
|
||||
# Start app pool
|
||||
Start-WebAppPool -Name $appPoolName
|
||||
Write-Host "Application pool started successfully"
|
||||
} else {
|
||||
Write-Host "Warning: Application pool '$appPoolName' not found. Using IISReset instead."
|
||||
iisreset /restart
|
||||
Write-Host "IIS restarted successfully"
|
||||
}
|
||||
157
Esp32_Code/ESPSCREEN/ESPSCREEN.ino
Normal file
157
Esp32_Code/ESPSCREEN/ESPSCREEN.ino
Normal file
@@ -0,0 +1,157 @@
|
||||
#include <WiFi.h>
|
||||
#include "EPD.h"
|
||||
#include "DEV_Config.h"
|
||||
#include "GUI_Paint.h"
|
||||
|
||||
// — Wi-Fi & image endpoint ———————————————————————————————
|
||||
const char* ssid = "x";
|
||||
const char* password = "x";
|
||||
const char* HOST = "192.168.x.x";
|
||||
const uint16_t PORT = 5000;
|
||||
const char* PATH = "/Home/default.bmp";
|
||||
|
||||
// — Framebuffers for black & red ——————————————————————————————
|
||||
UBYTE *BlackImage = nullptr;
|
||||
UBYTE *RYImage = nullptr;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
DEV_Module_Init();
|
||||
|
||||
// 1) Allocate framebuffers
|
||||
const int W = EPD_7IN5B_V2_WIDTH;
|
||||
const int H = EPD_7IN5B_V2_HEIGHT;
|
||||
size_t bufSize = ((W + 7) / 8) * H;
|
||||
BlackImage = (UBYTE*)malloc(bufSize);
|
||||
RYImage = (UBYTE*)malloc(bufSize);
|
||||
if (!BlackImage || !RYImage) {
|
||||
Serial.println("ERROR: not enough RAM"); while(1) delay(1000);
|
||||
}
|
||||
|
||||
// 2) Wi-Fi connect
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.print("Wi-Fi connecting");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500); Serial.print(".");
|
||||
}
|
||||
Serial.println(" ✅");
|
||||
Serial.print("ESP32 IP = "); Serial.println(WiFi.localIP());
|
||||
|
||||
// 3) Prepare white canvases
|
||||
Paint_NewImage(BlackImage, W, H, 0, WHITE);
|
||||
Paint_NewImage(RYImage, W, H, 0, WHITE);
|
||||
Paint_SelectImage(BlackImage); Paint_Clear(WHITE);
|
||||
Paint_SelectImage(RYImage); Paint_Clear(WHITE);
|
||||
|
||||
// 4) Manual HTTP GET via WiFiClient
|
||||
{
|
||||
WiFiClient client;
|
||||
Serial.printf("Connecting to %s:%u …", HOST, PORT);
|
||||
if (!client.connect(HOST, PORT)) {
|
||||
Serial.println(" FAILED");
|
||||
} else {
|
||||
Serial.println(" OK");
|
||||
|
||||
// Send the GET request
|
||||
client.printf("GET %s HTTP/1.1\r\n", PATH);
|
||||
client.printf("Host: %s\r\n", HOST);
|
||||
client.print ("Connection: close\r\n\r\n");
|
||||
|
||||
// Wait up to 15 s for the first byte
|
||||
uint32_t start = millis();
|
||||
while (!client.available() && millis() - start < 15000) {
|
||||
delay(10);
|
||||
}
|
||||
|
||||
if (!client.available()) {
|
||||
Serial.println("No response—timeout");
|
||||
} else {
|
||||
Serial.println("Received response, parsing…");
|
||||
|
||||
// ✅ 4.1 Read and parse status line
|
||||
String statusLine = client.readStringUntil('\n');
|
||||
Serial.print("HTTP Status Line: ");
|
||||
Serial.println(statusLine);
|
||||
|
||||
int statusCode = statusLine.substring(9, 12).toInt(); // "HTTP/1.1 200 OK"
|
||||
if (statusCode != 200) {
|
||||
Serial.printf("❌ HTTP Error: %d\n", statusCode);
|
||||
client.stop();
|
||||
return;
|
||||
}
|
||||
|
||||
// ✅ 4.2 Skip the remaining HTTP headers
|
||||
while (client.available()) {
|
||||
String line = client.readStringUntil('\n');
|
||||
if (line == "\r" || line == "") break; // End of headers
|
||||
}
|
||||
|
||||
// ✅ Continue with BMP header reading...
|
||||
// 4.3 Read BMP header
|
||||
uint8_t header[54];
|
||||
client.readBytes(header, 54);
|
||||
uint32_t dataOffset =
|
||||
uint32_t(header[10])
|
||||
| (uint32_t(header[11]) << 8)
|
||||
| (uint32_t(header[12]) << 16)
|
||||
| (uint32_t(header[13]) << 24);
|
||||
|
||||
// 4.3 Skip any extra header padding
|
||||
if (dataOffset > 54) {
|
||||
uint32_t toSkip = dataOffset - 54;
|
||||
uint8_t dum[32];
|
||||
while (toSkip) {
|
||||
size_t chunk = toSkip > sizeof(dum) ? sizeof(dum) : toSkip;
|
||||
client.readBytes(dum, chunk);
|
||||
toSkip -= chunk;
|
||||
}
|
||||
}
|
||||
|
||||
// 4.4 Decode bottom-up, line by line
|
||||
int rowSize = ((W * 3 + 3) / 4) * 4;
|
||||
uint8_t *rowBuf = (uint8_t*)malloc(rowSize);
|
||||
if (!rowBuf) {
|
||||
Serial.println("ERROR: rowBuf malloc failed");
|
||||
}
|
||||
else {
|
||||
for (int y = H - 1; y >= 0; y--) {
|
||||
client.readBytes(rowBuf, rowSize);
|
||||
|
||||
uint8_t mask = 0x80;
|
||||
uint32_t idx = (y * W) / 8;
|
||||
for (int x = 0; x < W; x++) {
|
||||
uint8_t b = rowBuf[x*3 + 0];
|
||||
uint8_t g = rowBuf[x*3 + 1];
|
||||
uint8_t r = rowBuf[x*3 + 2];
|
||||
|
||||
bool isRed = (r > 150 && g < 80 && b < 80);
|
||||
bool isBlack = (!isRed && ((r+g+b)/3 < 180));
|
||||
if (isRed) RYImage[idx] &= ~mask;
|
||||
if (isBlack) BlackImage[idx] &= ~mask;
|
||||
|
||||
mask >>= 1;
|
||||
if (!mask) { mask = 0x80; idx++; }
|
||||
}
|
||||
}
|
||||
free(rowBuf);
|
||||
Serial.println("BMP decoded successfully!");
|
||||
}
|
||||
}
|
||||
client.stop();
|
||||
}
|
||||
}
|
||||
|
||||
// 5) Display on the e-ink
|
||||
EPD_7IN5B_V2_Init();
|
||||
EPD_7IN5B_V2_Display(BlackImage, RYImage);
|
||||
DEV_Delay_ms(2000);
|
||||
EPD_7IN5B_V2_Sleep();
|
||||
|
||||
// 6) Clean up
|
||||
free(BlackImage);
|
||||
free(RYImage);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// nothing
|
||||
}
|
||||
544
Esp32_Code/INFOSCREEN_WITH_INTERVAL/INFOSCREEN_WITH_INTERVAL.ino
Normal file
544
Esp32_Code/INFOSCREEN_WITH_INTERVAL/INFOSCREEN_WITH_INTERVAL.ino
Normal file
@@ -0,0 +1,544 @@
|
||||
#include <WiFi.h>
|
||||
#include <HTTPClient.h>
|
||||
#include <stdint.h>
|
||||
#include "DEV_Config.h"
|
||||
#include "EPD.h"
|
||||
#include "GUI_Paint.h"
|
||||
#include <ArduinoJson.h>
|
||||
#include <JPEGDEC.h>
|
||||
|
||||
// WiFi credentials
|
||||
const char* ssid = "x";
|
||||
const char* password = "x";
|
||||
|
||||
// API endpoints
|
||||
const char* connectionInformation = "http://x/home/configuration";
|
||||
|
||||
// These will be updated from the connection information
|
||||
String imageUrl = ""; // Will be populated from JSON
|
||||
uint64_t sleepDuration = 30e6; // Default 30 seconds in microseconds
|
||||
|
||||
// Display dimensions - use the constants from Waveshare library
|
||||
#define EPD_WIDTH EPD_7IN5B_V2_WIDTH
|
||||
#define EPD_HEIGHT EPD_7IN5B_V2_HEIGHT
|
||||
|
||||
// =========== IMAGE TUNING PARAMETERS ===========
|
||||
// These will be updated from the configuration
|
||||
uint8_t blackTextThreshold = 190; // Default (0-255)
|
||||
bool enableDithering = true; // Default
|
||||
uint8_t ditherStrength = 8; // Default (8-32)
|
||||
bool enhanceContrast = true; // Default
|
||||
uint8_t contrastLevel = 30; // Default (0-100)
|
||||
// ===============================================
|
||||
|
||||
// Framebuffers for black and red layers
|
||||
UBYTE *BlackImage, *RYImage;
|
||||
|
||||
// Error buffers for dithering
|
||||
int16_t *errorR = NULL;
|
||||
int16_t *errorG = NULL;
|
||||
int16_t *errorB = NULL;
|
||||
|
||||
// Create an instance of the JPEG decoder
|
||||
JPEGDEC jpeg;
|
||||
|
||||
// Apply contrast adjustment to RGB values
|
||||
void adjustContrast(uint8_t *r, uint8_t *g, uint8_t *b) {
|
||||
if (!enhanceContrast) return;
|
||||
|
||||
float contrast = (contrastLevel / 100.0) + 1.0; // Convert to decimal & shift range: [0..2]
|
||||
float intercept = 128 * (1 - contrast);
|
||||
|
||||
*r = constrain((*r * contrast) + intercept, 0, 255);
|
||||
*g = constrain((*g * contrast) + intercept, 0, 255);
|
||||
*b = constrain((*b * contrast) + intercept, 0, 255);
|
||||
}
|
||||
|
||||
// JPEG draw callback function for JPEGDEC
|
||||
int jpegDrawCallback(JPEGDRAW *pDraw) {
|
||||
// Get MCU block information
|
||||
uint16_t *pPixels = pDraw->pPixels;
|
||||
int x = pDraw->x;
|
||||
int y = pDraw->y;
|
||||
int width = pDraw->iWidth;
|
||||
int height = pDraw->iHeight;
|
||||
|
||||
// Initialize error buffers for dithering if needed
|
||||
if (enableDithering && errorR == NULL) {
|
||||
errorR = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t));
|
||||
errorG = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t));
|
||||
errorB = (int16_t*)malloc(EPD_WIDTH * sizeof(int16_t));
|
||||
|
||||
if (errorR && errorG && errorB) {
|
||||
memset(errorR, 0, EPD_WIDTH * sizeof(int16_t));
|
||||
memset(errorG, 0, EPD_WIDTH * sizeof(int16_t));
|
||||
memset(errorB, 0, EPD_WIDTH * sizeof(int16_t));
|
||||
} else {
|
||||
Serial.println("Failed to allocate dithering buffers");
|
||||
if (errorR) free(errorR);
|
||||
if (errorG) free(errorG);
|
||||
if (errorB) free(errorB);
|
||||
errorR = errorG = errorB = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
// Process each row in this MCU block
|
||||
for (int iy = 0; iy < height; iy++) {
|
||||
// Reset error buffers for each row
|
||||
if (enableDithering && errorR != NULL) {
|
||||
memset(errorR, 0, EPD_WIDTH * sizeof(int16_t));
|
||||
memset(errorG, 0, EPD_WIDTH * sizeof(int16_t));
|
||||
memset(errorB, 0, EPD_WIDTH * sizeof(int16_t));
|
||||
}
|
||||
|
||||
// Process each pixel in the row
|
||||
for (int ix = 0; ix < width; ix++) {
|
||||
int pos_x = x + ix;
|
||||
int pos_y = y + iy;
|
||||
|
||||
// Skip if outside display bounds
|
||||
if (pos_x >= EPD_WIDTH || pos_y >= EPD_HEIGHT) continue;
|
||||
|
||||
// Get the 16-bit pixel value (RGB565)
|
||||
uint16_t pixel = pPixels[iy * width + ix];
|
||||
|
||||
// Extract RGB components (565 format) and convert to 0-255 range
|
||||
uint8_t r = ((pixel >> 11) & 0x1F) << 3;
|
||||
uint8_t g = ((pixel >> 5) & 0x3F) << 2;
|
||||
uint8_t b = (pixel & 0x1F) << 3;
|
||||
|
||||
// Apply contrast adjustment if enabled
|
||||
if (enhanceContrast) {
|
||||
adjustContrast(&r, &g, &b);
|
||||
}
|
||||
|
||||
// Apply dithering errors if enabled
|
||||
if (enableDithering && errorR != NULL) {
|
||||
r = constrain(r + (errorR[pos_x] / ditherStrength), 0, 255);
|
||||
g = constrain(g + (errorG[pos_x] / ditherStrength), 0, 255);
|
||||
b = constrain(b + (errorB[pos_x] / ditherStrength), 0, 255);
|
||||
}
|
||||
|
||||
// Calculate grayscale value
|
||||
float gray = (r * 0.299 + g * 0.587 + b * 0.114);
|
||||
|
||||
// ===== IMPROVED COLOR CLASSIFICATION LOGIC =====
|
||||
// Variable for final color (0=black, 1=white, 2=red)
|
||||
int finalColor;
|
||||
|
||||
// Check for "redness" - how much stronger red is than other components
|
||||
float redness = r / (float)(g + b + 1); // Add 1 to avoid division by zero
|
||||
|
||||
// Check if this is likely a red pixel based on redness
|
||||
if (r > 100 && redness > 1.5) {
|
||||
finalColor = 2; // Red
|
||||
}
|
||||
// If not red, determine if it's black or white based on grayscale
|
||||
else if (gray < blackTextThreshold) {
|
||||
finalColor = 0; // Black
|
||||
}
|
||||
else {
|
||||
finalColor = 1; // White
|
||||
}
|
||||
|
||||
// Determine target colors for error calculation
|
||||
uint8_t targetR, targetG, targetB;
|
||||
|
||||
switch (finalColor) {
|
||||
case 0: // Black
|
||||
targetR = targetG = targetB = 0;
|
||||
break;
|
||||
case 2: // Red
|
||||
targetR = 255;
|
||||
targetG = targetB = 0;
|
||||
break;
|
||||
default: // White
|
||||
targetR = targetG = targetB = 255;
|
||||
break;
|
||||
}
|
||||
|
||||
// Calculate and distribute dithering errors
|
||||
if (enableDithering && errorR != NULL) {
|
||||
int16_t err_r = r - targetR;
|
||||
int16_t err_g = g - targetG;
|
||||
int16_t err_b = b - targetB;
|
||||
|
||||
// Floyd-Steinberg dithering pattern
|
||||
if (pos_x + 1 < EPD_WIDTH) {
|
||||
// Right pixel (7/16)
|
||||
errorR[pos_x + 1] += (err_r * 7) >> 4;
|
||||
errorG[pos_x + 1] += (err_g * 7) >> 4;
|
||||
errorB[pos_x + 1] += (err_b * 7) >> 4;
|
||||
}
|
||||
|
||||
if (pos_x > 0 && pos_x + 1 < EPD_WIDTH) {
|
||||
errorR[pos_x - 1] += (err_r * 3) >> 4; // left-down (3/16)
|
||||
errorG[pos_x - 1] += (err_g * 3) >> 4;
|
||||
errorB[pos_x - 1] += (err_b * 3) >> 4;
|
||||
|
||||
errorR[pos_x] += (err_r * 5) >> 4; // down (5/16)
|
||||
errorG[pos_x] += (err_g * 5) >> 4;
|
||||
errorB[pos_x] += (err_b * 5) >> 4;
|
||||
|
||||
errorR[pos_x + 1] += (err_r * 1) >> 4; // right-down (1/16)
|
||||
errorG[pos_x + 1] += (err_g * 1) >> 4;
|
||||
errorB[pos_x + 1] += (err_b * 1) >> 4;
|
||||
}
|
||||
}
|
||||
|
||||
// Draw the pixel based on the final color
|
||||
switch (finalColor) {
|
||||
case 0: // Black
|
||||
Paint_SelectImage(BlackImage);
|
||||
Paint_SetPixel(pos_x, pos_y, BLACK);
|
||||
Paint_SelectImage(RYImage);
|
||||
Paint_SetPixel(pos_x, pos_y, WHITE);
|
||||
break;
|
||||
|
||||
case 2: // Red
|
||||
Paint_SelectImage(BlackImage);
|
||||
Paint_SetPixel(pos_x, pos_y, WHITE);
|
||||
Paint_SelectImage(RYImage);
|
||||
Paint_SetPixel(pos_x, pos_y, BLACK); // BLACK in RY buffer = RED
|
||||
break;
|
||||
|
||||
default: // White
|
||||
Paint_SelectImage(BlackImage);
|
||||
Paint_SetPixel(pos_x, pos_y, WHITE);
|
||||
Paint_SelectImage(RYImage);
|
||||
Paint_SetPixel(pos_x, pos_y, WHITE);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 1; // Continue decoding
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Serial.println("E-Ink Display Initialization");
|
||||
|
||||
// Calculate buffer size as in Waveshare example
|
||||
UWORD Imagesize = ((EPD_WIDTH % 8 == 0) ? (EPD_WIDTH / 8) : (EPD_WIDTH / 8 + 1)) * EPD_HEIGHT;
|
||||
|
||||
// Allocate framebuffers
|
||||
BlackImage = (UBYTE *)malloc(Imagesize);
|
||||
RYImage = (UBYTE *)malloc(Imagesize);
|
||||
|
||||
if ((BlackImage == NULL) || (RYImage == NULL)) {
|
||||
Serial.println("Failed to allocate memory for framebuffers!");
|
||||
while(1); // Halt if memory allocation fails
|
||||
}
|
||||
|
||||
// Initialize e-ink display exactly as in Waveshare example
|
||||
DEV_Module_Init();
|
||||
EPD_7IN5B_V2_Init();
|
||||
// EPD_7IN5B_V2_Clear();
|
||||
DEV_Delay_ms(500);
|
||||
|
||||
// Initialize the Paint library with the buffers
|
||||
Paint_NewImage(BlackImage, EPD_WIDTH, EPD_HEIGHT, 0, WHITE);
|
||||
Paint_NewImage(RYImage, EPD_WIDTH, EPD_HEIGHT, 0, WHITE);
|
||||
|
||||
Serial.println("Buffers allocated and cleared");
|
||||
|
||||
// Connect to WiFi
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.print("Connecting to WiFi");
|
||||
int wifiAttempts = 0;
|
||||
while (WiFi.status() != WL_CONNECTED && wifiAttempts < 20) {
|
||||
delay(500);
|
||||
Serial.print(".");
|
||||
wifiAttempts++;
|
||||
}
|
||||
|
||||
if (WiFi.status() == WL_CONNECTED) {
|
||||
Serial.println();
|
||||
Serial.println("WiFi connected");
|
||||
Serial.print("IP address: ");
|
||||
Serial.println(WiFi.localIP());
|
||||
} else {
|
||||
Serial.println();
|
||||
Serial.println("WiFi connection failed!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Test connectivity to server and get configuration
|
||||
Serial.println("Fetching connection information...");
|
||||
if (fetchConnectionInformation()) {
|
||||
// Fetch and display image
|
||||
fetchAndDisplayImage();
|
||||
} else {
|
||||
Serial.println("Server connectivity test failed - skipping image fetch");
|
||||
}
|
||||
|
||||
// Free dithering buffers if allocated
|
||||
if (errorR) free(errorR);
|
||||
if (errorG) free(errorG);
|
||||
if (errorB) free(errorB);
|
||||
errorR = errorG = errorB = NULL;
|
||||
|
||||
// Put display to sleep
|
||||
EPD_7IN5B_V2_Sleep();
|
||||
|
||||
// Free framebuffers
|
||||
free(BlackImage);
|
||||
free(RYImage);
|
||||
BlackImage = NULL;
|
||||
RYImage = NULL;
|
||||
|
||||
// Enter deep sleep
|
||||
Serial.print("Going to sleep for ");
|
||||
Serial.print(sleepDuration / 60000000);
|
||||
Serial.println(" minutes");
|
||||
esp_sleep_enable_timer_wakeup(sleepDuration);
|
||||
esp_deep_sleep_start();
|
||||
}
|
||||
|
||||
bool fetchConnectionInformation() {
|
||||
HTTPClient http;
|
||||
http.begin(connectionInformation);
|
||||
http.setTimeout(10000);
|
||||
|
||||
int httpCode = http.GET();
|
||||
|
||||
Serial.print("HTTP response code: ");
|
||||
Serial.println(httpCode);
|
||||
|
||||
// Handle the response payload
|
||||
String payload = "";
|
||||
|
||||
if (httpCode == HTTP_CODE_OK) {
|
||||
payload = http.getString();
|
||||
|
||||
// Debug output to show the exact response
|
||||
Serial.println("-----RAW HTTP RESPONSE BEGIN-----");
|
||||
Serial.println(payload);
|
||||
Serial.println("-----RAW HTTP RESPONSE END-----");
|
||||
|
||||
// Check if payload is empty
|
||||
if (payload.length() == 0) {
|
||||
Serial.println("Warning: Server returned empty response");
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Try to find JSON content in the response
|
||||
int jsonStart = payload.indexOf('{');
|
||||
int jsonEnd = payload.lastIndexOf('}');
|
||||
|
||||
if (jsonStart >= 0 && jsonEnd >= 0 && jsonEnd > jsonStart) {
|
||||
String jsonPayload = payload.substring(jsonStart, jsonEnd + 1);
|
||||
Serial.println("-----EXTRACTED JSON BEGIN-----");
|
||||
Serial.println(jsonPayload);
|
||||
Serial.println("-----EXTRACTED JSON END-----");
|
||||
|
||||
// Deserialize the JSON document - Increased buffer size for more parameters
|
||||
StaticJsonDocument<768> doc;
|
||||
DeserializationError error = deserializeJson(doc, jsonPayload);
|
||||
if (error) {
|
||||
Serial.print("JSON parsing failed: ");
|
||||
Serial.println(error.c_str());
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Extract values from the JSON
|
||||
if (doc.containsKey("informationBoardImageUrl")) {
|
||||
imageUrl = doc["informationBoardImageUrl"].as<String>();
|
||||
Serial.print("Image URL set to: ");
|
||||
Serial.println(imageUrl);
|
||||
} else {
|
||||
Serial.println("Warning: informationBoardImageUrl not found in JSON");
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (doc.containsKey("updateIntervalMinutes")) {
|
||||
int minutes = doc["updateIntervalMinutes"].as<int>();
|
||||
sleepDuration = (uint64_t)minutes * 60 * 1000000; // Convert minutes to microseconds
|
||||
Serial.print("Update interval set to: ");
|
||||
Serial.print(minutes);
|
||||
Serial.println(" minutes");
|
||||
} else {
|
||||
Serial.println("Warning: updateIntervalMinutes not found in JSON");
|
||||
// Keep default sleep duration
|
||||
}
|
||||
|
||||
// Extract new image processing parameters
|
||||
if (doc.containsKey("blackTextThreshold")) {
|
||||
blackTextThreshold = doc["blackTextThreshold"].as<uint8_t>();
|
||||
Serial.print("Black text threshold set to: ");
|
||||
Serial.println(blackTextThreshold);
|
||||
}
|
||||
|
||||
if (doc.containsKey("enableDithering")) {
|
||||
enableDithering = doc["enableDithering"].as<bool>();
|
||||
Serial.print("Dithering enabled: ");
|
||||
Serial.println(enableDithering ? "true" : "false");
|
||||
}
|
||||
|
||||
if (doc.containsKey("ditheringStrength")) {
|
||||
ditherStrength = doc["ditheringStrength"].as<uint8_t>();
|
||||
Serial.print("Dithering strength set to: ");
|
||||
Serial.println(ditherStrength);
|
||||
}
|
||||
|
||||
if (doc.containsKey("enhanceContrast")) {
|
||||
enhanceContrast = doc["enhanceContrast"].as<bool>();
|
||||
Serial.print("Contrast enhancement enabled: ");
|
||||
Serial.println(enhanceContrast ? "true" : "false");
|
||||
}
|
||||
|
||||
if (doc.containsKey("contrastStrength")) {
|
||||
contrastLevel = doc["contrastStrength"].as<uint8_t>();
|
||||
Serial.print("Contrast level set to: ");
|
||||
Serial.println(contrastLevel);
|
||||
}
|
||||
|
||||
http.end();
|
||||
return true;
|
||||
} else {
|
||||
Serial.println("No valid JSON object found in the response");
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
Serial.print("HTTP request failed with code: ");
|
||||
Serial.println(httpCode);
|
||||
http.end();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void fetchAndDisplayImage() {
|
||||
// Check WiFi connection before making HTTP request
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
Serial.println("WiFi not connected, cannot fetch image");
|
||||
return;
|
||||
}
|
||||
|
||||
if (imageUrl.length() == 0) {
|
||||
Serial.println("Image URL not set, cannot fetch image");
|
||||
return;
|
||||
}
|
||||
|
||||
HTTPClient http;
|
||||
http.begin(imageUrl);
|
||||
http.setTimeout(30000); // Set 30 second timeout
|
||||
http.addHeader("User-Agent", "ESP32");
|
||||
|
||||
Serial.print("Starting HTTP GET for image: ");
|
||||
Serial.println(imageUrl);
|
||||
int httpCode = http.GET();
|
||||
Serial.print("HTTP response code: ");
|
||||
Serial.println(httpCode);
|
||||
|
||||
if (httpCode == HTTP_CODE_OK) {
|
||||
int len = http.getSize();
|
||||
Serial.print("Content length: ");
|
||||
Serial.println(len);
|
||||
|
||||
if (len > 0) {
|
||||
Serial.print("Free heap before allocation: ");
|
||||
Serial.println(ESP.getFreeHeap());
|
||||
|
||||
// Check if we have enough memory
|
||||
if (ESP.getFreeHeap() < len + 10000) { // Keep 10KB buffer
|
||||
Serial.println("Not enough memory to load image");
|
||||
http.end();
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t *buffer = (uint8_t*)malloc(len);
|
||||
if (buffer) {
|
||||
Serial.print("Allocated ");
|
||||
Serial.print(len);
|
||||
Serial.println(" bytes for image buffer.");
|
||||
|
||||
// Clear both buffers before processing new image - USING PAINT LIBRARY
|
||||
Paint_SelectImage(BlackImage);
|
||||
Paint_Clear(WHITE);
|
||||
Paint_SelectImage(RYImage);
|
||||
Paint_Clear(WHITE);
|
||||
|
||||
WiFiClient *stream = http.getStreamPtr();
|
||||
int totalBytesRead = 0;
|
||||
unsigned long timeout = millis() + 30000; // 30 second timeout for reading
|
||||
while (totalBytesRead < len && millis() < timeout) {
|
||||
int bytesRead = stream->readBytes(buffer + totalBytesRead, len - totalBytesRead);
|
||||
if (bytesRead == 0) {
|
||||
delay(5); // Short delay if no data available
|
||||
if (stream->available() == 0) {
|
||||
if (totalBytesRead < len) {
|
||||
Serial.println("Stream ended prematurely.");
|
||||
}
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
totalBytesRead += bytesRead;
|
||||
}
|
||||
}
|
||||
Serial.print("Total bytes read: ");
|
||||
Serial.println(totalBytesRead);
|
||||
|
||||
if (totalBytesRead == len) {
|
||||
// Process and display the image using JPEGDEC
|
||||
Serial.println("Decoding JPEG image...");
|
||||
|
||||
// Open JPEG image from memory
|
||||
if (jpeg.openRAM(buffer, len, jpegDrawCallback)) {
|
||||
// Get information about the image
|
||||
int jpegWidth = jpeg.getWidth();
|
||||
int jpegHeight = jpeg.getHeight();
|
||||
Serial.print("JPEG image dimensions: ");
|
||||
Serial.print(jpegWidth);
|
||||
Serial.print(" x ");
|
||||
Serial.println(jpegHeight);
|
||||
|
||||
// Decode the image
|
||||
if (jpeg.decode(0, 0, 0)) {
|
||||
Serial.println("JPEG image decoded successfully");
|
||||
} else {
|
||||
Serial.println("Error decoding JPEG image");
|
||||
}
|
||||
|
||||
// Close the file
|
||||
jpeg.close();
|
||||
|
||||
// Display the processed image - using Waveshare's function
|
||||
Serial.println("Sending image to display...");
|
||||
EPD_7IN5B_V2_Display(BlackImage, RYImage);
|
||||
Serial.println("Image displayed successfully.");
|
||||
} else {
|
||||
Serial.println("Failed to open JPEG image");
|
||||
}
|
||||
} else {
|
||||
Serial.println("Failed to read entire image.");
|
||||
}
|
||||
free(buffer);
|
||||
} else {
|
||||
Serial.println("Failed to allocate buffer!");
|
||||
}
|
||||
} else {
|
||||
Serial.println("Content length unknown or invalid.");
|
||||
}
|
||||
} else if (httpCode == HTTPC_ERROR_CONNECTION_REFUSED) {
|
||||
Serial.println("Connection refused - server may be down");
|
||||
} else if (httpCode == HTTPC_ERROR_CONNECTION_LOST) {
|
||||
Serial.println("Connection lost during request");
|
||||
} else if (httpCode == HTTPC_ERROR_NO_HTTP_SERVER) {
|
||||
Serial.println("No HTTP server found");
|
||||
} else if (httpCode == HTTPC_ERROR_NOT_CONNECTED) {
|
||||
Serial.println("Not connected to server");
|
||||
} else {
|
||||
Serial.printf("HTTP GET failed, error: %d\n", httpCode);
|
||||
}
|
||||
|
||||
http.end();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Empty - using deep sleep instead
|
||||
}
|
||||
@@ -7,6 +7,12 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HomeApi", "HomeApi\HomeApi.csproj", "{0F340BDE-7B8E-4ACD-8A24-5B5BFFB424F4}"
|
||||
EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "ESP32_CODE", "ESP32_CODE", "{B3BCE85B-5021-4D4D-8758-CA7AAFF86C2D}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
Esp32_Code\ESPSCREEN\ESPSCREEN.ino = Esp32_Code\ESPSCREEN\ESPSCREEN.ino
|
||||
Esp32_Code\INFOSCREEN_WITH_INTERVAL\INFOSCREEN_WITH_INTERVAL.ino = Esp32_Code\INFOSCREEN_WITH_INTERVAL\INFOSCREEN_WITH_INTERVAL.ino
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -20,5 +26,6 @@ Global
|
||||
EndGlobalSection
|
||||
GlobalSection(NestedProjects) = preSolution
|
||||
{0F340BDE-7B8E-4ACD-8A24-5B5BFFB424F4} = {FF03E920-D5E9-4BE0-AA6F-DB2E9287D3E4}
|
||||
{B3BCE85B-5021-4D4D-8758-CA7AAFF86C2D} = {FF03E920-D5E9-4BE0-AA6F-DB2E9287D3E4}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
|
||||
@@ -6,13 +6,30 @@ 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()
|
||||
{
|
||||
var result = await mediator.Send(new GetWeather.Command());
|
||||
return Ok(result);
|
||||
return Ok(await mediator.Send(new Weather.Command()));
|
||||
}
|
||||
|
||||
[HttpGet("default.jpg")]
|
||||
public async Task<IActionResult> GetImage()
|
||||
{
|
||||
return File(await mediator.Send(new ImageGeneration.Command()), "image/jpeg");
|
||||
}
|
||||
|
||||
[HttpGet("configuration")]
|
||||
public async Task<ActionResult<MicroProcessorConfiguration>> GetCombinedBuffers()
|
||||
{
|
||||
return Ok(await mediator.Send(new Configuration.Command()));
|
||||
}
|
||||
|
||||
[HttpGet("departure-board")]
|
||||
public async Task<ActionResult<List<TimeTable>>> GetDepartureBoard()
|
||||
{
|
||||
return Ok(await mediator.Send(new DepartureBoard.Command()));
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,8 @@ public static class ContractExtensions
|
||||
So2 = weather.Current.Air_Quality.So2, // Sulfur Dioxide
|
||||
Pm10 = weather.Current.Air_Quality.Pm10, // Particulate Matter 10 micrometers or less
|
||||
Pm2_5 = weather.Current.Air_Quality.Pm2_5, // Particulate Matter 2.5 micrometers or less
|
||||
Us_Epa_Index = weather.Current.Air_Quality.Us_Epa_Index, // US EPA Air Quality Index
|
||||
Gb_Defra_Index = weather.Current.Air_Quality.Gb_Defra_Index, // UK DEFRA Air Quality Index
|
||||
},
|
||||
AuroraProbability = new Probability
|
||||
{
|
||||
@@ -96,6 +98,8 @@ public static class ContractExtensions
|
||||
MaxTempC = day.Day.Maxtemp_C,
|
||||
MinTempC = day.Day.Mintemp_C,
|
||||
DayIcon = day.Day.Condition.Icon,
|
||||
IconCode = day.Day.Condition.Code,
|
||||
ChanceOfRain = day.Day.Daily_Chance_Of_Rain,
|
||||
Astro = new Models.Astro
|
||||
{
|
||||
Moon_Illumination = day.Astro.Moon_Illumination,
|
||||
@@ -126,4 +130,23 @@ public static class ContractExtensions
|
||||
};
|
||||
}
|
||||
|
||||
public static List<TimeTable>? ToContract(this TrafikLabsApiResponse response)
|
||||
{
|
||||
if (response?.Departure is null)
|
||||
return [];
|
||||
|
||||
return response.Departure.Select(dep => new TimeTable
|
||||
{
|
||||
LineNumber = dep.ProductAtStop?.DisplayNumber ?? dep.ProductAtStop?.Line,
|
||||
LineName = dep.ProductAtStop?.Name,
|
||||
TransportType = dep.ProductAtStop?.CatOutL,
|
||||
Operator = dep.ProductAtStop?.Operator,
|
||||
StopName = dep.Stop,
|
||||
DepartureTime = $"{dep.Date} {dep.Time}",
|
||||
Direction = dep.Direction,
|
||||
JourneyDetailRef = dep.JourneyDetailRef?.Ref,
|
||||
Notes = dep.Notes?.Note?.Select(n => n.Value).ToList() ?? [],
|
||||
InternalTransportationName = dep.ProductAtStop?.InternalName
|
||||
}).ToList();
|
||||
}
|
||||
}
|
||||
31
HomeApi/Handlers/Configuration.cs
Normal file
31
HomeApi/Handlers/Configuration.cs
Normal 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
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
18
HomeApi/Handlers/DepartureBoard.cs
Normal file
18
HomeApi/Handlers/DepartureBoard.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
using HomeApi.Integration;
|
||||
using HomeApi.Models;
|
||||
using MediatR;
|
||||
|
||||
namespace HomeApi.Handlers;
|
||||
|
||||
public static class DepartureBoard
|
||||
{
|
||||
public record Command : IRequest<List<TimeTable>>;
|
||||
|
||||
public class Handler(IDepartureBoardService departureBoardService) : IRequestHandler<Command, List<TimeTable>>
|
||||
{
|
||||
public async Task<List<TimeTable>> Handle(Command request, CancellationToken cancellationToken)
|
||||
{
|
||||
return await departureBoardService.GetDepartureBoard() ?? new List<TimeTable>();
|
||||
}
|
||||
}
|
||||
}
|
||||
79
HomeApi/Handlers/ImageGeneration.cs
Normal file
79
HomeApi/Handlers/ImageGeneration.cs
Normal file
@@ -0,0 +1,79 @@
|
||||
using System.Dynamic;
|
||||
using System.Reflection;
|
||||
using HomeApi.Models.Configuration;
|
||||
using MediatR;
|
||||
using Microsoft.Extensions.Options;
|
||||
using PuppeteerSharp;
|
||||
using RazorLight;
|
||||
|
||||
namespace HomeApi.Handlers;
|
||||
|
||||
public static class ImageGeneration
|
||||
{
|
||||
public record Command : IRequest<Stream>;
|
||||
|
||||
public class Handler(
|
||||
IWebHostEnvironment env,
|
||||
IMediator mediator,
|
||||
IOptions<ApiConfiguration> apiConfiguration)
|
||||
: IRequestHandler<Command, Stream>
|
||||
{
|
||||
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 model = new Models.Image
|
||||
{
|
||||
Weather = weather,
|
||||
TimeTable = departureBoard
|
||||
};
|
||||
|
||||
if(weather is null)
|
||||
throw new Exception("Weather data not found");
|
||||
|
||||
var engine = new RazorLightEngineBuilder()
|
||||
.SetOperatingAssembly(Assembly.GetExecutingAssembly())
|
||||
.UseEmbeddedResourcesProject(typeof(ImageGeneration))
|
||||
.UseMemoryCachingProvider()
|
||||
.Build();
|
||||
|
||||
var path = Path.Combine(env.WebRootPath, "index.cshtml");
|
||||
|
||||
var template = await File.ReadAllTextAsync(path, cancellationToken);
|
||||
|
||||
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)
|
||||
{
|
||||
var browserFetcher = new BrowserFetcher();
|
||||
await browserFetcher.DownloadAsync();
|
||||
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
|
||||
{
|
||||
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 = [WaitUntilNavigation.Networkidle0] });
|
||||
return await page.ScreenshotStreamAsync(new ScreenshotOptions { Type = ScreenshotType.Jpeg, Quality = 60 });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace HomeApi.Handlers;
|
||||
|
||||
public static class GetWeather
|
||||
public static class Weather
|
||||
{
|
||||
public record Command : IRequest<WeatherInformation>;
|
||||
|
||||
@@ -5,20 +5,30 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<PreserveCompilationContext>true</PreserveCompilationContext>
|
||||
<EnableDefaultContentItems>false</EnableDefaultContentItems>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="MediatR" Version="13.0.0" />
|
||||
<PackageReference Include="MediatR.Extensions.Microsoft.DependencyInjection" Version="11.1.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.7"/>
|
||||
<PackageReference Include="PuppeteerSharp" Version="20.2.0" />
|
||||
<PackageReference Include="RazorLight" Version="2.3.1" />
|
||||
<PackageReference Include="Refit.HttpClientFactory" Version="8.0.0" />
|
||||
<PackageReference Include="Scalar.AspNetCore" Version="2.5.6" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\README.md" />
|
||||
<Content Include="..\.dockerignore">
|
||||
<Link>.dockerignore</Link>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="wwwroot\index.cshtml">
|
||||
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
@HomeApi_HostAddress = http://localhost:5128
|
||||
|
||||
GET {{HomeApi_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
|
||||
@@ -12,6 +12,14 @@ public class AuroraService(IAuroraClient auroraApi) : IAuroraService
|
||||
{
|
||||
public Task<AuroraForecastApiResponse> GetAuroraForecastAsync(string lat, string lon)
|
||||
{
|
||||
return auroraApi.GetForecastAsync(latitude: lat, longitude: lon);
|
||||
try
|
||||
{
|
||||
return auroraApi.GetForecastAsync(latitude: lat, longitude: lon);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
30
HomeApi/Integration/Client/ResRobotClient.cs
Normal file
30
HomeApi/Integration/Client/ResRobotClient.cs
Normal file
@@ -0,0 +1,30 @@
|
||||
using HomeApi.Models.Response;
|
||||
using Refit;
|
||||
|
||||
namespace HomeApi.Integration.Client;
|
||||
|
||||
public interface IResRobotClient
|
||||
{
|
||||
[Get("/v2.1/departureBoard")]
|
||||
Task<TrafikLabsApiResponse> GetDepartureBoardAsync(
|
||||
[AliasAs("accessId")] string accessId,
|
||||
[AliasAs("id")] string stopId,
|
||||
[AliasAs("direction")] string direction = null,
|
||||
[AliasAs("date")] string date = null, // Format: YYYY-MM-DD
|
||||
[AliasAs("time")] string time = null, // Format: HH:MM
|
||||
[AliasAs("duration")] int? duration = null,
|
||||
[AliasAs("maxJourneys")] int? maxJourneys = null,
|
||||
[AliasAs("operators")] string operators = null, // Example: "275,287"
|
||||
[AliasAs("products")] int? products = null,
|
||||
[AliasAs("passlist")] int? passlist = 0,
|
||||
[AliasAs("lang")] string language = "sv",
|
||||
[AliasAs("format")] string format = "json"
|
||||
);
|
||||
|
||||
[Get("/v2.1/location.name")]
|
||||
Task<LocationNameResponse> GetLocationsByNameAsync(
|
||||
[AliasAs("input")] string input,
|
||||
[AliasAs("format")] string format = "json",
|
||||
[AliasAs("accessId")] string accessId = "YOUR_API_KEY"
|
||||
);
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
using HomeApi.Models.Response;
|
||||
|
||||
namespace HomeApi.Integration.Client;
|
||||
|
||||
using Refit;
|
||||
|
||||
namespace HomeApi.Integration.Client.WeatherClient;
|
||||
|
||||
public interface IWeatherClient
|
||||
{
|
||||
[Get("/forecast.json")]
|
||||
Task<WeatherData> GetForecastAsync(
|
||||
[AliasAs("key")] string apiKey,
|
||||
[AliasAs("q")] string coordinates,
|
||||
[AliasAs("days")] int days = 7,
|
||||
[AliasAs("days")] int days = 14,
|
||||
[AliasAs("lang")] string language = "sv",
|
||||
[AliasAs("aqi")] string aqi = "yes",
|
||||
[AliasAs("alerts")] string alerts = "yes");
|
||||
46
HomeApi/Integration/DepartureBoardService.cs
Normal file
46
HomeApi/Integration/DepartureBoardService.cs
Normal file
@@ -0,0 +1,46 @@
|
||||
using HomeApi.Extensions;
|
||||
using HomeApi.Integration.Client;
|
||||
using HomeApi.Models;
|
||||
using HomeApi.Models.Configuration;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace HomeApi.Integration;
|
||||
|
||||
public interface IDepartureBoardService
|
||||
{
|
||||
Task<List<TimeTable>?> GetDepartureBoard();
|
||||
}
|
||||
|
||||
public class DepartureBoardService(IResRobotClient departureBoardApi, IOptions<ApiConfiguration> options) : IDepartureBoardService
|
||||
{
|
||||
private readonly ApiConfiguration _apiConfig = options.Value;
|
||||
|
||||
public async Task<List<TimeTable>?> GetDepartureBoard()
|
||||
{
|
||||
var locationResponse = await departureBoardApi.GetLocationsByNameAsync(
|
||||
input: _apiConfig.DefaultStation,
|
||||
format: "json",
|
||||
accessId: _apiConfig.Keys.ResRobot
|
||||
);
|
||||
|
||||
var id = locationResponse.StopLocationOrCoordLocation.FirstOrDefault()?.StopLocation?.ExtId;
|
||||
|
||||
if (id == null)
|
||||
return null;
|
||||
|
||||
var result = await departureBoardApi.GetDepartureBoardAsync(
|
||||
accessId: _apiConfig.Keys.ResRobot,
|
||||
stopId: id,
|
||||
direction: null,
|
||||
date: DateTime.Now.ToString("yyyy-MM-dd"),
|
||||
time: DateTime.Now.ToString("HH:mm"),
|
||||
duration: 60,
|
||||
maxJourneys: 10,
|
||||
passlist: 1,
|
||||
language: "sv",
|
||||
format: "json"
|
||||
);
|
||||
|
||||
return result.ToContract();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
using HomeApi.Integration.Client;
|
||||
using HomeApi.Integration.Client.WeatherClient;
|
||||
using HomeApi.Models.Configuration;
|
||||
using HomeApi.Models.Response;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
@@ -5,6 +5,8 @@ public class ApiConfiguration
|
||||
public Keys Keys { get; set; } = new();
|
||||
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
|
||||
@@ -12,6 +14,7 @@ public class BaseUrls
|
||||
public string Weather { get; set; } = string.Empty;
|
||||
public string Nominatim { get; set; } = string.Empty;
|
||||
public string Aurora { get; set; } = string.Empty;
|
||||
public string ResRobot { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class Keys
|
||||
@@ -19,4 +22,17 @@ public class Keys
|
||||
public string Weather { get; set; } = string.Empty;
|
||||
public string Nominatim { get; set; } = string.Empty;
|
||||
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;
|
||||
}
|
||||
7
HomeApi/Models/ImageGeneration.cs
Normal file
7
HomeApi/Models/ImageGeneration.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace HomeApi.Models;
|
||||
|
||||
public class Image
|
||||
{
|
||||
public WeatherInformation Weather { get; set; }
|
||||
public List<TimeTable> TimeTable { get; set; }
|
||||
}
|
||||
12
HomeApi/Models/MicroProcessorConfiguration.cs
Normal file
12
HomeApi/Models/MicroProcessorConfiguration.cs
Normal 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)
|
||||
}
|
||||
88
HomeApi/Models/Response/LocationNameResponse.cs
Normal file
88
HomeApi/Models/Response/LocationNameResponse.cs
Normal file
@@ -0,0 +1,88 @@
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
public class LocationNameResponse
|
||||
{
|
||||
[JsonPropertyName("stopLocationOrCoordLocation")]
|
||||
public List<StopLocationOrCoordLocation> StopLocationOrCoordLocation { get; set; }
|
||||
|
||||
[JsonPropertyName("TechnicalMessages")]
|
||||
public TechnicalMessages TechnicalMessages { get; set; }
|
||||
|
||||
[JsonPropertyName("serverVersion")]
|
||||
public string ServerVersion { get; set; }
|
||||
|
||||
[JsonPropertyName("dialectVersion")]
|
||||
public string DialectVersion { get; set; }
|
||||
|
||||
[JsonPropertyName("requestId")]
|
||||
public string RequestId { get; set; }
|
||||
}
|
||||
|
||||
public class StopLocationOrCoordLocation
|
||||
{
|
||||
[JsonPropertyName("StopLocation")]
|
||||
public StopLocation StopLocation { get; set; }
|
||||
}
|
||||
|
||||
public class StopLocation
|
||||
{
|
||||
[JsonPropertyName("productAtStop")]
|
||||
public List<ProductAtStop> ProductAtStop { get; set; }
|
||||
|
||||
[JsonPropertyName("timezoneOffset")]
|
||||
public int TimezoneOffset { get; set; }
|
||||
|
||||
[JsonPropertyName("id")]
|
||||
public string Id { get; set; }
|
||||
|
||||
[JsonPropertyName("extId")]
|
||||
public string ExtId { get; set; }
|
||||
|
||||
[JsonPropertyName("name")]
|
||||
public string Name { get; set; }
|
||||
|
||||
[JsonPropertyName("lon")]
|
||||
public double Lon { get; set; }
|
||||
|
||||
[JsonPropertyName("lat")]
|
||||
public double Lat { get; set; }
|
||||
|
||||
[JsonPropertyName("weight")]
|
||||
public int Weight { get; set; }
|
||||
|
||||
[JsonPropertyName("products")]
|
||||
public int Products { get; set; }
|
||||
|
||||
[JsonPropertyName("minimumChangeDuration")]
|
||||
public string MinimumChangeDuration { get; set; }
|
||||
}
|
||||
|
||||
public class ProductAtStop
|
||||
{
|
||||
[JsonPropertyName("icon")]
|
||||
public Icon Icon { get; set; }
|
||||
|
||||
[JsonPropertyName("cls")]
|
||||
public string Cls { get; set; }
|
||||
}
|
||||
|
||||
public class Icon
|
||||
{
|
||||
[JsonPropertyName("res")]
|
||||
public string Res { get; set; }
|
||||
}
|
||||
|
||||
public class TechnicalMessages
|
||||
{
|
||||
[JsonPropertyName("TechnicalMessage")]
|
||||
public List<TechnicalMessage> TechnicalMessage { get; set; }
|
||||
}
|
||||
|
||||
public class TechnicalMessage
|
||||
{
|
||||
[JsonPropertyName("value")]
|
||||
public string Value { get; set; }
|
||||
|
||||
[JsonPropertyName("key")]
|
||||
public string Key { get; set; }
|
||||
}
|
||||
84
HomeApi/Models/Response/TrafikLabsApiResponse.cs
Normal file
84
HomeApi/Models/Response/TrafikLabsApiResponse.cs
Normal file
@@ -0,0 +1,84 @@
|
||||
namespace HomeApi.Models.Response;
|
||||
public class TrafikLabsApiResponse
|
||||
{
|
||||
public List<Departure> Departure { get; set; }
|
||||
}
|
||||
|
||||
public class Departure
|
||||
{
|
||||
public JourneyDetailRef JourneyDetailRef { get; set; }
|
||||
public string JourneyStatus { get; set; }
|
||||
public ProductDetail ProductAtStop { get; set; }
|
||||
public List<ProductDetail> Product { get; set; }
|
||||
public Notes Notes { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string Type { get; set; }
|
||||
public string Stop { get; set; }
|
||||
public string Stopid { get; set; }
|
||||
public string StopExtId { get; set; }
|
||||
public double Lon { get; set; }
|
||||
public double Lat { get; set; }
|
||||
public string Time { get; set; }
|
||||
public string Date { get; set; }
|
||||
public bool Reachable { get; set; }
|
||||
public string Direction { get; set; }
|
||||
public string DirectionFlag { get; set; }
|
||||
}
|
||||
|
||||
public class JourneyDetailRef
|
||||
{
|
||||
public string Ref { get; set; }
|
||||
}
|
||||
|
||||
public class ProductDetail
|
||||
{
|
||||
public Icon Icon { get; set; }
|
||||
public OperatorInfo OperatorInfo { get; set; }
|
||||
public string Name { get; set; }
|
||||
public string InternalName { get; set; }
|
||||
public string DisplayNumber { get; set; }
|
||||
public string Num { get; set; }
|
||||
public string Line { get; set; }
|
||||
public string LineId { get; set; }
|
||||
public string CatOut { get; set; }
|
||||
public string CatIn { get; set; }
|
||||
public string CatCode { get; set; }
|
||||
public string Cls { get; set; }
|
||||
public string CatOutS { get; set; }
|
||||
public string CatOutL { get; set; }
|
||||
public string OperatorCode { get; set; }
|
||||
public string Operator { get; set; }
|
||||
public string Admin { get; set; }
|
||||
public string MatchId { get; set; }
|
||||
public int? RouteIdxFrom { get; set; }
|
||||
public int? RouteIdxTo { get; set; }
|
||||
}
|
||||
|
||||
public class Icon
|
||||
{
|
||||
public string Res { get; set; }
|
||||
}
|
||||
|
||||
public class OperatorInfo
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public string NameS { get; set; }
|
||||
public string NameN { get; set; }
|
||||
public string NameL { get; set; }
|
||||
public string Id { get; set; }
|
||||
}
|
||||
|
||||
public class Notes
|
||||
{
|
||||
public List<Note> Note { get; set; }
|
||||
}
|
||||
|
||||
public class Note
|
||||
{
|
||||
public string Value { get; set; }
|
||||
public string Key { get; set; }
|
||||
public string Type { get; set; }
|
||||
public int RouteIdxFrom { get; set; }
|
||||
public int RouteIdxTo { get; set; }
|
||||
public string TxtN { get; set; }
|
||||
}
|
||||
15
HomeApi/Models/TimeTable.cs
Normal file
15
HomeApi/Models/TimeTable.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace HomeApi.Models;
|
||||
|
||||
public class TimeTable
|
||||
{
|
||||
public string LineNumber { get; set; } // e.g. "43", "832"
|
||||
public string LineName { get; set; } // e.g. "Länstrafik - Tåg 43"
|
||||
public string TransportType { get; set; } // e.g. "Tåg", "Buss"
|
||||
public string Operator { get; set; } // e.g. "SL"
|
||||
public string StopName { get; set; } // e.g. "Vega station (Haninge kn)"
|
||||
public string DepartureTime { get; set; } // e.g. 2025-07-15 01:03
|
||||
public string Direction { get; set; } // e.g. "Farsta Strand station"
|
||||
public string JourneyDetailRef { get; set; } // e.g. "1|39437|0|1|15072025"
|
||||
public List<string> Notes { get; set; } // e.g. "Pendeltåg", "Endast 2 klass"
|
||||
public string InternalTransportationName { get; set; } // e.g. "Pendeltåg 43"
|
||||
}
|
||||
@@ -62,6 +62,9 @@ public class Forecast
|
||||
public WeatherSummary? Day { get; set; }
|
||||
public WeatherSummary? Night { get; set; }
|
||||
public Astro Astro { get; set; }
|
||||
public int IconCode { get; set; }
|
||||
|
||||
public int ChanceOfRain { get; set; }
|
||||
}
|
||||
public class Astro
|
||||
{
|
||||
|
||||
@@ -11,11 +11,10 @@ builder.Services.AddIntegration(builder.Configuration);
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.MapOpenApi();
|
||||
app.MapScalarApiReference();
|
||||
}
|
||||
app.UseStaticFiles();
|
||||
|
||||
app.MapOpenApi();
|
||||
app.MapScalarApiReference();
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using HomeApi.Extensions;
|
||||
using HomeApi.Integration;
|
||||
using HomeApi.Integration.Client;
|
||||
using HomeApi.Integration.Client.WeatherClient;
|
||||
using HomeApi.Models.Configuration;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Refit;
|
||||
@@ -28,7 +29,11 @@ public static class RegisterIntegration
|
||||
|
||||
services.AddRefitClient<IWeatherClient>()
|
||||
.ConfigureBaseAddress(apiConfiguration => apiConfiguration.BaseUrls.Weather);
|
||||
|
||||
services.AddRefitClient<IResRobotClient>()
|
||||
.ConfigureBaseAddress(apiConfiguration => apiConfiguration.BaseUrls.ResRobot);
|
||||
|
||||
services.AddScoped<IDepartureBoardService, DepartureBoardService>();
|
||||
services.AddScoped<IGeocodingService, GeocodingService>();
|
||||
services.AddScoped<IAuroraService, AuroraService>();
|
||||
services.AddScoped<IWeatherService, WeatherService>();
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
{
|
||||
"Kestrel": {
|
||||
"Endpoints": {
|
||||
"Http": {
|
||||
"Url": "http://*:5000"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
@@ -6,15 +13,28 @@
|
||||
}
|
||||
},
|
||||
"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": "KEY",
|
||||
"SL": ""
|
||||
"Weather": "NOT COMMITED",
|
||||
"ResRobot": "NOT COMMITED"
|
||||
},
|
||||
"BaseUrls": {
|
||||
"Nominatim": "https://nominatim.openstreetmap.org",
|
||||
"Aurora": "http://api.auroras.live",
|
||||
"Weather": "https://api.weatherapi.com/v1"
|
||||
"Weather": "https://api.weatherapi.com/v1",
|
||||
"ResRobot": "https://api.resrobot.se"
|
||||
},
|
||||
"DefaultCity": "Vega stockholms lan"
|
||||
}
|
||||
"DefaultCity": "Vega stockholms lan",
|
||||
"DefaultStation": "Vega Station"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
{
|
||||
"Kestrel": {
|
||||
"Endpoints": {
|
||||
"Http": {
|
||||
"Url": "http://*:5000"
|
||||
}
|
||||
}
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
@@ -6,16 +13,28 @@
|
||||
}
|
||||
},
|
||||
"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": "KEY",
|
||||
"SL": ""
|
||||
"Weather": "NOT COMMITED",
|
||||
"ResRobot": "NOT COMMITED"
|
||||
},
|
||||
"BaseUrls": {
|
||||
"Nominatim": "https://nominatim.openstreetmap.org",
|
||||
"Aurora": "http://api.auroras.live",
|
||||
"Weather": "https://api.weatherapi.com/v1"
|
||||
"Weather": "https://api.weatherapi.com/v1",
|
||||
"ResRobot": "https://api.resrobot.se"
|
||||
},
|
||||
"DefaultCity": "Vega stockholms lan"
|
||||
"DefaultCity": "Vega stockholms lan",
|
||||
"DefaultStation": "Vega Station"
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
|
||||
635
HomeApi/wwwroot/index.cshtml
Normal file
635
HomeApi/wwwroot/index.cshtml
Normal file
@@ -0,0 +1,635 @@
|
||||
@using HomeApi.Models
|
||||
@using System;
|
||||
@using System.Linq;
|
||||
@using System.Collections.Generic;
|
||||
@model HomeApi.Models.Image
|
||||
|
||||
@functions {
|
||||
private string GetDayStatus(string input)
|
||||
{
|
||||
var date = DateTime.Parse(input);
|
||||
var today = DateTime.Today;
|
||||
var dayOfWeek = date.DayOfWeek.ToString();
|
||||
|
||||
if (date.Date == today)
|
||||
return "Today";
|
||||
if (date.Date == today.AddDays(1))
|
||||
return "Tomorrow";
|
||||
if (date >= today.AddDays(1) && date < today.AddDays(7))
|
||||
return dayOfWeek;
|
||||
return $"On {date:dddd, dd MMM yyyy}";
|
||||
}
|
||||
|
||||
private string GetTransPortIcon(string transportType)
|
||||
{
|
||||
var transportIcons = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
{ "buss", "fa-bus" },
|
||||
{ "bus", "fa-bus" },
|
||||
{ "tunnelbana", "fa-train-subway" },
|
||||
{ "metro", "fa-train-subway" },
|
||||
{ "tåg", "fa-train" },
|
||||
{ "train", "fa-train" },
|
||||
{ "båt", "fa-ferry" },
|
||||
{ "ferry", "fa-ferry" }
|
||||
};
|
||||
|
||||
foreach (var keyword in transportIcons.Keys)
|
||||
{
|
||||
if (transportType.Contains(keyword, StringComparison.OrdinalIgnoreCase))
|
||||
return transportIcons[keyword];
|
||||
}
|
||||
|
||||
return "fa-question-circle";
|
||||
}
|
||||
|
||||
private string GetAirQualityStatus(AirQuality data)
|
||||
{
|
||||
var highestAqi = Math.Max(data.Us_Epa_Index, data.Gb_Defra_Index);
|
||||
|
||||
return highestAqi switch
|
||||
{
|
||||
<= 50 => "Good",
|
||||
<= 100 => "Moderate",
|
||||
<= 150 => "Unhealthy for Sensitive Groups",
|
||||
<= 200 => "Unhealthy",
|
||||
<= 300 => "Very Unhealthy",
|
||||
_ => "Hazardous"
|
||||
};
|
||||
}
|
||||
|
||||
private static string GetWeatherIcon(int code, bool isNight = false)
|
||||
{
|
||||
var map = new Dictionary<int, string>
|
||||
{
|
||||
// Clear/Sunny
|
||||
{ 1000, isNight ? "fa-moon" : "fa-sun" },
|
||||
// Partly cloudy
|
||||
{ 1003, isNight ? "fa-cloud-moon" : "fa-cloud-sun" },
|
||||
// Cloudy/Overcast
|
||||
{ 1006, "fa-cloud" },
|
||||
{ 1009, "fa-cloud" },
|
||||
// Mist/Fog
|
||||
{ 1030, "fa-smog" },
|
||||
{ 1135, "fa-smog" },
|
||||
{ 1147, "fa-smog" },
|
||||
// Rain/drizzle
|
||||
{ 1063, "fa-cloud-rain" },
|
||||
{ 1150, "fa-cloud-drizzle" },
|
||||
{ 1153, "fa-cloud-drizzle" },
|
||||
{ 1180, "fa-cloud-rain" },
|
||||
{ 1183, "fa-cloud-rain" },
|
||||
{ 1186, "fa-cloud-showers-heavy" },
|
||||
{ 1189, "fa-cloud-showers-heavy" },
|
||||
{ 1240, "fa-cloud-showers-heavy" },
|
||||
{ 1243, "fa-cloud-showers-heavy" },
|
||||
{ 1246, "fa-cloud-showers-heavy" },
|
||||
// Sleet, freezing drizzle/rain
|
||||
{ 1069, "fa-cloud-meatball" },
|
||||
{ 1072, "fa-cloud-meatball" },
|
||||
{ 1168, "fa-cloud-meatball" },
|
||||
{ 1171, "fa-cloud-meatball" },
|
||||
{ 1198, "fa-cloud-meatball" },
|
||||
{ 1201, "fa-cloud-meatball" },
|
||||
{ 1204, "fa-cloud-meatball" },
|
||||
{ 1207, "fa-cloud-meatball" },
|
||||
{ 1249, "fa-cloud-meatball" },
|
||||
{ 1252, "fa-cloud-meatball" },
|
||||
// Snow
|
||||
{ 1066, "fa-snowflake" },
|
||||
{ 1114, "fa-snowflake" },
|
||||
{ 1117, "fa-snowflake" },
|
||||
{ 1210, "fa-snowflake" },
|
||||
{ 1213, "fa-snowflake" },
|
||||
{ 1216, "fa-snowflake" },
|
||||
{ 1219, "fa-snowflake" },
|
||||
{ 1222, "fa-snowflake" },
|
||||
{ 1225, "fa-snowflake" },
|
||||
{ 1255, "fa-snowflake" },
|
||||
{ 1258, "fa-snowflake" },
|
||||
// Snow showers
|
||||
{ 1261, "fa-snowflake" },
|
||||
{ 1264, "fa-snowflake" },
|
||||
{ 1279, "fa-snowflake" },
|
||||
{ 1282, "fa-snowflake" },
|
||||
// Thunderstorms
|
||||
{ 1087, "fa-bolt" },
|
||||
{ 1273, "fa-bolt" },
|
||||
{ 1276, "fa-bolt" },
|
||||
// Ice pellets
|
||||
{ 1237, "fa-icicles" },
|
||||
};
|
||||
|
||||
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>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Weather Dashboard</title>
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
<style>
|
||||
/* Reset and base styles */
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
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 */
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 0 0% 20%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 0 0% 20%;
|
||||
--primary: 0 0% 30%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--muted: 0 0% 96%;
|
||||
--muted-foreground: 0 0% 50%;
|
||||
--border: 0 0% 85%;
|
||||
|
||||
/* Icon colors - All red */
|
||||
--weather: 0 85% 60%;
|
||||
--weather-sunny: 0 85% 60%;
|
||||
--weather-cloudy: 0 85% 60%;
|
||||
--weather-rainy: 0 85% 60%;
|
||||
--weather-aurora: 0 85% 60%;
|
||||
|
||||
/* Air quality colors - Red */
|
||||
--air-good: 0 85% 60%;
|
||||
--air-moderate: 0 85% 60%;
|
||||
--air-bad: 0 85% 60%;
|
||||
|
||||
/* Transport colors - Red */
|
||||
--transport-color: 0 85% 60%;
|
||||
}
|
||||
|
||||
/* Main weather card */
|
||||
.weather-card {
|
||||
width: 800px;
|
||||
height: 480px;
|
||||
background: linear-gradient(135deg,
|
||||
hsl(var(--card)) 0%,
|
||||
hsl(var(--card)) 50%,
|
||||
hsl(var(--muted) / 0.3) 100%);
|
||||
border: 2px solid hsl(var(--border) / 0.2);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
|
||||
padding: 24px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr 1fr;
|
||||
gap: 24px;
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
|
||||
/* Left Column - Current Weather */
|
||||
.current-weather {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.location {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
|
||||
.location-icon {
|
||||
color: hsl(0 85% 60%) !important;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.location-text {
|
||||
font-weight: 500;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.current-temp {
|
||||
text-align: center;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.temp-main {
|
||||
font-size: 36px;
|
||||
font-weight: bold;
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
|
||||
.feels-like {
|
||||
font-size: 14px;
|
||||
color: hsl(var(--muted-foreground));
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.weather-details {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.detail-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.detail-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.detail-value {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.cloud-icon {
|
||||
color: hsl(var(--weather-cloudy)) !important;
|
||||
}
|
||||
|
||||
.wind-icon, .activity-icon {
|
||||
color: hsl(0 85% 60%) !important;
|
||||
}
|
||||
|
||||
.aurora-icon {
|
||||
color: hsl(var(--weather-aurora)) !important;
|
||||
}
|
||||
|
||||
.air-quality-badge {
|
||||
background: hsl(var(--air-good));
|
||||
color: hsl(0, 0%, 100%) !important;
|
||||
padding: 8px 16px;
|
||||
border-radius: 20px;
|
||||
font-size: 12px;
|
||||
font-weight: bolder;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* Middle Column - Forecast */
|
||||
.forecast-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-weight: 600;
|
||||
color: hsl(var(--foreground));
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.forecast-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.forecast-card {
|
||||
background: hsl(var(--muted) / 0.2);
|
||||
border: 1px solid hsl(var(--border) / 0.5);
|
||||
border-radius: 8px;
|
||||
padding: 8px;
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.forecast-date {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
|
||||
.forecast-icon {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin: 4px 0;
|
||||
color: hsl(var(--weather)) !important;
|
||||
}
|
||||
|
||||
.forecast-condition {
|
||||
font-size: 12px;
|
||||
color: hsl(var(--muted-foreground));
|
||||
}
|
||||
|
||||
.forecast-temp {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: hsl(var(--foreground));
|
||||
}
|
||||
|
||||
.forecast-rain {
|
||||
font-size: 12px;
|
||||
color: hsl(var(--muted-foreground));
|
||||
}
|
||||
|
||||
.weather-sunny {
|
||||
color: hsl(var(--weather-sunny));
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.weather-cloudy {
|
||||
color: hsl(var(--weather-cloudy));
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.weather-rainy {
|
||||
color: hsl(var(--weather-rainy));
|
||||
font-size: 24px;
|
||||
}
|
||||
|
||||
.sun-moon-info {
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid hsl(var(--border));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.sun-moon-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.sun-moon-label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.sun-moon-value {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.moon-phase-label {
|
||||
font-size: 12px;
|
||||
color: hsl(var(--muted-foreground));
|
||||
}
|
||||
|
||||
.sunrise-icon, .sunset-icon {
|
||||
color: hsl(0 85% 60%) !important;
|
||||
}
|
||||
|
||||
.moon-icon {
|
||||
color: hsl(0 85% 60%) !important;
|
||||
}
|
||||
|
||||
/* Right Column - Transport */
|
||||
.transport-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.transport-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.transport-item {
|
||||
background: hsl(var(--card));
|
||||
border: 1px solid hsl(var(--border));
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 12px;
|
||||
transition: box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.transport-item:hover {
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.transport-item i {
|
||||
font-size: 20px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.transport-color {
|
||||
color: hsl(var(--transport-color)) !important;
|
||||
}
|
||||
|
||||
.transport-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.transport-name {
|
||||
font-weight: 500;
|
||||
font-size: 14px;
|
||||
color: hsl(var(--foreground));
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.transport-destination {
|
||||
font-size: 12px;
|
||||
color: hsl(var(--muted-foreground));
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
width: 152px;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.transport-time {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: hsl(var(--primary));
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.last-updated {
|
||||
padding-top: 16px;
|
||||
margin-top: 16px;
|
||||
border-top: 1px solid hsl(var(--border));
|
||||
}
|
||||
|
||||
.update-text {
|
||||
font-size: 12px;
|
||||
color: hsl(var(--muted-foreground));
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="weather-card @UseHighContrast(ViewBag.IsHighContrast)">
|
||||
<!-- Left Column - Current Weather -->
|
||||
<div class="current-weather">
|
||||
<div class="location">
|
||||
<i class="fas fa-map-marker-alt location-icon"></i>
|
||||
<span class="location-text">@Model.Weather.CityName</span>
|
||||
</div>
|
||||
|
||||
<div class="current-temp">
|
||||
<div class="temp-main">@Model.Weather.Current.Temperature°C</div>
|
||||
<div class="feels-like">Feels like @Model.Weather.Current.Feelslike°C</div>
|
||||
</div>
|
||||
|
||||
<div class="weather-details">
|
||||
<div class="detail-item">
|
||||
<div class="detail-label">
|
||||
<i class="fas fa-cloud cloud-icon"></i>
|
||||
<span>Clouds</span>
|
||||
</div>
|
||||
<span class="detail-value">@Model.Weather.Current.Cloud%</span>
|
||||
</div>
|
||||
|
||||
<div class="detail-item">
|
||||
<div class="detail-label">
|
||||
<i class="fas fa-wind wind-icon"></i>
|
||||
<span>Wind</span>
|
||||
</div>
|
||||
<span class="detail-value">@Model.Weather.Current.WindPerMeterSecond.ToString("0.##") m/s @Model.Weather.Current.WindDirection</span>
|
||||
</div>
|
||||
|
||||
<div class="detail-item">
|
||||
<div class="detail-label">
|
||||
<i class="fas fa-chart-line activity-icon"></i>
|
||||
<span>Gusts</span>
|
||||
</div>
|
||||
<span class="detail-value">@Model.Weather.Current.WindGustPerMeterSecond.ToString("0.##") m/s</span>
|
||||
</div>
|
||||
|
||||
<div class="detail-item">
|
||||
<div class="detail-label">
|
||||
<i class="fas fa-star aurora-icon"></i>
|
||||
<span>Aurora</span>
|
||||
</div>
|
||||
<span class="detail-value">@Model.Weather.Current.AuroraProbability.Value%</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="air-quality-badge">
|
||||
Air Quality: @GetAirQualityStatus(Model.Weather.Current.AirQuality)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Middle Column - Forecast -->
|
||||
<div class="forecast-section">
|
||||
<h3 class="section-title">@Model.Weather.Forecast.Count-Day Forecast</h3>
|
||||
|
||||
<div class="forecast-grid">
|
||||
@foreach (var day in Model.Weather.Forecast)
|
||||
{
|
||||
<div class="forecast-card">
|
||||
<div class="forecast-date">@GetDayStatus(day.Date)</div>
|
||||
<div class="forecast-icon">
|
||||
<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>
|
||||
<div class="forecast-rain">Rain: @day.ChanceOfRain%</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="sun-moon-info">
|
||||
<div class="sun-moon-item">
|
||||
<div class="sun-moon-label">
|
||||
<i class="fas fa-sun sunrise-icon"></i>
|
||||
<span>Sunrise</span>
|
||||
</div>
|
||||
<span class="sun-moon-value">@Model.Weather.Forecast[0].Astro.Sunrise</span>
|
||||
</div>
|
||||
|
||||
<div class="sun-moon-item">
|
||||
<div class="sun-moon-label">
|
||||
<i class="fas fa-sun sunset-icon"></i>
|
||||
<span>Sunset</span>
|
||||
</div>
|
||||
<span class="sun-moon-value">@Model.Weather.Forecast[0].Astro.Sunset</span>
|
||||
</div>
|
||||
|
||||
<div class="sun-moon-item">
|
||||
<div class="sun-moon-label">
|
||||
<i class="fas fa-moon moon-icon"></i>
|
||||
<span>Moonrise</span>
|
||||
</div>
|
||||
<span class="sun-moon-value">@Model.Weather.Forecast[0].Astro.Moonrise</span>
|
||||
</div>
|
||||
|
||||
<div class="sun-moon-item">
|
||||
<div class="sun-moon-label">
|
||||
<i class="fas fa-moon moon-icon"></i>
|
||||
<span>Moonset</span>
|
||||
</div>
|
||||
<span class="sun-moon-value">@Model.Weather.Forecast[0].Astro.Moonset</span>
|
||||
</div>
|
||||
|
||||
<div class="sun-moon-item">
|
||||
<span class="moon-phase-label">Moon phase</span>
|
||||
<span class="sun-moon-value">@Model.Weather.Forecast[0].Astro.Moon_Illumination%</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Right Column - Public Transport -->
|
||||
<div class="transport-section">
|
||||
<h3 class="section-title">Upcoming Departures</h3>
|
||||
|
||||
<div class="transport-list">
|
||||
@foreach (var transport in Model.TimeTable.Take(5))
|
||||
{
|
||||
|
||||
var departureTime = DateTime.Parse(transport.DepartureTime);
|
||||
var minutesUntilDeparture = (int)(departureTime - DateTime.Now).TotalMinutes;
|
||||
|
||||
<div class="transport-item">
|
||||
<i class="fas transport-color @GetTransPortIcon(transport.InternalTransportationName)"></i>
|
||||
<div class="transport-info">
|
||||
<div class="transport-name">@transport.LineNumber</div>
|
||||
<div class="transport-destination">to @transport.Direction</div>
|
||||
</div>
|
||||
<div class="transport-time">@DateTime.Parse(transport.DepartureTime).ToShortTimeString() (@minutesUntilDeparture min)</div>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
<div class="last-updated">
|
||||
<div class="update-text">Last updated: <span id="current-time"></span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Update current time
|
||||
function updateTime() {
|
||||
const now = new Date();
|
||||
document.getElementById('current-time').textContent = now.toLocaleTimeString();
|
||||
}
|
||||
|
||||
updateTime();
|
||||
setInterval(updateTime, 1000);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
110
README.md
110
README.md
@@ -1 +1,109 @@
|
||||
E-ink solar panel screen showing info, this is the api for it. Low effort code
|
||||
# This [](https://github.com/Myxelium/HomeScreen/actions/workflows/build.yml)
|
||||
Core api and Esp32 code for displaying weather data and public transport information on a e-ink display.
|
||||
|
||||
<img width="800" height="480" alt="image" src="https://github.com/user-attachments/assets/ef5af0c6-ea3a-494d-b2af-3de6e70b3e6a" />
|
||||
|
||||
## Features 😺
|
||||
- Display current weather data
|
||||
- Display public transport information
|
||||
- Display time and date
|
||||
|
||||
## Requirements
|
||||
- ESP32 board
|
||||
- E-ink display (e.g. Waveshare 7.5 inch)
|
||||
|
||||
# Installation
|
||||
|
||||
This section provides instructions for setting up and running the HomeApi project.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- [.NET 9.0 SDK](https://dotnet.microsoft.com/download/dotnet/9.0) or later
|
||||
- Docker (optional, for containerized deployment)
|
||||
- Git (to clone the repository)
|
||||
|
||||
## Option 1: Local Development Setup
|
||||
|
||||
1. Clone the repository:
|
||||
```bash
|
||||
git clone https://github.com/Myxelium/HomeScreen.git
|
||||
cd HomeApi
|
||||
```
|
||||
|
||||
2. Restore dependencies:
|
||||
```bash
|
||||
dotnet restore
|
||||
```
|
||||
|
||||
3. Build the project:
|
||||
```bash
|
||||
dotnet build
|
||||
```
|
||||
|
||||
4. Run the application:
|
||||
```bash
|
||||
dotnet run
|
||||
```
|
||||
|
||||
The API will be available at `http://localhost:5000`.
|
||||
|
||||
## Option 2: Docker Deployment
|
||||
|
||||
1. Build the Docker image:
|
||||
```bash
|
||||
docker build -t homeapi .
|
||||
```
|
||||
|
||||
2. Run the container:
|
||||
```bash
|
||||
docker run -d -p 5000 --name homeapi homeapi
|
||||
```
|
||||
|
||||
The API will be accessible at `http://localhost:5000`.
|
||||
|
||||
## Configuration
|
||||
|
||||
The application uses the standard .NET configuration system. You can modify settings in:
|
||||
|
||||
- `appsettings.json` - Default configuration
|
||||
- `appsettings.Development.json` - Development environment configuration
|
||||
|
||||
API endpoints:
|
||||
- Weather data: GET `/home`
|
||||
- Generated image: GET `/home/default.jpg`
|
||||
- Configuration data: GET `/home/configuration`
|
||||
- Departure board: GET `/home/departure-board`
|
||||
|
||||
## API Documentation
|
||||
|
||||
When running, API documentation is available through Scalar at `/scalar`.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
subgraph ESP32 Device
|
||||
ESP[ESP32 E-Ink Display]
|
||||
ESP -->|HTTP GET /home/configuration| API
|
||||
ESP -->|HTTP GET /home/default.jpg| API
|
||||
end
|
||||
|
||||
subgraph HomeApi
|
||||
API[HomeControllerAPI]
|
||||
API -->|MediatR| Handlers
|
||||
Handlers -->|Service Calls| Services
|
||||
Services -->|Refit Clients| Clients
|
||||
Clients -->|External APIs| ExtAPIs
|
||||
API -->|Returns JSON/JPEG| ESP
|
||||
end
|
||||
|
||||
subgraph ExternalAPIs
|
||||
WeatherAPI[Weather API]
|
||||
AuroraAPI[Aurora API]
|
||||
NominatimAPI[Nominatim API]
|
||||
ResRobotAPI[ResRobot API]
|
||||
end
|
||||
|
||||
ExtAPIs -.-> WeatherAPI
|
||||
ExtAPIs -.-> AuroraAPI
|
||||
ExtAPIs -.-> NominatimAPI
|
||||
ExtAPIs -.-> ResRobotAPI
|
||||
```
|
||||
|
||||
20
compose.yaml
20
compose.yaml
@@ -1,13 +1,15 @@
|
||||
services:
|
||||
homeapi:
|
||||
image: homeapi
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
version: '3.8'
|
||||
|
||||
homeapi-1:
|
||||
image: homeapi-1
|
||||
services:
|
||||
homeapi:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: HomeApi/Dockerfile
|
||||
|
||||
image: homeapi:latest
|
||||
ports:
|
||||
- "5000:5000"
|
||||
environment:
|
||||
- ASPNETCORE_ENVIRONMENT=Development
|
||||
volumes:
|
||||
- ./HomeApi/appsettings.Development.json:/app/appsettings.Development.json:ro
|
||||
restart: unless-stopped
|
||||
Reference in New Issue
Block a user