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/CHANGELOG.md CHANGED
@@ -6,6 +6,69 @@ What changed for people who use the dechatter widget and command line. The forma
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.3.0] - 2026-11-12
10
+
11
+ ### Changed
12
+
13
+ - The widget runs a round itself: press Start in the widget instead of loading the program
14
+ into cncjs and pressing play. It sends one move at a time through cncjs and waits for the
15
+ controller to report Idle at its end, so it knows exactly when each cut starts and ends
16
+ and records those windows with the sound. Hold, Resume and Stop are in the widget; Stop
17
+ always holds first and resets the controller only once it has reported the hold complete
18
+ (or Idle) and nothing has changed for a second; if the connection drops meanwhile, nothing
19
+ is reset, then or on reconnect. An alarm (its state or an `ALARM:` line) ends the round with
20
+ nothing more sent and is left for you to clear (the widget never unlocks). With a
21
+ manual spindle no `M0` is sent: the widget asks for each speed and waits for Continue, so
22
+ the "set the spindle" prompt shows only once the machine has stopped. Start is refused
23
+ while cncjs runs a job of its own, in alarm or hold, or before the machine's units are
24
+ known, and a job cncjs starts during the round stops it. If the machine refuses, or the
25
+ microphone closes, while the round is being prepared, it does not start and no recording
26
+ is kept. While a round runs,
27
+ or starts, its session stays open: the session list, New, Import and Setup wait for it to
28
+ end.
29
+ `program.nc` is still written, unchanged, for the command line.
30
+
31
+ - On a machine in G20 the whole widget shows inches, not only the wizard and the programs:
32
+ the session summary, round headings and pass table, the front face position, the best
33
+ cuts, the chip-load sweep result and the stability map's axes. Inches have 4 decimals
34
+ (chip loads 5), with millimetres alongside where there is room. Files stay in mm.
35
+
36
+ ### Added
37
+
38
+ - **Reset** next to the widget's session list, and `dechatter reset <session>` (with
39
+ `--yes` to skip the question), discard every round of a session and keep its setup. The
40
+ session starts again from round 1 and its setup can be changed freely, for instance after
41
+ a run in the air to check the toolpath, or one with Z zero set wrong. It asks first,
42
+ naming the rounds and recordings lost, offers Export first, and is refused while the
43
+ session records or a cncjs job of its program runs, and for a session whose setup does
44
+ not load (delete that one instead); rounds that do not load are no obstacle. A stale `report.html` in the session goes too.
45
+ - **Delete** next to the widget's session list removes a session from the browser for good,
46
+ after a confirmation that names its rounds and recordings and offers Export first. It
47
+ works for sessions that no longer load, such as ones from dechatter 0.1.x. One whose setup
48
+ does not load cannot be exported, and the confirmation says so instead. It is refused while the session
49
+ records or a cncjs job of its program runs.
50
+
51
+ ### Fixed
52
+
53
+ - Cuts were matched to the wrong passes, seen on a real manual-spindle session: light cuts at
54
+ a low speed fell under one level threshold for the whole recording, and the rest slid onto
55
+ the wrong passes; passes never run had cuts forced onto them. A round the widget runs is
56
+ now analysed from the cut and dwell windows it recorded. A recording without them is
57
+ searched against the spindle's own noise around each cut, keeps the pass order with the
58
+ narrowest cuts taken as the unheard ones, and marks passes after the last cut as "likely
59
+ not run". A widget run that ended before its first cut leaves the round to run again,
60
+ and a cut stopped before the cutter reached the stock counts as not run. A hold before
61
+ the cutter reaches the stock no longer puts air into the cut analysed. Silence in a
62
+ recording, even most of it (a recorder left running after the round), short pauses with
63
+ the spindle off, or silence broken up by knocks, is told from a quiet spindle under loud
64
+ cuts, and no longer hides the spindle's level.
65
+ A pass whose spindle speed was found at the edge of its search is flagged.
66
+ - A recording could get stuck with no way to stop it, and Export was disabled meanwhile. The
67
+ recording now follows the widget's own run, which always ends (Stop, the last pass, an
68
+ error or a lost connection) and keeps the cuts made. A run held for a minute, or a machine
69
+ idle but not where its move ends, points to Stop. Export works during a run, without the
70
+ round in progress, and says so.
71
+
9
72
  ## [0.2.0] - 2026-11-12
