dechatter 0.2.0 → 0.4.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/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
+ }
package/web/units.js ADDED
@@ -0,0 +1,43 @@
1
+ // Lengths, feeds and removal rates as the machine's units show them. Everything is stored in
2
+ // millimetres; on a machine in G20 it is shown in inches (4 decimals), with mm alongside
3
+ // where there is room, as the printed report does.
4
+
5
+ export const MM_PER_INCH = 25.4;
6
+ const MM3_PER_IN3 = MM_PER_INCH ** 3;
7
+
8
+ // Enough decimals that a hundred-thousandth of an inch survives the trip to millimetres.
9
+ export const tidy = (number) => Number(number.toFixed(5));
10
+
11
+ // "3.175 mm", or "0.1250 in" and with `mmToo` "0.1250 in (3.175 mm)". Millimetres drop
12
+ // trailing zeros: "5 mm".
13
+ export function length(mm, units, { mmToo = false, places = 3, inchPlaces = 4 } = {}) {
14
+ const metric = `${Number(mm.toFixed(places))} mm`;
15
+ if (units !== 'in') {
16
+ return metric;
17
+ }
18
+ const inches = `${(mm / MM_PER_INCH).toFixed(inchPlaces)} in`;
19
+ return mmToo ? `${inches} (${metric})` : inches;
20
+ }
21
+
22
+ // A chip load is a few hundredths of a millimetre: one more decimal each way.
23
+ export function chipLoad(mm, units, options = {}) {
24
+ return length(mm, units, { ...options, places: 4, inchPlaces: 5 });
25
+ }
26
+
27
+ export function feed(mmPerMin, units, { mmToo = false } = {}) {
28
+ const metric = `${Math.round(mmPerMin)} mm/min`;
29
+ if (units !== 'in') {
30
+ return metric;
31
+ }
32
+ const inches = `${(mmPerMin / MM_PER_INCH).toFixed(1)} in/min`;
33
+ return mmToo ? `${inches} (${metric})` : inches;
34
+ }
35
+
36
+ export function rate(cm3PerMin, units, { mmToo = false } = {}) {
37
+ const metric = `${cm3PerMin.toFixed(2)} cm³/min`;
38
+ if (units !== 'in') {
39
+ return metric;
40
+ }
41
+ const inches = `${((cm3PerMin * 1000) / MM3_PER_IN3).toFixed(3)} in³/min`;
42
+ return mmToo ? `${inches} (${metric})` : inches;
43
+ }
package/web/widget.css CHANGED
@@ -79,6 +79,10 @@ button:disabled { color: #999; cursor: not-allowed; }
79
79
  button.primary { color: #fff; background: #337ab7; border-color: #2e6da4; }
80
80
  button.primary:hover:not(:disabled) { background: #286090; }
81
81
  button.primary:disabled { color: #fff; opacity: 0.55; }
82
+ button.danger { color: #fff; background: #c9302c; border-color: #ac2925; }
83
+ button.danger:hover:not(:disabled) { background: #ac2925; }
84
+ dialog { max-width: min(360px, calc(100vw - 32px)); border: 1px solid #ccc; border-radius: 3px; }
85
+ dialog p { margin: 0 0 8px; }
82
86
  td select { padding: 1px 2px; }
83
87
 
84
88
  .recording { color: #c9302c; font-weight: bold; }