cncjs-handwheel 0.7.1 → 0.7.3

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/README.md CHANGED
@@ -131,6 +131,7 @@ Start from `cncjs-handwheel.config.example.json`.
131
131
  | `device.hupcl`, `dtr`, `rts` | modem control line handling (the defaults are fine with the udev rule) |
132
132
  | `device.power` | `{line, poweredWhen, pollMs, debounceMs}`: detect that the handwheel is switched off while the USB cable is still plugged in, see "Detecting a switched-off handwheel". Off unless `line` is set |
133
133
  | `status.intervalMs`, `status.minGapMs` | status line at least every 400 ms (the heartbeat), and never more often than every 350 ms (about 3 per second); a burst of commands or position changes costs one line per gap, always carrying the latest values. Explicit `?` / `STATUS?` requests are answered at once |
134
+ | `health.windowMs` | the counters in the widget header (reconnects, errors, dropped) count the last this many ms (default 900000 = 15 minutes, at least one minute), so they return to zero after a quiet period. `/status` carries both these as `recent` and the totals since the bridge started |
134
135
  | `status.pollAfterCommand` | ask Grbl for a fresh report after pendant commands (at most one per `status.minGapMs`) |
135
136
  | `status.format` | `grbl` or `json` |
136
137
  | `jog.translate` | rewrite jogs like `G21G91X10F500` to `$J=...` so they do not leave Grbl in relative mode (default `true`; `false` or `--no-jog-translate` sends the pendant's lines as plain gcode, for comparing behavior) |
@@ -138,6 +139,7 @@ Start from `cncjs-handwheel.config.example.json`.
138
139
  | `jog.cancelSettleMs` | wait between emptying the CNCjs feeder queue and sending the Grbl jog cancel (default 40 ms, see "Jog cancel") |
139
140
  | `jog.stallMs` | if the controller acknowledges nothing for this long (default 2000), the unanswered lines are assumed lost: the bridge prints a warning, counts a stall and starts counting afresh |
140
141
  | `jog.echo` | tag jog lines with `{echo: false}` as context (default `false`; other gcode is not tagged). CNCjs passes it on in its `serialport:write` event, so a console widget can hide the `feeder> $J=...` echo. Stock CNCjs ignores it (see "Quieting the CNCjs console") |
142
+ | `guard.duringJob` | `true` (default): while a job is running or paused (or its state is not known yet) no gcode line from the pendant is sent, see "Jobs and the pendant" |
141
143
  | `http` | health endpoint (`enabled`, `host`, `port`) |
142
144
  | `log.max` | pendant log lines kept for the widget |
143
145
 
@@ -228,19 +230,20 @@ handshake and whenever something changes. Which message depends on the CNCjs ver
228
230
  |---|---|---|
229
231
  | cncjs master (after #1069) | `widget:state` | `fullscreen` |
230
232
  | cncjs between #1060 and #1069 | `change` with `payload.fullscreen`, and `widget:fullscreenchange` | `fullscreen` |
231
- | a CNCjs with the Custom widget `props` (theRealThor's fork) | `change` with `payload.props` | `fullscreen`, `colorMode` (`light` or `dark`), `disabled` |
233
+ | an earlier fork-only build of the Custom widget | `change` with `payload.props` | `fullscreen`, `disabled` (a `colorMode` in it is ignored) |
232
234
 
233
235
  The widget follows `fullscreen` (expands and collapses with CNCjs's own fullscreen button; its own expand button then
234
- hides) and, where sent, `colorMode`, in every setup, same origin or not. Unknown fields are ignored, and a plain port
235
- `change` is not treated as an update. Upstream cncjs does not send `colorMode` (yet), so there the colours come from
236
- the fallbacks below.
236
+ hides) in every setup, same origin or not. Unknown fields are ignored, and a plain port `change` is not treated as an
237
+ update. There is no colour message: see below.
237
238
 
238
- **Colours.** Light or dark follows CNCjs's `colorMode` where CNCjs sends it. Served from the same origin as CNCjs the widget also takes
239
+ **Colours.** Light or dark follows CNCjs through the `prefers-color-scheme` media query. CNCjs sets `color-scheme: light` or
240
+ `dark` on its root element, the browser passes that on to the iframe, and the widget follows the query live, also across
241
+ origins (Chrome, Edge, Firefox; Safari only since 2026, older Safari reports the OS preference). Served from the same origin as CNCjs the widget also takes
239
242
  its colours from CNCjs's own theme tokens (`--color-surface`, `--color-widget-header-bg`,
240
243
  `--color-status-danger-text`, ... see `widget/src/hostTheme.js` for the mapping) and follows a mode change live. CNCjs has no green
241
244
  token, so the OK green is the widget's own. Where it cannot read the page (cross-origin, such as the Vite dev server) or
242
- CNCjs lacks a token, the widget's own light and dark stylesheet applies. Without a `colorMode` message (upstream cncjs) it reads
243
- `data-color-mode` off the CNCjs page (same origin only) and finally the OS preference; `?theme=` overrides all of it.
245
+ CNCjs lacks a token, the widget's own light and dark stylesheet applies. Same origin, it also reads `data-color-mode` off the
246
+ CNCjs page, which beats the media query where the browser does not pass the scheme on; `?theme=` overrides all of it.
244
247
 
245
248
  **Fullscreen.** With the fullscreen state above, the log pane takes the height that is left when it can read the
246
249
  CNCjs page (same origin), so the CNCjs widget only scrolls when the screen is too short for the cards; elsewhere the
@@ -262,7 +265,7 @@ Pendant to bridge:
262
265
  | Line | Effect |
263
266
  |---|---|
264
267
  | `G21G91X+10F2000` | jog (sent as `$J=...`); any other line that looks like gcode (words such as `G10 L20 P1 Z15.05`, a Grbl `$` command, a CNCjs `%` line) is sent to the controller as gcode. Other text is not sent: it is shown in the widget's log as `[not gcode, not sent] ...` and counted (`pendant.strayLines`, and in `garbageLines`, the widget's Drop). Turn that off with `device.strictGcode: false` |
