dechatter 0.1.0 → 0.1.1

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,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, 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, 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
+ }