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
3 changes: 3 additions & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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).

---
Expand Down
12 changes: 12 additions & 0 deletions docs/USAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
14 changes: 14 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,20 @@ function SettingsDialog({ onClose }: { onClose: () => void }) {
))}
</select>
</div>
<div className="field-row">
<span className="field-label">Firmware</span>
<select
className="input"
value={state.device.firmware}
onChange={(e) =>
store.updateDevice({ firmware: e.target.value as 'auto' | 'grbl' | 'xtool' })
}
>
<option value="auto">Auto-detect</option>
<option value="grbl">GRBL</option>
<option value="xtool">xTool (D1 and similar)</option>
</select>
</div>
<div className="field-row">
<span className="field-label">Max S</span>
<input
Expand Down
3 changes: 3 additions & 0 deletions src/gcode/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ export interface DeviceConfig {
type: 'grbl';
name: string;
baudRate: number;
/** Controller dialect: detected on connect, or forced (see serial/dialect.ts) */
firmware: 'auto' | 'grbl' | 'xtool';
/** Maximum S word value (GRBL usually 1000) */
maxS: number;
/** Rapid / travel speed in mm per minute */
Expand All @@ -126,6 +128,7 @@ export const DEFAULT_DEVICE: DeviceConfig = {
type: 'grbl',
name: 'GRBL',
baudRate: 115200,
firmware: 'auto',
maxS: 1000,
rapidRate: 3000,
laserMode: 'M4',
Expand Down
37 changes: 37 additions & 0 deletions src/serial/dialect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { describe, expect, it } from 'vitest';
import { dialectFromLine, isChatter, jogLines, statusPoll } from './dialect';

describe('serial/dialect', () => {
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);
});
});
48 changes: 48 additions & 0 deletions src/serial/dialect.ts
Original file line number Diff line number Diff line change
@@ -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: '<MPos:x,y,z,a>'.
* - 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:');
}
95 changes: 95 additions & 0 deletions src/serial/machine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {}
async disconnect(): Promise<void> {}
async write(data: string): Promise<void> {
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<FakeTransport> {
const t = new FakeTransport();
const m = machine as unknown as { firmware: FirmwareSetting; attach(t: Transport): Promise<void> };
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<MPos:-15.000000,4.500000,0.000000,0.000000>\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(['?']);
});
});
Loading