265
- | `!` / `~` / `^X` (0x18) | feed hold / cycle start / reset, each as a line of its own (reset at most once per 2 s) |
268
+ | `!` / `~` / `^X` (0x18) | feed hold / cycle start / reset, each as a line of its own (reset at most once per 2 s). While a job is running `!` is sent as CNCjs `gcode:pause` and while it is paused `~` as `gcode:resume` (see "Jobs and the pendant"); otherwise they are `feedhold` and `cyclestart` |
266
269
  | `$X` | unlock; sent to CNCjs as its `unlock` command, because a gcode line is dropped by CNCjs while the machine is in Alarm |
267
270
  | `... ; comment` | as in gcode, everything after a `;` that is not at the start of the line is a comment: it is not sent, only the part before it is the command. So `0x18; Reset the machine` is a reset and `$X; Unlock` an unlock. (A line that starts with `;` is a log entry) |
268
271
  | `0x85` (the single byte, as a line of its own) or `JOGCANCEL` | cancel the jog in progress (Grbl only), see "Jog cancel" below |
@@ -278,6 +281,7 @@ Bridge to pendant:
278
281
  | `<Idle\|MPos:x,y,z\|WPos:x,y,z\|FS:feed,spindle>` | status: at most about 3 per second, at least every 400 ms, and shortly after every command |
279
282
  | `<Disconnected>` | the bridge is up, but CNCjs or the CNC port is not |
280
283
  | `ERR:CNCJS_NOT_READY` | a command was dropped because the CNC port is not open |
284
+ | `ERR:JOB_ACTIVE` | a gcode line was dropped because a job is running or paused (at most once a second), see "Jobs and the pendant" |
281
285
  | `PONG` | answer to `PING` |
282
286
 
283
287
  The status right after a command shows where the machine was at that moment; Grbl's `ok` only means the move was
@@ -367,6 +371,32 @@ Two other sources of console noise can be reduced from the bridge's side:
367
371
  Set `status.pollAfterCommand` to `false`; CNCjs polls the controller by itself and the pendant still gets status lines.
368
372
  - The `ok` for every jog is echoed by CNCjs (`serialport:read`); only a console filter can hide those.
369
373
 
374
+ ## Jobs and the pendant
375
+
376
+ When a job is paused in CNCjs only the job itself is held, not the queue that other commands go through. A jog, a button's
377
+ gcode or a macro sent from the pendant during the pause is written to Grbl at once; Grbl does not run it before the job is
378
+ resumed, and then it runs *between two program lines*. It also upsets the accounting of the sender (the `ok` of the injected
379
+ line is counted for a program line) and, if it fails, pauses the job again with a misleading error.
380
+
381
+ The bridge therefore follows the CNCjs workflow state (`workflow:state`: `idle`, `running`, `paused`) and, unless it is `idle`
382
+ (or not known yet, for example just after a reconnect):
383
+
384
+ - drops every gcode line from the pendant: jogs, button gcode, each line of a macro, `$X`. The pendant gets `ERR:JOB_ACTIVE`
385
+ (at most once a second), the widget's log shows `[a job is paused, not sent] ...`, and `/status` counts them under
386
+ `guard.dropped`;
387
+ - lets the real-time commands through: `!`, `~`, `^X`, `?` and jog cancel. With a job on, `!` pauses the job (CNCjs `gcode:pause`) and `~` resumes a paused one (`gcode:resume`) instead of the plain `feedhold` / `cyclestart`, so the CNCjs workflow follows the machine, and an `M0` / `M6` pause can be continued from the pendant;
388
+ - turns **`M5`** and **`M3`** into Grbl's real-time *toggle spindle stop* (`0x9E`) instead of sending them as gcode. Grbl
389
+ accepts that byte only while the machine is in **Hold** (a job paused with a feed hold); the spindle then stops, and
390
+ Grbl switches it on again by itself when the job is resumed. `M5` stops the spindle, `M3` (with or without `S`, which
391
+ cannot be applied) switches on again a spindle that the bridge stopped. Because `0x9E` is a toggle, a second `M5` and an
392
+ `M3` without a stop before are ignored. Outside Hold, and for controllers other than Grbl, they are dropped like other
393
+ gcode.
394
+
395
+ `/status` shows the workflow state under `cncjs.workflow` and the counters under `guard` (`dropped`, `spindle`, `lastAgeMs`).
396
+ `guard.duringJob: false` turns all this off. The byte is written through CNCjs (`write`); CNCjs sends a string, which a
397
+ serial port encodes as UTF-8, so Grbl sees `0xC2 0x9E`. Grbl 1.1 ignores the extended-ASCII byte it does not know (`0xC2`) and
398
+ acts on `0x9E`, as it does for the override buttons of CNCjs; check once on your machine.
399
+
370
400
  ## Jog cancel
371
401
 
372
402
  For real jogging the pendant sends one long jog when the wheel or button starts (`$J=G21G91X1000F2000`) and a jog cancel when
@@ -21,6 +21,7 @@ const http = require('http');
21
21
  const { Command } = require('commander');
22
22
  const { SerialPort } = require('serialport');
23
23
  const connectToCncjs = require('../index');
24
+ const guard = require('../lib/guard');
24
25
  const pkg = require('../package.json');
25
26
 
26
27
  const DEFAULT_CONFIG_FILE = path.join(os.homedir(), '.cncjs-handwheel.config');
@@ -67,6 +68,9 @@ const DEFAULTS = {
67
68
  // debounceMs: a change must last this long before it counts (opening the port can reset the ESP32)
68
69
  power: { line: null, poweredWhen: 'clear', pollMs: 250, debounceMs: 1000 }
69
70
  },
