From d0af97122912dc7ea50fddc88a8b1a0c1f40e623 Mon Sep 17 00:00:00 2001 From: Michael Shepanski <435619+pkkid@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:32:44 -0500 Subject: [PATCH 1/3] feat(serial): support xTool firmware (D1) alongside stock GRBL xTool's controllers answer GRBL commands but differ in ways that left the D1 connected yet unable to move: - input is line based, so the bare '?' poll corrupted the next command; - '$J=' jogs are acknowledged but ignored, and motion only runs after an M2 program end (which is how LightBurn jogs it); - status reports carry no state word and come with an extra 'ok'; - 'ok:IDLE' / 'ok:512' chatter is not an acknowledgement. The dialect lives in serial/dialect.ts. On connect the machine sends $I and switches to the xTool command set only when the controller answers '[XTool ...]'; otherwise, or if nothing answers within 1.5 s, it behaves as before. A new Firmware device setting (Auto-detect / GRBL / xTool) lets users force either dialect; GRBL skips the $I entirely. Verified on an xTool D1 (fw 40.30.002.01): connect, status and jog. Co-Authored-By: Claude Opus 5.5 --- TODO.md | 3 ++ docs/USAGE.md | 12 +++++ src/App.tsx | 14 ++++++ src/gcode/types.ts | 3 ++ src/serial/dialect.test.ts | 37 +++++++++++++++ src/serial/dialect.ts | 48 +++++++++++++++++++ src/serial/machine.test.ts | 95 +++++++++++++++++++++++++++++++++++++ src/serial/machine.ts | 84 ++++++++++++++++++++++++++++---- src/ui/panels/RightDock.tsx | 4 +- 9 files changed, 289 insertions(+), 11 deletions(-) create mode 100644 src/serial/dialect.test.ts create mode 100644 src/serial/dialect.ts diff --git a/TODO.md b/TODO.md index d34e261..ee71632 100644 --- a/TODO.md +++ b/TODO.md @@ -154,6 +154,8 @@ Política, plantillas y cómo mockear los límites: [AGENTS.md](AGENTS.md). - [ ] Galvo / EZCad (BSLFiber) - [ ] Repeat marking / array desde la UI del láser - [x] Estimación de tiempo con aceleraciones +- [x] Firmware xTool (D1): detección con `$I`, jog con `M2` y sondeo `?\n` +- [ ] xTool: verificar Pause/Stop, progreso y trabajos largos en hardware real ### Producto - [ ] Empaquetado firmado (AppImage/NSIS/DMG) @@ -284,6 +286,7 @@ consumo de memoria. - Trace limitado a 700 px de lado mayor. - El raster de GCode se limita a 360 muestras por eje y muestrea la imagen por tiles (máx. 1600 px de lado). - Rotary, cámaras, Print & Cut y DSP están pendientes. +- xTool D1: solo se validó conexión y jog en hardware (fw 40.30.002.01). El firmware ejecuta el movimiento al recibir `M2`, así que el progreso del trabajo puede adelantarse al láser, y no se verificó si respeta `!`, `~` y `Ctrl+X` (Pause/Stop). - El puerto serie en Electron auto-selecciona el primer dispositivo (mejorable con un selector nativo). --- diff --git a/docs/USAGE.md b/docs/USAGE.md index 88aff0d..cc7733e 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -101,6 +101,16 @@ Cada color de la paleta es una capa (C00, C01, …). 2. Pulsa **Connect**. 3. Verás estado (`Idle`, `Run`, `Hold`, `Alarm`), `MPos`, feed y spindle. +#### Firmware +**Settings → Machine (GRBL) → Firmware** elige el dialecto del controlador: + +- **Auto-detect** (por defecto): al conectar envía `$I`. Si responde `[XTool …]` + usa el juego de comandos xTool; si responde `[VER:…]`, no responde o la placa se + reinicia al abrir el puerto, se comporta como GRBL estándar. +- **GRBL**: comportamiento GRBL de siempre, sin enviar `$I`. +- **xTool (D1 and similar)**: fuerza el dialecto xTool. Para el xTool D1 usa + **Baud 230400**. + ### Trabajo - **Frame**: mueve el cabezal alrededor de la selección (láser apagado, `S0`). - **Start**: genera el plan y lo transmite con control de flujo. @@ -110,6 +120,8 @@ Cada color de la paleta es una capa (C00, C01, …). ### Move - Jog por pasos (`$J`), **Home** (`$H`), **Unlock** (`$X`), **Origin** (`G10 L20 P1 X0 Y0`). +- En máquinas xTool el jog se envía como `G91` / `G1 … S0` / `G90` / `M2`, porque + ese firmware ignora `$J` y solo ejecuta el movimiento al recibir `M2`. - Ajusta **Step** y **Feed**. ### Consola y macros diff --git a/src/App.tsx b/src/App.tsx index 1a39bf4..eaefafd 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -340,6 +340,20 @@ function SettingsDialog({ onClose }: { onClose: () => void }) { ))} +
+ Firmware + +
Max S { + it('recognises controllers from their $I / banner lines', () => { + expect(dialectFromLine('[XTool D1:ver 40.30.002.01 B1]')).toBe('xtool'); + expect(dialectFromLine('[VER:1.1h.20190825:]')).toBe('grbl'); + expect(dialectFromLine("Grbl 1.1h ['$' for help]")).toBe('grbl'); + expect(dialectFromLine('ok')).toBeNull(); + expect(dialectFromLine('[MSG:Pgm End]')).toBeNull(); + }); + + it('polls stock GRBL with the real-time ? at all times', () => { + expect(statusPoll('grbl', false)).toBe('?'); + expect(statusPoll('grbl', true)).toBe('?'); + }); + + it('polls xTool with a full line, and not while a job streams', () => { + expect(statusPoll('xtool', false)).toBe('?\n'); + expect(statusPoll('xtool', true)).toBeNull(); + }); + + it('jogs stock GRBL with $J', () => { + expect(jogLines('grbl', 10, 0, 600)).toEqual(['$J=G91 X10 F600']); + expect(jogLines('grbl', 0, -1, 1000)).toEqual(['$J=G91 Y-1 F1000']); + }); + + it('jogs xTool with a relative move ended by M2', () => { + expect(jogLines('xtool', 0, -10, 6000)).toEqual(['G91', 'G1 Y-10 F6000 S0', 'G90', 'M2']); + }); + + it('treats ok:… lines as chatter, not acknowledgements', () => { + expect(isChatter('ok:IDLE')).toBe(true); + expect(isChatter('ok:512')).toBe(true); + expect(isChatter('ok')).toBe(false); + }); +}); diff --git a/src/serial/dialect.ts b/src/serial/dialect.ts new file mode 100644 index 0000000..33a3a92 --- /dev/null +++ b/src/serial/dialect.ts @@ -0,0 +1,48 @@ +/** + * Controller dialects. Most machines speak stock GRBL; xTool's firmware (D1 + * and similar) answers to GRBL commands but differs in ways that matter: + * + * - Input is strictly line based. GRBL's bare '?' real-time poll is buffered + * and corrupts the next command, so status needs '?\n'. + * - That status reply comes with an extra 'ok', which would be miscounted as a + * line acknowledgement while a job streams, so polling pauses during jobs. + * - '$J=' jogs are acknowledged but ignored, and motion commands are only + * executed after an M2 program end (this is also how LightBurn jogs it). + * - Status reports carry no state word: ''. + * - It emits 'ok:IDLE' / 'ok:512' chatter that is not an acknowledgement. + */ +export type Dialect = 'grbl' | 'xtool'; + +/** Device setting: detect from the controller's '$I' reply, or force one. */ +export type FirmwareSetting = 'auto' | Dialect; + +/** Sent on connect when auto-detecting; both dialects answer '$I'. */ +export const IDENTIFY_COMMAND = '\n$I\n'; + +/** How long to wait for an identification before assuming stock GRBL. */ +export const IDENTIFY_TIMEOUT_MS = 1500; + +/** Dialect announced by a controller line, or null if the line says nothing. */ +export function dialectFromLine(line: string): Dialect | null { + if (/^\[XTool/i.test(line)) return 'xtool'; + if (/^\[VER:|^Grbl /.test(line)) return 'grbl'; + return null; +} + +/** Status poll to send now, or null to skip this tick. */ +export function statusPoll(dialect: Dialect, jobActive: boolean): string | null { + if (dialect === 'xtool') return jobActive ? null : '?\n'; + return '?'; +} + +/** Lines that move the head by (dx, dy) mm at `feed` mm/min, laser off. */ +export function jogLines(dialect: Dialect, dx: number, dy: number, feed: number): string[] { + const axes = [dx !== 0 ? `X${dx}` : '', dy !== 0 ? `Y${dy}` : ''].filter(Boolean).join(' '); + if (dialect === 'xtool') return ['G91', `G1 ${axes} F${feed} S0`, 'G90', 'M2']; + return [`$J=G91 ${axes} F${feed}`]; +} + +/** Controller output that is neither data nor an acknowledgement. */ +export function isChatter(line: string): boolean { + return line.startsWith('ok:'); +} diff --git a/src/serial/machine.test.ts b/src/serial/machine.test.ts index 39b0c69..8a04c00 100644 --- a/src/serial/machine.test.ts +++ b/src/serial/machine.test.ts @@ -11,3 +11,98 @@ describe('machine console', () => { expect(first?.text).not.toContain('0.6.1'); }); }); + +import { afterEach, beforeEach, vi } from 'vitest'; +import type { FirmwareSetting } from './dialect'; +import type { Transport } from './transport'; + +/** Records writes and lets a test play controller replies. */ +class FakeTransport implements Transport { + readonly name = 'Fake'; + readonly isMock = false; + writes: string[] = []; + private data = new Set<(chunk: string) => void>(); + async connect(): Promise {} + async disconnect(): Promise {} + async write(data: string): Promise { + this.writes.push(data); + } + onData(h: (chunk: string) => void) { + this.data.add(h); + return () => this.data.delete(h); + } + onClose() { + return () => undefined; + } + reply(text: string): void { + this.data.forEach((h) => h(text)); + } +} + +async function connect(firmware: FirmwareSetting = 'auto'): Promise { + const t = new FakeTransport(); + const m = machine as unknown as { firmware: FirmwareSetting; attach(t: Transport): Promise }; + m.firmware = firmware; + await m.attach(t); + return t; +} + +describe('machine controller dialects', () => { + beforeEach(() => vi.useFakeTimers()); + afterEach(async () => { + await machine.disconnect(false); + vi.useRealTimers(); + }); + + it('asks the controller to identify itself before polling', async () => { + const t = await connect(); + expect(t.writes).toEqual(['\n$I\n']); + vi.advanceTimersByTime(1000); + expect(t.writes).toEqual(['\n$I\n']); + }); + + it('keeps stock GRBL behaviour once identified', async () => { + const t = await connect(); + t.reply('[VER:1.1h.20190825:]\n[OPT:V,15,128]\nok\n'); + t.writes = []; + vi.advanceTimersByTime(260); + expect(t.writes).toEqual(['?']); + t.writes = []; + machine.jog(10, 0, 600); + expect(t.writes).toEqual(['$J=G91 X10 F600\n']); + }); + + it('falls back to stock GRBL when nothing answers (board still resetting)', async () => { + const t = await connect(); + vi.advanceTimersByTime(1800); + expect(t.writes.at(-1)).toBe('?'); + }); + + it('switches to the xTool command set when the controller says so', async () => { + const t = await connect(); + t.reply('ok\nok\n[XTool D1:ver 40.30.002.01 B1]\n'); + t.writes = []; + vi.advanceTimersByTime(260); + expect(t.writes).toEqual(['?\n']); + + t.reply('ok\n\nok:IDLE\n'); + expect(machine.getState().mpos).toEqual({ x: -15, y: 4.5, z: 0 }); + expect(machine.getState().status).toBe('idle'); + + t.writes = []; + machine.jog(0, -10, 6000); + expect(t.writes).toEqual(['G91\nG1 Y-10 F6000 S0\nG90\nM2\n']); + }); + + it('honours a forced firmware setting without asking', async () => { + const t = await connect('xtool'); + vi.advanceTimersByTime(260); + expect(t.writes).toEqual(['?\n']); + }); + + it('forced GRBL behaves exactly as before: no $I, bare ? polls', async () => { + const t = await connect('grbl'); + vi.advanceTimersByTime(260); + expect(t.writes).toEqual(['?']); + }); +}); diff --git a/src/serial/machine.ts b/src/serial/machine.ts index b2b8613..67901cf 100644 --- a/src/serial/machine.ts +++ b/src/serial/machine.ts @@ -1,5 +1,15 @@ import { useSyncExternalStore } from 'react'; import type { JobPlan } from '@/gcode/types'; +import { + IDENTIFY_COMMAND, + IDENTIFY_TIMEOUT_MS, + dialectFromLine, + isChatter, + jogLines, + statusPoll, + type Dialect, + type FirmwareSetting, +} from './dialect'; import { MockTransport, WebSerialTransport, type Transport } from './transport'; export type MachineStatus = @@ -143,6 +153,11 @@ class Machine { private logBuffer: LogLine[] = []; private logTimer: number | null = null; private logCounter = 1; + /** See serial/dialect.ts. Polling waits until the dialect is known. */ + private firmware: FirmwareSetting = 'auto'; + private dialect: Dialect = 'grbl'; + private dialectKnown = false; + private identifyTimer: number | null = null; getState = (): MachineState => this.state; @@ -219,7 +234,11 @@ class Machine { } } - async connectSerial(baudRate: number, portIndex?: number): Promise { + async connectSerial( + baudRate: number, + portIndex?: number, + firmware: FirmwareSetting = 'auto', + ): Promise { if (!navigator.serial) { throw new Error('Web Serial is not available in this environment'); } @@ -230,6 +249,7 @@ class Machine { port = await navigator.serial.requestPort(); } const transport = new WebSerialTransport(port, baudRate); + this.firmware = firmware; await this.attach(transport); await this.refreshPorts(); } @@ -242,6 +262,7 @@ class Machine { } async connectMock(): Promise { + this.firmware = 'grbl'; await this.attach(new MockTransport()); } @@ -259,12 +280,40 @@ class Machine { lastError: null, }); this.pushLog('info', `Connected to ${transport.name}`); + this.identify(); this.startPolling(); } + /** Settle the dialect: forced by the device setting, or asked with $I. */ + private identify(): void { + this.dialect = 'grbl'; + this.dialectKnown = false; + if (this.firmware !== 'auto') { + this.setDialect(this.firmware); + return; + } + // A board that resets on open (Arduino) misses the $I and stays GRBL. + this.identifyTimer = window.setTimeout(() => { + this.identifyTimer = null; + this.dialectKnown = true; + }, IDENTIFY_TIMEOUT_MS); + void this.writeRaw(IDENTIFY_COMMAND); + } + + private setDialect(dialect: Dialect): void { + if (this.identifyTimer) window.clearTimeout(this.identifyTimer); + this.identifyTimer = null; + this.dialectKnown = true; + if (dialect === this.dialect) return; + this.dialect = dialect; + if (dialect === 'xtool') this.pushLog('info', 'Using xTool command set'); + } + async disconnect(log = true): Promise { this.stopJob(false); this.stopPolling(); + if (this.identifyTimer) window.clearTimeout(this.identifyTimer); + this.identifyTimer = null; if (this.transport) { try { await this.transport.disconnect(); @@ -304,7 +353,9 @@ class Machine { private startPolling(): void { this.stopPolling(); this.pollTimer = window.setInterval(() => { - if (this.transport) void this.writeRaw('?'); + if (!this.transport || !this.dialectKnown) return; + const poll = statusPoll(this.dialect, this.job !== null); + if (poll) void this.writeRaw(poll); }, 250); } @@ -330,6 +381,9 @@ class Machine { }; private handleLine(line: string): void { + if (isChatter(line)) return; + const dialect = dialectFromLine(line); + if (dialect && this.firmware === 'auto' && !this.dialectKnown) this.setDialect(dialect); if (line.startsWith('<')) { this.parseStatus(line); return; @@ -363,13 +417,15 @@ class Machine { private parseStatus(line: string): void { const body = line.replace(/^.*$/, ''); const parts = body.split('|'); - const status = mapStatus(parts[0] ?? 'Idle'); + // xTool reports '' with no state word; keep the current status. + const hasState = !(parts[0] ?? '').includes(':'); + const status = hasState ? mapStatus(parts[0] ?? 'Idle') : this.state.status; let mpos = this.state.mpos; let wpos = this.state.wpos; let feed = this.state.feed; let spindle = this.state.spindle; - for (const part of parts.slice(1)) { + for (const part of hasState ? parts.slice(1) : parts) { if (part.startsWith('MPos:')) { const [x, y, z] = part.slice(5).split(',').map(Number); mpos = { x: x || 0, y: y || 0, z: z || 0 }; @@ -431,11 +487,21 @@ class Machine { } jog(dx: number, dy: number, feed = 1000): void { - const parts = ['$J=G91']; - if (dx !== 0) parts.push(`X${dx}`); - if (dy !== 0) parts.push(`Y${dy}`); - parts.push(`F${feed}`); - this.sendCommand(parts.join(' ')); + this.sendLines(jogLines(this.dialect, dx, dy, feed)); + } + + /** Like sendCommand for a short program, written in one go. */ + private sendLines(lines: string[]): void { + if (!this.transport) { + this.pushLog('error', 'Not connected'); + return; + } + if (this.job) { + this.pushLog('error', 'Wait for the current job to finish (use Pause/Stop)'); + return; + } + lines.forEach((line) => this.pushLog('out', line)); + void this.writeRaw(lines.map((line) => `${line}\n`).join('')); } home(): void { diff --git a/src/ui/panels/RightDock.tsx b/src/ui/panels/RightDock.tsx index c67b91a..fd5ed2c 100644 --- a/src/ui/panels/RightDock.tsx +++ b/src/ui/panels/RightDock.tsx @@ -416,9 +416,9 @@ function LaserPanel() { if (port === 'mock') { await machine.connectMock(); } else if (port === 'auto') { - await machine.connectSerial(device.baudRate); + await machine.connectSerial(device.baudRate, undefined, device.firmware); } else { - await machine.connectSerial(device.baudRate, Number(port)); + await machine.connectSerial(device.baudRate, Number(port), device.firmware); } } catch (e) { setError((e as Error).message); From 2e95336603c8771f142e3f99b3bcde871a15201c Mon Sep 17 00:00:00 2001 From: Michael Shepanski <435619+pkkid@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:30:34 -0500 Subject: [PATCH 2/3] fix(serial): show a real port chooser and release the port on disconnect The desktop build answered Electron's select-serial-port event itself, taking the first port whose name contained "tty". On Linux that is often the motherboard UART (/dev/ttyS0), so the app reported "connected" while GCode went nowhere, and the user never saw which port was used. - Forward the port list to a renderer dialog that shows OS port names, preselects the USB adapter and flags built-in UARTs. - Show the chosen port name in the Laser panel and the port dropdown. - Disconnect now cancels the pending read so the port actually closes. - Serialize writes so a status poll overlapping a command no longer fails on the locked writer and drops the connection. Co-Authored-By: Claude Opus 5.5 --- TODO.md | 1 - docs/ARCHITECTURE.md | 5 +- docs/USAGE.md | 10 ++- electron/main.ts | 20 +++-- electron/preload.ts | 18 ++++ electron/serialPort.test.ts | 111 ++++++++++++++++++++++++ electron/serialPort.ts | 144 +++++++++++++++++++++++++++++++ src/App.tsx | 6 +- src/serial/machine.ts | 19 +++- src/serial/portChooser.ts | 63 ++++++++++++++ src/serial/transport.test.ts | 58 +++++++++++++ src/serial/transport.ts | 39 ++++++--- src/types/electron.d.ts | 20 +++++ src/ui/SerialPortDialog.test.tsx | 100 +++++++++++++++++++++ src/ui/SerialPortDialog.tsx | 102 ++++++++++++++++++++++ 15 files changed, 690 insertions(+), 26 deletions(-) create mode 100644 electron/serialPort.test.ts create mode 100644 electron/serialPort.ts create mode 100644 src/serial/portChooser.ts create mode 100644 src/serial/transport.test.ts create mode 100644 src/ui/SerialPortDialog.test.tsx create mode 100644 src/ui/SerialPortDialog.tsx diff --git a/TODO.md b/TODO.md index d34e261..b92e884 100644 --- a/TODO.md +++ b/TODO.md @@ -284,7 +284,6 @@ consumo de memoria. - Trace limitado a 700 px de lado mayor. - El raster de GCode se limita a 360 muestras por eje y muestrea la imagen por tiles (máx. 1600 px de lado). - Rotary, cámaras, Print & Cut y DSP están pendientes. -- El puerto serie en Electron auto-selecciona el primer dispositivo (mejorable con un selector nativo). --- diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5a29257..40f8156 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -158,7 +158,10 @@ UI (Laser/Move/Console) - `machine` mantiene estado observable: conexión, `MPos`, feed, spindle, trabajo, progreso y logs. - Polling de estado cada 250 ms (`?`). - Pausa/resume con `!`/`~`; stop con feed hold + soft reset (`Ctrl+X`). -- En Electron, el proceso principal concede permisos Web Serial y selecciona el puerto. +- En Electron, el proceso principal concede permisos Web Serial y reenvía la lista de + puertos (`select-serial-port`) al renderer por IPC (`serial:choose-port`); el + diálogo `SerialPortDialog` responde con `serial:port-chosen`. La lógica de + recomendación (USB primero, nunca `ttyS*`) está en `electron/serialPort.ts`. --- diff --git a/docs/USAGE.md b/docs/USAGE.md index 88aff0d..c2a51b7 100644 --- a/docs/USAGE.md +++ b/docs/USAGE.md @@ -96,9 +96,15 @@ Cada color de la paleta es una capa (C00, C01, …). ## 5. Conectar una máquina GRBL 1. Panel **Laser** → **Port**: - - **Ask on connect…**: pide permiso Web Serial y abre el puerto. + - **Ask on connect…**: al conectar, la app de escritorio muestra los puertos + serie reales (`/dev/ttyUSB0`, `COM3`, `/dev/cu.usbserial-…`) con el puerto USB + preseleccionado y descrito por su chip (p. ej. `CH340 USB serial (QinHeng) · + 1a86:7523`). Los puertos integrados de la placa base (`/dev/ttyS0`–`ttyS31`) + se ocultan tras **Show N built-in ports**: casi nunca son un láser. - **Simulator (demo)**: no requiere hardware; simula estados, oks y tiempos. -2. Pulsa **Connect**. + - Los puertos ya autorizados aparecen en la lista con su nombre. +2. Pulsa **Connect**. El panel muestra el puerto conectado; **Disconnect** lo + libera para que otra aplicación pueda usarlo. 3. Verás estado (`Idle`, `Run`, `Hold`, `Alarm`), `MPos`, feed y spindle. ### Trabajo diff --git a/electron/main.ts b/electron/main.ts index d9abb71..4ab5810 100644 --- a/electron/main.ts +++ b/electron/main.ts @@ -10,6 +10,7 @@ import { type MenuItemConstructorOptions, } from 'electron'; import path from 'node:path'; +import { SerialPortBroker } from './serialPort'; import fs from 'node:fs'; import { checkForUpdates, @@ -33,6 +34,7 @@ const userDataOverride = process.env.OPENBURN_USER_DATA_DIR; if (userDataOverride) app.setPath('userData', path.resolve(userDataOverride)); let mainWindow: BrowserWindow | null = null; +const serialPorts = new SerialPortBroker(); let windowStateTimer: NodeJS.Timeout | null = null; function persistWindowState(win: BrowserWindow): void { @@ -129,14 +131,16 @@ function createWindow() { } }); - // Allow Web Serial access from the renderer (GRBL connection). + // Allow Web Serial access from the renderer (GRBL connection). Electron has + // no built-in port chooser, so the list goes to the renderer's dialog. const ses = mainWindow.webContents.session; - ses.on('select-serial-port', (event, portList, _webContents, callback) => { + ses.on('select-serial-port', (event, portList, webContents, callback) => { event.preventDefault(); - // Prefer a USB/UART looking port; otherwise use the first one. - const port = - portList.find((p) => /usb|tty|acm|serial/i.test(p.portName ?? '')) ?? portList[0]; - callback(port ? port.portId : ''); + serialPorts.open( + portList, + (request) => webContents.send('serial:choose-port', request), + callback, + ); }); ses.setPermissionCheckHandler((_wc, permission) => permission === 'serial'); ses.setDevicePermissionHandler((details) => details.deviceType === 'serial'); @@ -144,6 +148,10 @@ function createWindow() { // ---- IPC handlers --------------------------------------------------------- +ipcMain.on('serial:port-chosen', (_e, requestId: number, portId: string | null) => { + serialPorts.resolve(requestId, portId); +}); + ipcMain.handle('dialog:openFile', async (_e, filters) => { const result = await dialog.showOpenDialog(mainWindow!, { properties: ['openFile'], diff --git a/electron/preload.ts b/electron/preload.ts index 28a79df..e0b4caf 100644 --- a/electron/preload.ts +++ b/electron/preload.ts @@ -26,6 +26,12 @@ export interface UpdaterState { manual?: boolean; } +export interface SerialPortRequest { + requestId: number; + ports: { portId: string; name: string; description: string; usb: boolean }[]; + recommendedId: string | null; +} + export interface RecentFile { path: string; name: string; @@ -101,6 +107,18 @@ const api = { return () => ipcRenderer.removeListener('updater:open-dialog', listener); }, }, + serial: { + /** Fired when the renderer asks for a port (navigator.serial.requestPort). */ + onChoosePort: (callback: (request: SerialPortRequest) => void): (() => void) => { + const listener = (_event: Electron.IpcRendererEvent, request: SerialPortRequest) => + callback(request); + ipcRenderer.on('serial:choose-port', listener); + return () => ipcRenderer.removeListener('serial:choose-port', listener); + }, + /** Answer a request; null cancels it. */ + choosePort: (requestId: number, portId: string | null): void => + ipcRenderer.send('serial:port-chosen', requestId, portId), + }, platform: process.platform, isElectron: true, }; diff --git a/electron/serialPort.test.ts b/electron/serialPort.test.ts new file mode 100644 index 0000000..14cc213 --- /dev/null +++ b/electron/serialPort.test.ts @@ -0,0 +1,111 @@ +// @vitest-environment node +import { describe, expect, it, vi } from 'vitest'; +import { SerialPortBroker, describeSerialPorts, describeUsbDevice, pickSerialPort } from './serialPort'; + +describe('pickSerialPort', () => { + it('prefers a USB adapter over the motherboard serial port listed first (regression)', () => { + const ports = [ + { portId: 'a', portName: 'ttyS0' }, + { portId: 'b', portName: 'ttyUSB0', vendorId: '6790', productId: '29987' }, + ]; + expect(pickSerialPort(ports)?.portId).toBe('b'); + }); + + it('falls back to USB-looking names when vendor ids are missing', () => { + const ports = [ + { portId: 'a', portName: 'ttyS0' }, + { portId: 'b', portName: 'ttyS1' }, + { portId: 'c', portName: 'ttyACM0' }, + ]; + expect(pickSerialPort(ports)?.portId).toBe('c'); + }); + + it('accepts a Windows COM port', () => { + expect(pickSerialPort([{ portId: 'a', portName: 'COM3' }])?.portId).toBe('a'); + }); + + it('recommends nothing when only built-in UARTs exist', () => { + expect(pickSerialPort([{ portId: 'a', portName: 'ttyS0' }])).toBeUndefined(); + expect(pickSerialPort([])).toBeUndefined(); + }); +}); + +describe('describeSerialPorts', () => { + it('lists USB ports first with full device paths on Linux', () => { + const request = describeSerialPorts( + 7, + [ + { portId: 'a', portName: 'ttyS0' }, + { portId: 'b', portName: 'ttyUSB0', displayName: 'USB Serial', vendorId: '6790', productId: '29987' }, + ], + 'linux', + ); + expect(request).toEqual({ + requestId: 7, + recommendedId: 'b', + ports: [ + { portId: 'b', name: '/dev/ttyUSB0', description: 'CH340 USB serial (QinHeng) · 1a86:7523', usb: true }, + { portId: 'a', name: '/dev/ttyS0', description: '', usb: false }, + ], + }); + }); + + it('keeps Windows names as they are', () => { + const request = describeSerialPorts(1, [{ portId: 'a', portName: 'COM3' }], 'win32'); + expect(request.ports[0]?.name).toBe('COM3'); + }); +}); + +describe('SerialPortBroker', () => { + it('routes the renderer answer to the matching callback', () => { + const broker = new SerialPortBroker(); + const send = vi.fn(); + const callback = vi.fn(); + broker.open([{ portId: 'p1', portName: 'ttyUSB0' }], send, callback); + const { requestId } = send.mock.calls[0]![0]; + broker.resolve(requestId + 1, 'p1'); + expect(callback).not.toHaveBeenCalled(); + broker.resolve(requestId, 'p1'); + expect(callback).toHaveBeenCalledWith('p1'); + }); + + it('treats a dismissed chooser as a cancelled request', () => { + const broker = new SerialPortBroker(); + const send = vi.fn(); + const callback = vi.fn(); + broker.open([], send, callback); + broker.resolve(send.mock.calls[0]![0].requestId, null); + expect(callback).toHaveBeenCalledWith(''); + }); + + it('cancels an abandoned request when a new one opens', () => { + const broker = new SerialPortBroker(); + const first = vi.fn(); + broker.open([], vi.fn(), first); + broker.open([], vi.fn(), vi.fn()); + expect(first).toHaveBeenCalledWith(''); + }); +}); + +describe('describeUsbDevice', () => { + // Real values Electron reported for an xTool D1 (decimal ids). + const d1 = { portId: 'x', portName: 'ttyUSB0', displayName: 'USB Serial', vendorId: '6790', productId: '29987' }; + + it('names known USB serial chips like lsusb does', () => { + expect(describeUsbDevice(d1)).toBe('CH340 USB serial (QinHeng) · 1a86:7523'); + expect(describeUsbDevice({ portId: 'y', vendorId: String(0x10c4), productId: String(0xea60) })).toBe( + 'CP210x USB serial (Silicon Labs) · 10c4:ea60', + ); + }); + + it('matches any product from vendors that only make boards', () => { + expect(describeUsbDevice({ portId: 'z', vendorId: String(0x2341), productId: String(0x0043) })).toBe( + 'Arduino board (Arduino) · 2341:0043', + ); + }); + + it('falls back to the device name, then a generic label', () => { + expect(describeUsbDevice({ ...d1, vendorId: '1', productId: '2' })).toBe('USB Serial · 0001:0002'); + expect(describeUsbDevice({ portId: 'q', portName: 'ttyACM0' })).toBe('USB serial device'); + }); +}); diff --git a/electron/serialPort.ts b/electron/serialPort.ts new file mode 100644 index 0000000..a60530d --- /dev/null +++ b/electron/serialPort.ts @@ -0,0 +1,144 @@ +/** Minimal shape of the ports Electron passes to 'select-serial-port'. */ +export interface SerialPortCandidate { + portId: string; + portName?: string; + displayName?: string; + vendorId?: string; + productId?: string; +} + +/** A port as shown in the renderer's chooser. */ +export interface SerialPortChoice { + portId: string; + /** OS name of the port: /dev/ttyUSB0, COM3, /dev/cu.usbserial-1410… */ + name: string; + /** What the device is, e.g. "CH340 USB serial (QinHeng) · 1a86:7523". */ + description: string; + usb: boolean; +} + +export interface SerialPortRequest { + requestId: number; + ports: SerialPortChoice[]; + /** Port to preselect, or null when none looks like a laser. */ + recommendedId: string | null; +} + +// USB serial chips and boards commonly found in GRBL lasers, keyed by +// hex vendor id, then product id ('*' = any product from that vendor). +const USB_DEVICES: Record }> = { + '1a86': { + vendor: 'QinHeng', + products: { '7523': 'CH340 USB serial', '5523': 'CH341 USB serial', '55d4': 'CH9102 USB serial' }, + }, + '0403': { + vendor: 'FTDI', + products: { '6001': 'FT232R USB serial', '6015': 'FT231X USB serial', '6010': 'FT2232 USB serial' }, + }, + '10c4': { vendor: 'Silicon Labs', products: { ea60: 'CP210x USB serial' } }, + '067b': { vendor: 'Prolific', products: { '2303': 'PL2303 USB serial' } }, + '2341': { vendor: 'Arduino', products: { '*': 'Arduino board' } }, + '2a03': { vendor: 'Arduino', products: { '*': 'Arduino board' } }, + '0483': { vendor: 'STMicroelectronics', products: { '5740': 'STM32 virtual COM port' } }, + '303a': { vendor: 'Espressif', products: { '*': 'ESP32 USB serial' } }, + '2e8a': { vendor: 'Raspberry Pi', products: { '*': 'RP2040 board' } }, + '1d50': { vendor: 'OpenMoko', products: { '6015': 'Smoothieboard' } }, +}; + +/** + * Electron reports USB ids as decimal strings ("6790"); turn one into the + * 4-digit hex form lsusb and datasheets use ("1a86"). + */ +function hexId(id: string | undefined): string | null { + if (!id || !/^\d+$/.test(id)) return null; + return Number(id).toString(16).padStart(4, '0'); +} + +/** "CH340 USB serial (QinHeng) · 1a86:7523", or a generic fallback. */ +export function describeUsbDevice(port: SerialPortCandidate): string { + const vid = hexId(port.vendorId); + const pid = hexId(port.productId); + const ids = vid && pid ? ` · ${vid}:${pid}` : ''; + const known = vid ? USB_DEVICES[vid] : undefined; + const product = known && pid ? (known.products[pid] ?? known.products['*']) : undefined; + if (known && product) return `${product} (${known.vendor})${ids}`; + // The device's own name is often just "USB Serial"; still better than nothing. + if (port.displayName && port.displayName !== port.portName) return `${port.displayName}${ids}`; + return `USB serial device${ids}`; +} + +// USB-to-serial adapters and native USB CDC devices across platforms. +const USB_NAME = /ttyUSB|ttyACM|usbserial|usbmodem|cu\.wch|wchusbserial/i; +// Built-in UARTs that are never a laser (Linux /dev/ttyS*, macOS Bluetooth). +const BUILTIN_NAME = /^(\/dev\/)?ttyS\d+$|bluetooth|debug-console/i; + +const rawName = (p: SerialPortCandidate) => p.portName ?? p.displayName ?? ''; +const isUsb = (p: SerialPortCandidate) => Boolean(p.vendorId) || USB_NAME.test(rawName(p)); + +/** + * Choose the port most likely to be a GRBL controller. USB devices win, and + * motherboard UARTs (ttyS0) are never recommended: picking one connects + * "successfully" but sends GCode nowhere. + */ +export function pickSerialPort(ports: T[]): T | undefined { + return ( + ports.find((p) => p.vendorId) ?? + ports.find((p) => USB_NAME.test(rawName(p))) ?? + ports.find((p) => !BUILTIN_NAME.test(rawName(p))) + ); +} + +/** Build the chooser payload: USB ports first, the recommended one preselected. */ +export function describeSerialPorts( + requestId: number, + ports: SerialPortCandidate[], + platform: string = process.platform, +): SerialPortRequest { + const choices = ports.map((p): SerialPortChoice => { + const raw = rawName(p) || p.portId; + const name = platform === 'linux' && !raw.includes('/') ? `/dev/${raw}` : raw; + const usb = isUsb(p); + const description = usb + ? describeUsbDevice(p) + : p.displayName && p.displayName !== raw + ? p.displayName + : ''; + return { portId: p.portId, name, description, usb }; + }); + choices.sort((a, b) => Number(b.usb) - Number(a.usb)); + return { requestId, ports: choices, recommendedId: pickSerialPort(ports)?.portId ?? null }; +} + +/** + * Tracks port requests between Electron's 'select-serial-port' event and the + * renderer's chooser dialog, so each answer reaches the right callback. + */ +export class SerialPortBroker { + private nextId = 1; + private pending = new Map void>(); + + open( + ports: SerialPortCandidate[], + send: (request: SerialPortRequest) => void, + callback: (portId: string) => void, + ): void { + // Chromium only allows one chooser at a time; drop any abandoned one. + this.cancelAll(); + const requestId = this.nextId++; + this.pending.set(requestId, callback); + send(describeSerialPorts(requestId, ports)); + } + + /** Answer a request; null or an unknown port cancels it. */ + resolve(requestId: number, portId: string | null): void { + const callback = this.pending.get(requestId); + if (!callback) return; + this.pending.delete(requestId); + callback(portId ?? ''); + } + + cancelAll(): void { + for (const callback of this.pending.values()) callback(''); + this.pending.clear(); + } +} diff --git a/src/App.tsx b/src/App.tsx index 1a39bf4..5acd26b 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -16,6 +16,7 @@ import { StatusBar } from '@/ui/StatusBar'; import { Modal, NumberField, UnitsContext, WorkspaceContext } from '@/ui/common'; import { PreviewDialog } from '@/ui/PreviewDialog'; import { UpdateBanner, UpdateDialog } from '@/ui/UpdateDialog'; +import { SerialPortDialog } from '@/ui/SerialPortDialog'; import { DiscardChangesDialog } from '@/ui/DiscardChangesDialog'; import { RecoveryDialog } from '@/ui/RecoveryDialog'; import { WelcomeDialog } from '@/ui/WelcomeDialog'; @@ -221,6 +222,7 @@ export default function App() {
+ {settingsOpen && setSettingsOpen(false)} />} {deviceOpen && setDeviceOpen(false)} />} {updateOpen && setUpdateOpen(false)} />} @@ -499,8 +501,8 @@ function DeviceSettingsDialog({ onClose }: { onClose: () => void }) { Show bed outline

- Serial communication uses the Web Serial API. In the desktop build, choose a port in the - Laser panel to grant access; the simulator lets you try job streaming without hardware. + Serial communication uses the Web Serial API. In the desktop build, Connect in the Laser + panel lists the available ports; the simulator lets you try job streaming without hardware.

); diff --git a/src/serial/machine.ts b/src/serial/machine.ts index b2b8613..1bf9881 100644 --- a/src/serial/machine.ts +++ b/src/serial/machine.ts @@ -1,6 +1,7 @@ import { useSyncExternalStore } from 'react'; import type { JobPlan } from '@/gcode/types'; import { MockTransport, WebSerialTransport, type Transport } from './transport'; +import { portChooser } from './portChooser'; export type MachineStatus = | 'disconnected' @@ -133,6 +134,8 @@ class Machine { private listeners = new Set<() => void>(); private transport: Transport | null = null; private serialPorts: SerialPort[] = []; + /** OS names (/dev/ttyUSB0, COM3) of ports picked in the desktop chooser. */ + private portNames = new WeakMap(); private buffer = ''; private job: ActiveJob | null = null; private pendingBytes: number[] = []; @@ -208,9 +211,10 @@ class Machine { const info = port.getInfo?.() ?? {}; const vid = info.usbVendorId?.toString(16).padStart(4, '0'); const pid = info.usbProductId?.toString(16).padStart(4, '0'); + const name = this.portNames.get(port); return { index, - label: vid && pid ? `USB ${vid}:${pid}` : `Serial port ${index + 1}`, + label: name ?? (vid && pid ? `USB ${vid}:${pid}` : `Serial port ${index + 1}`), }; }); this.setState({ ports }); @@ -227,20 +231,27 @@ class Machine { if (portIndex !== undefined && this.serialPorts[portIndex]) { port = this.serialPorts[portIndex]; } else { - port = await navigator.serial.requestPort(); + port = await this.askForPort(); } - const transport = new WebSerialTransport(port, baudRate); + const transport = new WebSerialTransport(port, baudRate, this.portNames.get(port)); await this.attach(transport); await this.refreshPorts(); } async requestPort(): Promise { if (!navigator.serial) throw new Error('Web Serial is not available'); - const port = await navigator.serial.requestPort(); + const port = await this.askForPort(); this.serialPorts = [...this.serialPorts.filter((p) => p !== port), port]; await this.refreshPorts(); } + private async askForPort(): Promise { + const port = await navigator.serial!.requestPort(); + const choice = portChooser.takeLastChoice(); + if (choice) this.portNames.set(port, choice.name); + return port; + } + async connectMock(): Promise { await this.attach(new MockTransport()); } diff --git a/src/serial/portChooser.ts b/src/serial/portChooser.ts new file mode 100644 index 0000000..15cb7bd --- /dev/null +++ b/src/serial/portChooser.ts @@ -0,0 +1,63 @@ +import { useSyncExternalStore } from 'react'; + +/** + * Renderer side of the desktop serial port chooser. Electron forwards + * navigator.serial.requestPort() here instead of picking a port silently, and + * the dialog answers through choose(). + */ +export interface PortChooserState { + request: OpenBurnSerialPortRequest | null; +} + +let state: PortChooserState = { request: null }; +let lastChoice: OpenBurnSerialPortChoice | null = null; +let unsubscribeBridge: (() => void) | null = null; +const listeners = new Set<() => void>(); + +function setState(next: PortChooserState): void { + state = next; + listeners.forEach((l) => l()); +} + +export const portChooser = { + getState: (): PortChooserState => state, + + subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => listeners.delete(listener); + }, + + /** Start listening to the Electron bridge; a no-op in the browser build. */ + init(): void { + if (unsubscribeBridge) return; + const bridge = window.openburn?.serial; + if (!bridge) return; + unsubscribeBridge = bridge.onChoosePort((request) => setState({ request })); + }, + + dispose(): void { + unsubscribeBridge?.(); + unsubscribeBridge = null; + setState({ request: null }); + }, + + /** Answer the pending request; null cancels it. */ + choose(portId: string | null): void { + const request = state.request; + if (!request) return; + lastChoice = request.ports.find((p) => p.portId === portId) ?? null; + window.openburn?.serial?.choosePort(request.requestId, lastChoice ? portId : null); + setState({ request: null }); + }, + + /** The port picked in the last dialog, consumed once by the connection code. */ + takeLastChoice(): OpenBurnSerialPortChoice | null { + const choice = lastChoice; + lastChoice = null; + return choice; + }, +}; + +export function usePortChooser(): PortChooserState { + return useSyncExternalStore(portChooser.subscribe, portChooser.getState, portChooser.getState); +} diff --git a/src/serial/transport.test.ts b/src/serial/transport.test.ts new file mode 100644 index 0000000..a1c7a54 --- /dev/null +++ b/src/serial/transport.test.ts @@ -0,0 +1,58 @@ +// @vitest-environment node +import { describe, expect, it } from 'vitest'; +import { WebSerialTransport } from './transport'; + +/** A Web Serial port backed by real streams that never receives data. */ +function idlePort() { + const written: string[] = []; + let open = false; + const port = { + readable: null as ReadableStream | null, + writable: null as WritableStream | null, + async open() { + open = true; + // Like an idle controller: read() stays pending until cancelled. + port.readable = new ReadableStream(); + port.writable = new WritableStream({ + async write(chunk) { + await new Promise((r) => setTimeout(r, 5)); + written.push(new TextDecoder().decode(chunk)); + }, + }); + }, + async close() { + if (port.readable?.locked) throw new Error('readable is locked'); + open = false; + }, + getInfo: () => ({}), + }; + return { port: port as unknown as SerialPort, written, isOpen: () => open }; +} + +describe('WebSerialTransport', () => { + it('closes the port on disconnect even when no data is arriving (regression)', async () => { + const { port, isOpen } = idlePort(); + const transport = new WebSerialTransport(port, 115200); + await transport.connect(); + const result = await Promise.race([ + transport.disconnect().then(() => 'closed'), + new Promise((r) => setTimeout(() => r('hung'), 500)), + ]); + expect(result).toBe('closed'); + expect(isOpen()).toBe(false); + }); + + it('queues overlapping writes instead of failing on the locked writer (regression)', async () => { + const { port, written } = idlePort(); + const transport = new WebSerialTransport(port, 115200); + await transport.connect(); + await Promise.all([transport.write('?'), transport.write('G0 X1\n'), transport.write('?')]); + expect(written).toEqual(['?', 'G0 X1\n', '?']); + await transport.disconnect(); + }); + + it('names itself after the chosen port', () => { + expect(new WebSerialTransport(idlePort().port, 115200, '/dev/ttyUSB0').name).toBe('/dev/ttyUSB0'); + expect(new WebSerialTransport(idlePort().port, 115200).name).toBe('Serial'); + }); +}); diff --git a/src/serial/transport.ts b/src/serial/transport.ts index 1a7ae9e..1b95a9d 100644 --- a/src/serial/transport.ts +++ b/src/serial/transport.ts @@ -10,17 +10,21 @@ export interface Transport { export class WebSerialTransport implements Transport { readonly isMock = false; - readonly name = 'Serial'; + readonly name: string; private port: SerialPort; private baudRate: number; private dataHandlers = new Set<(chunk: string) => void>(); private closeHandlers = new Set<() => void>(); private closed = false; private readTask: Promise | null = null; + private reader: ReadableStreamDefaultReader | null = null; + private writeChain: Promise = Promise.resolve(); - constructor(port: SerialPort, baudRate: number) { + /** `portName` is the OS name shown to the user, e.g. /dev/ttyUSB0. */ + constructor(port: SerialPort, baudRate: number, portName?: string) { this.port = port; this.baudRate = baudRate; + this.name = portName ?? 'Serial'; } async connect(): Promise { @@ -33,6 +37,7 @@ export class WebSerialTransport implements Transport { const decoder = new TextDecoder(); while (!this.closed && this.port.readable) { const reader = this.port.readable.getReader(); + this.reader = reader; try { for (;;) { const { value, done } = await reader.read(); @@ -45,6 +50,7 @@ export class WebSerialTransport implements Transport { } catch { // Device unplugged or stream cancelled } finally { + this.reader = null; reader.releaseLock(); } if (this.closed) break; @@ -54,18 +60,31 @@ export class WebSerialTransport implements Transport { this.emitClose(); } - async write(data: string): Promise { - if (!this.port.writable) throw new Error('Serial port is not writable'); - const writer = this.port.writable.getWriter(); - try { - await writer.write(new TextEncoder().encode(data)); - } finally { - writer.releaseLock(); - } + write(data: string): Promise { + // Serialize writes: a second getWriter() while one is held throws, which + // happens when a status poll overlaps a command. + const next = this.writeChain.then(async () => { + if (!this.port.writable) throw new Error('Serial port is not writable'); + const writer = this.port.writable.getWriter(); + try { + await writer.write(new TextEncoder().encode(data)); + } finally { + writer.releaseLock(); + } + }); + this.writeChain = next.catch(() => undefined); + return next; } async disconnect(): Promise { this.closed = true; + try { + // reader.read() blocks until data arrives; cancel it so the read loop + // exits and the port can actually close. + await this.reader?.cancel(); + } catch { + /* ignore */ + } try { await this.readTask; } catch { diff --git a/src/types/electron.d.ts b/src/types/electron.d.ts index a729328..e9d9741 100644 --- a/src/types/electron.d.ts +++ b/src/types/electron.d.ts @@ -56,6 +56,25 @@ declare global { clear(): Promise; } + interface OpenBurnSerialPortChoice { + portId: string; + /** OS name: /dev/ttyUSB0, COM3, /dev/cu.usbserial-1410… */ + name: string; + description: string; + usb: boolean; + } + + interface OpenBurnSerialPortRequest { + requestId: number; + ports: OpenBurnSerialPortChoice[]; + recommendedId: string | null; + } + + interface OpenBurnSerialApi { + onChoosePort(callback: (request: OpenBurnSerialPortRequest) => void): () => void; + choosePort(requestId: number, portId: string | null): void; + } + interface OpenBurnFileApi { openFile(filters?: { name: string; extensions: string[] }[]): Promise; saveFile(options?: { @@ -77,6 +96,7 @@ declare global { autosave: OpenBurnAutosaveApi; recent: OpenBurnRecentApi; updater?: OpenBurnUpdaterApi; + serial?: OpenBurnSerialApi; platform: string; isElectron: boolean; } diff --git a/src/ui/SerialPortDialog.test.tsx b/src/ui/SerialPortDialog.test.tsx new file mode 100644 index 0000000..3f23f69 --- /dev/null +++ b/src/ui/SerialPortDialog.test.tsx @@ -0,0 +1,100 @@ +import { act, render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { portChooser } from '@/serial/portChooser'; +import { SerialPortDialog } from './SerialPortDialog'; + +let emit: (request: OpenBurnSerialPortRequest) => void = () => undefined; +const choosePort = vi.fn(); + +const request: OpenBurnSerialPortRequest = { + requestId: 3, + recommendedId: 'usb', + ports: [ + { portId: 'usb', name: '/dev/ttyUSB0', description: 'CH340 USB serial (QinHeng) · 1a86:7523', usb: true }, + // Linux lists /dev/ttyS0-31 on most PCs. + ...Array.from({ length: 32 }, (_, i) => ({ + portId: `uart${i}`, + name: `/dev/ttyS${i}`, + description: '', + usb: false, + })), + ], +}; + +beforeEach(() => { + choosePort.mockReset(); + (window as unknown as { openburn: unknown }).openburn = { + serial: { + onChoosePort: (cb: typeof emit) => { + emit = cb; + return () => undefined; + }, + choosePort, + }, + }; +}); + +afterEach(() => { + portChooser.dispose(); + delete (window as unknown as { openburn?: unknown }).openburn; +}); + +describe('SerialPortDialog', () => { + it('stays hidden until the app asks for a port', () => { + render(); + expect(screen.queryByText('Choose serial port')).toBeNull(); + }); + + it('lists only the USB port, described, and preselected', async () => { + render(); + act(() => emit(request)); + expect(screen.getByText('/dev/ttyUSB0')).toBeTruthy(); + expect(screen.getByText('CH340 USB serial (QinHeng) · 1a86:7523')).toBeTruthy(); + expect(screen.queryByText('/dev/ttyS0')).toBeNull(); + const radios = screen.getAllByRole('radio') as HTMLInputElement[]; + expect(radios).toHaveLength(1); + expect(radios[0]!.checked).toBe(true); + + await userEvent.click(screen.getByRole('button', { name: 'Connect' })); + expect(choosePort).toHaveBeenCalledWith(3, 'usb'); + expect(portChooser.takeLastChoice()?.name).toBe('/dev/ttyUSB0'); + expect(screen.queryByText('Choose serial port')).toBeNull(); + }); + + it('can reveal and pick a built-in port', async () => { + render(); + act(() => emit(request)); + await userEvent.click(screen.getByRole('button', { name: 'Show 32 built-in ports' })); + expect(screen.getAllByRole('radio')).toHaveLength(33); + expect(screen.getAllByText('Built-in serial port, usually not a laser')).toHaveLength(32); + await userEvent.click(screen.getAllByRole('radio')[1]!); + await userEvent.click(screen.getByRole('button', { name: 'Connect' })); + expect(choosePort).toHaveBeenCalledWith(3, 'uart0'); + }); + + it('shows every port when none of them is USB', () => { + render(); + act(() => + emit({ requestId: 5, recommendedId: null, ports: request.ports.filter((p) => !p.usb) }), + ); + expect(screen.getByText(/No USB serial ports found/)).toBeTruthy(); + expect(screen.getAllByRole('radio')).toHaveLength(32); + expect(screen.queryByRole('button', { name: /built-in ports/ })).toBeNull(); + }); + + it('cancels the request when dismissed', async () => { + render(); + act(() => emit(request)); + await userEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(choosePort).toHaveBeenCalledWith(3, null); + expect(portChooser.takeLastChoice()).toBeNull(); + }); + + it('explains an empty port list', () => { + render(); + act(() => emit({ requestId: 4, recommendedId: null, ports: [] })); + expect(screen.getByText(/No serial ports found/)).toBeTruthy(); + expect((screen.getByRole('button', { name: 'Connect' }) as HTMLButtonElement).disabled).toBe(true); + }); +}); diff --git a/src/ui/SerialPortDialog.tsx b/src/ui/SerialPortDialog.tsx new file mode 100644 index 0000000..505a942 --- /dev/null +++ b/src/ui/SerialPortDialog.tsx @@ -0,0 +1,102 @@ +import { useEffect, useState } from 'react'; +import { portChooser, usePortChooser } from '@/serial/portChooser'; +import { Modal } from './common'; + +/** Lets the user see and pick the actual serial port before connecting. */ +export function SerialPortDialog() { + const { request } = usePortChooser(); + + useEffect(() => { + portChooser.init(); + }, []); + + if (!request) return null; + return ; +} + +function PortList({ request }: { request: OpenBurnSerialPortRequest }) { + const [selected, setSelected] = useState( + request.recommendedId ?? request.ports[0]?.portId ?? null, + ); + const [showAll, setShowAll] = useState(false); + const cancel = () => portChooser.choose(null); + + // Linux exposes dozens of motherboard UARTs (/dev/ttyS0-31) that are never a + // laser; only USB ports (and the recommendation) are listed by default. + const relevant = request.ports.filter((p) => p.usb || p.portId === request.recommendedId); + const hiddenCount = request.ports.length - relevant.length; + const visible = showAll || relevant.length === 0 ? request.ports : relevant; + + return ( + + + + + } + > + {request.ports.length === 0 ? ( +

