feat: Initialize backend with NestJS framework and serial communication

- Added package.json for backend dependencies and scripts.
- Implemented basic AppController and AppService with a simple "Hello World!" endpoint.
- Created SerialModule for handling serial communication with the Pico.
- Developed SerialController and SerialService to manage serial ports and commands.
- Implemented event streaming for serial data.
- Added Jest tests for AppController and e2e tests for the application.
- Set up TypeScript configuration for the backend.
- Created frontend SendBox component for sending commands to the backend.
- Established Pico firmware for controlling a stepper motor via serial commands.
- Documented project structure and usage in README files.
This commit is contained in:
2025-08-27 22:11:33 +02:00
parent bd41ffbe79
commit d607308b1d
32 changed files with 11622 additions and 165 deletions

View File

@@ -0,0 +1,89 @@
import { Controller, Get, Post, Body, Res, Req } from '@nestjs/common';
import type { Response, Request } from 'express';
import { SerialService } from './serial.service';
@Controller('serial')
export class SerialController {
constructor(private readonly serial: SerialService) {}
@Get('ports')
async ports() {
console.log('[SerialController] GET /serial/ports');
const p = await this.serial.listPorts();
console.log('[SerialController] ports ->', p);
return p;
}
@Post('open')
async open(@Body() body: { path: string; baud?: number }) {
console.log('[SerialController] POST /serial/open', body);
try {
this.serial.open(body.path, body.baud ?? 115200);
return { ok: true };
} catch (e: any) {
console.error('[SerialController] open error', e);
return { ok: false, error: String(e) };
}
}
@Post('close')
async close() {
console.log('[SerialController] POST /serial/close');
this.serial.close();
return { ok: true };
}
@Post('send')
async send(@Body() body: { payload: string }) {
console.log('[SerialController] POST /serial/send', body.payload);
try {
this.serial.send(body.payload);
return { ok: true };
} catch (e: any) {
console.error('[SerialController] send error', e);
return { ok: false, error: String(e) };
}
}
@Get('status')
status() {
return this.serial.status();
}
@Get('stream')
stream(@Req() req: Request, @Res() res: Response) {
// SSE stream
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
});
res.flushHeaders?.();
const sendEvent = (event: string, data: any) => {
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
};
const offData = this.serial.on('data', (line) => sendEvent('data', { line }));
const offOpen = this.serial.on('open', () => sendEvent('open', { ts: Date.now() }));
const offClose = this.serial.on('close', () => sendEvent('close', { ts: Date.now() }));
const offErr = this.serial.on('error', (err) => sendEvent('error', { message: String(err) }));
console.log('[SerialController] SSE client connected');
// send a ping every 20s to keep connection alive
const ping = setInterval(() => res.write(': ping\n\n'), 20000);
req.on('close', () => {
console.log('[SerialController] SSE client disconnected');
clearInterval(ping);
offData();
offOpen();
offClose();
offErr();
});
return res;
}
}

View File

@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { SerialService } from './serial.service';
import { SerialController } from './serial.controller';
@Module({
providers: [SerialService],
controllers: [SerialController],
exports: [SerialService],
})
export class SerialModule {}

View File

@@ -0,0 +1,154 @@
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { EventEmitter } from 'events';
// serialport has ESM/CJS shape differences and limited typings; require at runtime and keep as any
const SP: any = require('serialport');
const ReadlineParserModule: any = require('@serialport/parser-readline');
// normalize constructor and parser
const SerialCtor: any = SP?.SerialPort ?? SP;
const ParserCtor: any = ReadlineParserModule?.ReadlineParser ?? ReadlineParserModule;
type PortInfo = {
path: string;
manufacturer?: string;
serialNumber?: string;
pnpId?: string;
locationId?: string;
productId?: string;
vendorId?: string;
};
@Injectable()
export class SerialService implements OnModuleDestroy, OnModuleInit {
private emitter = new EventEmitter();
private port: any = null;
private parser: any = null;
async listPorts(): Promise<PortInfo[]> {
console.log('[SerialService] listPorts()');
let ports: any[] = [];
try {
if (typeof SP.list === 'function') {
ports = await SP.list();
} else {
// try the separate list package
try {
const listMod: any = require('@serialport/list');
if (typeof listMod.list === 'function') ports = await listMod.list();
else if (typeof listMod === 'function') ports = await listMod();
} catch (e) {
// fallback: empty list
ports = [];
}
}
} catch (e) {
console.error('[SerialService] listPorts error', e);
ports = [];
}
console.log('[SerialService] listPorts ->', ports);
return ports.map((p: any) => ({
path: p.path || p.comName,
manufacturer: p.manufacturer,
serialNumber: p.serialNumber,
pnpId: p.pnpId,
locationId: p.locationId,
productId: p.productId,
vendorId: p.vendorId,
}));
}
open(path: string, baudRate = 115200) {
this.close();
console.log('[SerialService] opening port', path, 'baud', baudRate);
this.port = new SerialCtor({ path, baudRate, autoOpen: false } as any);
this.parser = this.port.pipe(new ParserCtor({ delimiter: '\n' }));
this.port.on('open', () => {
console.log('[SerialService] port open', path);
this.emitter.emit('open');
});
this.port.on('error', (err: any) => {
console.error('[SerialService] port error', err);
this.emitter.emit('error', err?.message ?? String(err));
});
this.parser.on('data', (line: string) => {
console.log('[SerialService] RX:', line);
this.emitter.emit('data', line);
});
// open the port
try {
this.port.open((err: any) => {
if (err) {
console.error('[SerialService] open callback error', err);
this.emitter.emit('error', err?.message ?? String(err));
} else {
console.log('[SerialService] open callback success');
}
});
} catch (e: any) {
console.error('[SerialService] open exception', e);
this.emitter.emit('error', e?.message ?? String(e));
}
}
close() {
if (this.parser) {
this.parser.removeAllListeners();
this.parser = null;
}
if (this.port) {
try {
console.log('[SerialService] closing port', this.port?.path ?? '(unknown)');
this.port.close();
} catch (e) {
console.error('[SerialService] close error', e);
}
this.port = null;
}
this.emitter.emit('close');
}
send(line: string) {
if (!this.port || !(this.port.writable || this.port.isOpen)) {
console.warn('[SerialService] send called but port not open');
throw new Error('Port not open');
}
// write and flush
console.log('[SerialService] TX:', line);
this.port.write(line + '\n', (err: any) => {
if (err) console.error('[SerialService] write error', err);
else console.log('[SerialService] write success');
});
}
status() {
const s = {
open: !!(this.port && (this.port.isOpen || this.port.writable)),
path: this.port?.path ?? null,
};
console.log('[SerialService] status ->', s);
return s;
}
on(event: 'data' | 'open' | 'close' | 'error', cb: (...args: any[]) => void) {
this.emitter.on(event, cb);
return () => this.emitter.off(event, cb);
}
onModuleDestroy() {
this.close();
}
onModuleInit() {
const port = process.env.SERIAL_PORT;
const baud = process.env.SERIAL_BAUD ? Number(process.env.SERIAL_BAUD) : undefined;
if (port) {
try {
console.log('[SerialService] AUTO opening port from SERIAL_PORT=', port, 'baud=', baud ?? 115200);
this.open(port, baud ?? 115200);
} catch (e: any) {
console.warn('[SerialService] AUTO open failed', e?.message ?? e);
}
}
}
}