do singnalR stuff

This commit is contained in:
Christian Werner 2025-10-12 20:43:02 +02:00
parent 96bf4ed028
commit a065b327fb
30 changed files with 14019 additions and 8 deletions

View File

@ -0,0 +1,20 @@
using Microsoft.AspNetCore.SignalR;
namespace c64_inteface;
public class ArduinoMessage
{
public string StatusText { get; set; }
public string Status { get; set; }
}
public class ArduinoHub : Hub
{
private const string ArduinoConnectionMessage = "ArduinoConnectionMessage";
public async Task SendMessage(ArduinoMessage msg)
{
if (Clients is not null)
await Clients.All.SendAsync(ArduinoConnectionMessage, msg);
}
}

View File

@ -1,4 +1,5 @@
using System.IO.Ports;
using System.Text;
namespace c64_inteface;
@ -10,12 +11,14 @@ public class MonitorBackgroundService : IHostedService, IDisposable
private readonly ILogger<MonitorBackgroundService> _logger;
private readonly ArduinoMessageContainer _arduinoMessageContainer;
private readonly ArduinoHub _arduinoHub;
private SerialPort? _arduinoPort;
public MonitorBackgroundService(ILogger<MonitorBackgroundService> logger, ArduinoMessageContainer arduinoMessageContainer)
public MonitorBackgroundService(ILogger<MonitorBackgroundService> logger, ArduinoMessageContainer arduinoMessageContainer, ArduinoHub arduinoHub)
{
_logger = logger;
_arduinoMessageContainer = arduinoMessageContainer;
_arduinoHub = arduinoHub;
}
public Task StartAsync(CancellationToken stoppingToken)
@ -34,13 +37,34 @@ public class MonitorBackgroundService : IHostedService, IDisposable
{
try
{
await _arduinoHub.SendMessage(new ArduinoMessage
{
Status = "online",
StatusText =
$"Sending message with {Encoding.ASCII.GetBytes(_arduinoMessageContainer.Message).Length} bytes..."
});
_logger.LogInformation("Sending message: {Message}", _arduinoMessageContainer.Message);
await _arduinoHub.SendMessage(new ArduinoMessage
{
Status = "online",
StatusText = "Done"
});
_arduinoPort?.WriteLine(_arduinoMessageContainer.Message);
_arduinoMessageContainer.Ready = false;
}
catch (Exception e)
{
Console.WriteLine(e);
await _arduinoHub.SendMessage(new ArduinoMessage()
{
StatusText = "Error: " + e.Message,
Status = "offline"
});
}
}
}
@ -62,6 +86,12 @@ public class MonitorBackgroundService : IHostedService, IDisposable
{
while (_arduinoPort is null && !cancellationToken.IsCancellationRequested)
{
await _arduinoHub.SendMessage(new ArduinoMessage()
{
StatusText = "Searching for Arduino...",
Status = "offline"
});
var ports = SerialPort.GetPortNames().ToList();
_logger.LogInformation("available ports: {Ports}", ports);
@ -106,6 +136,11 @@ public class MonitorBackgroundService : IHostedService, IDisposable
}
_logger.LogInformation("Arduino found on {portName}", portName);
await _arduinoHub.SendMessage(new ArduinoMessage()
{
StatusText = $"Arduino found on {portName}",
Status = "online"
});
_arduinoPort = port;

View File

@ -7,11 +7,16 @@ var builder = WebApplication.CreateBuilder(args);
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddSignalR();
builder.Services.AddSingleton<ArduinoMessageContainer>();
builder.Services.AddHostedService<MonitorBackgroundService>();
builder.Services.AddSingleton<ArduinoHub>();
builder.Services.AddCors(cfg => cfg.AddPolicy("cringe", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
var app = builder.Build();
app.UseCors("cringe");
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
@ -28,4 +33,11 @@ app.MapGet("/api/{message}", (string message, ArduinoMessageContainer arduinoMes
})
.WithName("SendMessageToArduino");
app.UseWebSockets(new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromSeconds(120),
});
app.MapHub<ArduinoHub>("/ArduinoHub");
app.Run();

View File

@ -4,12 +4,6 @@
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<PublishSingleFile>true</PublishSingleFile>
<SelfContained>true</SelfContained>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<DebugType>none</DebugType>
<DebugSymbols>false</DebugSymbols>
<AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
</PropertyGroup>
<ItemGroup>

View File

@ -0,0 +1,3 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AHost_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E2_003Fresharper_002Dhost_003FSourcesCache_003Fcfb8165d037ea5062589e7be2a322d53397b1abadab026bb319132b6a24556_003FHost_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AServiceProvider_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003FAppData_003FRoaming_003FJetBrains_003FRider2025_002E2_003Fresharper_002Dhost_003FSourcesCache_003Fce37be1a06b16c6faa02038d2cc477dd3bca5b217ceeb41c5f2ad45c1bf9_003FServiceProvider_002Ecs/@EntryIndexedValue">ForceIncluded</s:String></wpf:ResourceDictionary>

View File

@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
web/c64_web_interface/.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}

View File

@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}