10
73
 
11
74
  ### Changed
@@ -97,7 +160,8 @@ What changed for people who use the dechatter widget and command line. The forma
97
160
  Sessions export to a zip the command line reads, and import in another browser.
98
161
  - Published on npm as `dechatter`, with third-party notices for the bundled Pyodide.
99
162
 
100
- [Unreleased]: https://github.com/pedropaulovc/dechatter/compare/v0.2.0...HEAD
163
+ [Unreleased]: https://github.com/pedropaulovc/dechatter/compare/v0.3.0...HEAD
164
+ [0.3.0]: https://github.com/pedropaulovc/dechatter/compare/v0.2.0...v0.3.0
101
165
  [0.2.0]: https://github.com/pedropaulovc/dechatter/compare/v0.1.1...v0.2.0
102
166
  [0.1.1]: https://github.com/pedropaulovc/dechatter/compare/v0.1.0...v0.1.1
103
167
  [0.1.0]: https://github.com/pedropaulovc/dechatter/releases/tag/v0.1.0
package/README.md CHANGED
@@ -59,7 +59,7 @@ a page the microphone on those. Then, in the widget:
59
59
 
60
60
  1. Create a session. A short wizard asks for the machine, the tool, the cut and the stock. It
61
61
  shows lengths in inches when the machine is in G20 and in millimetres when it is in G21,
62
- or with no machine connected. Its last step holds the planner's settings, which rarely
62
+ or with no machine connected; so does the rest of the widget. Its last step holds the planner's settings, which rarely
63
63
  need changing. Settings with a sensible default or a computed value (the machine's name,
64
64
  the holder, the cut's limits and chip load, the program's dwell, clearance, plunge feed,
65
65
  truing width and coolant, and the planner) sit in a collapsed Advanced section of their
@@ -87,9 +87,22 @@ a page the microphone on those. Then, in the widget:
87
87
  plan uses the new setup. `dechatter plan` refuses the same changes made by hand.
88
88
  2. Plan a round. Round 1 is a coarse grid of speeds and widths.
89
89
  3. Set the work zero at the left end of the stock, on its front face, at the top.
90
- 4. Load the program into cncjs and press play in cncjs. The widget never starts the machine.
91
- 5. Recording starts when the job starts and stops when it ends. The widget then shows each
92
- pass as stable or chatter, the stability map and the best cuts so far.
90
+ 4. Press Start. The widget runs the round itself through cncjs, one move at a time: it
91
+ sends a move, waits until the controller reports Idle at its end, then sends the next.
92
+ So it knows when every cut starts and ends, and records those times with the sound; at
93
+ most one move is ever queued, so if the tab closes or the connection drops the machine
94
+ finishes that move and stands. Hold, Resume and Stop are in the widget (cncjs's own feed
95
+ hold works too). Stop holds, waits until the controller reports the hold complete (or
96
+ Idle) and nothing changes for a second, then resets it; if the hold never completes, or
97
+ the connection drops meanwhile, it does not reset, and says so. An alarm stops the round with nothing more sent and is left for you
98
+ to clear in cncjs (home, or unlock): the widget never unlocks. While a round runs, its
99
+ session stays open: the session list, New, Import and Setup wait for it to end. Start is refused while cncjs runs a job of its own, while the machine is in
100
+ alarm or held, or before its G20/G21 mode is known, and a job cncjs starts during the
101
+ round stops the round. To check the toolpath first, raise Z zero and run the round in the
102
+ air, then Reset the session (next to the session list) and set Z zero back on the top of
103
+ the stock.
104
+ 5. Recording starts with Start and stops when the last pass ends, or on Stop. The widget
105
+ then shows each pass as stable or chatter, the stability map and the best cuts so far.
93
106
  6. If your ears disagree with a verdict, change it in the table. Plan the next round and
94
107
  repeat until the widget reports convergence.
95
108
  7. Optionally, plan the chip-load sweep it then offers: the best cut once more at five
@@ -111,17 +124,26 @@ browser kept any of that processing on.
111
124
 
112
125
  Sessions are stored in that browser (IndexedDB), per cncjs address. Export saves one as a zip
113
126
  holding `setup.toml` and each round's plan, program, `recording.wav`, results and the job
