dechatter 0.2.0 → 0.3.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
@@ -3,6 +3,8 @@
3
3
  // and analysis are dechatter's Python running in a worker (engine.js).
4
4
 
5
5
  import { Mic } from './mic.js';
6
+ import { PHASE, Stepper } from './stepper.js';
7
+ import { chipLoad, feed, length, rate } from './units.js';
6
8
  import { STEPS, draw, placehold, read, reveal } from './wizard.js';
7
9
 
8
10
  const params = new URLSearchParams(location.search);
@@ -25,14 +27,19 @@ const cnc = {
25
27
  socket: null,
26
28
  link: 'connecting', // connecting | no-port | ready | offline
27
29
  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
30
+ workflow: null, // idle | running | paused: cncjs's own sender; null until cncjs reports it
31
+ activeState: '', // the controller's state as cncjs last reported it: Idle, Run, Hold, Alarm…
32
+ subState: null, // with Hold, Grbl's Hold:N: 0 once the hold is complete
33
+ wpos: null, // its work position then, as cncjs reports it
34
+ reportInches: false, // the controller reports positions in inches (Grbl's $13=1)
31
35
  // mm | in: the machine's G21/G20 mode as cncjs last reported it; null until it has. The
32
36
  // wizard shows lengths in it and programs are written in it, so a job never changes it.
33
37
  units: null,
34
- loadedUnits: null, // mm | in: the units of the program this widget last loaded into cncjs
35
38
  };
39
+ // The round the widget is running, one block at a time: { stepper, round, name }, else null.
40
+ // It is set the moment Start is pressed, so a second Start finds it and what cncjs reports
41
+ // while the round is being prepared reaches the stepper. The session stays pinned to it.
42
+ let run = null;
36
43
  const mic = new Mic();
37
44
  let boot = 'Starting'; // what the engine is loading; null once it is ready
38
45
  let fatal = ''; // why the engine could not start; nothing works without it
@@ -40,8 +47,20 @@ let names = []; // sessions stored in this browser
40
47
  let current = localStorage.getItem(SESSION_KEY) ?? '';
41
48
  let state = null; // the current session, as the engine last reported it
42
49
  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
50
+ let timeline = []; // the run's windows and events, saved with its recording
51
+ // Engine requests in flight; the controls wait while there are any.
52
+ let requests = 0;
53
+ const busy = () => requests > 0;
54
+
55
+ function requestDone() {
56
+ requests -= 1;
57
+ }
58
+ // The delete or reset confirmation: closed, being prepared, or open. While it is not
59
+ // closed, the session it names cannot change.
60
+ let dialog = 'closed';
61
+ // Whether the open session's setup loads ('loads' | 'refused'), as the engine checks it;
62
+ // null with no session open. Reset and Export need it to load; the rounds need not.
63
+ let setupStatus = null;
45
64
  let stockChoice = 'same'; // survives redraws: planning on the wrong face position cuts air or too deep
46
65
 
47
66
  // ---- engine (Python in a worker) -------------------------------------------------------
@@ -84,33 +103,62 @@ function showError(message) {
84
103
  $('error').hidden = !message;
85
104
  }
86
105
 