View File

@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}

View File

@ -0,0 +1,27 @@
# C64WebInterface
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.3.17.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.

View File

@ -0,0 +1,101 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"c64_web_interface": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/c64_web_interface",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "c64_web_interface:build:production"
},
"development": {
"buildTarget": "c64_web_interface:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "c64_web_interface:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
}
}
}
}
}

13424
web/c64_web_interface/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,39 @@
{
"name": "c64-web-interface",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.3.0",
"@angular/common": "^17.3.0",
"@angular/compiler": "^17.3.0",
"@angular/core": "^17.3.0",
"@angular/forms": "^17.3.0",
"@angular/platform-browser": "^17.3.0",
"@angular/platform-browser-dynamic": "^17.3.0",
"@angular/router": "^17.3.0",
"@microsoft/signalr": "^9.0.6",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.3.17",
"@angular/cli": "^17.3.17",
"@angular/compiler-cli": "^17.3.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.4.2"
}
}

View File

@ -0,0 +1,4 @@
<div class="arduino">
<span class="statusIcon" attr.data-status="{{arduinoService.status().status}}"></span>
<span class="statusText">{{arduinoService.status().statusText}}</span>
</div>

View File

@ -0,0 +1,26 @@
.arduino {
display: flex;
flex-direction: row;
font-size: 24px;
align-items: center;
.statusIcon {
width: 24px;
height: 24px;
border-radius: 100%;
background-color: gray;
}
.statusIcon[data-status="offline"] {
background-color: red;
}
.statusIcon[data-status="online"] {
background-color: green;
}
.statusText {
margin-left: 8px;
}
}

View File

@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have the 'c64_web_interface' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('c64_web_interface');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, c64_web_interface');
});
});

View File

@ -0,0 +1,31 @@
import {Component, inject, OnInit} from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {ArduinoMessage, ArduinoServiceService} from "./arduino-service.service";
import {takeUntilDestroyed, toObservable} from "@angular/core/rxjs-interop";
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent implements OnInit {
title = 'c64_web_interface';
status: ArduinoMessage|null = null;
arduinoService = inject(ArduinoServiceService);
constructor() {
toObservable(this.arduinoService.status)
.pipe(takeUntilDestroyed())
.subscribe(status => this.status = status);
}
ngOnInit(): void {
}
}

View File

@ -0,0 +1,8 @@
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes)]
};

View File

@ -0,0 +1,3 @@
import { Routes } from '@angular/router';
export const routes: Routes = [];

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { ArduinoServiceService } from './arduino-service.service';
describe('ArduinoServiceService', () => {
let service: ArduinoServiceService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(ArduinoServiceService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,35 @@
import {Injectable, signal} from '@angular/core';
import * as signalR from '@microsoft/signalr';
export interface ArduinoMessage {
status: string;
statusText: string;
}
@Injectable({
providedIn: 'root',
})
export class ArduinoServiceService {
public status = signal<ArduinoMessage>({} as ArduinoMessage);
private hubConnection: signalR.HubConnection;
constructor() {
this.hubConnection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost:5216/ArduinoHub', {
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets
})
.build();
this.hubConnection.on('ArduinoConnectionMessage', (message) => {
this.status.set(message);
console.log(`Message: ${message}`);
});
this.hubConnection.start()
.catch(err => console.error(err));
}
sendMessage(user: string, message: string): void {
this.hubConnection.invoke('SendMessage', user, message)
.catch(err => console.error(err));
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>C64WebInterface</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

View File

@ -0,0 +1 @@
/* You can add global styles to this file, and also import other style files */

View File

@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}

View File

@ -0,0 +1,32 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}