114
- timeline cncjs reported, plus `report.html`. Import loads it in another browser, and unzipped it is a session
127
+ timeline of the run (each pass's cut and dwell windows), plus `report.html`. Import loads it in another browser, and unzipped it is a session
115
128
  folder the command line reads. Keep the tab open while a round runs: the recording lives in
116
- the page until the job ends.
129
+ the page until the round ends. Export works during a run too, without that round. If a run
130
+ seems stuck (held for a minute, or the machine idle but not where its move ends), the widget
131
+ says so and points to Stop, which keeps and analyses the cuts made so far. Reset, next to the session list, discards every round and
132
+ keeps the setup, so the session starts again from round 1 and its setup can be changed
133
+ freely (`dechatter reset <session>` on the command line); it needs a setup that loads,
134
+ though its rounds need not. Delete removes a session for good after asking, and offers
135
+ Export first. It also removes sessions that no longer load, such as ones from dechatter
136
+ 0.1.x; one whose setup does not load cannot be exported.
137
+ Both are refused while that session records or its job runs.
117
138
 
118
139
  ### Manual spindle
119
140
 
120
141
  If the spindle is started and set by hand, choose "me, by hand" on the wizard's first step
121
142
  (`spindle = "manual"` under `[machine]` in a setup file). The program then never commands the
122
- spindle. It stops with `M0` before each speed, with
123
- the cutter clear of the work, and the widget (and cncjs) shows the speed to set. Set it and
124
- press resume in cncjs. Cuts are grouped by speed, lightest first, so a round has one stop per
143
+ spindle. In the widget, the round stops before each speed with the cutter clear of the work
144
+ and shows the speed to set: set it and press Continue. The program file (`program.nc`, for
145
+ the command line) stops with `M0` at the same places instead: set the speed and press resume
146
+ in cncjs. Cuts are grouped by speed, lightest first, so a round has one stop per
125
147
  speed: five in round 1. The first stop is where you start the spindle, and you stop it yourself
126
148
  after the program ends.
127
149
 
@@ -145,6 +167,7 @@ dechatter analyze al-10mm recording.wav # classifies each pass
145
167
  dechatter plan al-10mm # next round, or "converged"
146
168
  dechatter plan al-10mm --sweep # once converged: chip-load sweep of the best cut
147
169
  dechatter report al-10mm # stability map and best cuts so far
170
+ dechatter reset al-10mm # discard every round, keep the setup (asks first)
148
171
  dechatter report al-10mm --html al-10mm.html --units in # printable report
149
172
  ```
150
173
 
@@ -176,9 +199,19 @@ remaining spectrum and at least 10 dB above the same frequency in the dwell just
176
199
  pass, when the spindle was turning in air. The second test rejects tones the machine makes
177
200
  without cutting, such as drive whine.
178
201
 
179
- Passes are found in the recording by level, then matched in order to the planned passes by
180
- how long each cut should last. A quiet pass that goes undetected is reported as missing and
181
- does not shift the others. If matching fails, mark the cuts yourself and pass
202
+ When the widget ran the round, it recorded where every cut and every dwell is, and those
203
+ windows are used as they are: the cut from where the cutter meets the stock to where it
204
+ leaves it, without any time the machine was held, and the dwell before it as the air
205
+ reference. A pass the run never reached is "not run". A run that ended before its first cut
206
+ is not analysed, and the round stays planned to run again.
207
+
208
+ A recording made otherwise (the command line, a phone) is searched for its cuts by their
209
+ level over the spindle's own noise around them, since the spindle gets louder as it speeds
210
+ up and a light cut is only a few dB over it. The cuts found are matched in order to the
211
+ planned passes by how long each should last; at one speed the narrowest cuts are the ones
212
+ that can go unheard, so those are the ones taken as missing. Passes after the last cut heard
213
+ are "likely not run" (a verdict can still be set by hand, should one have run unheard), and a pass whose spindle speed was found at the edge of its ±5% search is
214
+ flagged ("speed?" in the widget). If matching fails, mark the cuts yourself and pass
182
215
  `--segments labels.txt` (start and end seconds per pass; an Audacity label export works).
183
216
 
184
217
  `results.json` in each round holds the verdicts and the numbers behind them. If your ears
@@ -249,6 +282,7 @@ mount it, reset the face to `Y0` and run `dechatter plan --new-stock`.
249
282
  uv sync
250
283
  uv run pytest
251
284
  uv run ruff check .
285
+ node --test tests/js/stepper.test.mjs # the widget's stepper against a scripted controller
252
286
  uv run validation/purdue.py ~/purdue-cache # downloads about 370 MB once
253
287
  ```
254
288
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dechatter",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "CNCjs custom widget that finds chatter-free milling speeds, widths and depths from test cuts heard through the microphone.",
5
5
  "keywords": [
6
6
  "cncjs",
@@ -35,6 +35,7 @@
35
35
  },
36
36
  "scripts": {
37
37
  "build": "node .github/build_widget.mjs",
38
+ "test": "node --test tests/js/stepper.test.mjs",
38
39
  "prepack": "npm run build"
39
40
  }
40
41
  }
