dechatter 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/widget.js CHANGED
@@ -1,806 +1,863 @@
1
- // dechatter cncjs widget. Everything runs in this page: cncjs is reached over its socket.io
2
- // API (load the program, watch the job), the microphone is the browser's, and the planning
3
- // and analysis are dechatter's Python running in a worker (engine.js).
4
-
5
- import { Mic } from './mic.js';
6
- import { STEPS, draw, read } from './wizard.js';
7
-
8
- const params = new URLSearchParams(location.search);
9
- const token = params.get('token') ?? '';
10
- const cncjsOrigin = params.get('host') ?? location.origin;
11
-
12
- const TIMELINE_LIMIT = 5000;
13
- const LEVEL_MS = 250;
14
- const SESSION_KEY = 'dechatter.session';
15
- const DEVICE_KEY = 'dechatter.microphone';
16
- const $ = (id) => document.getElementById(id);
17
-
18
- const MACHINE_UNITS = { G20: 'in', G21: 'mm' };
19
- const UNITS_TEXT = {
20
- mm: 'Lengths in mm: the machine is in G21.',
21
- in: 'Lengths in inches: the machine is in G20.',
22
- unknown: 'Lengths in mm. With the machine connected they follow its G20/G21 mode.',
23
- kept: 'Lengths in inches, as before the stopped job. The machine is now in G21: send G20 to put it back in inches.',
24
- };
25
- const KEEP_UNITS_KEY = 'dechatter.keep-units';
26
- const OWN_PROGRAM = /^dechatter-.*\.nc$/; // the names the engine gives its programs
27
- const cnc = {
28
- socket: null,
29
- link: 'connecting', // connecting | no-port | ready | offline
30
- port: '',
31
- workflow: null, // idle | running | paused; null until cncjs reports it
32
- program: '', // name of the G-code file cncjs has loaded
33
- pause: null, // { text, settled } while the program waits at an M0, else null
34
- units: null, // mm | in: how the wizard shows lengths; null until the machine's mode is known
35
- reported: null, // mm | in: the machine's G21/G20 mode as cncjs last reported it
36
- settled: null, // mm | in: the last report taken while no job ran; null until there is one
37
- // in from the start of one of this widget's jobs on an inch machine until the machine is
38
- // back in G20. Stored per machine, so a reload after a stopped job does not forget it.
39
- keep: null,
40
- lines: { received: 0, total: 0 }, // how far cncjs got through the loaded program
41
- };
42
- const mic = new Mic();
43
- let boot = 'Starting'; // what the engine is loading; null once it is ready
44
- let fatal = ''; // why the engine could not start; nothing works without it
45
- let names = []; // sessions stored in this browser
46
- let current = localStorage.getItem(SESSION_KEY) ?? '';
47
- let state = null; // the current session, as the engine last reported it
48
- let editing = null; // { values, materials, step } while the setup wizard is open, else null
49
- let timeline = []; // what cncjs reported since the job last started; saved with the recording
50
- let busy = false; // an engine request is in flight
51
- let stockChoice = 'same'; // survives redraws: planning on the wrong face position cuts air or too deep
52
-
53
- // ---- engine (Python in a worker) -------------------------------------------------------
54
-
55
- const worker = new Worker(new URL('./engine.js', import.meta.url), { type: 'module' });
56
- const pending = new Map();
57
- let nextId = 1;
58
-
59
- worker.onmessage = ({ data }) => {
60
- if ('boot' in data) {
61
- boot = data.boot;
62
- fatal = data.fatal ?? fatal;
63
- render();
64
- return;
65
- }
66
- const { resolve, reject } = pending.get(data.id);
67
- pending.delete(data.id);
68
- if ('error' in data) {
69
- reject(new Error(data.error));
70
- return;
71
- }
72
- resolve(data.ok);
73
- };
74
- worker.onerror = (event) => {
75
- fatal = `dechatter could not start its engine${event.message ? `: ${event.message}` : ''}. Export the widget again with \`dechatter widget\`.`;
76
- render();
77
- };
78
-
79
- function engine(method, ...args) {
80
- return new Promise((resolve, reject) => {
81
- const id = nextId;
82
- nextId += 1;
83
- pending.set(id, { resolve, reject });
84
- worker.postMessage({ id, method, args });
85
- });
86
- }
87
-
88
- function showError(message) {
89
- $('error').textContent = message;
90
- $('error').hidden = !message;
91
- }
92
-
93
- // Run one request that answers with the session's new state.
94
- async function act(method, ...args) {
95
- busy = true;
96
- render();
97
- try {
98
- state = await engine(method, current, ...args);
99
- showError('');
100
- } catch (err) {
101
- showError(err.message);
102
- } finally {
103
- busy = false;
104
- syncRecording();
105
- render();
106
- }
107
- }
108
-
109
- async function openSession(name) {
110
- current = name;
111
- editing = null;
112
- state = null;
113
- localStorage.setItem(SESSION_KEY, name);
114
- if (name) {
115
- await act('state');
116
- }
117
- render();
118
- }
119
-
120
- async function newSession() {
121
- const name = window.prompt('Name this tool assembly, for example al-10mm-3fl');
122
- if (!name) {
123
- return;
124
- }
125
- try {
126
- await engine('create', name.trim());
127
- names = await engine('names');
128
- current = name.trim();
129
- localStorage.setItem(SESSION_KEY, current);
130
- state = null;
131
- await openWizard();
132
- showError('');
133
- } catch (err) {
134
- showError(err.message);
135
- }
136
- render();
137
- }
138
-
139
- // Start the wizard on the session's stored setup. The form is redrawn even when it last
140
- // showed this same step, so nothing typed into an earlier wizard is left on screen.
141
- async function openWizard() {
142
- editing = { ...(await engine('setup_form', current)), step: 0 };
143
- $('setup-form').dataset.key = '';
144
- }
145
-
146
- async function editSetup() {
147
- try {
148
- await openWizard();
149
- } catch (err) {
150
- showError(err.message);
151
- }
152
- render();
153
- }
154
-
155
- // Lengths are shown in the machine's units; millimetres until cncjs has reported them.
156
- function units() {
157
- return cnc.units ?? 'mm';
158
- }
159
-
160
- function keepStep() {
161
- read($('setup-form'), STEPS[editing.step], editing.values, units());
162
- }
163
-
164
- async function nextStep() {
165
- if (!$('setup-form').reportValidity()) {
166
- return;
167
- }
168
- keepStep();
169
- if (editing.step < STEPS.length - 1) {
170
- editing.step += 1;
171
- render();
172
- return;
173
- }
174
- const wizard = editing;
175
- await act('save_setup', JSON.stringify(wizard.values));
176
- if (editing !== wizard) {
177
- return; // cancelled, or another session opened, while the save was in flight
178
- }
179
- // On a refusal the reason is shown and the wizard stays open on what was typed.
180
- editing = $('error').hidden ? null : wizard;
181
- render();
182
- }
183
-
184
- function previousStep() {
185
- keepStep();
186
- editing.step -= 1;
187
- render();
188
- }
189
-
190
- async function exportSession() {
191
- try {
192
- const bytes = await engine('export_zip', current);
193
- const url = URL.createObjectURL(new Blob([bytes], { type: 'application/zip' }));
194
- // cncjs sandboxes widget frames without allow-downloads, so the cncjs page itself
195
- // (same origin) starts the download.
196
- const host = window.parent.document;
197
- const link = host.createElement('a');
198
- link.href = url;
199
- link.download = `${current}.zip`;
200
- host.body.append(link);
201
- link.click();
202
- link.remove();
203
- setTimeout(() => URL.revokeObjectURL(url), 60000);
204
- } catch (err) {
205
- showError(err.message);
206
- }
207
- }
208
-
209
- async function importSession(file) {
210
- try {
211
- const name = await engine('import_zip', new Uint8Array(await file.arrayBuffer()));
212
- names = await engine('names');
213
- await openSession(name);
214
- } catch (err) {
215
- showError(err.message);
216
- }
217
- render();
218
- }
219
-
220
- // ---- microphone ------------------------------------------------------------------------
221
-
222
- async function openMic(deviceId) {
223
- try {
224
- await mic.start(deviceId);
225
- localStorage.setItem(DEVICE_KEY, deviceId ?? '');
226
- const devices = await mic.devices();
227
- $('device').replaceChildren(
228
- el('option', { value: '' }, 'default microphone'),
229
- ...devices.map((d) => el('option', { value: d.id }, d.label || 'microphone')),
230
- );
231
- $('device').value = deviceId ?? '';
232
- showError('');
233
- } catch (err) {
234
- showError(`Microphone: ${err.message}. Allow microphone access for this site, then press Enable microphone.`);
235
- }
236
- render();
237
- }
238
-
239
- function renderLevel() {
240
- const level = mic.open ? mic.levelDb : null;
241
- $('level').value = level ?? -100;
242
- $('level-db').textContent = level === null ? (mic.open ? 'no signal: click anywhere in this panel' : '') : `${Math.round(level)} dB`;
243
- if (mic.recording) {
244
- const clock = $('recording-clock');
245
- if (clock) {
246
- clock.textContent = minutes(Math.round(mic.seconds));
247
- }
248
- }
249
- }
250
-
251
- // ---- cncjs -----------------------------------------------------------------------------
252
-
253
- function loadScript(src) {
254
- return new Promise((resolve, reject) => {
255
- const script = document.createElement('script');
256
- script.src = src;
257
- script.onload = resolve;
258
- script.onerror = () => reject(new Error(`cannot load ${src}`));
259
- document.head.append(script);
260
- });
261
- }
262
-
263
- function note(event, detail) {
264
- if (timeline.length < TIMELINE_LIMIT) {
265
- timeline.push({ t: Date.now() / 1000, event, ...detail });
266
- }
267
- }
268
-
269
- function setPort(port) {
270
- cnc.port = port;
271
- cnc.link = port ? 'ready' : 'no-port';
272
- cnc.keep = port ? localStorage.getItem(keepKey()) : null;
273
- if (!port) {
274
- cnc.reported = null;
275
- cnc.settled = null;
276
- showIn(null);
277
- }
278
- render();
279
- }
280
-
281
- function keepKey() {
282
- return `${KEEP_UNITS_KEY}|${cncjsOrigin}|${cnc.port}`;
283
- }
284
-
285
- function hold(units) {
286
- cnc.keep = units;
287
- if (units) {
288
- localStorage.setItem(keepKey(), units);
289
- return;
290
- }
291
- localStorage.removeItem(keepKey());
292
- }
293
-
294
- function showIn(next) {
295
- if (next === cnc.units) {
296
- return;
297
- }
298
- if (editing) {
299
- keepStep();
300
- }
301
- cnc.units = next;
302
- }
303
-
304
- // The stopped job left G21 behind and the machine has not gone back to G20 since.
305
- function keptFromStoppedJob() {
306
- return cnc.keep !== null && cnc.workflow === 'idle' && cnc.reported !== null && cnc.reported !== cnc.keep;
307
- }
308
-
309
- // The machine's G20/G21 mode decides how the wizard shows lengths. Programs run in G21 and
310
- // put an inch machine back in G20 as their last step, so a job that ran to its end changes
311
- // nothing. A job stopped part-way leaves G21 behind, which is not the operator's choice: an
312
- // inch machine then stays in inches here until it goes back to G20 or the operator says
313
- // to follow the machine.
314
- function followMachine() {
315
- if (!cnc.reported || cnc.workflow === null) {
316
- return;
317
- }
318
- if (cnc.workflow !== 'idle') {
319
- // cncjs does not refresh the mode during a job; what it repeats right after one is
320
- // still this value, and must not pass for the machine going back to G20.
321
- cnc.settled = cnc.reported;
322
- return;
323
- }
324
- // Only one of this widget's programs ends by restoring G20.
325
- const finished = OWN_PROGRAM.test(cnc.program) && cnc.lines.total > 0 && cnc.lines.received >= cnc.lines.total;
326
- const wentBack = cnc.reported === cnc.keep && cnc.settled !== cnc.reported;
327
- if (cnc.keep && (finished || wentBack)) {
328
- hold(null);
329
- }
330
- cnc.settled = cnc.reported;
331
- showIn(cnc.keep ?? cnc.reported);
332
- }
333
-
334
- async function connectCncjs() {
335
- try {
336
- await loadScript(`${cncjsOrigin}/socket.io/socket.io.js`);
337
- } catch (err) {
338
- cnc.link = 'offline';
339
- showError(`${err.message}. Open this widget from inside cncjs.`);
340
- render();
341
- return;
342
- }
343
- const socket = window.io.connect(cncjsOrigin, { query: `token=${token}` });
344
- cnc.socket = socket;
345
-
346
- socket.on('connect', () => {
347
- cnc.link = cnc.port ? 'ready' : 'no-port';
348
- // Ask the cncjs page which port it has open; it answers with a "change" message.
349
- window.parent.postMessage({ token, action: { type: 'connect' } }, '*');
350
- render();
351
- });
352
- socket.on('disconnect', () => {
353
- cnc.link = 'offline';
354
- render();
355
- });
356
- socket.on('error', (err) => {
357
- cnc.link = 'offline';
358
- showError(`cncjs refused the connection: ${err?.message ?? err}`);
359
- render();
360
- });
361
- socket.on('serialport:open', ({ port }) => setPort(port));
362
- socket.on('serialport:close', () => setPort(''));
363
- socket.on('gcode:load', (name) => {
364
- cnc.program = name;
365
- render();
366
- });
367
- socket.on('gcode:unload', () => {
368
- cnc.program = '';
369
- render();
370
- });
371
- socket.on('sender:status', (status) => {
372
- cnc.program = status.name ?? cnc.program;
373
- cnc.lines = { received: status.received, total: status.total };
374
- followMachine();
375
- note('sender', { sent: status.sent, received: status.received, total: status.total });
376
- // A manual-spindle program stops at "M0 (set the spindle to N rpm, then resume)". cncjs
377
- // reports the pause as soon as it sends the line; the machine has only stopped once
378
- // everything sent was acknowledged.
379
- const reason = status.hold ? status.holdReason : null;
380
- const pause = reason?.data === 'M0'
381
- ? { text: /\(([^)]*)\)/.exec(reason.msg ?? '')?.[1] ?? 'program pause', settled: status.received >= status.sent }
382
- : null;
383
- if (JSON.stringify(pause) !== JSON.stringify(cnc.pause)) {
384
- cnc.pause = pause;
385
- render();
386
- }
387
- });
388
- socket.on('workflow:state', (workflow) => {
389
- if (workflow === 'running' && cnc.workflow !== 'paused') {
390
- timeline = [];
391
- }
392
- // Only this widget's programs switch the machine to G21. Another job starting changes
393
- // nothing: the machine is still in the G21 a stopped job left.
394
- if (workflow === 'running' && cnc.workflow === 'idle' && cnc.units === 'in' && OWN_PROGRAM.test(cnc.program)) {
395
- hold('in');
396
- }
397
- cnc.workflow = workflow;
398
- followMachine();
399
- note('workflow', { state: workflow });
400
- syncRecording();
401
- render();
402
- });
403
- socket.on('controller:state', (_type, controller) => {
404
- cnc.reported = MACHINE_UNITS[controller?.parserstate?.modal?.units] ?? cnc.reported;
405
- followMachine();
406
- render();
407
- });
408
- }
409
-
410
- window.addEventListener('message', (event) => {
411
- const { token: theirs, action } = { ...event.data };
412
- if (theirs !== token || action?.type !== 'change') {
413
- return;
414
- }
415
- const port = action.payload?.port ?? '';
416
- if (port) {
417
- // Joining an open port makes cncjs replay its sender and workflow state to this socket.
418
- cnc.socket.emit('open', port, {});
419
- }
420
- setPort(port);
421
- });
422
-
423
- // ---- recording follows the job ---------------------------------------------------------
424
-
425
- function plannedRound() {
426
- const last = state?.rounds.at(-1);
427
- return last && !last.analysed ? last : null;
428
- }
429
-
430
- // Record exactly while cncjs runs the planned round's program.
431
- function syncRecording() {
432
- if (!state || busy) {
433
- return;
434
- }
435
- const round = plannedRound();
436
- if (!mic.recording && round && cnc.workflow === 'running' && cnc.program === round.program) {
437
- if (!mic.open) {
438
- showError('The job is running but the microphone is not open, so this run cannot be analysed. Enable the microphone and run the round again.');
439
- return;
440
- }
441
- mic.record();
442
- act('record_start', round.round);
443
- return;
444
- }
445
- if (mic.recording && cnc.workflow === 'idle' && cnc.link === 'ready') {
446
- const samples = mic.finish();
447
- act('record_stop', samples, mic.rate, JSON.stringify(timeline));
448
- }
449
- }
450
-
451
- async function loadProgram(round) {
452
- busy = true;
453
- render();
454
- try {
455
- // Capture has to be running before the job can start; the listener below does not wait.
456
- await mic.resume();
457
- const gcode = await engine('program', current, round.round, units());
458
- await new Promise((resolve, reject) => {
459
- cnc.socket.emit('command', cnc.port, 'gcode:load', round.program, gcode, {}, (err) =>
460
- err ? reject(new Error(`cncjs could not load the program: ${err.message ?? err}`)) : resolve(),
461
- );
462
- });
463
- cnc.program = round.program;
464
- showError('');
465
- } catch (err) {
466
- showError(err.message);
467
- } finally {
468
- busy = false;
469
- render();
470
- }
471
- }
472
-
473
- // ---- rendering -------------------------------------------------------------------------
474
-
475
- function el(tag, props = {}, ...children) {
476
- const node = Object.assign(document.createElement(tag), props);
477
- node.append(...children);
478
- return node;
479
- }
480
-
481
- function button(label, onclick, props = {}) {
482
- return el('button', { onclick, ...props }, label);
483
- }
484
-
485
- const LINK_TEXT = {
486
- connecting: 'connecting',
487
- 'no-port': 'connected; open a serial port in cncjs',
488
- offline: 'not connected',
489
- };
490
-
491
- function renderLinks() {
492
- const job = cnc.workflow ?? 'state unknown';
493
- $('cncjs').textContent = cnc.link === 'ready' ? `${cnc.port}, ${job}` : LINK_TEXT[cnc.link];
494
- $('device').hidden = !mic.open;
495
- $('level').hidden = !mic.open;
496
- $('enable-mic').hidden = mic.open;
497
- $('mic-warning').hidden = mic.processing.length === 0;
498
- $('mic-warning').textContent = `The browser kept ${mic.processing.join(', ')} on. Verdicts may be wrong; try another microphone or browser.`;
499
- }
500
-
501
- function renderSessions() {
502
- const select = $('sessions');
503
- select.replaceChildren(
504
- el('option', { value: '' }, names.length ? 'choose a session' : 'no sessions yet'),
505
- ...names.map((name) => el('option', { value: name }, name)),
506
- );
507
- select.value = names.includes(current) ? current : '';
508
- select.disabled = busy || mic.recording;
509
- $('summary').textContent = state?.summary ?? '';
510
- for (const id of ['edit-setup', 'export']) {
511
- $(id).disabled = !state || busy || mic.recording;
512
- }
513
- }
514
-
515
- function minutes(seconds) {
516
- return seconds < 90 ? `${seconds} s` : `${Math.round(seconds / 60)} min`;
517
- }
518
-
519
- function renderSetup() {
520
- $('setup').hidden = editing === null;
521
- if (editing === null) {
522
- $('setup-form').dataset.key = '';
523
- return;
524
- }
525
- const step = STEPS[editing.step];
526
- $('setup-title').textContent = `Setup ${editing.step + 1} of ${STEPS.length}: ${step.title}`;
527
- $('setup-hint').textContent = step.hint;
528
- $('setup-back').hidden = editing.step === 0;
529
- $('setup-next').textContent = editing.step === STEPS.length - 1 ? 'Save' : 'Next';
530
- $('setup-next').disabled = busy;
531
- const kept = keptFromStoppedJob();
532
- $('units').textContent = UNITS_TEXT[kept ? 'kept' : (cnc.units ?? 'unknown')];
533
- $('follow-machine').hidden = !kept;
534
- // Redraw the fields only when the step or the machine's units change, so typing is not
535
- // interrupted otherwise. A change of units drops an entry that is only half typed.
536
- const key = `${current}|${editing.step}|${units()}`;
537
- if ($('setup-form').dataset.key !== key) {
538
- draw($('setup-form'), step, editing.values, units(), editing.materials);
539
- $('setup-form').dataset.key = key;
540
- }
541
- }
542
-
543
- function renderStep() {
544
- const step = $('step');
545
- step.replaceChildren();
546
- step.hidden = !state || editing !== null;
547
- if (step.hidden) {
548
- return;
549
- }
550
- const round = plannedRound();
551
-
552
- if (mic.recording) {
553
- step.append(
554
- el('p', { className: 'recording' }, `Recording round ${state.recording_round ?? ''}: `, el('span', { id: 'recording-clock' }, '0 s')),
555
- el('p', {}, 'Feed-hold and stop the job in cncjs if a cut gets violent. The passes that ran still count.'),
556
- ...(cnc.pause ? [el('p', { className: 'instruction' }, cnc.pause.settled ? `Now ${cnc.pause.text} in cncjs.` : 'Wait for the machine to stop.')] : []),
557
- );
558
- return;
559
- }
560
-
561
- if (busy) {
562
- step.append(el('p', {}, 'Working…'));
563
- return;
564
- }
565
-
566
- if (state.next === 'converged') {
567
- step.append(el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'));
568
- return;
569
- }
570
-
571
- if (state.next === 'plan') {
572
- const first = state.rounds.length === 0;
573
- const stock = el('select', {}, el('option', { value: 'same' }, 'same block'), el('option', { value: 'fresh' }, 'fresh block, face at Y0'));
574
- stock.value = stockChoice;
575
- stock.onchange = () => {
576
- stockChoice = stock.value;
577
- };
578
- const shallower = !first && state.next_depth_mm !== state.depth_mm;
579
- const label = `Plan round ${state.rounds.length + 1}${shallower ? ` at ${state.next_depth_mm} mm depth` : ''}`;
580
- const plan = button(label, async () => {
581
- await act('plan', first ? 'same' : stockChoice);
582
- stockChoice = 'same';
583
- }, { className: 'primary' });
584
- const next = shallower
585
- ? `${state.depth_mm} mm depth is settled. Next come cuts ${state.next_depth_mm} mm deep, starting from the widths that were stable.`
586
- : 'Plan the next cuts from what was measured.';
587
- step.append(el('p', {}, first ? 'Plan a coarse grid of test cuts.' : next));
588
- step.append(el('p', {}, plan, ...(first ? [] : [' on the ', stock])));
589
- return;
590
- }
591
-
592
- const tests = round.passes.filter((p) => p.kind === 'test').length;
593
- const speedChanges = (r) => r.passes.filter((p, i) => i === 0 || p.rpm !== r.passes[i - 1].rpm).length;
594
- const loaded = cnc.program === round.program;
595
- const ready = cnc.link === 'ready' && cnc.workflow === 'idle' && mic.open;
596
- const load = button(loaded ? 'Reload program' : 'Load into cncjs', () => loadProgram(round), { className: loaded ? '' : 'primary', disabled: !ready });
597
- step.append(
598
- el('p', {}, `Round ${round.round}: ${tests} test cuts ${round.depth_mm} mm deep, about ${minutes(round.run_time_s)} plus rapids. The front face ends at Y${round.face_y_end_mm}.`),
599
- el('ol', {},
600
- el('li', {}, 'Zero X at the left end of the stock, Y on its front face, Z on top.'),
601
- el('li', {}, load, mic.open ? '' : ' (enable the microphone first)'),
602
- el('li', {}, loaded ? 'Press play in cncjs. Recording starts and stops with the job. Keep this tab open.' : 'Press play in cncjs.'),
603
- ...(state.spindle === 'manual' ? [el('li', {}, `The program pauses before each of its ${speedChanges(round)} spindle speeds. Set the speed shown here, then resume in cncjs.`)] : []),
604
- ),
605
- );
606
- if (round.has_recording) {
607
- step.append(el('p', {}, 'The last run could not be analysed. Run the round again, or ', button('Analyse the last recording again', () => act('analyze', round.round))));
608
- }
609
- }
610
-
611
- function verdictCell(round, pass) {
612
- if (pass.kind !== 'test') {
613
- return el('td', {}, pass.kind);
614
- }
615
- if (!round.analysed) {
616
- return el('td', {}, '');
617
- }
618
- const select = el('select', { disabled: busy },
619
- ...(pass.verdict ? [] : [el('option', { value: '' }, 'not heard')]),
620
- el('option', { value: 'stable' }, pass.status === 'aborted' ? 'stable (aborted)' : 'stable'),
621
- el('option', { value: 'unstable' }, pass.status === 'aborted' ? 'chatter (aborted)' : 'chatter'),
622
- );
623
- select.value = pass.verdict ?? '';
624
- select.title = pass.chatter_hz ? `peak ${Math.round(pass.chatter_hz)} Hz, ${pass.prominence_db} dB over the floor` : '';
625
- select.onchange = () => act('set_verdict', round.round, pass.id, select.value);
626
- return el('td', { className: pass.verdict ?? '' }, select);
627
- }
628
-
629
- function renderRound() {
630
- const round = editing === null ? state?.rounds.at(-1) : null;
631
- $('round').hidden = !round;
632
- if (!round) {
633
- return;
634
- }
635
- $('round-title').textContent = `Round ${round.round}${round.analysed ? ' results' : ''}, ${round.depth_mm} mm deep`;
636
- $('passes').replaceChildren(
637
- ...round.passes.map((p) =>
638
- el('tr', { className: p.kind === 'test' ? '' : 'prep' },
639
- el('td', {}, String(p.id)),
640
- el('td', {}, String(p.rpm)),
641
- el('td', {}, p.width_mm.toFixed(2)),
642
- el('td', {}, String(Math.round(p.feed_mm_min))),
643
- el('td', {}, p.p_stable === null ? '' : p.p_stable.toFixed(2)),
644
- verdictCell(round, p),
645
- ),
646
- ),
647
- );
648
- }
649
-
650
- function renderMap() {
651
- // A depth that has no cuts of its own yet still has a map: what deeper cuts showed stable.
652
- $('map-section').hidden = editing !== null || !state || !state.rounds.some((r) => r.analysed);
653
- if ($('map-section').hidden) {
654
- return;
655
- }
656
- $('map-title').textContent = `Stability map at ${state.depth_mm} mm depth`;
657
- const { speeds, widths, p } = state.map;
658
- const canvas = $('map');
659
- const ctx = canvas.getContext('2d');
660
- const pad = { left: 40, bottom: 16, top: 4, right: 4 };
661
- const w = canvas.width - pad.left - pad.right;
662
- const h = canvas.height - pad.top - pad.bottom;
663
- ctx.clearRect(0, 0, canvas.width, canvas.height);
664
-
665
- const cellW = w / speeds.length;
666
- const cellH = h / widths.length;
667
- speeds.forEach((_, s) => {
668
- widths.forEach((_, i) => {
669
- ctx.fillStyle = `hsl(${Math.round(120 * p[s][i])} 65% 60%)`;
670
- ctx.fillRect(pad.left + s * cellW, pad.top + h - (i + 1) * cellH, cellW + 0.5, cellH + 0.5);
671
- });
672
- });
673
-
674
- const x = (rpm) => pad.left + ((rpm - speeds[0]) / (speeds.at(-1) - speeds[0])) * (w - cellW) + cellW / 2;
675
- const y = (width) => pad.top + h - ((width - widths[0]) / (widths.at(-1) - widths[0])) * (h - cellH) - cellH / 2;
676
- ctx.lineWidth = 1.5;
677
- ctx.strokeStyle = '#000';
678
- for (const o of state.observations) {
679
- const [cx, cy] = [x(o.rpm), y(o.width_mm)];
680
- ctx.beginPath();
681
- if (o.verdict === 'stable') {
682
- ctx.fillStyle = '#fff';
683
- ctx.arc(cx, cy, 3, 0, 2 * Math.PI);
684
- ctx.fill();
685
- } else {
686
- ctx.moveTo(cx - 3, cy - 3);
687
- ctx.lineTo(cx + 3, cy + 3);
688
- ctx.moveTo(cx + 3, cy - 3);
689
- ctx.lineTo(cx - 3, cy + 3);
690
- }
691
- ctx.stroke();
692
- }
693
-
694
- ctx.fillStyle = '#777';
695
- ctx.font = '10px Arial';
696
- ctx.textBaseline = 'top';
697
- ctx.textAlign = 'left';
698
- ctx.fillText(`${speeds[0]} rpm`, pad.left, pad.top + h + 3);
699
- ctx.textAlign = 'right';
700
- ctx.fillText(String(speeds.at(-1)), pad.left + w, pad.top + h + 3);
701
- ctx.fillText(`${widths.at(-1)}`, pad.left - 3, pad.top);
702
- ctx.textBaseline = 'bottom';
703
- ctx.fillText(`${widths[0]} mm`, pad.left - 3, pad.top + h);
704
- }
705
-
706
- function renderBest() {
707
- const best = editing === null ? (state?.best ?? []) : [];
708
- $('best-section').hidden = best.length === 0;
709
- $('best').replaceChildren(
710
- ...best.map((b) =>
711
- el('tr', {},
712
- el('td', {}, String(b.rpm)),
713
- el('td', {}, `${b.width_mm.toFixed(2)} mm`),
714
- el('td', {}, `${b.depth_mm} mm`),
715
- el('td', {}, String(b.feed_mm_min)),
716
- el('td', {}, b.mrr_cm3_min.toFixed(2)),
717
- ),
718
- ),
719
- );
720
- }
721
-
722
- function render() {
723
- $('boot').hidden = boot === null && !fatal;
724
- $('boot').className = fatal ? 'error' : 'muted';
725
- $('boot').textContent = fatal || (boot === null ? '' : `${boot}. The first load takes a few seconds.`);
726
- $('main').hidden = boot !== null || Boolean(fatal);
727
- if ($('main').hidden) {
728
- return;
729
- }
730
- renderSessions();
731
- renderLinks();
732
- renderSetup();
733
- renderStep();
734
- renderRound();
735
- renderMap();
736
- renderBest();
737
- }
738
-
739
- // ---- wiring ----------------------------------------------------------------------------
740
-
741
- $('sessions').onchange = () => openSession($('sessions').value);
742
- $('new-session').onclick = newSession;
743
- $('edit-setup').onclick = editSetup;
744
- $('setup-back').onclick = previousStep;
745
- $('setup-form').onsubmit = (event) => {
746
- event.preventDefault();
747
- nextStep();
748
- };
749
- $('follow-machine').onclick = () => {
750
- hold(null);
751
- followMachine();
752
- render();
753
- };
754
- $('cancel-setup').onclick = () => {
755
- editing = null;
756
- showError('');
757
- render();
758
- };
759
- $('export').onclick = exportSession;
760
- $('import').onclick = () => $('import-file').click();
761
- $('import-file').onchange = () => {
762
- const [file] = $('import-file').files;
763
- $('import-file').value = '';
764
- if (file) {
765
- importSession(file);
766
- }
767
- };
768
- $('enable-mic').onclick = () => openMic(localStorage.getItem(DEVICE_KEY) || undefined);
769
- $('device').onchange = () => openMic($('device').value || undefined);
770
-
771
- // Tell the cncjs page how tall the widget wants to be.
772
- new ResizeObserver(() => {
773
- const { scrollHeight, scrollWidth } = document.body;
774
- window.parent.postMessage({ token, action: { type: 'resize', payload: { scrollHeight, scrollWidth } } }, '*');
775
- }).observe(document.body);
776
-
777
- // Browsers can hold audio capture back until the user interacts with the page, for instance
778
- // after a reload. Any click, tap or key in the widget lets it run. Touch only counts as
779
- // interaction when the finger lifts, hence pointerup as well.
780
- for (const type of ['pointerdown', 'pointerup', 'keydown']) {
781
- document.addEventListener(type, () => {
782
- mic.resume().catch((err) => console.warn(`dechatter: microphone did not resume: ${err.message}`));
783
- });
784
- }
785
-
786
- // Leaving mid-recording loses the run: the samples are only in this page.
787
- window.addEventListener('beforeunload', (event) => {
788
- if (mic.recording) {
789
- event.preventDefault();
790
- }
791
- });
792
-
793
- render();
794
- connectCncjs();
795
- openMic(localStorage.getItem(DEVICE_KEY) || undefined);
796
- setInterval(renderLevel, LEVEL_MS);
797
-
798
- try {
799
- names = await engine('names');
800
- if (!names.includes(current)) {
801
- current = '';
802
- }
803
- await openSession(current);
804
- } catch (err) {
805
- showError(err.message);
806
- }
1
+ // dechatter cncjs widget. Everything runs in this page: cncjs is reached over its socket.io
2
+ // API (load the program, watch the job), the microphone is the browser's, and the planning
3
+ // and analysis are dechatter's Python running in a worker (engine.js).
4
+
5
+ import { Mic } from './mic.js';
6
+ import { STEPS, draw, placehold, read, reveal } from './wizard.js';
7
+
8
+ const params = new URLSearchParams(location.search);
9
+ const token = params.get('token') ?? '';
10
+ const cncjsOrigin = params.get('host') ?? location.origin;
11
+
12
+ const TIMELINE_LIMIT = 5000;
13
+ const LEVEL_MS = 250;
14
+ const SESSION_KEY = 'dechatter.session';
15
+ const DEVICE_KEY = 'dechatter.microphone';
16
+ const $ = (id) => document.getElementById(id);
17
+
18
+ const MACHINE_UNITS = { G20: 'in', G21: 'mm' };
19
+ const UNITS_TEXT = {
20
+ mm: 'Lengths in mm: the machine is in G21.',
21
+ in: 'Lengths in inches: the machine is in G20.',
22
+ unknown: 'Lengths in mm. With the machine connected they follow its G20/G21 mode.',
23
+ };
24
+ const cnc = {
25
+ socket: null,
26
+ link: 'connecting', // connecting | no-port | ready | offline
27
+ port: '',
28
+ workflow: null, // idle | running | paused; null until cncjs reports it
29
+ program: '', // name of the G-code file cncjs has loaded
30
+ pause: null, // { text, settled } while the program waits at an M0, else null
31
+ // mm | in: the machine's G21/G20 mode as cncjs last reported it; null until it has. The
32
+ // wizard shows lengths in it and programs are written in it, so a job never changes it.
33
+ units: null,
34
+ loadedUnits: null, // mm | in: the units of the program this widget last loaded into cncjs
35
+ };
36
+ const mic = new Mic();
37
+ let boot = 'Starting'; // what the engine is loading; null once it is ready
38
+ let fatal = ''; // why the engine could not start; nothing works without it
39
+ let names = []; // sessions stored in this browser
40
+ let current = localStorage.getItem(SESSION_KEY) ?? '';
41
+ let state = null; // the current session, as the engine last reported it
42
+ let editing = null; // { values, defaults, materials, computed, step } while the setup wizard is open, else null
43
+ let timeline = []; // what cncjs reported since the job last started; saved with the recording
44
+ let busy = false; // an engine request is in flight
45
+ let stockChoice = 'same'; // survives redraws: planning on the wrong face position cuts air or too deep
46
+
47
+ // ---- engine (Python in a worker) -------------------------------------------------------
48
+
49
+ const worker = new Worker(new URL('./engine.js', import.meta.url), { type: 'module' });
50
+ const pending = new Map();
51
+ let nextId = 1;
52
+
53
+ worker.onmessage = ({ data }) => {
54
+ if ('boot' in data) {
55
+ boot = data.boot;
56
+ fatal = data.fatal ?? fatal;
57
+ render();
58
+ return;
59
+ }
60
+ const { resolve, reject } = pending.get(data.id);
61
+ pending.delete(data.id);
62
+ if ('error' in data) {
63
+ reject(new Error(data.error));
64
+ return;
65
+ }
66
+ resolve(data.ok);
67
+ };
68
+ worker.onerror = (event) => {
69
+ fatal = `dechatter could not start its engine${event.message ? `: ${event.message}` : ''}. Export the widget again with \`dechatter widget\`.`;
70
+ render();
71
+ };
72
+
73
+ function engine(method, ...args) {
74
+ return new Promise((resolve, reject) => {
75
+ const id = nextId;
76
+ nextId += 1;
77
+ pending.set(id, { resolve, reject });
78
+ worker.postMessage({ id, method, args });
79
+ });
80
+ }
81
+
82
+ function showError(message) {
83
+ $('error').textContent = message;
84
+ $('error').hidden = !message;
85
+ }
86
+
87
+ // Run one request that answers with the session's new state.
88
+ async function act(method, ...args) {
89
+ busy = true;
90
+ render();
91
+ try {
92
+ state = await engine(method, current, ...args);
93
+ showError('');
94
+ } catch (err) {
95
+ showError(err.message);
96
+ } finally {
97
+ busy = false;
98
+ syncRecording();
99
+ render();
100
+ }
101
+ }
102
+
103
+ async function openSession(name) {
104
+ current = name;
105
+ editing = null;
106
+ state = null;
107
+ localStorage.setItem(SESSION_KEY, name);
108
+ if (name) {
109
+ await act('state');
110
+ }
111
+ render();
112
+ }
113
+
114
+ async function newSession() {
115
+ const name = window.prompt('Name this tool assembly, for example al-10mm-3fl');
116
+ if (!name) {
117
+ return;
118
+ }
119
+ try {
120
+ await engine('create', name.trim());
121
+ names = await engine('names');
122
+ current = name.trim();
123
+ localStorage.setItem(SESSION_KEY, current);
124
+ state = null;
125
+ await openWizard();
126
+ showError('');
127
+ } catch (err) {
128
+ showError(err.message);
129
+ }
130
+ render();
131
+ }
132
+
133
+ // Start the wizard on the session's stored setup. The form is redrawn even when it last
134
+ // showed this same step, so nothing typed into an earlier wizard is left on screen.
135
+ async function openWizard() {
136
+ editing = { ...(await engine('setup_form', current)), computed: null, step: 0 };
137
+ $('setup-form').dataset.key = '';
138
+ }
139
+
140
+ // What the planner makes of the entries left empty, from what the wizard holds so far.
141
+ // Only shown as placeholders, filled in when the answer comes: the step is already drawn
142
+ // and may hold typing. Values the wizard cannot make sense of yet show none, and an answer
143
+ // overtaken by a later request is dropped.
144
+ async function preview(wizard) {
145
+ wizard.asked = (wizard.asked ?? 0) + 1;
146
+ const asked = wizard.asked;
147
+ let computed = null;
148
+ try {
149
+ computed = await engine('setup_preview', JSON.stringify(wizard.values));
150
+ } catch {
151
+ computed = null;
152
+ }
153
+ if (editing !== wizard || wizard.asked !== asked) {
154
+ return;
155
+ }
156
+ wizard.computed = computed;
157
+ placehold($('setup-form'), STEPS[wizard.step], units(), wizard);
158
+ }
159
+
160
+ function goToStep(step) {
161
+ editing.step = Math.min(Math.max(step, 0), STEPS.length - 1);
162
+ render();
163
+ preview(editing);
164
+ }
165
+
166
+ async function editSetup() {
167
+ try {
168
+ await openWizard();
169
+ } catch (err) {
170
+ showError(err.message);
171
+ }
172
+ render();
173
+ }
174
+
175
+ // Lengths are shown in the machine's units; millimetres until cncjs has reported them.
176
+ function units() {
177
+ return cnc.units ?? 'mm';
178
+ }
179
+
180
+ function keepStep() {
181
+ read($('setup-form'), STEPS[editing.step], editing.values, units());
182
+ }
183
+
184
+ async function nextStep() {
185
+ reveal($('setup-form'));
186
+ if (!$('setup-form').reportValidity()) {
187
+ return;
188
+ }
189
+ keepStep();
190
+ if (editing.step < STEPS.length - 1) {
191
+ goToStep(editing.step + 1);
192
+ return;
193
+ }
194
+ if (busy) {
195
+ return; // already saving
196
+ }
197
+ // A job may be running one of this session's programs; a new setup could discard it.
198
+ if (cnc.workflow === 'running' || cnc.workflow === 'paused') {
199
+ showError('A job is running in cncjs. Save the setup once it has ended.');
200
+ render();
201
+ return;
202
+ }
203
+ const wizard = editing;
204
+ await act('save_setup', JSON.stringify(wizard.values));
205
+ if (editing !== wizard) {
206
+ return; // cancelled, or another session opened, while the save was in flight
207
+ }
208
+ // On a refusal the reason is shown and the wizard stays open on what was typed.
209
+ editing = $('error').hidden ? null : wizard;
210
+ render();
211
+ }
212
+
213
+ function previousStep() {
214
+ keepStep();
215
+ goToStep(editing.step - 1);
216
+ }
217
+
218
+ function download(blob, filename) {
219
+ const url = URL.createObjectURL(blob);
220
+ // cncjs sandboxes widget frames without allow-downloads, so the cncjs page itself
221
+ // (same origin) starts the download.
222
+ const host = window.parent.document;
223
+ const link = host.createElement('a');
224
+ link.href = url;
225
+ link.download = filename;
226
+ host.body.append(link);
227
+ link.click();
228
+ link.remove();
229
+ setTimeout(() => URL.revokeObjectURL(url), 60000);
230
+ }
231
+
232
+ // Both carry the report, whose lengths follow the machine's units (mm until known).
233
+ async function exportSession() {
234
+ try {
235
+ const bytes = await engine('export_zip', current, units());
236
+ download(new Blob([bytes], { type: 'application/zip' }), `${current}.zip`);
237
+ } catch (err) {
238
+ showError(err.message);
239
+ }
240
+ }
241
+
242
+ async function downloadReport() {
243
+ try {
244
+ const page = await engine('report_html', current, units());
245
+ download(new Blob([page], { type: 'text/html' }), `${current}-report.html`);
246
+ } catch (err) {
247
+ showError(err.message);
248
+ }
249
+ }
250
+
251
+ async function importSession(file) {
252
+ try {
253
+ const name = await engine('import_zip', new Uint8Array(await file.arrayBuffer()));
254
+ names = await engine('names');
255
+ await openSession(name);
256
+ } catch (err) {
257
+ showError(err.message);
258
+ }
259
+ render();
260
+ }
261
+
262
+ // ---- microphone ------------------------------------------------------------------------
263
+
264
+ async function openMic(deviceId) {
265
+ try {
266
+ await mic.start(deviceId);
267
+ localStorage.setItem(DEVICE_KEY, deviceId ?? '');
268
+ const devices = await mic.devices();
269
+ $('device').replaceChildren(
270
+ el('option', { value: '' }, 'default microphone'),
271
+ ...devices.map((d) => el('option', { value: d.id }, d.label || 'microphone')),
272
+ );
273
+ $('device').value = deviceId ?? '';
274
+ showError('');
275
+ } catch (err) {
276
+ showError(`Microphone: ${err.message}. Allow microphone access for this site, then press Enable microphone.`);
277
+ }
278
+ render();
279
+ }
280
+
281
+ function renderLevel() {
282
+ const level = mic.open ? mic.levelDb : null;
283
+ $('level').value = level ?? -100;
284
+ $('level-db').textContent = level === null ? (mic.open ? 'no signal: click anywhere in this panel' : '') : `${Math.round(level)} dB`;
285
+ if (mic.recording) {
286
+ const clock = $('recording-clock');
287
+ if (clock) {
288
+ clock.textContent = minutes(Math.round(mic.seconds));
289
+ }
290
+ }
291
+ }
292
+
293
+ // ---- cncjs -----------------------------------------------------------------------------
294
+
295
+ function loadScript(src) {
296
+ return new Promise((resolve, reject) => {
297
+ const script = document.createElement('script');
298
+ script.src = src;
299
+ script.onload = resolve;
300
+ script.onerror = () => reject(new Error(`cannot load ${src}`));
301
+ document.head.append(script);
302
+ });
303
+ }
304
+
305
+ function note(event, detail) {
306
+ if (timeline.length < TIMELINE_LIMIT) {
307
+ timeline.push({ t: Date.now() / 1000, event, ...detail });
308
+ }
309
+ }
310
+
311
+ function setPort(port) {
312
+ // Another port may be another machine: its units are unknown until cncjs reports them.
313
+ if (port !== cnc.port) {
314
+ showIn(null);
315
+ cnc.loadedUnits = null;
316
+ }
317
+ cnc.port = port;
318
+ cnc.link = port ? 'ready' : 'no-port';
319
+ render();
320
+ }
321
+
322
+ function showIn(next) {
323
+ if (next === cnc.units) {
324
+ return;
325
+ }
326
+ if (editing) {
327
+ keepStep();
328
+ }
329
+ cnc.units = next;
330
+ }
331
+
332
+ async function connectCncjs() {
333
+ try {
334
+ await loadScript(`${cncjsOrigin}/socket.io/socket.io.js`);
335
+ } catch (err) {
336
+ cnc.link = 'offline';
337
+ showError(`${err.message}. Open this widget from inside cncjs.`);
338
+ render();
339
+ return;
340
+ }
341
+ const socket = window.io.connect(cncjsOrigin, { query: `token=${token}` });
342
+ cnc.socket = socket;
343
+
344
+ socket.on('connect', () => {
345
+ cnc.link = cnc.port ? 'ready' : 'no-port';
346
+ // Ask the cncjs page which port it has open; it answers with a "change" message.
347
+ window.parent.postMessage({ token, action: { type: 'connect' } }, '*');
348
+ render();
349
+ });
350
+ socket.on('disconnect', () => {
351
+ cnc.link = 'offline';
352
+ render();
353
+ });
354
+ socket.on('error', (err) => {
355
+ cnc.link = 'offline';
356
+ showError(`cncjs refused the connection: ${err?.message ?? err}`);
357
+ render();
358
+ });
359
+ socket.on('serialport:open', ({ port }) => setPort(port));
360
+ socket.on('serialport:close', () => setPort(''));
361
+ socket.on('gcode:load', (name) => {
362
+ cnc.program = name;
363
+ render();
364
+ });
365
+ socket.on('gcode:unload', () => {
366
+ cnc.program = '';
367
+ cnc.loadedUnits = null;
368
+ render();
369
+ });
370
+ socket.on('sender:status', (status) => {
371
+ cnc.program = status.name ?? cnc.program;
372
+ note('sender', { sent: status.sent, received: status.received, total: status.total });
373
+ // A manual-spindle program stops at "M0 (set the spindle to N rpm, then resume)". cncjs
374
+ // reports the pause as soon as it sends the line; the machine has only stopped once
375
+ // everything sent was acknowledged.
376
+ const reason = status.hold ? status.holdReason : null;
377
+ const pause = reason?.data === 'M0'
378
+ ? { text: /\(([^)]*)\)/.exec(reason.msg ?? '')?.[1] ?? 'program pause', settled: status.received >= status.sent }
379
+ : null;
380
+ if (JSON.stringify(pause) !== JSON.stringify(cnc.pause)) {
381
+ cnc.pause = pause;
382
+ render();
383
+ }
384
+ });
385
+ socket.on('workflow:state', (workflow) => {
386
+ if (workflow === 'running' && cnc.workflow !== 'paused') {
387
+ timeline = [];
388
+ }
389
+ cnc.workflow = workflow;
390
+ note('workflow', { state: workflow });
391
+ syncRecording();
392
+ render();
393
+ });
394
+ socket.on('controller:state', (_type, controller) => {
395
+ showIn(MACHINE_UNITS[controller?.parserstate?.modal?.units] ?? cnc.units);
396
+ render();
397
+ });
398
+ }
399
+
400
+ window.addEventListener('message', (event) => {
401
+ const { token: theirs, action } = { ...event.data };
402
+ if (theirs !== token || action?.type !== 'change') {
403
+ return;
404
+ }
405
+ const port = action.payload?.port ?? '';
406
+ if (port) {
407
+ // Joining an open port makes cncjs replay its sender and workflow state to this socket.
408
+ cnc.socket.emit('open', port, {});
409
+ }
410
+ setPort(port);
411
+ });
412
+
413
+ // ---- recording follows the job ---------------------------------------------------------
414
+
415
+ // cncjs holds this round's program as this widget loaded it, in the units the machine
416
+ // reports now. After a reload of the widget the units it was loaded in are unknown.
417
+ function loadedHere(round) {
418
+ return cnc.program === round.program && cnc.loadedUnits !== null && cnc.loadedUnits === cnc.units;
419
+ }
420
+
421
+ function plannedRound() {
422
+ const last = state?.rounds.at(-1);
423
+ return last && !last.analysed ? last : null;
424
+ }
425
+
426
+ // Record exactly while cncjs runs the planned round's program.
427
+ function syncRecording() {
428
+ if (!state || busy) {
429
+ return;
430
+ }
431
+ const round = plannedRound();
432
+ if (!mic.recording && round && cnc.workflow === 'running' && cnc.program === round.program && !loadedHere(round)) {
433
+ showError('This run is not recorded: the program in cncjs may be in other units than the machine is in now. Stop the job, load the program again from here, then run it.');
434
+ return;
435
+ }
436
+ if (!mic.recording && round && cnc.workflow === 'running' && loadedHere(round)) {
437
+ if (!mic.open) {
438
+ showError('The job is running but the microphone is not open, so this run cannot be analysed. Enable the microphone and run the round again.');
439
+ return;
440
+ }
441
+ mic.record();
442
+ act('record_start', round.round);
443
+ return;
444
+ }
445
+ if (mic.recording && cnc.workflow === 'idle' && cnc.link === 'ready') {
446
+ const samples = mic.finish();
447
+ act('record_stop', samples, mic.rate, JSON.stringify(timeline));
448
+ }
449
+ }
450
+
451
+ async function loadProgram(round) {
452
+ busy = true;
453
+ render();
454
+ try {
455
+ // Capture has to be running before the job can start; the listener below does not wait.
456
+ await mic.resume();
457
+ const programUnits = cnc.units;
458
+ const gcode = await engine('program', current, round.round, programUnits);
459
+ await new Promise((resolve, reject) => {
460
+ cnc.socket.emit('command', cnc.port, 'gcode:load', round.program, gcode, {}, (err) =>
461
+ err ? reject(new Error(`cncjs could not load the program: ${err.message ?? err}`)) : resolve(),
462
+ );
463
+ });
464
+ cnc.program = round.program;
465
+ cnc.loadedUnits = programUnits;
466
+ showError('');
467
+ } catch (err) {
468
+ showError(err.message);
469
+ } finally {
470
+ busy = false;
471
+ render();
472
+ }
473
+ }
474
+
475
+ // ---- rendering -------------------------------------------------------------------------
476
+
477
+ function el(tag, props = {}, ...children) {
478
+ const node = Object.assign(document.createElement(tag), props);
479
+ node.append(...children);
480
+ return node;
481
+ }
482
+
483
+ function button(label, onclick, props = {}) {
484
+ return el('button', { onclick, ...props }, label);
485
+ }
486
+
487
+ const LINK_TEXT = {
488
+ connecting: 'connecting',
489
+ 'no-port': 'connected; open a serial port in cncjs',
490
+ offline: 'not connected',
491
+ };
492
+
493
+ function renderLinks() {
494
+ const job = cnc.workflow ?? 'state unknown';
495
+ $('cncjs').textContent = cnc.link === 'ready' ? `${cnc.port}, ${job}` : LINK_TEXT[cnc.link];
496
+ $('device').hidden = !mic.open;
497
+ $('level').hidden = !mic.open;
498
+ $('enable-mic').hidden = mic.open;
499
+ $('mic-warning').hidden = mic.processing.length === 0;
500
+ $('mic-warning').textContent = `The browser kept ${mic.processing.join(', ')} on. Verdicts may be wrong; try another microphone or browser.`;
501
+ }
502
+
503
+ function renderSessions() {
504
+ const select = $('sessions');
505
+ select.replaceChildren(
506
+ el('option', { value: '' }, names.length ? 'choose a session' : 'no sessions yet'),
507
+ ...names.map((name) => el('option', { value: name }, name)),
508
+ );
509
+ select.value = names.includes(current) ? current : '';
510
+ select.disabled = busy || mic.recording;
511
+ $('summary').textContent = state?.summary ?? '';
512
+ for (const id of ['edit-setup', 'export']) {
513
+ $(id).disabled = !state || busy || mic.recording;
514
+ }
515
+ }
516
+
517
+ function minutes(seconds) {
518
+ return seconds < 90 ? `${seconds} s` : `${Math.round(seconds / 60)} min`;
519
+ }
520
+
521
+ function renderSetup() {
522
+ $('setup').hidden = editing === null;
523
+ if (editing === null) {
524
+ $('setup-form').dataset.key = '';
525
+ return;
526
+ }
527
+ const step = STEPS[editing.step];
528
+ $('setup-title').textContent = `Setup ${editing.step + 1} of ${STEPS.length}: ${step.title}`;
529
+ $('setup-hint').textContent = step.hint;
530
+ $('setup-back').hidden = editing.step === 0;
531
+ $('setup-next').textContent = editing.step === STEPS.length - 1 ? 'Save' : 'Next';
532
+ $('setup-next').disabled = busy;
533
+ $('units').textContent = UNITS_TEXT[cnc.units ?? 'unknown'];
534
+ // Redraw the fields only when the step or the machine's units change, so typing is not
535
+ // interrupted otherwise. A change of units drops an entry that is only half typed.
536
+ const key = `${current}|${editing.step}|${units()}`;
537
+ if ($('setup-form').dataset.key !== key) {
538
+ draw($('setup-form'), step, editing.values, units(), editing);
539
+ $('setup-form').dataset.key = key;
540
+ }
541
+ }
542
+
543
+ // Planning on the wrong face position cuts air or too deep: the choice survives redraws.
544
+ function stockSelect() {
545
+ const stock = el('select', {}, el('option', { value: 'same' }, 'same block'), el('option', { value: 'fresh' }, 'fresh block, face at Y0'));
546
+ stock.value = stockChoice;
547
+ stock.onchange = () => {
548
+ stockChoice = stock.value;
549
+ };
550
+ return stock;
551
+ }
552
+
553
+ function renderStep() {
554
+ const step = $('step');
555
+ step.replaceChildren();
556
+ step.hidden = !state || editing !== null;
557
+ if (step.hidden) {
558
+ return;
559
+ }
560
+ const round = plannedRound();
561
+
562
+ if (mic.recording) {
563
+ step.append(
564
+ el('p', { className: 'recording' }, `Recording round ${state.recording_round ?? ''}: `, el('span', { id: 'recording-clock' }, '0 s')),
565
+ el('p', {}, 'Feed-hold and stop the job in cncjs if a cut gets violent. The passes that ran still count.'),
566
+ ...(cnc.pause ? [el('p', { className: 'instruction' }, cnc.pause.settled ? `Now ${cnc.pause.text} in cncjs.` : 'Wait for the machine to stop.')] : []),
567
+ );
568
+ return;
569
+ }
570
+
571
+ if (busy) {
572
+ step.append(el('p', {}, 'Working…'));
573
+ return;
574
+ }
575
+
576
+ if (state.discarded_round !== null) {
577
+ step.append(el('p', {}, `Round ${state.discarded_round} had not been run and was planned from the old setup, so it was discarded.`));
578
+ }
579
+
580
+ if (state.next === 'converged') {
581
+ step.append(
582
+ el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'),
583
+ el('p', {}, button('Download the report', downloadReport, { className: 'primary' }), ' to print and keep with the tool.'),
584
+ );
585
+ return;
586
+ }
587
+
588
+ if (state.next === 'sweep') {
589
+ const best = state.best[0];
590
+ const stock = stockSelect();
591
+ step.append(
592
+ el('p', {}, 'Converged: no further cut is expected to add removal rate. The best stable cuts are below.'),
593
+ el('p', {}, `One more round can find how hard the best cut (${best.rpm} rpm, ${best.width_mm.toFixed(2)} mm wide, ${best.depth_mm} mm deep) can be pushed: the same cut at rising chip loads, lightest first. Its cuts do not change the map.`),
594
+ el('p', {}, button('Plan the chip-load sweep', async () => {
595
+ await act('plan_sweep', stockChoice);
596
+ stockChoice = 'same';
597
+ }, { className: 'primary' }), ' on the ', stock),
598
+ el('p', {}, button('Download the report', downloadReport), ' as it stands.'),
599
+ );
600
+ return;
601
+ }
602
+
603
+ if (state.next === 'setup') {
604
+ step.append(
605
+ el('p', {}, 'This session still holds the example setup, not your machine. Fill it in before planning.'),
606
+ el('p', {}, button('Open the setup wizard', editSetup, { className: 'primary' })),
607
+ );
608
+ return;
609
+ }
610
+
611
+ if (state.next === 'plan') {
612
+ const first = state.rounds.length === 0;
613
+ const stock = stockSelect();
614
+ const shallower = !first && state.next_depth_mm !== state.depth_mm;
615
+ const label = `Plan round ${state.rounds.length + 1}${shallower ? ` at ${state.next_depth_mm} mm depth` : ''}`;
616
+ const plan = button(label, async () => {
617
+ await act('plan', first ? 'same' : stockChoice);
618
+ stockChoice = 'same';
619
+ }, { className: 'primary' });
620
+ const next = shallower
621
+ ? `${state.depth_mm} mm depth is settled. Next come cuts ${state.next_depth_mm} mm deep, starting from the widths that were stable.`
622
+ : 'Plan the next cuts from what was measured.';
623
+ step.append(el('p', {}, first ? 'Plan a coarse grid of test cuts.' : next));
624
+ step.append(el('p', {}, plan, ...(first ? [] : [' on the ', stock])));
625
+ return;
626
+ }
627
+
628
+ const tests = round.passes.filter((p) => p.kind === 'test').length;
629
+ const speedChanges = (r) => r.passes.filter((p, i) => i === 0 || p.rpm !== r.passes[i - 1].rpm).length;
630
+ const loaded = loadedHere(round);
631
+ // The name matches, but the units it was loaded in differ or are not known: load it again.
632
+ const unsure = cnc.program === round.program && !loaded;
633
+ // The program is written in the machine's units, so they have to be known first.
634
+ const ready = cnc.link === 'ready' && cnc.workflow === 'idle' && cnc.units !== null && mic.open;
635
+ const load = button(loaded ? 'Reload program' : 'Load into cncjs', () => loadProgram(round), { className: loaded ? '' : 'primary', disabled: !ready });
636
+ // cncjs reports the mode from the controller's parser state. Until it does, the operator
637
+ // can say which it is: the program sets that mode itself, so a wrong choice cannot
638
+ // misplace a cut, only leave the machine in the other mode afterwards.
639
+ const declare = el('select', {}, el('option', { value: '' }, 'machine units?'), el('option', { value: 'mm' }, 'mm (G21)'), el('option', { value: 'in' }, 'inches (G20)'));
640
+ declare.onchange = () => {
641
+ showIn(declare.value || null);
642
+ render();
643
+ };
644
+ const unknownUnits = mic.open && cnc.link === 'ready' && cnc.units === null;
645
+ step.append(
646
+ el('p', {}, `Round ${round.round}: ${tests} test cuts ${round.depth_mm} mm deep, about ${minutes(round.run_time_s)} plus rapids. The front face ends at Y${round.face_y_end_mm}.`),
647
+ el('ol', {},
648
+ el('li', {}, 'Zero X at the left end of the stock, Y on its front face, Z on top.'),
649
+ el('li', {}, load, ...(unknownUnits ? [' cncjs has not reported G20 or G21 yet; the machine is in ', declare] : []), mic.open ? '' : ' (enable the microphone first)'),
650
+ el('li', {}, loaded ? 'Press play in cncjs. Recording starts and stops with the job. Keep this tab open.' : 'Press play in cncjs.'),
651
+ ...(state.spindle === 'manual' ? [el('li', {}, `The program pauses before each of its ${speedChanges(round)} spindle speeds. Set the speed shown here, then resume in cncjs.`)] : []),
652
+ ),
653
+ );
654
+ if (unsure) {
655
+ step.append(el('p', { className: 'instruction' }, 'cncjs holds this round\'s program, but it was loaded in other units than the machine is in now, or before this widget was reloaded. Load it again before pressing play; a run of it as it is will not be recorded.'));
656
+ }
657
+ if (round.has_recording) {
658
+ step.append(el('p', {}, 'The last run could not be analysed. Run the round again, or ', button('Analyse the last recording again', () => act('analyze', round.round))));
659
+ }
660
+ }
661
+
662
+ function verdictCell(round, pass) {
663
+ if (pass.kind !== 'test') {
664
+ return el('td', {}, pass.kind);
665
+ }
666
+ if (!round.analysed) {
667
+ return el('td', {}, '');
668
+ }
669
+ const select = el('select', { disabled: busy },
670
+ ...(pass.verdict ? [] : [el('option', { value: '' }, 'not heard')]),
671
+ el('option', { value: 'stable' }, pass.status === 'aborted' ? 'stable (aborted)' : 'stable'),
672
+ el('option', { value: 'unstable' }, pass.status === 'aborted' ? 'chatter (aborted)' : 'chatter'),
673
+ );
674
+ select.value = pass.verdict ?? '';
675
+ select.title = pass.chatter_hz ? `peak ${Math.round(pass.chatter_hz)} Hz, ${pass.prominence_db} dB over the floor` : '';
676
+ select.onchange = () => act('set_verdict', round.round, pass.id, select.value);
677
+ return el('td', { className: pass.verdict ?? '' }, select);
678
+ }
679
+
680
+ function renderRound() {
681
+ const round = editing === null ? state?.rounds.at(-1) : null;
682
+ $('round').hidden = !round;
683
+ if (!round) {
684
+ return;
685
+ }
686
+ const kind = round.planner === 'sweep' ? ' (chip-load sweep)' : '';
687
+ $('round-title').textContent = `Round ${round.round}${kind}${round.analysed ? ' results' : ''}, ${round.depth_mm} mm deep`;
688
+ $('passes').replaceChildren(
689
+ ...round.passes.map((p) =>
690
+ el('tr', { className: p.kind === 'test' ? '' : 'prep' },
691
+ el('td', {}, String(p.id)),
692
+ el('td', {}, String(p.rpm)),
693
+ el('td', {}, p.width_mm.toFixed(2)),
694
+ el('td', {}, String(Math.round(p.feed_mm_min))),
695
+ el('td', {}, p.p_stable === null ? '' : p.p_stable.toFixed(2)),
696
+ verdictCell(round, p),
697
+ ),
698
+ ),
699
+ );
700
+ }
701
+
702
+ function renderMap() {
703
+ // A depth that has no cuts of its own yet still has a map: what deeper cuts showed stable.
704
+ $('map-section').hidden = editing !== null || !state || !state.rounds.some((r) => r.analysed);
705
+ if ($('map-section').hidden) {
706
+ return;
707
+ }
708
+ $('map-title').textContent = `Stability map at ${state.depth_mm} mm depth`;
709
+ const { speeds, widths, p } = state.map;
710
+ const canvas = $('map');
711
+ const ctx = canvas.getContext('2d');
712
+ const pad = { left: 40, bottom: 16, top: 4, right: 4 };
713
+ const w = canvas.width - pad.left - pad.right;
714
+ const h = canvas.height - pad.top - pad.bottom;
715
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
716
+
717
+ const cellW = w / speeds.length;
718
+ const cellH = h / widths.length;
719
+ speeds.forEach((_, s) => {
720
+ widths.forEach((_, i) => {
721
+ ctx.fillStyle = `hsl(${Math.round(120 * p[s][i])} 65% 60%)`;
722
+ ctx.fillRect(pad.left + s * cellW, pad.top + h - (i + 1) * cellH, cellW + 0.5, cellH + 0.5);
723
+ });
724
+ });
725
+
726
+ const x = (rpm) => pad.left + ((rpm - speeds[0]) / (speeds.at(-1) - speeds[0])) * (w - cellW) + cellW / 2;
727
+ const y = (width) => pad.top + h - ((width - widths[0]) / (widths.at(-1) - widths[0])) * (h - cellH) - cellH / 2;
728
+ ctx.lineWidth = 1.5;
729
+ ctx.strokeStyle = '#000';
730
+ for (const o of state.observations) {
731
+ const [cx, cy] = [x(o.rpm), y(o.width_mm)];
732
+ ctx.beginPath();
733
+ if (o.verdict === 'stable') {
734
+ ctx.fillStyle = '#fff';
735
+ ctx.arc(cx, cy, 3, 0, 2 * Math.PI);
736
+ ctx.fill();
737
+ } else {
738
+ ctx.moveTo(cx - 3, cy - 3);
739
+ ctx.lineTo(cx + 3, cy + 3);
740
+ ctx.moveTo(cx + 3, cy - 3);
741
+ ctx.lineTo(cx - 3, cy + 3);
742
+ }
743
+ ctx.stroke();
744
+ }
745
+
746
+ ctx.fillStyle = '#777';
747
+ ctx.font = '10px Arial';
748
+ ctx.textBaseline = 'top';
749
+ ctx.textAlign = 'left';
750
+ ctx.fillText(`${speeds[0]} rpm`, pad.left, pad.top + h + 3);
751
+ ctx.textAlign = 'right';
752
+ ctx.fillText(String(speeds.at(-1)), pad.left + w, pad.top + h + 3);
753
+ ctx.fillText(`${widths.at(-1)}`, pad.left - 3, pad.top);
754
+ ctx.textBaseline = 'bottom';
755
+ ctx.fillText(`${widths[0]} mm`, pad.left - 3, pad.top + h);
756
+ }
757
+
758
+ function renderBest() {
759
+ const best = editing === null ? (state?.best ?? []) : [];
760
+ $('best-section').hidden = best.length === 0;
761
+ $('best').replaceChildren(
762
+ ...best.map((b) =>
763
+ el('tr', {},
764
+ el('td', {}, String(b.rpm)),
765
+ el('td', {}, `${b.width_mm.toFixed(2)} mm`),
766
+ el('td', {}, `${b.depth_mm} mm`),
767
+ el('td', {}, String(b.feed_mm_min)),
768
+ el('td', {}, b.mrr_cm3_min.toFixed(2)),
769
+ ),
770
+ ),
771
+ );
772
+ const sweep = state?.sweep;
773
+ $('sweep-result').hidden = !sweep || best.length === 0;
774
+ if (!sweep) {
775
+ return;
776
+ }
777
+ const where = `At ${sweep.rpm} rpm, ${sweep.width_mm.toFixed(2)} mm wide and ${sweep.depth_mm} mm deep`;
778
+ $('sweep-result').textContent = sweep.chip_load_mm === null
779
+ ? `Chip-load sweep: ${where.toLowerCase()}, even its lightest pass chattered. Keep the session's ${sweep.session_chip_load_mm} mm per tooth.`
780
+ : `Chip-load sweep: ${where.toLowerCase()}, the cut stayed stable up to ${sweep.chip_load_mm} mm per tooth (the session used ${sweep.session_chip_load_mm}): feed ${sweep.feed_mm_min} mm/min, ${sweep.mrr_cm3_min.toFixed(2)} cm³/min.`;
781
+ }
782
+
783
+ function render() {
784
+ $('boot').hidden = boot === null && !fatal;
785
+ $('boot').className = fatal ? 'error' : 'muted';
786
+ $('boot').textContent = fatal || (boot === null ? '' : `${boot}. The first load takes a few seconds.`);
787
+ $('main').hidden = boot !== null || Boolean(fatal);
788
+ if ($('main').hidden) {
789
+ return;
790
+ }
791
+ renderSessions();
792
+ renderLinks();
793
+ renderSetup();
794
+ renderStep();
795
+ renderRound();
796
+ renderMap();
797
+ renderBest();
798
+ }
799
+
800
+ // ---- wiring ----------------------------------------------------------------------------
801
+
802
+ $('sessions').onchange = () => openSession($('sessions').value);
803
+ $('new-session').onclick = newSession;
804
+ $('edit-setup').onclick = editSetup;
805
+ $('setup-back').onclick = previousStep;
806
+ $('setup-form').onsubmit = (event) => {
807
+ event.preventDefault();
808
+ nextStep();
809
+ };
810
+ $('cancel-setup').onclick = () => {
811
+ editing = null;
812
+ showError('');
813
+ render();
814
+ };
815
+ $('export').onclick = exportSession;
816
+ $('download-report').onclick = downloadReport;
817
+ $('import').onclick = () => $('import-file').click();
818
+ $('import-file').onchange = () => {
819
+ const [file] = $('import-file').files;
820
+ $('import-file').value = '';
821
+ if (file) {
822
+ importSession(file);
823
+ }
824
+ };
825
+ $('enable-mic').onclick = () => openMic(localStorage.getItem(DEVICE_KEY) || undefined);
826
+ $('device').onchange = () => openMic($('device').value || undefined);
827
+
828
+ // Tell the cncjs page how tall the widget wants to be.
829
+ new ResizeObserver(() => {
830
+ const { scrollHeight, scrollWidth } = document.body;
831
+ window.parent.postMessage({ token, action: { type: 'resize', payload: { scrollHeight, scrollWidth } } }, '*');
832
+ }).observe(document.body);
833
+
834
+ // Browsers can hold audio capture back until the user interacts with the page, for instance
835
+ // after a reload. Any click, tap or key in the widget lets it run. Touch only counts as
836
+ // interaction when the finger lifts, hence pointerup as well.
837
+ for (const type of ['pointerdown', 'pointerup', 'keydown']) {
838
+ document.addEventListener(type, () => {
839
+ mic.resume().catch((err) => console.warn(`dechatter: microphone did not resume: ${err.message}`));
840
+ });
841
+ }
842
+
843
+ // Leaving mid-recording loses the run: the samples are only in this page.
844
+ window.addEventListener('beforeunload', (event) => {
845
+ if (mic.recording) {
846
+ event.preventDefault();
847
+ }
848
+ });
849
+
850
+ render();
851
+ connectCncjs();
852
+ openMic(localStorage.getItem(DEVICE_KEY) || undefined);
853
+ setInterval(renderLevel, LEVEL_MS);
854
+
855
+ try {
856
+ names = await engine('names');
857
+ if (!names.includes(current)) {
858
+ current = '';
859
+ }
860
+ await openSession(current);
861
+ } catch (err) {
862
+ showError(err.message);
863
+ }