71
+ health: {
72
+ windowMs: 900000 // the counters in the widget header (reconnects, errors, dropped) cover this long; /status also keeps lifetime totals
73
+ },
70
74
  status: {
71
75
  format: 'grbl', // 'grbl' -> <Idle|MPos:..|WPos:..|FS:..> 'json' -> {"t":"status",...}
72
76
  intervalMs: 400, // unsolicited status line at least this often (also the pendant's "host alive" signal)
@@ -85,6 +89,12 @@ const DEFAULTS = {
85
89
  // 'serialport:write' event, so a console widget can skip them (see README); it changes nothing else
86
90
  jog: { translate: true, maxInFlight: 4, stallMs: 2000, echo: false },
87
91
 
92
+ // duringJob: while a job is running or paused (CNCjs workflow state not idle) no gcode line from the pendant is sent
93
+ // (jogs, button gcode, macros): CNCjs only holds the job, not its own queue, so a line sent during a pause would
94
+ // run in the middle of the program after the resume. Real-time commands (! ~ ^X ? jog cancel) still go through.
95
+ // M5 and M3 are turned into Grbl's real-time "toggle spindle stop" (0x9E), which works while the machine is in Hold
96
+ guard: { duringJob: true },
97
+
88
98
  // pendant console lines ("; ...") are kept here for the widget instead of being sent to Grbl
89
99
  log: { max: 500 },
90
100
 
@@ -202,11 +212,49 @@ const health = {
202
212
  reconnects: 0, errors: 0, lastError: null, logLines: 0, garbageLines: 0, strayLines: 0, link: null, info: null,
203
213
  powered: null, powerError: null }, // powered: null = unknown or not configured, true / false = switched on / off
204
214
  cncjs: { socketConnected: false, portOpen: false, port: cfg.cncjs.port, controllerType: cfg.cncjs.controllerType,
205
- lastError: null, droppedCommands: 0 },
215
+ lastError: null, droppedCommands: 0, workflow: null },
216
+ guard: { dropped: 0, spindle: 0, lastAt: null },
206
217
  jog: { sent: 0, merged: 0, discarded: 0, stalls: 0, cancels: 0, inFlight: 0, held: false, lastAt: null },
207
218
  lastCommand: null
208
219
  };
209
220
 
