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(/^, '').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);