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 && ( + + )} + + )} +
+ ); +}