221
+ /** Timestamps of recent events per counter; the lifetime totals live in `health`, these feed the rolling window. */
222
+ const recentEvents = { reconnects: [], errors: [], garbageLines: [], droppedCommands: [] };
223
+ const MAX_RECENT_EVENTS = 1000;
224
+
225
+ /**
226
+ * Remembers that an event happened now, for the rolling counters in the status report. Old entries are dropped,
227
+ * and so are the oldest ones beyond MAX_RECENT_EVENTS (a flood cannot grow the list without bound).
228
+ *
229
+ * @param {string} kind - a key of recentEvents
230
+ * @returns {void}
231
+ */
232
+ function noteEvent(kind) {
233
+ const list = recentEvents[kind];
234
+ const now = Date.now();
235
+ list.push(now);
236
+ const from = now - windowMs();
237
+ while (list.length && (list[0] < from || list.length > MAX_RECENT_EVENTS)) list.shift();
238
+ }
239
+
240
+ /**
241
+ * @returns {number} the length of the rolling window in ms (health.windowMs, at least one minute)
242
+ */
243
+ function windowMs() {
244
+ return Math.max(60000, Number(cfg.health && cfg.health.windowMs) || 900000);
245
+ }
246
+
247
+ /**
248
+ * Counts the events of one kind inside the rolling window.
249
+ *
250
+ * @param {string} kind - a key of recentEvents
251
+ * @returns {number}
252
+ */
253
+ function recentCount(kind) {
254
+ const from = Date.now() - windowMs();
255
+ return recentEvents[kind].filter((t) => t >= from).length;
256
+ }
257
+
210
258
  /**
211
259
  * Logs to the console, but only when -v / verbose is on.
212
260
  *
@@ -226,19 +274,21 @@ const socket = connectToCncjs(cncOpts, (err) => {
226
274
  });
227
275
 
228
276
  socket.on('connect', () => { health.cncjs.socketConnected = true; });
229
- socket.on('disconnect', () => { health.cncjs.socketConnected = false; health.cncjs.portOpen = false; resetJogs(); });
277
+ socket.on('disconnect', () => { health.cncjs.socketConnected = false; health.cncjs.portOpen = false; resetJogs(); setWorkflow(null); });
230
278
  socket.on('serialport:read', onControllerLine);
231
279
  socket.on('serialport:open', () => {
232
280
  if (!health.cncjs.portOpen) { lastWco = null; resetJogs(); } // a keepalive confirmation must not discard the work offset
233
281
  health.cncjs.portOpen = true;
234
282
  health.cncjs.lastError = null;
235
283
  });
236
- socket.on('serialport:close', () => { health.cncjs.portOpen = false; resetJogs(); });
284
+ socket.on('serialport:close', () => { health.cncjs.portOpen = false; resetJogs(); setWorkflow(null); });
285
+ socket.on('workflow:state', (state) => setWorkflow(typeof state === 'string' ? state : null));
237
286
 
238
287
  ['Grbl', 'Smoothie', 'TinyG'].forEach((type) => {
239
288
  let dumped = false;
240
289
  socket.on(type + ':state', (state) => {
241
290
  store.controller.state = state || {};
291
+ if (activeState() !== 'Hold') spindleStopped = false; // Grbl switches the spindle back on when the hold ends
242
292
  const wco = state && state.status && state.status.wco;
243
293
  if (wco) lastWco = wco;
244
294
  sendStatus(false); // forward changes right away (rate limited by status.minGapMs)
@@ -249,6 +299,84 @@ socket.on('serialport:close', () => { health.cncjs.portOpen = false; resetJogs()
249
299
 
250
300
  socket.on('sender:status', (data) => { store.sender.status = data || {}; });
251
301
 
302
+ // ---------------------------------------------------------------- job guard
303
+ // CNCjs workflow state ('idle', 'running', 'paused'); null until CNCjs has told us. See lib/guard.js.
304
+ let workflowState = null;
305
+ let spindleStopped = false; // the spindle was stopped with 0x9E from here and not switched on again
306
+
307
+ /**
308
+ * Records the CNCjs workflow state. When a job starts, a jog that is being held back is thrown away: it must
309
+ * not be released into the job.
310
+ *
311
+ * @param {?string} state - 'idle', 'running', 'paused' or null (not known)
312
+ * @returns {void}
313
+ */
314
+ function setWorkflow(state) {
315
+ if (state === workflowState) return;
316
+ log('workflow state:', workflowState, '->', state);
317
+ workflowState = state;
318
+ health.cncjs.workflow = state;
319
+ if (state !== 'idle') discardHeldJog();
320
+ if (state === 'idle') spindleStopped = false;
321
+ }
322
+
323
+ /**
324
+ * @returns {?string} the Grbl state from the last status report, e.g. 'Hold', 'Run', 'Idle'
325
+ */
326
+ function activeState() {
327
+ const st = store.controller.state && store.controller.state.status;
328
+ return (st && st.activeState) || null;
329
+ }
330
+
331
+ /**
332
+ * Tells whether the guard keeps gcode from the pendant out of the machine right now.
333
+ *
334
+ * @returns {boolean}
335
+ */
336
+ const jobGuarded = () => cfg.guard.duringJob !== false && workflowState !== 'idle';
337
+
338
+ let lastGuardNote = 0;
339
+ /**
340
+ * Applies the decision of the job guard to a gcode line: drops it (told to the pendant and the widget log, at most
341
+ * once a second) or sends the real-time byte in its place.
342
+ *
343
+ * @param {string} line - the gcode line from the pendant
344
+ * @param {object} d - the decision from guard.decide()
345
+ * @returns {boolean} true if something was sent to the machine
346
+ */
347
+ function applyGuard(line, d) {
348
+ if (d.action === 'realtime') {
349
+ if (!cncReady() || !socket.emit('write', cfg.cncjs.port, d.byte)) {
350
+ noteDropped('write', [d.what]);
351
+ sendToPendant('ERR:CNCJS_NOT_READY');
352
+ queueStatus();
353
+ return false;
354
+ }
355
+ spindleStopped = d.spindleStopped;
356
+ health.guard.spindle++;
357
+ health.lastCommand = { at: Date.now(), name: 'write', args: [d.what] };
358
+ log('pendant ->', d.what, '(real-time 0x9E) instead of', JSON.stringify(line));
359
+ answerCommand();
360
+ return true;
361
+ }
362
+ if (!d.quiet) {
363
+ health.guard.dropped++;
364
+ health.guard.lastAt = Date.now();
365
+ }
366
+ const now = Date.now();
367
+ if (!d.quiet && now - lastGuardNote >= 1000) {
368
+ lastGuardNote = now;
369
+ const text = line.replace(/[\x00-\x1f\x7f]/g, '');
370
+ console.warn('Dropped pendant gcode (' + d.reason + '): ' + text + ' [' + health.guard.dropped + ' dropped so far]');
371
+ addPendantLog('[' + d.reason + ', not sent] ' + text);
372
+ sendToPendant('ERR:JOB_ACTIVE');
373
+ queueStatus();
374
+ } else {
375
+ log('pendant -> dropped', JSON.stringify(line), '(' + d.reason + ')');
376
+ }
377
+ return false;
378
+ }
379
+
252
380
  let lastWco = null; // Grbl 1.1 only reports MPos *or* WPos, plus WCO now and then: WPos = MPos - WCO
253
381
  /**
254
382
  * Tells whether commands can currently reach the CNC controller
@@ -269,6 +397,7 @@ let lastDropWarn = 0;
269
397
  const fmtArgs = (args) => args.map((a) => (a !== null && typeof a === 'object' ? JSON.stringify(a) : a));
270
398
  function noteDropped(name, args) {
271
399
  health.cncjs.droppedCommands++;
400
+ noteEvent('droppedCommands');
272
401
  const now = Date.now();
273
402
  if (now - lastDropWarn < 1000) return;
274
403
  lastDropWarn = now;
@@ -390,7 +519,7 @@ function onPendantData(buf) {
390
519
  const drop = skipLine;
391
520
  rxBuf = '';
392
521
  skipLine = false;
393
- if (drop) health.pendant.garbageLines++;
522
+ if (drop) { health.pendant.garbageLines++; noteEvent('garbageLines'); }
394
523
  else if (line) onPendantLine(line);
395
524
  } else if (rxBuf.length < 256) {
396
525
  rxBuf += ch;
@@ -444,6 +573,7 @@ let lastDropLog = 0;
444
573
  */