+ No serial ports found. Check that the laser is plugged in and powered on, then try + again. +

+ ) : ( + <> + {relevant.length === 0 && ( +

+ No USB serial ports found. Check that the laser is plugged in and powered on. +

+ )} +
+ {visible.map((port) => ( + + ))} +
+ {hiddenCount > 0 && relevant.length > 0 && ( + + )} + + )} +
+ ); +} From 915f5bc9cc3b710f764dff040eb279d99f90f310 Mon Sep 17 00:00:00 2001 From: Santiago Leal Date: Tue, 17 Nov 2026 18:11:57 -0400 Subject: [PATCH 3/3] docs(serial): changelog, README and architecture for the serial integration Tie the two merged PRs together in user-facing docs: - CHANGELOG [Unreleased]: xTool firmware and the desktop port chooser under Added, the ttyS0 / disconnect / locked-writer bugs under Fixed, the xTool M2 limitation, and credit to @pkkid. - README and README.es: the port chooser and xTool detection in the GRBL control section. - ARCHITECTURE: xTool status polling and the M2 caveat next to the pause and stop commands. - TODO: a Serial/firmware block with the remaining follow-ups (port chooser e2e, hardware verification on xTool, migration test for openburn.device). Verified: npm run typecheck, npm run test (289/289) and npm run build. --- CHANGELOG.md | 29 +++++++++++++++++++++++++++++ README.es.md | 5 +++++ README.md | 6 +++++- TODO.md | 10 ++++++++++ docs/ARCHITECTURE.md | 7 +++++-- 5 files changed, 54 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f1da864..8ba648f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,35 @@ Todas las novedades relevantes de OpenBurn. El formato sigue ## [Unreleased] +### Añadido +- **Firmware xTool (D1 y similares)**: al conectar se envía `$I` y, si el + controlador responde `[XTool …]`, la app usa su juego de comandos (sondeo + `?\n`, jog `G91`/`G1 … S0`/`G90`/`M2`, ruido `ok:` ignorado). Con 1,5 s sin + respuesta se mantiene GRBL. Nuevo ajuste *Device → Firmware* (Auto-detect / + GRBL / xTool) para forzarlo. Lógica en `src/serial/dialect.ts`. +- **Selector de puerto serie real en escritorio**: *Connect* muestra los puertos + del sistema (`/dev/ttyUSB0`, `COM3`, `/dev/cu.usbserial-…`) con el chip USB + descrito, preselecciona el adaptador y oculta los UART de la placa base. + +### Arreglado +- El proceso principal ya no elige el primer puerto `tty` (a menudo + `/dev/ttyS0`): antes decía "conectado" mientras el GCode no llegaba a ningún + sitio. El puerto elegido se muestra en el panel Laser. +- **Disconnect** cancela la lectura pendiente, así que el puerto se libera de + verdad para otros programas. +- Las escrituras serie se serializan: un sondeo de estado que coincidía con un + comando ya no falla por el writer bloqueado ni tumba la conexión. + +### Limitaciones conocidas +- xTool solo se validó en conexión y jog (D1, fw 40.30.002.01); el progreso del + trabajo puede adelantarse al cabezal y Pause/Stop no está verificado. + +### Desarrollo +- Tests nuevos: `electron/serialPort.test.ts` (catálogo USB, recomendación de + puerto y broker), `src/serial/transport.test.ts` (escrituras serializadas y + cierre), `src/ui/SerialPortDialog.test.tsx` y `src/serial/dialect.test.ts`. +- Contribuciones de [@pkkid](https://github.com/pkkid) (PRs #3 y #4). + ## [0.11.0] - 2026-11-13 ### Añadido diff --git a/README.es.md b/README.es.md index 9f190a9..5c69478 100644 --- a/README.es.md +++ b/README.es.md @@ -147,7 +147,12 @@ Detalle completo en [CHANGELOG.md](CHANGELOG.md). ### Control GRBL - Conexión por **Web Serial** o con el **simulador integrado** (sin hardware). + En la app de escritorio, *Connect* lista los puertos reales del sistema con su + chip USB y nunca preselecciona el UART de la placa base (`/dev/ttyS0`). - Streaming con control de flujo, `Frame`, `Start`, `Pause/Resume` y `Stop`. +- **Firmware xTool** (D1 y similares): se detecta al conectar (`$I` → `[XTool …]`) + y también se puede forzar en **Settings → Machine**. En xTool el jog se envía + como `G91` / `G1 … S0` / `G90` / `M2`, porque ese firmware ignora `$J`. - Jog (`$J`), homing (`$H`), unlock (`$X`) y fijar origen (`G10 L20`). - Consola bidireccional y macros persistentes. - Estado en vivo: posición, feed, spindle, progreso y tiempo restante. diff --git a/README.md b/README.md index ea82721..ad20f69 100644 --- a/README.md +++ b/README.md @@ -145,8 +145,12 @@ Full details in [CHANGELOG.md](CHANGELOG.md). ### GRBL control - Connect over **Web Serial** or the **built-in simulator** (no hardware - needed). + needed). On the desktop app, Connect lists the real OS ports with their USB + chip and never preselects the motherboard UART (`/dev/ttyS0`). - Flow-controlled streaming, `Frame`, `Start`, `Pause/Resume` and `Stop`. +- **xTool firmware** (D1 and similar) is detected on connect (`$I` → `[XTool …]`) + and can also be forced in **Settings → Machine**. On xTool the jog is sent as + `G91` / `G1 … S0` / `G90` / `M2`, because that firmware ignores `$J`. - Jog (`$J`), homing (`$H`), unlock (`$X`) and set origin (`G10 L20`). - Two-way console and persistent macros. - Live status: position, feed, spindle, progress and time remaining. diff --git a/TODO.md b/TODO.md index 9278a1f..0fb78ef 100644 --- a/TODO.md +++ b/TODO.md @@ -300,3 +300,13 @@ consumo de memoria. - Raster progresivo/streaming para levantar el límite de 360 muestras por eje. - Sitio de documentación con buscador (hoy todo vive en `docs/`). - Plantillas de issue/PR, `CODE_OF_CONDUCT.md`, etiquetas `good first issue`. + +### Serie / firmware (tras los PRs #3 y #4) +- [x] Selector de puerto serie real en escritorio (`SerialPortDialog` + `electron/serialPort.ts`). +- [ ] E2E del diálogo de puerto: el proceso principal simula `select-serial-port` y se + comprueba que el diálogo elige el USB y no `ttyS0` (hoy solo hay tests unitarios y de + componente). +- [ ] Verificar Pause/Stop (`!`, `~`, `Ctrl+X`) y el progreso del job en un xTool real; + hoy el firmware solo mueve al recibir `M2`. +- [ ] Revisar que `openburn.device` antiguo sin `firmware` arranca en `auto` (el spread + de `loadDevice` lo cubre, pero falta un test explícito de migración). diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 40f8156..3c8cce7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -156,8 +156,11 @@ UI (Laser/Move/Console) ``` - `machine` mantiene estado observable: conexión, `MPos`, feed, spindle, trabajo, progreso y logs. -- Polling de estado cada 250 ms (`?`). -- Pausa/resume con `!`/`~`; stop con feed hold + soft reset (`Ctrl+X`). +- Polling de estado cada 250 ms (`?`); en xTool es `?\n` y se pausa durante + trabajos porque cada respuesta añade un `ok` que descontaría líneas. +- Pausa/resume con `!`/`~`; stop con feed hold + soft reset (`Ctrl+X`). En xTool + el firmware solo mueve al recibir `M2`, así que ningún trabajo nuevo debe + asumir que el progreso coincide con el cabezal (ver `TODO.md`). - En Electron, el proceso principal concede permisos Web Serial y reenvía la lista de puertos (`select-serial-port`) al renderer por IPC (`serial:choose-port`); el diálogo `SerialPortDialog` responde con `serial:port-chosen`. La lógica de