87
- // Run one request that answers with the session's new state.
88
- async function act(method, ...args) {
89
- busy = true;
106
+ // Run one request on a session that answers with its new state. The page takes that state
107
+ // only while the session is still the one open. Resolves whether the request succeeded.
108
+ async function actOn(name, method, ...args) {
109
+ requests += 1;
90
110
  render();
91
111
  try {
92
- state = await engine(method, current, ...args);
112
+ const next = await engine(method, name, ...args);
113
+ if (name === current) {
114
+ state = next;
115
+ }
93
116
  showError('');
117
+ return true;
94
118
  } catch (err) {
95
119
  showError(err.message);
120
+ return false;
96
121
  } finally {
97
- busy = false;
98
- syncRecording();
122
+ requestDone();
99
123
  render();
100
124
  }
101
125
  }
102
126
 
127
+ const act = (method, ...args) => actOn(current, method, ...args);
128
+
103
129
  async function openSession(name) {
104
130
  current = name;
105
131
  editing = null;
106
132
  state = null;
133
+ setupStatus = null;
107
134
  localStorage.setItem(SESSION_KEY, name);
108
135
  if (name) {
136
+ await checkSetup(name);
109
137
  await act('state');
110
138
  }
111
139
  render();
112
140
  }
113
141
 
142
+ // Whether a session's setup loads, apart from its rounds: a session whose rounds do not
143
+ // load can still be reset and exported.
144
+ async function checkSetup(name) {
145
+ requests += 1;
146
+ render();
147
+ try {
148
+ const { status } = await engine('setup_status', name);
149
+ if (name === current) {
150
+ setupStatus = status;
151
+ }
152
+ } catch (err) {
153
+ if (name === current) {
154
+ setupStatus = null;
155
+ showError(err.message);
156
+ }
157
+ } finally {
158
+ requestDone();
159
+ }
160
+ }
161
+
114
162
  async function newSession() {
115
163
  const name = window.prompt('Name this tool assembly, for example al-10mm-3fl');
116
164
  if (!name) {
@@ -122,6 +170,7 @@ async function newSession() {
122
170
  current = name.trim();
123
171
  localStorage.setItem(SESSION_KEY, current);
124
172
  state = null;
173
+ await checkSetup(current);
125
174
  await openWizard();
126
175
  showError('');
127
176
  } catch (err) {
@@ -191,7 +240,7 @@ async function nextStep() {
191
240
  goToStep(editing.step + 1);
192
241
  return;
193
242
  }
194
- if (busy) {
243
+ if (busy()) {
195
244
  return; // already saving
196
245
  }
197
246
  // A job may be running one of this session's programs; a new setup could discard it.
@@ -230,10 +279,13 @@ function download(blob, filename) {
230
279
  }
231
280
 
232
281
  // Both carry the report, whose lengths follow the machine's units (mm until known).
233
- async function exportSession() {
282
+ async function exportSession(name = current) {
234
283
  try {
235
- const bytes = await engine('export_zip', current, units());
236
- download(new Blob([bytes], { type: 'application/zip' }), `${current}.zip`);
284
+ const bytes = await engine('export_zip', name, units());
285
+ download(new Blob([bytes], { type: 'application/zip' }), `${name}.zip`);
286
+ if (run?.name === name) {
287
+ showError(`Exported ${name} without round ${run.round}: it is still running, and is stored once it ends.`);
288
+ }
237
289
  } catch (err) {
238
290
  showError(err.message);
239
291
  }
@@ -248,6 +300,108 @@ async function downloadReport() {
248
300
  }
249
301
  }
250
302
 
303
+ // The widget is running a round of this session.
304
+ function jobOf(name) {
305
+ return run !== null && run.name === name;
306
+ }
307
+
308
+ // Why a session cannot be deleted or reset now; '' when it can.
309
+ function busyRefusal(name, verb) {
310
+ if (mic.recording) {
311
+ return `A round is being recorded. ${verb} the session after the job.`;
312
+ }
313
+ if (jobOf(name)) {
314
+ return `A round of ${name} is running. ${verb} the session after it.`;
315
+ }
316
+ return '';
317
+ }
318
+
319
+ const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
320
+
321
+ // Deleting removes the session; resetting discards its rounds and keeps its setup. Both ask
322
+ // first, naming what goes, and offer Export. They read nothing but the folder, so a session
323
+ // that does not load (from dechatter 0.1.x, or damaged) can go too.
324
+ const ACTIONS = {
325
+ delete: {
326
+ verb: 'Delete',
327
+ question: (name, held) => `Delete session ${name}? It holds ${plural(held.rounds, 'round')} and ${plural(held.recordings, 'recording')}.`,
328
+ note: 'Deleting cannot be undone. Export keeps a copy as a zip.',
329
+ async run(name) {
330
+ names = await engine('delete', name);
331
+ await openSession('');
332
+ },
333
+ },
334
+ reset: {
335
+ verb: 'Reset',
336
+ question: (name, held) => `Reset session ${name}? Its ${plural(held.rounds, 'round')} and ${plural(held.recordings, 'recording')} are discarded; its setup stays, and planning starts again from round 1.`,
337
+ note: 'Resetting cannot be undone. Export keeps a copy as a zip.',
338
+ // On a refusal or failure the session shows as the engine has it now.
339
+ async run(name) {
340
+ try {
341
+ const after = await engine('reset', name);
342
+ if (name === current) {
343
+ state = after;
344
+ editing = null;
345
+ }
346
+ } catch (err) {
347
+ if (name === current) {
348
+ state = await engine('state', name).catch(() => state);
349
+ }
350
+ throw err;
351
+ }
352
+ },
353
+ },
354
+ };
355
+
356
+ async function ask(action) {
357
+ const name = current;
358
+ const { verb, question, note } = ACTIONS[action];
359
+ const refusal = busyRefusal(name, verb);
360
+ if (refusal) {
361
+ showError(refusal);
362
+ return;
363
+ }
364
+ dialog = 'preparing';
365
+ render();
366
+ try {
367
+ // A session whose setup does not load (from dechatter 0.1.x, or damaged) cannot be
368
+ // exported; one whose rounds alone do not load can.
369
+ const loads = setupStatus === 'loads';
370
+ $('confirm-question').textContent = question(name, await engine('contents', name));
371
+ $('confirm-note').textContent = loads ? note : `${note.split('.')[0]}. This session cannot be exported: its setup does not load (it is from dechatter 0.1.x, or damaged).`;
372
+ $('confirm-export').hidden = !loads;
373
+ $('confirm-go').textContent = verb;
374
+ Object.assign($('confirm-dialog').dataset, { session: name, action });
375
+ $('confirm-dialog').showModal();
376
+ dialog = 'open';
377
+ } catch (err) {
378
+ dialog = 'closed';
379
+ showError(err.message);
380
+ render();
381
+ }
382
+ }
383
+
384
+ async function confirmed() {
385
+ const { session: name, action } = $('confirm-dialog').dataset;
386
+ $('confirm-dialog').close();
387
+ const refusal = busyRefusal(name, ACTIONS[action].verb);
388
+ if (refusal) {
389
+ showError(refusal);
390
+ return;
391
+ }
392
+ requests += 1;
393
+ render();
394
+ try {
395
+ showError('');
396
+ await ACTIONS[action].run(name);
397
+ } catch (err) {
398
+ showError(err.message);
399
+ } finally {
400
+ requestDone();
401
+ }
402
+ render();
403
+ }
404
+
251
405
  async function importSession(file) {
252
406
  try {
253
407
  const name = await engine('import_zip', new Uint8Array(await file.arrayBuffer()));
@@ -312,7 +466,8 @@ function setPort(port) {
312
466
  // Another port may be another machine: its units are unknown until cncjs reports them.
313
467
  if (port !== cnc.port) {
314
468
  showIn(null);
315
- cnc.loadedUnits = null;
469
+ cnc.activeState = '';
470
+ run?.stepper.disconnected();
316
471
  }
317
472
  cnc.port = port;
318
473
  cnc.link = port ? 'ready' : 'no-port';
@@ -349,6 +504,7 @@ async function connectCncjs() {
349
504
  });
350
505
  socket.on('disconnect', () => {
351
506
  cnc.link = 'offline';
507
+ run?.stepper.disconnected(); // the machine finishes the one move it has, then stands
352
508
  render();
353
509
  });
354
510
  socket.on('error', (err) => {
@@ -358,41 +514,44 @@ async function connectCncjs() {
358
514
  });
359
515
  socket.on('serialport:open', ({ port }) => setPort(port));
360
516
  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();
517
+ socket.on('serialport:read', (line) => {
518
+ // A refused block ends the run: the stepper holds and resets. An alarm ends it too, but
519
+ // the controller has stopped the machine itself: nothing is sent.
520
+ const text = String(line);
521
+ if (!run || !/^(error|ALARM):/.test(text)) {
522
+ return;
523
+ }
524
+ note('controller', { line: text });
525
+ if (text.startsWith('ALARM:')) {
526
+ run.stepper.alarm(text);
527
+ return;
383
528
  }
529
+ run.stepper.error(text);
530
+ });
531
+ socket.on('controller:settings', (_type, settings) => {
532
+ cnc.reportInches = String(settings?.settings?.$13 ?? '0') === '1';
384
533
  });
385
534
  socket.on('workflow:state', (workflow) => {
386
- if (workflow === 'running' && cnc.workflow !== 'paused') {
387
- timeline = [];
388
- }
389
535
  cnc.workflow = workflow;
390
- note('workflow', { state: workflow });
391
- syncRecording();
536
+ // cncjs's own sender started a job while the widget runs a round: two senders on one
537
+ // machine. The widget's round stops.
538
+ if (workflow === 'running') {
539
+ run?.stepper.fail('cncjs started a job of its own while the round ran');
540
+ }
392
541
  render();
393
542
  });
394
543
  socket.on('controller:state', (_type, controller) => {
395
544
  showIn(MACHINE_UNITS[controller?.parserstate?.modal?.units] ?? cnc.units);
545
+ const status = controller?.status ?? {};
546
+ cnc.wpos = status.wpos ?? cnc.wpos;
547
+ if (status.activeState !== cnc.activeState) {
548
+ cnc.activeState = status.activeState ?? '';
549
+ if (run) {
550
+ note('controller', { state: cnc.activeState });
551
+ }
552
+ }
553
+ cnc.subState = status.subState ?? null;
554
+ run?.stepper.controller({ activeState: status.activeState, subState: cnc.subState, wpos: status.wpos });
396
555
  render();
397
556
  });
398
557
  }
@@ -410,66 +569,139 @@ window.addEventListener('message', (event) => {
410
569
  setPort(port);
411
570
  });
412
571
 
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
- }
572
+ // ---- the widget runs the round --------------------------------------------------------
420
573
 
421
574
  function plannedRound() {
422
575
  const last = state?.rounds.at(-1);
423
576
  return last && !last.analysed ? last : null;
424
577
  }
425
578
 
426
- // Record exactly while cncjs runs the planned round's program.
427
- function syncRecording() {
428
- if (!state || busy) {
429
- return;
579
+ // Why a round cannot start now; '' when it can.
580
+ function startRefusal() {
581
+ if (run) {
582
+ return 'A round is already running.';
430
583
  }
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;
584
+ if (!mic.open) {
585
+ return 'Enable the microphone first.';
435
586
  }
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;
587
+ return machineRefusal();
588
+ }
589
+
590
+ // Why the machine cannot take a round now; '' when it can.
591
+ function machineRefusal() {
592
+ if (cnc.link !== 'ready') {
593
+ return 'Open the machine\'s port in cncjs first.';
594
+ }
595
+ if (cnc.units === null) {
596
+ return 'cncjs has not reported G20 or G21 yet: say which the machine is in.';
597
+ }
598
+ if (cnc.workflow === 'running' || cnc.workflow === 'paused') {
599
+ return 'cncjs is running a job of its own. Let it end, or stop it, first.';
600
+ }
601
+ if (cnc.activeState === 'Alarm') {
602
+ return 'The machine is in alarm. Clear it in cncjs (home, or unlock) first.';
444
603
  }
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));
604
+ if (cnc.activeState === 'Hold' || cnc.activeState === 'Door') {
605
+ return `The machine is in ${cnc.activeState}. Resume or reset it in cncjs first.`;
448
606
  }
607
+ return '';
449
608
  }
450
609
 
451
- async function loadProgram(round) {
452
- busy = true;
610
+ const command = (...args) => cnc.socket.emit('command', cnc.port, ...args);
611
+
612
+ // Record while the widget runs the round one block at a time; then analyse what ran.
613
+ async function startRound(round) {
614
+ const refusal = startRefusal();
615
+ if (refusal) {
616
+ showError(refusal);
617
+ return;
618
+ }
619
+ const name = current;
620
+ // Before any wait: Start is now refused, and a lost link, an error or alarm line or a
621
+ // job of cncjs's own while the round is prepared ends the stepper before it sends a thing.
622
+ const stepper = new Stepper({
623
+ io: {
624
+ send: (lines) => command('gcode', lines),
625
+ feedhold: () => command('feedhold'),
626
+ cyclestart: () => command('cyclestart'),
627
+ reset: () => command('reset'),
628
+ },
629
+ reportInches: cnc.reportInches,
630
+ onChange: () => render(),
631
+ onWindow: ({ kind, ...window }) => note(kind, window),
632
+ });
633
+ // cncjs reports the controller only when it changes: start from what it said last.
634
+ stepper.controller({ activeState: cnc.activeState, subState: cnc.subState, wpos: cnc.wpos });
635
+ run = { stepper, round: round.round, name };
453
636
  render();
637
+ let blocks;
454
638
  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('');
639
+ await mic.resume(); // capture has to be running before the first cut
640
+ blocks = await engine('steps', name, round.round, cnc.units);
467
641
  } catch (err) {
642
+ run = null;
468
643
  showError(err.message);
469
- } finally {
470
- busy = false;
471
644
  render();
645
+ return;
646
+ }
647
+ // The machine may have changed during those waits: check again before recording.
648
+ if (notStarted(stepper)) {
649
+ return;
650
+ }
651
+ timeline = [];
652
+ mic.record();
653
+ note('record', { round: round.round, units: cnc.units });
654
+ if (!(await actOn(name, 'record_start', round.round))) {
655
+ mic.finish();
656
+ run = null;
657
+ render();
658
+ return;
659
+ }
660
+ // Once more: nothing has been sent, so a refusal now drops the recording unsaved.
661
+ const late = notStartedReason(stepper);
662
+ if (late) {
663
+ mic.finish();
664
+ await actOn(name, 'record_cancel');
665
+ run = null;
666
+ showError(late);
667
+ render();
668
+ return;
669
+ }
670
+ const outcome = await stepper.run(blocks);
671
+ note('run', { outcome, reason: stepper.reason });
672
+ const samples = mic.finish();
673
+ run = null;
674
+ await actOn(name, 'record_stop', samples, mic.rate, JSON.stringify(timeline));
675
+ if (outcome === PHASE.FAILED) {
676
+ // Both, when the analysis refused too: why the round ended, then why it was not analysed.
677
+ const analysis = $('error').hidden ? '' : ` ${$('error').textContent}`;
678
+ showError(`The round ended early: ${stepper.reason.replace(/\.$/, '')}. The cuts made before it count.${analysis}`);
679
+ }
680
+ }
681
+
682
+ // Why a round about to start cannot: the machine now refuses, the microphone closed, or
683
+ // the stepper was ended (a lost link, an error or alarm line, a cncjs job) before it sent
684
+ // a block; '' if it can.
685
+ function notStartedReason(stepper) {
686
+ if (stepper.finished) {
687
+ return `The round did not start: ${stepper.reason.replace(/\.$/, '')}. Nothing was sent.`;
688
+ }
689
+ if (!mic.open) {
690
+ return 'The round did not start: the microphone closed. Enable it, then press Start again.';
691
+ }
692
+ return machineRefusal();
693
+ }
694
+
695
+ // Whether the round cannot start after all; if so, says why and lets Start go again.
696
+ function notStarted(stepper) {
697
+ const reason = notStartedReason(stepper);
698
+ if (!reason) {
699
+ return false;
472
700
  }
701
+ run = null;
702
+ showError(reason);
703
+ render();
704
+ return true;
473
705
  }
474
706
 
475
707
  // ---- rendering -------------------------------------------------------------------------
@@ -507,11 +739,27 @@ function renderSessions() {
507
739
  ...names.map((name) => el('option', { value: name }, name)),
508
740
  );
509
741
  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;
742
+ // A run records into its own session: another one cannot be opened, made or imported.
743
+ const pinned = busy() || dialog !== 'closed' || mic.recording || run !== null;
744
+ select.disabled = pinned;
745
+ $('new-session').disabled = pinned;
746
+ $('import').disabled = pinned;
747
+ $('summary').textContent = state ? summary(state) : '';
748
+ $('edit-setup').disabled = !state || pinned;
749
+ // Export reads only what is stored: it works while a round runs, without that round.
750
+ $('export').disabled = setupStatus !== 'loads' || busy();
751
+ // Also for a session that failed to load: deleting it is the way to be rid of it.
752
+ for (const [id, verb] of [['delete-session', 'Delete'], ['reset-session', 'Reset']]) {
753
+ $(id).disabled = !names.includes(current) || busy() || Boolean(busyRefusal(current, verb)) || dialog !== 'closed';
514
754
  }
755
+ // Reset keeps the setup, so the setup has to load; Delete is the way out otherwise.
756
+ $('reset-session').disabled ||= setupStatus !== 'loads';
757
+ }
758
+
759
+ // The session's tool and cut in one line, lengths in the machine's units.
760
+ function summary({ summary: s, spindle }) {
761
+ const depths = s.depths_mm.map((depth) => length(depth, units())).join(', ');
762
+ return `Ø ${length(s.diameter_mm, units())}, ${s.flutes} flutes, ${s.material}, depth ${depths}, ${chipLoad(s.chip_load_mm, units())} per tooth${spindle === 'manual' ? ', manual spindle' : ''}`;
515
763
  }
516
764
 
517
765
  function minutes(seconds) {
@@ -529,7 +777,7 @@ function renderSetup() {
529
777
  $('setup-hint').textContent = step.hint;
530
778
  $('setup-back').hidden = editing.step === 0;
531
779
  $('setup-next').textContent = editing.step === STEPS.length - 1 ? 'Save' : 'Next';
532
- $('setup-next').disabled = busy;
780
+ $('setup-next').disabled = busy();
533
781
  $('units').textContent = UNITS_TEXT[cnc.units ?? 'unknown'];
534
782
  // Redraw the fields only when the step or the machine's units change, so typing is not
535
783
  // interrupted otherwise. A change of units drops an entry that is only half typed.
@@ -550,25 +798,103 @@ function stockSelect() {
550
798
  return stock;
551
799
  }
552
800
 
801
+ const STEP_TEXT = {
802
+ setup: 'Setting up',
803
+ rapid: 'Moving to the next pass',
804
+ spindle: 'Setting the spindle speed',
805
+ plunge: 'Plunging beside the stock',
806
+ dwell: 'Spindle at speed in the air',
807
+ cut: 'Cutting',
808
+ retract: 'Backing off',
809
+ end: 'Finishing',
810
+ };
811
+
812
+ const HELD_LONG_S = 60;
813
+ const IDLE_AWAY_S = 5;
814
+
815
+ // Why the run seems stuck, pointing to Stop; '' while it is not.
816
+ function stall(stepper) {
817
+ const now = Date.now() / 1000;
818
+ if (stepper.phase === PHASE.HELD && now - stepper.holds.at(-1)[0] >= HELD_LONG_S) {
819
+ return `Held for ${Math.round(now - stepper.holds.at(-1)[0])} s. Resume, or Stop the round: the cuts made so far are analysed.`;
820
+ }
821
+ if (stepper.idleAway !== null && now - stepper.idleAway >= IDLE_AWAY_S) {
822
+ return 'The machine reports Idle, but not where this move ends. Check it in cncjs; if it will not move on, Stop the round: the cuts made so far are analysed.';
823
+ }
824
+ if (cnc.link !== 'ready') {
825
+ return 'The connection to cncjs or the machine is lost.';
826
+ }
827
+ return '';
828
+ }
829
+
830
+ // While the widget runs a round: where it is, and Hold, Resume, Continue and Stop. The panel
831
+ // is built once per run and updated in place: cncjs reports the controller several times a
832
+ // second, and controls rebuilt that often would lose a click.
833
+ let runView = null;
834
+
835
+ function buildRunView(current) {
836
+ const view = { run: current };
837
+ view.title = el('p', { className: 'recording' }, '', el('span', { id: 'recording-clock' }, '0 s'));
838
+ view.doing = el('p', {});
839
+ view.ask = el('p', { className: 'instruction', hidden: true });
840
+ view.askText = el('span', {});
841
+ view.continue = button('Continue', () => current.stepper.continueSpindle(), { className: 'primary' });
842
+ view.ask.append(view.askText, view.continue);
843
+ view.hold = button('Hold', () => current.stepper.hold());
844
+ view.resume = button('Resume', () => current.stepper.resume(), { className: 'primary' });
845
+ view.stop = button('Stop', () => current.stepper.stop(), { className: 'danger' });
846
+ view.stuck = el('p', { className: 'instruction', hidden: true });
847
+ view.root = el('div', {},
848
+ view.title,
849
+ view.doing,
850
+ view.ask,
851
+ el('p', {}, view.hold, ' ', view.resume, ' ', view.stop),
852
+ view.stuck,
853
+ el('p', { className: 'muted' }, 'Stop if a cut gets violent: the cuts made so far still count. Feed hold in cncjs works too.'),
854
+ );
855
+ return view;
856
+ }
857
+
858
+ function updateRunView(view) {
859
+ const { stepper, round } = view.run;
860
+ view.title.firstChild.textContent = `Recording round ${round}: `;
861
+ const block = stepper.block;
862
+ const where = block?.pass_id === null || block?.pass_id === undefined ? '' : `, pass ${block.pass_id}`;
863
+ const doing = stepper.phase === PHASE.HELD ? 'Held' : (STEP_TEXT[block?.step] ?? 'Starting');
864
+ view.doing.textContent = `${doing}${where} (block ${Math.max((stepper.index ?? 0) + 1, 1)} of ${stepper.total || '…'}).`;
865
+ const asking = stepper.phase === PHASE.SET_SPINDLE;
866
+ view.ask.hidden = !asking;
867
+ view.askText.textContent = asking ? `Set the spindle to ${block.rpm} rpm, then ` : '';
868
+ view.hold.hidden = stepper.phase !== PHASE.MOVING;
869
+ view.resume.hidden = stepper.phase !== PHASE.HELD;
870
+ // Nothing moves before the first block: a double-clicked Start must not land on Stop.
871
+ view.stop.disabled = stepper.phase === PHASE.READY || stepper.finished || stepper.phase === PHASE.STOPPING;
872
+ const stuck = stall(stepper);
873
+ view.stuck.hidden = !stuck;
874
+ view.stuck.textContent = stuck;
875
+ }
876
+
553
877
  function renderStep() {
554
878
  const step = $('step');
555
- step.replaceChildren();
556
879
  step.hidden = !state || editing !== null;
557
- if (step.hidden) {
880
+ if (run && !step.hidden) {
881
+ if (runView?.run !== run) {
882
+ runView = buildRunView(run);
883
+ }
884
+ if (step.firstChild !== runView.root || step.childNodes.length !== 1) {
885
+ step.replaceChildren(runView.root);
886
+ }
887
+ updateRunView(runView);
558
888
  return;
559
889
  }
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
- );
890
+ runView = null;
891
+ step.replaceChildren();
892
+ if (step.hidden) {
568
893
  return;
569
894
  }
895
+ const round = plannedRound();
570
896
 
571
- if (busy) {
897
+ if (busy()) {
572
898
  step.append(el('p', {}, 'Working…'));
573
899
  return;
574
900
  }
@@ -590,7 +916,7 @@ function renderStep() {
590
916
  const stock = stockSelect();
591
917
  step.append(
592
918
  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.`),
919
+ el('p', {}, `One more round can find how hard the best cut (${best.rpm} rpm, ${length(best.width_mm, units())} wide, ${length(best.depth_mm, units())} deep) can be pushed: the same cut at rising chip loads, lightest first. Its cuts do not change the map.`),
594
920
  el('p', {}, button('Plan the chip-load sweep', async () => {
595
921
  await act('plan_sweep', stockChoice);
596
922
  stockChoice = 'same';
@@ -612,13 +938,13 @@ function renderStep() {
612
938
  const first = state.rounds.length === 0;
613
939
  const stock = stockSelect();
614
940
  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` : ''}`;
941
+ const label = `Plan round ${state.rounds.length + 1}${shallower ? ` at ${length(state.next_depth_mm, units())} depth` : ''}`;
616
942
  const plan = button(label, async () => {
617
943
  await act('plan', first ? 'same' : stockChoice);
618
944
  stockChoice = 'same';
619
945
  }, { className: 'primary' });
620
946
  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.`
947
+ ? `${length(state.depth_mm, units(), { mmToo: true })} depth is settled. Next come cuts ${length(state.next_depth_mm, units(), { mmToo: true })} deep, starting from the widths that were stable.`
622
948
  : 'Plan the next cuts from what was measured.';
623
949
  step.append(el('p', {}, first ? 'Plan a coarse grid of test cuts.' : next));
624
950
  step.append(el('p', {}, plan, ...(first ? [] : [' on the ', stock])));
@@ -627,12 +953,8 @@ function renderStep() {
627
953
 
628
954
  const tests = round.passes.filter((p) => p.kind === 'test').length;
629
955
  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 });
956
+ const refusal = startRefusal();
957
+ const start = button('Start', () => startRound(round), { className: 'primary', disabled: Boolean(refusal) || busy() });
636
958
  // cncjs reports the mode from the controller's parser state. Until it does, the operator
637
959
  // can say which it is: the program sets that mode itself, so a wrong choice cannot
638
960
  // misplace a cut, only leave the machine in the other mode afterwards.
@@ -641,18 +963,17 @@ function renderStep() {
641
963
  showIn(declare.value || null);
642
964
  render();
643
965
  };
644
- const unknownUnits = mic.open && cnc.link === 'ready' && cnc.units === null;
966
+ const unknownUnits = cnc.link === 'ready' && cnc.units === null;
645
967
  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}.`),
968
+ el('p', {}, `Round ${round.round}: ${tests} test cuts ${length(round.depth_mm, units(), { mmToo: true })} deep, about ${minutes(round.run_time_s)} plus rapids. The front face ends at Y ${length(round.face_y_end_mm, units(), { mmToo: true })}.`),
647
969
  el('ol', {},
648
970
  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.`)] : []),
971
+ el('li', {}, start, ' runs the round from here, one move at a time, and records it. Keep this tab open.', ...(unknownUnits ? [' cncjs has not reported G20 or G21 yet; the machine is in ', declare] : [])),
972
+ ...(state.spindle === 'manual' ? [el('li', {}, `Before each of its ${speedChanges(round)} spindle speeds the round stops; set the speed shown here and press Continue.`)] : []),
652
973
  ),
653
974
  );
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.'));
975
+ if (refusal && !unknownUnits) {
976
+ step.append(el('p', { className: 'muted' }, refusal));
656
977
  }
657
978
  if (round.has_recording) {
658
979
  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))));
@@ -666,15 +987,23 @@ function verdictCell(round, pass) {
666
987
  if (!round.analysed) {
667
988
  return el('td', {}, '');
668
989
  }
669
- const select = el('select', { disabled: busy },
670
- ...(pass.verdict ? [] : [el('option', { value: '' }, 'not heard')]),
990
+ if (pass.status === 'not run' && !pass.verdict) {
991
+ return el('td', { className: 'muted' }, 'not run');
992
+ }
993
+ const select = el('select', { disabled: busy() },
994
+ ...(pass.verdict ? [] : [el('option', { value: '' }, pass.status === 'likely not run' ? 'likely not run' : 'not heard')]),
671
995
  el('option', { value: 'stable' }, pass.status === 'aborted' ? 'stable (aborted)' : 'stable'),
672
996
  el('option', { value: 'unstable' }, pass.status === 'aborted' ? 'chatter (aborted)' : 'chatter'),
673
997
  );
674
998
  select.value = pass.verdict ?? '';
675
999
  select.title = pass.chatter_hz ? `peak ${Math.round(pass.chatter_hz)} Hz, ${pass.prominence_db} dB over the floor` : '';
676
1000
  select.onchange = () => act('set_verdict', round.round, pass.id, select.value);
677
- return el('td', { className: pass.verdict ?? '' }, select);
1001
+ // The spindle speed heard sits at the edge of the search around this pass's: the sound
1002
+ // may be another pass's. Worth a listen before trusting the verdict.
1003
+ const edge = pass.spindle_fit === 'edge'
1004
+ ? [el('span', { className: 'muted', title: 'The spindle speed heard is at the edge of what this pass could be: check it.' }, ' speed?')]
1005
+ : [];
1006
+ return el('td', { className: pass.verdict ?? '' }, select, ...edge);
678
1007
  }
679
1008
 
680
1009
  function renderRound() {
@@ -684,14 +1013,14 @@ function renderRound() {
684
1013
  return;
685
1014
  }
686
1015
  const kind = round.planner === 'sweep' ? ' (chip-load sweep)' : '';
687
- $('round-title').textContent = `Round ${round.round}${kind}${round.analysed ? ' results' : ''}, ${round.depth_mm} mm deep`;
1016
+ $('round-title').textContent = `Round ${round.round}${kind}${round.analysed ? ' results' : ''}, ${length(round.depth_mm, units(), { mmToo: true })} deep`;
688
1017
  $('passes').replaceChildren(
689
1018
  ...round.passes.map((p) =>
690
1019
  el('tr', { className: p.kind === 'test' ? '' : 'prep' },
691
1020
  el('td', {}, String(p.id)),
692
1021
  el('td', {}, String(p.rpm)),
693
- el('td', {}, p.width_mm.toFixed(2)),
694
- el('td', {}, String(Math.round(p.feed_mm_min))),
1022
+ el('td', {}, length(p.width_mm, units())),
1023
+ el('td', {}, feed(p.feed_mm_min, units())),
695
1024
  el('td', {}, p.p_stable === null ? '' : p.p_stable.toFixed(2)),
696
1025
  verdictCell(round, p),
697
1026
  ),
@@ -705,11 +1034,11 @@ function renderMap() {
705
1034
  if ($('map-section').hidden) {
706
1035
  return;
707
1036
  }
708
- $('map-title').textContent = `Stability map at ${state.depth_mm} mm depth`;
1037
+ $('map-title').textContent = `Stability map at ${length(state.depth_mm, units(), { mmToo: true })} depth`;
709
1038
  const { speeds, widths, p } = state.map;
710
1039
  const canvas = $('map');
711
1040
  const ctx = canvas.getContext('2d');
712
- const pad = { left: 40, bottom: 16, top: 4, right: 4 };
1041
+ const pad = { left: units() === 'in' ? 56 : 40, bottom: 16, top: 4, right: 4 };
713
1042
  const w = canvas.width - pad.left - pad.right;
714
1043
  const h = canvas.height - pad.top - pad.bottom;
715
1044
  ctx.clearRect(0, 0, canvas.width, canvas.height);
@@ -750,9 +1079,9 @@ function renderMap() {
750
1079
  ctx.fillText(`${speeds[0]} rpm`, pad.left, pad.top + h + 3);
751
1080
  ctx.textAlign = 'right';
752
1081
  ctx.fillText(String(speeds.at(-1)), pad.left + w, pad.top + h + 3);
753
- ctx.fillText(`${widths.at(-1)}`, pad.left - 3, pad.top);
1082
+ ctx.fillText(length(widths.at(-1), units()).split(' ')[0], pad.left - 3, pad.top);
754
1083
  ctx.textBaseline = 'bottom';
755
- ctx.fillText(`${widths[0]} mm`, pad.left - 3, pad.top + h);
1084
+ ctx.fillText(length(widths[0], units()), pad.left - 3, pad.top + h);
756
1085
  }
757
1086
 
758
1087
  function renderBest() {
@@ -762,10 +1091,10 @@ function renderBest() {
762
1091
  ...best.map((b) =>
763
1092
  el('tr', {},
764
1093
  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)),
1094
+ el('td', {}, length(b.width_mm, units())),
1095
+ el('td', {}, length(b.depth_mm, units())),
1096
+ el('td', {}, feed(b.feed_mm_min, units())),
1097
+ el('td', {}, rate(b.mrr_cm3_min, units())),
769
1098
  ),
770
1099
  ),
771
1100
  );
@@ -774,10 +1103,11 @@ function renderBest() {
774
1103
  if (!sweep) {
775
1104
  return;
776
1105
  }
777
- const where = `At ${sweep.rpm} rpm, ${sweep.width_mm.toFixed(2)} mm wide and ${sweep.depth_mm} mm deep`;
1106
+ const u = units();
1107
+ const where = `at ${sweep.rpm} rpm, ${length(sweep.width_mm, u)} wide and ${length(sweep.depth_mm, u)} deep`;
778
1108
  $('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.`;
1109
+ ? `Chip-load sweep: ${where}, even its lightest pass chattered. Keep the session's ${chipLoad(sweep.session_chip_load_mm, u, { mmToo: true })} per tooth.`
1110
+ : `Chip-load sweep: ${where}, the cut stayed stable up to ${chipLoad(sweep.chip_load_mm, u, { mmToo: true })} per tooth (the session used ${chipLoad(sweep.session_chip_load_mm, u)}): feed ${feed(sweep.feed_mm_min, u, { mmToo: true })}, ${rate(sweep.mrr_cm3_min, u, { mmToo: true })}.`;
781
1111
  }
782
1112
 
783
1113
  function render() {
@@ -812,7 +1142,22 @@ $('cancel-setup').onclick = () => {
812
1142
  showError('');
813
1143
  render();
814
1144
  };
815
- $('export').onclick = exportSession;
1145
+ $('export').onclick = () => exportSession();
1146
+ $('delete-session').onclick = () => ask('delete');
1147
+ $('reset-session').onclick = () => ask('reset');
1148
+ // The page's error line is behind the dialog: say there how the export went.
1149
+ $('confirm-dialog').addEventListener('close', () => {
1150
+ dialog = 'closed';
1151
+ render();
1152
+ });
1153
+ $('confirm-export').onclick = async () => {
1154
+ showError('');
1155
+ await exportSession($('confirm-dialog').dataset.session);
1156
+ const { verb } = ACTIONS[$('confirm-dialog').dataset.action];
1157
+ $('confirm-note').textContent = $('error').hidden ? `Exported. ${verb} it now, or cancel.` : `Not exported: ${$('error').textContent}`;
1158
+ };
1159
+ $('confirm-go').onclick = confirmed;
1160
+ $('confirm-cancel').onclick = () => $('confirm-dialog').close();
816
1161
  $('download-report').onclick = downloadReport;
817
1162
  $('import').onclick = () => $('import-file').click();
818
1163
  $('import-file').onchange = () => {
@@ -841,8 +1186,9 @@ for (const type of ['pointerdown', 'pointerup', 'keydown']) {
841
1186
  }
842
1187
 
843
1188
  // Leaving mid-recording loses the run: the samples are only in this page.
1189
+ // Leaving mid-round loses the recording; the machine finishes its one move and stands.
844
1190
  window.addEventListener('beforeunload', (event) => {
845
- if (mic.recording) {
1191
+ if (run || mic.recording) {
846
1192
  event.preventDefault();
847
1193
  }
848
1194
  });
@@ -851,6 +1197,8 @@ render();
851
1197
  connectCncjs();
852
1198
  openMic(localStorage.getItem(DEVICE_KEY) || undefined);
853
1199
  setInterval(renderLevel, LEVEL_MS);
1200
+ // cncjs reports only changes: a run that stalls gets no news, so its panel is redrawn anyway.
1201
+ setInterval(() => run && renderStep(), 1000);
854
1202
 
855
1203
  try {
856
1204
  names = await engine('names');