Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).

---

Expand Down
5 changes: 4 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.

---

Expand Down
10 changes: 8 additions & 2 deletions docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 14 additions & 6 deletions electron/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 {
Expand Down Expand Up @@ -129,21 +131,27 @@ 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');
}

// ---- 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'],
Expand Down
18 changes: 18 additions & 0 deletions electron/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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,
};
Expand Down
111 changes: 111 additions & 0 deletions electron/serialPort.test.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
144 changes: 144 additions & 0 deletions electron/serialPort.ts
Original file line number Diff line number Diff line change
@@ -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<string, { vendor: string; products: Record<string, string> }> = {
'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<T extends SerialPortCandidate>(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<number, (portId: string) => 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();
}
}
Loading