package/web/dechatter.zip CHANGED
Binary file
package/web/engine.js CHANGED
@@ -5,7 +5,7 @@ import { loadPyodide } from './pyodide/pyodide.js';
5
5
 
6
6
  const ROOT = '/sessions';
7
7
  // Calls that change files; the filesystem is flushed to IndexedDB after each of them.
8
- const WRITES = new Set(['create', 'save_setup', 'plan', 'plan_sweep', 'record_stop', 'analyze', 'set_verdict', 'import_zip']);
8
+ const WRITES = new Set(['create', 'delete', 'reset', 'save_setup', 'plan', 'plan_sweep', 'record_stop', 'analyze', 'set_verdict', 'import_zip']);
9
9
 
10
10
  let pyodide;
11
11
  let call;
@@ -68,7 +68,8 @@ async function handle({ method, args }) {
68
68
  return { ok: bytes };
69
69
  }
70
70
  const reply = JSON.parse(result);
71
- if ('ok' in reply && WRITES.has(method)) {
71
+ // Also after a refused or failed write: memory may have changed before it failed.
72
+ if (WRITES.has(method)) {
72
73
  await sync(false);
73
74
  }
74
75
  return reply;
package/web/index.html CHANGED
@@ -13,6 +13,8 @@
13
13
  <div id="main" hidden>
14
14
  <header>
15
15
  <select id="sessions" aria-label="Session"></select>
16
+ <button id="reset-session" disabled>Reset</button>
17
+ <button id="delete-session" disabled>Delete</button>
16
18
  <button id="new-session">New</button>
17
19
  <button id="edit-setup" disabled>Setup</button>
18
20
  <button id="export" disabled>Export</button>
@@ -46,6 +48,16 @@
46
48
  </p>
47
49
  </section>
48
50
 
51
+ <dialog id="confirm-dialog" aria-labelledby="confirm-question">
52
+ <p id="confirm-question"></p>
53
+ <p id="confirm-note" class="muted"></p>
54
+ <p class="wizard-buttons">
55
+ <button id="confirm-export" type="button">Export first</button>
56
+ <button id="confirm-go" type="button" class="danger">Delete</button>
57
+ <button id="confirm-cancel" type="button">Cancel</button>
58
+ </p>
59
+ </dialog>
60
+
49
61
  <section id="step" hidden></section>
50
62
 
51
63
  <section id="round" hidden>
@@ -69,7 +81,7 @@
69
81
  <section id="best-section" hidden>
70
82
  <h2>Best stable cuts <button id="download-report" type="button">Download report</button></h2>
71
83
  <table>
72
- <thead><tr><th>rpm</th><th>width</th><th>depth</th><th>feed</th><th>cm³/min</th></tr></thead>
84
+ <thead><tr><th>rpm</th><th>width</th><th>depth</th><th>feed</th><th>removal</th></tr></thead>
73
85
  <tbody id="best"></tbody>
74
86
  </table>
75
87
  <p id="sweep-result" class="muted legend" hidden></p>
package/web/stepper.js ADDED
@@ -0,0 +1,402 @@
1
+ // Runs a round through cncjs's controller one block at a time, so the widget knows when
2
+ // each cut starts and ends. A controller buffers whatever it is sent and reports no line
3
+ // numbers by default (FluidNC, stock Grbl), so the only way to know where the machine is
4
+ // is to send one move, then wait until it reports Idle at that move's end.
5
+ //
6
+ // The stepper talks to the machine through `io` (cncjs's socket commands) and learns its
7
+ // state from controller() (cncjs's controller:state), error() (an error: line), alarm()
8
+ // (an ALARM: line) and disconnected(). Nothing here touches the page.
9
+
10
+ // What the run is doing; the widget shows it.
11
+ export const PHASE = {
12
+ READY: 'ready', // not started
13
+ MOVING: 'moving', // a block was sent; waiting for Idle at its end
14
+ DWELLING: 'dwelling', // spindle at speed in the air beside the stock
15
+ SET_SPINDLE: 'set-spindle', // manual spindle: waiting for the operator's Continue
16
+ HELD: 'held', // the controller holds (feed hold, from here or from cncjs)
17
+ STOPPING: 'stopping',
18
+ DONE: 'done', // every block ran
19
+ STOPPED: 'stopped', // the operator stopped it
20
+ FAILED: 'failed', // an error, an alarm or a lost connection ended it
21
+ };
22
+
23
+ const FINISHED = new Set([PHASE.DONE, PHASE.STOPPED, PHASE.FAILED]);
24
+ const HOLD_STATES = new Set(['Hold', 'Door']);
25
+ // Stop: hold, wait until the controller reports the hold complete or Idle, then reset. A
26
+ // reset while the machine still moves loses its position (Grbl ALARM:3), so if it does not
27
+ // settle in this long, nothing is reset and the operator is told.
28
+ const SETTLE_TIMEOUT_S = 15;
29
+ // The machine is at rest once it has said Hold:0 or Idle and nothing has changed for this
30
+ // long: cncjs polls about every 250 ms and reports changes, the position among them. Grbl
31
+ // 0.9 reports a bare Hold, which cncjs reads as Hold:0, while it still decelerates, and an
32
+ // Idle can be stale (see holdThenReset).
33
+ const QUIET_S = 1;
34
+ const POLL_MS = 250;
35
+ const ALARM_ADVICE = 'Clear it in cncjs (home, or unlock if you are sure the position is still right).';
36
+
37
+ class Ended extends Error {}
38
+
39
+ // How a halt ended.
40
+ const HALT = {
41
+ RESET: 'reset', // the machine had stopped; it was reset
42
+ UNSETTLED: 'unsettled', // it never said it stopped: nothing was reset
43
+ ALARM: 'alarm', // the controller went into alarm: it stopped itself
44
+ };
45
+
46
+ // The link to cncjs and the machine. Once lost, nothing more is sent: socket.io buffers
47
+ // what is emitted while disconnected and sends it on reconnect, maybe minutes later.
48
+ const LINK = { UP: 'up', LOST: 'lost' };
49
+
50
+ // What a report says of the machine's motion. At rest (Idle, or a complete hold) counts
51
+ // once nothing changes for QUIET_S.
52
+ export const REST = {
53
+ IDLE: 'idle',
54
+ HOLD_COMPLETE: 'hold-complete', // Hold:0
55
+ OTHER: 'other', // moving, decelerating, or in another state
56
+ };
57
+
58
+ export const holdComplete = (state) => state.activeState === 'Hold' && state.subState === 0;
59
+
60
+ export function restOf(state) {
61
+ if (state.activeState === 'Idle') {
62
+ return REST.IDLE;
63
+ }
64
+ return holdComplete(state) ? REST.HOLD_COMPLETE : REST.OTHER;
65
+ }
66
+
67
+ // Whether two reports differ in what the stepper sees: cncjs also reports when only the
68
+ // feed, the spindle speed or the planner buffer changed.
69
+ const changed = (a, b) => a.activeState !== b.activeState || a.subState !== b.subState || JSON.stringify(a.wpos) !== JSON.stringify(b.wpos);
70
+ const UNSETTLED_ADVICE = 'so it was not reset. Make sure it has stopped, then reset it in cncjs.';
71
+
72
+ // Positions match within this many mm: controllers report three decimals in mm, or four in
73
+ // inches, and a program in inches rounds its words to four decimals.
74
+ const TOLERANCE_MM = 0.02;
75
+
76
+ export class Stepper {
77
+ // io: { send(lines), feedhold(), cyclestart(), reset() }. It never unlocks ($X): an
78
+ // alarm is for the operator to clear.
79
+ // reportInches: the controller reports positions in inches (Grbl's $13=1); targets are mm.
80
+ constructor({ io, reportInches = false, now = () => Date.now() / 1000, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), onChange = () => {}, onWindow = () => {} }) {
81
+ this.io = io;
82
+ this.scale = reportInches ? 25.4 : 1;
83
+ this.now = now;
84
+ this.sleep = sleep;
85
+ this.onChange = onChange;
86
+ this.onWindow = onWindow; // a dwell or cut window, as soon as it is complete
87
+ this.phase = PHASE.READY;
88
+ this.block = null; // the block being run
89
+ this.index = -1;
90
+ this.total = 0;
91
+ this.reason = ''; // why it stopped or failed
92
+ this.state = { activeState: '', subState: null, wpos: null };
93
+ this.watchers = []; // halt() waiting for the next report; unlike waiters, they outlive the end of the run
94
+ this.alarmedBy = null; // the alarm that ended the run, if one did
95
+ this.link = LINK.UP;
96
+ this.waiters = [];
97
+ this.ended = null; // the Ended error every wait rejects with, once the run is over
98
+ this.holds = []; // [start, end] of holds during the current block
99
+ // Since when the controller has said Idle somewhere other than where the block ends: a
100
+ // move it dropped, or a position it reports differently. null while that is not so.
101
+ this.idleAway = null;
102
+ this.continued = null;
103
+ this.halting = null;
104
+ }
105
+
106
+ get finished() {
107
+ return FINISHED.has(this.phase);
108
+ }
109
+
110
+ // ---- what the controller says ------------------------------------------------------
111
+
112
+ // subState: Grbl's Hold:N, as cncjs reports it: 0 once the hold is complete.
113
+ controller({ activeState, subState = null, wpos }) {
114
+ this.state = { activeState: activeState ?? '', subState, wpos: wpos ?? this.state.wpos };
115
+ if (activeState === 'Alarm') {
116
+ this.alarm('an alarm');
117
+ return;
118
+ }
119
+ this.wakeWatchers();
120
+ const away = this.phase === PHASE.MOVING && activeState === 'Idle' && !this.at(this.state.wpos, this.block?.target ?? {});
121
+ this.idleAway = away ? (this.idleAway ?? this.now()) : null;
122
+ const held = HOLD_STATES.has(activeState);
123
+ if (held && this.phase === PHASE.MOVING) {
124
+ this.holds.push([this.now(), null]);
125
+ this.set(PHASE.HELD);
126
+ }
127
+ if (!held && this.phase === PHASE.HELD && activeState) {
128
+ this.holds.at(-1)[1] = this.now();
129
+ this.set(PHASE.MOVING);
130
+ }
131
+ for (const waiter of [...this.waiters]) {
132
+ if (waiter.until(this.state)) {
133
+ this.waiters.splice(this.waiters.indexOf(waiter), 1);
134
+ waiter.resolve(this.now());
135
+ }
136
+ }
137
+ }
138
+
139
+ error(message) {
140
+ this.fail(message);
141
+ }
142
+
143
+ // The controller has stopped the machine itself: nothing is sent, not even a hold or a
144
+ // reset, and a halt under way ends at once.
145
+ alarm(what) {
146
+ if (this.alarmedBy !== null || this.phase === PHASE.DONE || this.phase === PHASE.STOPPED) {
147
+ return;
148
+ }
149
+ this.alarmedBy = what;
150
+ this.end(PHASE.FAILED, `the controller reported ${what}. ${ALARM_ADVICE}`);
151
+ this.wakeWatchers();
152
+ }
153
+
154
+ // The socket or the port went away. A halt under way ends at once, sending nothing, and
155
+ // a run already ending keeps the reason it ended for.
156
+ disconnected() {
157
+ this.link = LINK.LOST;
158
+ if (!this.finished && this.phase !== PHASE.STOPPING) {
159
+ this.end(PHASE.FAILED, 'the connection to cncjs or the machine was lost');
160
+ }
161
+ this.wakeWatchers();
162
+ }
163
+
164
+ // Wake halt(): a report came, or the run can no longer be halted.
165
+ wakeWatchers() {
166
+ for (const resolve of this.watchers.splice(0)) {
167
+ resolve(this.state);
168
+ }
169
+ }
170
+
171
+ // ---- what the operator does --------------------------------------------------------
172
+
173
+ hold() {
174
+ if (this.phase === PHASE.MOVING) {
175
+ this.io.feedhold();
176
+ }
177
+ }
178
+
179
+ resume() {
180
+ if (this.phase === PHASE.HELD) {
181
+ this.io.cyclestart();
182
+ }
183
+ }
184
+
185
+ continueSpindle() {
186
+ if (this.phase === PHASE.SET_SPINDLE) {
187
+ this.continued?.();
188
+ }
189
+ }
190
+
191
+ // Stop sending, hold, wait for the hold to complete, then reset.
192
+ async stop(reason = 'stopped by the operator') {
193
+ if (this.finished || this.phase === PHASE.STOPPING) {
194
+ return;
195
+ }
196
+ const was = this.phase;
197
+ this.end(PHASE.STOPPING, reason);
198
+ this.halting = (async () => {
199
+ const halt = was === PHASE.READY ? HALT.RESET : await this.halt(was);
200
+ this.set(halt === HALT.RESET ? PHASE.STOPPED : PHASE.FAILED);
201
+ })();
202
+ await this.halting;
203
+ }
204
+
205
+ // Bring the machine to rest and reset it. `was`: the phase the run was in.
206
+ async halt(was) {
207
+ if (this.alarmedBy !== null) {
208
+ return HALT.ALARM;
209
+ }
210
+ if (was !== PHASE.MOVING && was !== PHASE.HELD) {
211
+ // Dwelling or waiting for the spindle: the last move was seen to end where it should.
212
+ this.io.reset();
213
+ return HALT.RESET;
214
+ }
215
+ try {
216
+ return await this.holdThenReset();
217
+ } finally {
218
+ this.watchers = [];
219
+ }
220
+ }
221
+
222
+ // A move was sent: the last report may predate it (cncjs reports only changes), and even
223
+ // a report after the hold can carry the status of a `?` answered before the move started
224
+ // (cncjs re-emits the last status when the parser state changes). So Idle or Hold:0
225
+ // counts only once reported after the hold and unchanged for QUIET_S. A hold already
226
+ // complete when the move was sent keeps that move from starting: it counts the same way.
227
+ async holdThenReset() {
228
+ const since = this.now();
229
+ let report = this.nextReport(); // watch before holding: the controller may answer at once
230
+ this.io.feedhold();
231
+ let quietSince = holdComplete(this.state) ? since : null;
232
+ let last = this.state;
233
+ for (;;) {
234
+ const state = await Promise.race([report, this.sleep(POLL_MS).then(() => null)]);
235
+ if (this.alarmedBy !== null) {
236
+ return HALT.ALARM;
237
+ }
238
+ if (this.link === LINK.LOST) {
239
+ this.reason = `${this.reason}; the connection was lost while stopping, ${UNSETTLED_ADVICE}`;
240
+ return HALT.UNSETTLED;
241
+ }
242
+ if (state) {
243
+ report = this.nextReport();
244
+ if (restOf(state) === REST.OTHER) {
245
+ quietSince = null;
246
+ } else if (quietSince === null || changed(state, last)) {
247
+ quietSince = this.now();
248
+ }
249
+ last = state;
250
+ }
251
+ if (quietSince !== null && this.now() - quietSince >= QUIET_S) {
252
+ this.io.reset();
253
+ return HALT.RESET;
254
+ }
255
+ if (this.now() - since >= SETTLE_TIMEOUT_S) {
256
+ this.reason = `${this.reason}; the machine did not report the hold complete, ${UNSETTLED_ADVICE}`;
257
+ return HALT.UNSETTLED;
258
+ }
259
+ }
260
+ }
261
+
262
+ nextReport() {
263
+ return new Promise((resolve) => this.watchers.push(resolve));
264
+ }
265
+
266
+ fail(reason) {
267
+ if (this.finished || this.phase === PHASE.STOPPING) {
268
+ return;
269
+ }
270
+ const was = this.phase;
271
+ this.end(PHASE.FAILED, reason);
272
+ if (was !== PHASE.READY) {
273
+ this.halting = this.halt(was);
274
+ }
275
+ }
276
+
277
+ // A Hold already in place when a move starts (cncjs's own feed hold) holds that move.
278
+ enterHoldIfHeld() {
279
+ if (HOLD_STATES.has(this.state.activeState) && this.phase === PHASE.MOVING) {
280
+ this.holds.push([this.now(), null]);
281
+ this.set(PHASE.HELD);
282
+ }
283
+ }
284
+
285
+ // ---- the run -----------------------------------------------------------------------
286
+
287
+ // Run the blocks; resolves with the phase it ended in (done, stopped or failed).
288
+ async run(blocks) {
289
+ this.total = blocks.length;
290
+ try {
291
+ for (const [index, block] of blocks.entries()) {
292
+ this.index = index;
293
+ this.block = block;
294
+ await this.runBlock(block);
295
+ }
296
+ this.set(PHASE.DONE);
297
+ } catch (err) {
298
+ if (!(err instanceof Ended)) {
299
+ this.fail(err.message);
300
+ }
301
+ }
302
+ await this.halting; // a stop or failure finishes holding and resetting first
303
+ return this.phase;
304
+ }
305
+
306
+ async runBlock(block) {
307
+ this.check();
308
+ if (block.step === 'set-spindle') {
309
+ this.set(PHASE.SET_SPINDLE);
310
+ const waiter = { until: () => false };
311
+ await new Promise((resolve, reject) => {
312
+ Object.assign(waiter, { resolve, reject });
313
+ this.continued = resolve;
314
+ this.waiters.push(waiter);
315
+ });
316
+ this.waiters.splice(this.waiters.indexOf(waiter), 1);
317
+ this.continued = null;
318
+ return;
319
+ }
320
+ if (block.step === 'dwell') {
321
+ this.set(PHASE.DWELLING);
322
+ const start = this.now();
323
+ await this.pause(block.seconds * 1000);
324
+ this.onWindow({ kind: 'dwell', pass: block.pass_id, start, end: this.now() });
325
+ return;
326
+ }
327
+ if (block.target === null) {
328
+ this.io.send(block.lines); // moves nothing: no position to wait for
329
+ return;
330
+ }
331
+ this.holds = [];
332
+ this.idleAway = null;
333
+ this.set(PHASE.MOVING);
334
+ const start = this.now();
335
+ this.io.send(block.lines);
336
+ this.enterHoldIfHeld();
337
+ const window = (end, more = {}) => ({ kind: 'cut', pass: block.pass_id, start, end, holds: this.holds.map(([s, e]) => [s, e ?? end]), ...more });
338
+ let end;
339
+ try {
340
+ end = await this.wait((state) => state.activeState === 'Idle' && this.at(state.wpos, block.target));
341
+ } catch (err) {
342
+ // A cut cut short still counts, up to where it stopped.
343
+ if (block.step === 'cut' && err instanceof Ended) {
344
+ this.onWindow(window(this.endedAt, { aborted: true }));
345
+ }
346
+ throw err;
347
+ }
348
+ if (block.step === 'cut') {
349
+ this.onWindow(window(end));
350
+ }
351
+ }
352
+
353
+ at(wpos, target) {
354
+ if (!wpos) {
355
+ return false;
356
+ }
357
+ return Object.entries(target).every(([axis, mm]) => Math.abs(Number(wpos[axis]) * this.scale - mm) <= TOLERANCE_MM);
358
+ }
359
+
360
+ // cncjs reports the controller's state only when it changes: a move that leaves the
361
+ // machine where it stood (already Idle there) is done at once.
362
+ wait(until) {
363
+ this.check();
364
+ if (until(this.state)) {
365
+ return Promise.resolve(this.now());
366
+ }
367
+ return new Promise((resolve, reject) => this.waiters.push({ until, resolve, reject }));
368
+ }
369
+
370
+ // A dwell: the stepper's own clock, cut short by a stop.
371
+ async pause(ms) {
372
+ let stop;
373
+ const ended = new Promise((_, reject) => {
374
+ stop = { until: () => false, resolve: () => {}, reject };
375
+ this.waiters.push(stop);
376
+ });
377
+ await Promise.race([this.sleep(ms), ended]);
378
+ this.waiters.splice(this.waiters.indexOf(stop), 1);
379
+ this.check();
380
+ }
381
+
382
+ check() {
383
+ if (this.ended) {
384
+ throw this.ended;
385
+ }
386
+ }
387
+
388
+ end(phase, reason) {
389
+ this.reason = reason;
390
+ this.endedAt = this.now(); // where a cut under way stopped counting
391
+ this.ended = new Ended(reason);
392
+ for (const waiter of this.waiters.splice(0)) {
393
+ waiter.reject(this.ended);
394
+ }
395
+ this.set(phase);
396
+ }
397
+
398
+ set(phase) {
399
+ this.phase = phase;
400
+ this.onChange(this);
401
+ }
402
+ }