445
574
  function dropLine(raw) {
446
575
  health.pendant.garbageLines++;
576
+ noteEvent('garbageLines');
447
577
  const now = Date.now();
448
578
  if (cfg.verbose && now - lastDropLog > 1000) {
449
579
  lastDropLog = now;
@@ -527,7 +657,8 @@ function onPendantLine(raw) {
527
657
  // stop means stop: jogs still held back must not fire after a feed hold or a reset
528
658
  if (raw === '!' || raw === '\x18') discardHeldJog();
529
659
  if (raw === '\x18') jog.inFlight = 0; // a soft reset flushes everything Grbl had not answered yet
530
- return sendCommand(REALTIME[raw]);
660
+ // with a job on, ! and ~ pause and resume the job, so that the CNCjs workflow follows the machine
661
+ return sendCommand(guard.realtimeCommand(raw, workflowState));
531
662
  }
532
663
  // decode as UTF-8, drop ANSI colour codes, tabs -> spaces
533
664
  let line = Buffer.from(raw, 'binary').toString('utf8').replace(ANSI, '').replace(/\t/g, ' ').trim();
@@ -548,6 +679,7 @@ function onPendantLine(raw) {
548
679
  if (cfg.device.strictGcode !== false && !looksLikeGcode(line)) {
549
680
  // Not gcode: most likely a log line that lost its ";" or a piece of one. Never hand it to the controller.
550
681
  health.pendant.garbageLines++;
682
+ noteEvent('garbageLines');
551
683
  health.pendant.strayLines = (health.pendant.strayLines || 0) + 1;
552
684
  addPendantLog('[not gcode, not sent] ' + line.replace(/[\x00-\x1f\x7f]/g, ''));
553
685
  return;
@@ -625,6 +757,10 @@ function writeGcode(line) {
625
757
  * @returns {boolean} true if the line was sent or held back
626
758
  */
627
759
  function sendGcodeLine(line) {
760
+ // without a connection the normal path answers with ERR:CNCJS_NOT_READY
761
+ const d = !cncReady() ? { action: 'pass' } : guard.decide(line, { enabled: cfg.guard.duringJob !== false, workflow: workflowState, activeState: activeState(),
762
+ controllerType: cfg.cncjs.controllerType, spindleStopped });
763
+ if (d.action !== 'pass') return applyGuard(line, d);
628
764
  const j = cfg.jog.maxInFlight > 0 ? parseJog(line) : null;
629
765
  if (j) return queueJog(j);
630
766
  flushJog(true);
@@ -664,6 +800,7 @@ function queueJog(j) {
664
800
  function flushJog(force) {
665
801
  const p = jog.pending;
666
802
  if (!p) return;
803
+ if (jobGuarded()) { discardHeldJog(); return; }
667
804
  if (!force && (cancelTimer || jog.inFlight >= cfg.jog.maxInFlight)) return;
668
805
  jog.pending = null;
669
806
  health.jog.held = false;
@@ -906,6 +1043,8 @@ const statusTimer = setInterval(() => sendStatus(false), Math.max(10, Math.min(1
906
1043
  // ---------------------------------------------------------------- pendant serial link
907
1044
  let pendantPort = null;
908
1045
  let reconnectTimer = null;
1046
+ let downSince = null; // when the pendant link was lost (null while it is up)
1047
+ const REAL_OUTAGE_MS = 10000; // a link that was down this long was unplugged or switched off, not a glitch
909
1048
 
910
1049
  /**
911
1050
  * Records a pendant serial error in the health data and prints it.
@@ -915,6 +1054,7 @@ let reconnectTimer = null;
915
1054
  */
916
1055
  function noteError(err) {
917
1056
  health.pendant.errors++;
1057
+ noteEvent('errors');
918
1058
  health.pendant.lastError = err.message;
919
1059
  console.error('Pendant error:', err.message);
920
1060
  }
@@ -926,9 +1066,11 @@ function noteError(err) {
926
1066
  */
927
1067
  function scheduleReconnect() {
928
1068
  if (shuttingDown || reconnectTimer) return;
1069
+ if (downSince === null) downSince = Date.now();
929
1070
  reconnectTimer = setTimeout(() => {
930
1071
  reconnectTimer = null;
931
1072
  health.pendant.reconnects++;
1073
+ noteEvent('reconnects');
932
1074
  openPendant();
933
1075
  }, cfg.device.reconnectMs);
934
1076
  }
@@ -1042,6 +1184,7 @@ function openPendant() {
1042
1184
  port.on('close', () => {
1043
1185
  health.pendant.connected = false;
1044
1186
  health.pendant.info = null; // a stale battery level is worse than none
1187
+ discardHeldJog(); // a jog held back for a handwheel that is gone must not fire later
1045
1188
  stopPowerWatch();
1046
1189
  if (!shuttingDown) console.log('Pendant port closed');
1047
1190
  scheduleReconnect();
@@ -1062,6 +1205,14 @@ function openPendant() {
1062
1205
  port.set(lines, (setErr) => { if (setErr) noteError(setErr); });
1063
1206
  }
1064
1207
  health.pendant.connected = true;
1208
+ // Every retry while the wheel was away counted as a reconnect and an error (hundreds after a night unplugged).
1209
+ // After a real outage they say nothing about the link, so the rolling counters start over; short drops stay counted
1210
+ // so a flapping link still shows. The totals since start are not touched.
1211
+ if (downSince !== null && Date.now() - downSince >= REAL_OUTAGE_MS) {
1212
+ recentEvents.reconnects.length = 0;
1213
+ recentEvents.errors.length = 0;
1214
+ }
1215
+ downSince = null;
1065
1216
  health.pendant.link = detectLink(cfg.device.path);
1066
1217
  health.pendant.lastError = null;
1067
1218
  console.log('Pendant connected on ' + cfg.device.path);
@@ -1089,7 +1240,18 @@ function healthReport() {
1089
1240
  lastTxAgeMs: age(health.pendant.lastTx),
1090
1241
  info: health.pendant.info && Object.assign({}, health.pendant.info, { ageMs: age(health.pendant.info.at) }) }),
1091
1242
  cncjs: health.cncjs,
1243
+ // The same counters over the last windowMs only (they age out by themselves); the totals above count since the bridge started.
1244
+ recent: {
1245
+ windowMs: windowMs(),
1246
+ reconnects: recentCount('reconnects'),
1247
+ errors: recentCount('errors'),
1248
+ garbageLines: recentCount('garbageLines'),
1249
+ droppedCommands: recentCount('droppedCommands'),
1250
+ lastError: recentCount('errors') > 0 ? health.pendant.lastError : null
1251
+ },
1092
1252
  jog: Object.assign({}, health.jog, { lastAgeMs: age(health.jog.lastAt) }),
1253
+ // gcode from the pendant kept out of the machine during a job; spindle = real-time spindle toggles sent instead of M3 / M5
1254
+ guard: Object.assign({}, health.guard, { enabled: cfg.guard.duringJob !== false, lastAgeMs: age(health.guard.lastAt) }),
1093
1255
  lastCommand: health.lastCommand,
1094
1256
  status: snapshot()
1095
1257
  };
@@ -22,6 +22,7 @@
22
22
  "rts": null,
23
23
  "power": { "line": null, "poweredWhen": "clear", "pollMs": 250, "debounceMs": 1000 }
24
24
  },
25
+ "health": { "windowMs": 900000 },
25
26
  "status": {
26
27
  "format": "grbl",
27
28
  "intervalMs": 400,
@@ -36,6 +37,7 @@
36
37
  "cancelSettleMs": 40,
37
38
  "echo": false
38
39
  },
40
+ "guard": { "duringJob": true },
39
41
  "http": { "enabled": true, "host": "127.0.0.1", "port": 8001 },
40
42
  "log": { "max": 500 }
41
43
  }
package/lib/guard.js ADDED
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ // Guard against sending gcode lines from the pendant while a job is on (running or paused).
4
+ //
5
+ // Why: in CNCjs only the job (the sender) is held when a job is paused; a line sent in the meantime (a jog, a
6
+ // button's gcode, a macro) goes to Grbl at once and ends up between two program lines, where it runs after the
7
+ // resume. See "Jobs and the pendant" in the README.
8
+ //
9
+ // Rule: while the CNCjs workflow is not idle (or not known yet) every gcode line from the pendant is dropped.
10
+ // Exception: M3 and M5 are not sent as gcode but turned into Grbl's real-time "toggle spindle stop" (0x9E),
11
+ // which Grbl only accepts in the Hold state and which it undoes by itself when the job is resumed:
12
+ // M5 -> 0x9E, the spindle stops (the line is ignored if this guard stopped it already)
13
+ // M3 (or M3 S..)-> 0x9E, the spindle that this guard stopped is switched on again, with the speed it had
14
+ // (the S word of M3 cannot be applied: the spindle comes back with the speed of the program)
15
+
16
+ /** Grbl 1.1 real-time command "toggle spindle stop". */
17
+ const SPINDLE_STOP = '\x9e';
18
+
19
+ const SPINDLE_ON = /^M0?3(?:S(?:\d+\.?\d*|\.\d+))?$/;
20
+ const SPINDLE_OFF = /^M0?5$/;
21
+
22
+ /**
23
+ * Reduces a gcode line to its words: comments and blanks removed, upper case.
24
+ *
25
+ * @param {string} line - a gcode line
26
+ * @returns {string} e.g. 'M3S6000' for 'M3 S6000 ; Start the spindle'
27
+ */
28
+ function compact(line) {
29
+ return String(line).replace(/;.*$/, '').replace(/\([^)]*\)/g, '').replace(/\s+/g, '').toUpperCase();
30
+ }
31
+
32
+ /**
33
+ * Tells whether a line is a plain spindle command.
34
+ *
35
+ * @param {string} line - a gcode line
36
+ * @returns {?string} 'start' for M3 (optionally with a speed), 'stop' for M5, null for anything else
37
+ */
38
+ function spindleCommand(line) {
39
+ const c = compact(line);
40
+ if (SPINDLE_OFF.test(c)) return 'stop';
41
+ if (SPINDLE_ON.test(c)) return 'start';
42
+ return null;
43
+ }
44
+
45
+ /**
46
+ * Says what to do with a gcode line from the pendant.
47
+ *
48
+ * @param {string} line - the gcode line
49
+ * @param {object} ctx
50
+ * @param {boolean} ctx.enabled - the guard is on (config guard.duringJob)
51
+ * @param {?string} ctx.workflow - CNCjs workflow state: 'idle', 'running', 'paused'; null = not known yet
52
+ * @param {?string} ctx.activeState - Grbl state from the status report, e.g. 'Hold'
53
+ * @param {string} ctx.controllerType - 'Grbl', 'Smoothie' or 'TinyG'
54
+ * @param {boolean} ctx.spindleStopped - the spindle was stopped by this guard and not switched on again
55
+ * @returns {{action: 'pass'}
56
+ * | {action: 'drop', reason: string, quiet?: boolean}
57
+ * | {action: 'realtime', byte: string, spindleStopped: boolean, what: string}} what to do: send the line as
58
+ * it is, drop it (quiet: no complaint to the pendant), or send the real-time byte instead
59
+ */
60
+ function decide(line, ctx) {
61
+ if (!ctx.enabled || ctx.workflow === 'idle') return { action: 'pass' };
62
+ const why = ctx.workflow ? 'a job is ' + ctx.workflow : 'the job state is not known yet';
63
+ const word = spindleCommand(line);
64
+ if (!word) return { action: 'drop', reason: why };
65
+ if (ctx.controllerType !== 'Grbl') return { action: 'drop', reason: why + ' (spindle control during a job needs Grbl)' };
66
+ if (ctx.activeState !== 'Hold') return { action: 'drop', reason: why + ' (the spindle can only be switched while the machine is in Hold)' };
67
+ if (word === 'stop' && ctx.spindleStopped) return { action: 'drop', reason: 'the spindle is stopped already', quiet: true };
68
+ if (word === 'start' && !ctx.spindleStopped) return { action: 'drop', reason: 'the spindle was not stopped from the pendant', quiet: true };
69
+ return { action: 'realtime', byte: SPINDLE_STOP, spindleStopped: word === 'stop', what: word === 'stop' ? 'spindle stop' : 'spindle on' };
70
+ }
71
+
72
+ /**
73
+ * Chooses the CNCjs command for a real-time byte from the pendant, so that the CNCjs workflow follows what the
74
+ * machine does. With a job on, `!` pauses the job (`gcode:pause`: workflow paused, then `!` to Grbl) and `~` resumes
75
+ * it (`gcode:resume`: `~` to Grbl, then workflow resumed); with the plain `feedhold` / `cyclestart` the machine
76
+ * stops and restarts while CNCjs still thinks the job is running, or stays paused after the machine moves again.
77
+ * Without a job (idle or not known) they are the plain commands.
78
+ *
79
+ * @param {string} raw - '!', '~' or '\x18'
80
+ * @param {?string} workflow - CNCjs workflow state: 'idle', 'running', 'paused'; null = not known yet
81
+ * @returns {string} the CNCjs command name
82
+ */
83
+ function realtimeCommand(raw, workflow) {
84
+ if (raw === '!') return workflow === 'running' ? 'gcode:pause' : 'feedhold';
85
+ if (raw === '~') return workflow === 'paused' ? 'gcode:resume' : 'cyclestart';
86
+ return 'reset';
87
+ }
88
+
89
+ module.exports = { decide, spindleCommand, compact, realtimeCommand, SPINDLE_STOP };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cncjs-handwheel",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "CNCjs pendant bridge for a serial (USB/Bluetooth) ESP32 CNC handwheel",
5
5
  "keywords": [
6
6
  "cncjs",
@@ -29,10 +29,11 @@
29
29
  ],
30
30
  "scripts": {
31
31
  "start": "node bin/cncjs-handwheel",
32
- "check": "node --check index.js && node --check bin/cncjs-handwheel && node --check lib/service.js",
32
+ "check": "node --check index.js && node --check bin/cncjs-handwheel && node --check lib/service.js && node --check lib/guard.js",
33
33
  "prepublishOnly": "npm run check && npm run build:widget",
34
34
  "build:widget": "npm install --prefix widget && npm run build --prefix widget",
35
- "dev:widget": "npm run dev --prefix widget"
35
+ "dev:widget": "npm run dev --prefix widget",
36
+ "test": "node --test test/*.test.js"
36
37
  },
37
38
  "engines": {
38
39
  "node": ">=20"
@@ -1 +1 @@
1
- :root{--bg: #fff;--fg: #333;--muted: #777;--card: #fafafa;--border: #ddd;--ok: #2e8b3d;--warn: #c77c00;--down: #c9302c;--offline: #8a8a8a;--unknown: #8a8a8a;--accent: #337ab7;--head-bg: #f6f7f8;--head-fg: #222;--head-border: #ccc;color-scheme:light}:root[data-theme=dark]{--bg: #1e1f22;--fg: #dcdcdc;--muted: #9a9a9a;--card: #26282c;--border: #3a3d42;--ok: #52c262;--warn: #e0a030;--down: #ef6a64;--offline: #8f8f8f;--unknown: #8f8f8f;--accent: #6aaee6;--head-bg: #2b2e33;--head-fg: #dcdcdc;--head-border: #3a3d42;color-scheme:dark}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--fg);font:14px/1.35 Segoe UI,-apple-system,BlinkMacSystemFont,Helvetica Neue,Helvetica,Arial,sans-serif}code,.mono{font-family:Segoe UI Mono,SFMono-Medium,SF Mono,Menlo,Consolas,Courier,monospace}.widget{padding:8px}.widget.level-ok{--level: var(--ok)}.widget.level-warn{--level: var(--warn)}.widget.level-down{--level: var(--down)}.widget.level-offline{--level: var(--offline)}.widget.level-unknown{--level: var(--unknown)}.head{display:flex;align-items:center;gap:10px;min-height:44px}.icon{color:var(--level);display:flex;flex:none}.title{flex:1;min-width:0;display:flex;flex-direction:column}.title strong{color:var(--level);font-size:15px}.title small{color:var(--muted);font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.toggle{flex:none;width:44px;height:44px;border:1px solid var(--border);border-radius:4px;background:var(--btn-bg, var(--card));color:var(--fg);font-size:16px;cursor:pointer}.toggle:focus-visible{outline:2px solid var(--focus, var(--accent));outline-offset:1px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:8px;margin-top:8px}.card{background:var(--bg);border:1px solid var(--head-border)}.card h3{margin:0;padding:0 10px;font-size:14px;font-weight:400;line-height:32px;background:var(--head-bg);color:var(--head-fg);border-bottom:1px solid var(--head-border)}.card .body{padding:6px 10px 8px}.logcard{margin-top:8px}.value b{font-weight:inherit}.bad{color:var(--down)}.good{color:var(--ok)}.row{display:flex;justify-content:space-between;gap:10px;padding:1px 0}.label{color:var(--muted)}.value{text-align:right;overflow-wrap:anywhere}.log{height:260px;overflow-y:auto;background:var(--card);padding:4px 8px;font-family:Segoe UI Mono,SFMono-Medium,SF Mono,Menlo,Consolas,Courier,monospace;font-size:12px}.logline{white-space:pre-wrap;overflow-wrap:anywhere}.logline .time,.empty,.hint{color:var(--muted)}.hint{margin:8px 0 0}.title small{white-space:normal;overflow:visible}.counts{display:flex;flex-wrap:nowrap;gap:2px 10px;margin-top:2px}.counts em{font-style:normal;color:var(--muted);margin-right:1px}.counts b{font-weight:600;font-variant-numeric:tabular-nums}.counts i{font-style:normal;color:var(--muted);margin:0 1px}.counts .good{color:var(--ok)}.counts .bad{color:var(--down)}.counts>span{white-space:nowrap}.counts>.mstate{min-width:2.7em}.counts>.grp-jog{min-width:8em}.mstate{font-weight:600}.mstate.busy{color:var(--accent)}.mstate.warn{color:var(--warn)}.mstate.bad{color:var(--down)}.pend{display:flex;align-items:center;flex-wrap:wrap;gap:6px 18px;margin-top:8px;padding-top:8px;border-top:1px solid var(--border)}.g{display:inline-flex;align-items:center;gap:6px}.g small{color:var(--muted);font-size:12px}.g.muted{color:var(--muted)}.bat .pct{font-weight:600;font-variant-numeric:tabular-nums}.bat.ok svg{color:var(--ok)}.bat.mid svg{color:var(--warn)}.bat.low svg,.bat.low .pct{color:var(--down)}.st{margin-left:auto}.st.s-ok{color:var(--ok)}.st.s-warn{color:var(--warn)}.st.s-err{color:var(--down)}.st.s-unk{color:var(--muted)}.st.s-warn small{color:var(--warn);font-weight:600}.st.s-err small{color:var(--down);font-weight:600}html.embedded,html.embedded body{overflow-y:hidden}
1
+ :root{--bg: #fff;--fg: #333;--muted: #777;--card: #fafafa;--border: #ddd;--ok: #2e8b3d;--warn: #c77c00;--down: #c9302c;--offline: #8a8a8a;--unknown: #8a8a8a;--accent: #337ab7;--head-bg: #f6f7f8;--head-fg: #222;--head-border: #ccc;color-scheme:light}:root[data-theme=dark]{--bg: #1e1f22;--fg: #dcdcdc;--muted: #9a9a9a;--card: #26282c;--border: #3a3d42;--ok: #52c262;--warn: #e0a030;--down: #ef6a64;--offline: #8f8f8f;--unknown: #8f8f8f;--accent: #6aaee6;--head-bg: #2b2e33;--head-fg: #dcdcdc;--head-border: #3a3d42;color-scheme:dark}*{box-sizing:border-box}html,body{margin:0}body{background:var(--bg);color:var(--fg);font:14px/1.35 Segoe UI,-apple-system,BlinkMacSystemFont,Helvetica Neue,Helvetica,Arial,sans-serif}code,.mono{font-family:Segoe UI Mono,SFMono-Medium,SF Mono,Menlo,Consolas,Courier,monospace}.widget{padding:8px}.widget.level-ok{--level: var(--ok)}.widget.level-warn{--level: var(--warn)}.widget.level-down{--level: var(--down)}.widget.level-offline{--level: var(--offline)}.widget.level-unknown{--level: var(--unknown)}.head{display:flex;align-items:center;gap:10px;min-height:44px}.icon{color:var(--level);display:flex;flex:none}.title{flex:1;min-width:0;display:flex;flex-direction:column}.title strong{color:var(--level);font-size:15px}.title small{color:var(--muted);font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.toggle{flex:none;width:44px;height:44px;border:1px solid var(--border);border-radius:4px;background:var(--btn-bg, var(--card));color:var(--fg);font-size:16px;cursor:pointer}.toggle:focus-visible{outline:2px solid var(--focus, var(--accent));outline-offset:1px}.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:8px;margin-top:8px}.card{background:var(--bg);border:1px solid var(--head-border)}.card h3{margin:0;padding:0 10px;font-size:14px;font-weight:400;line-height:32px;background:var(--head-bg);color:var(--head-fg);border-bottom:1px solid var(--head-border)}.card .body{padding:6px 10px 8px}.logcard{margin-top:8px}.value b{font-weight:inherit}.bad{color:var(--down)}.good{color:var(--ok)}.row{display:flex;justify-content:space-between;gap:10px;padding:1px 0}.label{color:var(--muted)}.value{text-align:right;overflow-wrap:anywhere}.value small{color:var(--muted);font-size:12px}.log{height:260px;overflow-y:auto;background:var(--card);padding:4px 8px;font-family:Segoe UI Mono,SFMono-Medium,SF Mono,Menlo,Consolas,Courier,monospace;font-size:12px}.logline{white-space:pre-wrap;overflow-wrap:anywhere}.logline .time,.empty,.hint{color:var(--muted)}.hint{margin:8px 0 0}.title small{white-space:normal;overflow:visible}.counts{display:flex;flex-wrap:nowrap;gap:2px 10px;margin-top:2px}.counts em{font-style:normal;color:var(--muted);margin-right:1px}.counts b{font-weight:600;font-variant-numeric:tabular-nums}.counts i{font-style:normal;color:var(--muted);margin:0 1px}.counts .good{color:var(--ok)}.counts .bad{color:var(--down)}.counts>span{white-space:nowrap}.counts>.mstate{min-width:2.7em}.counts>.grp-jog{min-width:8em}.mstate{font-weight:600}.mstate.busy{color:var(--accent)}.mstate.warn{color:var(--warn)}.mstate.bad{color:var(--down)}.pend{display:flex;align-items:center;flex-wrap:wrap;gap:6px 18px;margin-top:8px;padding-top:8px;border-top:1px solid var(--border)}.g{display:inline-flex;align-items:center;gap:6px}.g small{color:var(--muted);font-size:12px}.g.muted{color:var(--muted)}.bat .pct{font-weight:600;font-variant-numeric:tabular-nums}.bat.ok svg{color:var(--ok)}.bat.mid svg{color:var(--warn)}.bat.low svg,.bat.low .pct{color:var(--down)}.st{margin-left:auto}.st.s-ok{color:var(--ok)}.st.s-warn{color:var(--warn)}.st.s-err{color:var(--down)}.st.s-unk{color:var(--muted)}.st.s-warn small{color:var(--warn);font-weight:600}.st.s-err small{color:var(--down);font-weight:600}html.embedded,html.embedded body{overflow-y:hidden}