cncjs-handwheel 0.7.3 → 1.0.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.
@@ -1,11 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  'use strict';
3
3
 
4
- // CNCjs <-> ESP32 pendant bridge.
5
- // pendant -> CNCjs : gcode lines (and a few realtime chars) read from the pendant's serial port
6
- // CNCjs -> pendant : status lines (state, MPos, WPos, feed/spindle) written to the pendant
7
- // Health/status of both links is exposed as JSON on http://127.0.0.1:8001/status (configurable).
8
- // Pendant logs can be accessed on http://127.0.0.1:8001/log (configurable)
4
+ // CNCjs <-> ESP32 pendant bridge: command line entry. The bridge itself is in lib/bridge.js.
9
5
 
10
6
  // "install-service" / "uninstall-service": set up the systemd unit (and udev rule or Bluetooth binding), then exit
11
7
  const subcommand = process.argv[2];
@@ -15,94 +11,14 @@ if (subcommand === 'install-service' || subcommand === 'uninstall-service') {
15
11
  }
16
12
 
17
13
  const fs = require('fs');
18
- const os = require('os');
19
14
  const path = require('path');
20
- const http = require('http');
21
15
  const { Command } = require('commander');
22
16
  const { SerialPort } = require('serialport');
23
17
  const connectToCncjs = require('../index');
24
- const guard = require('../lib/guard');
18
+ const { DEFAULT_CONFIG_FILE, loadConfig } = require('../lib/config');
19
+ const { start } = require('../lib/bridge');
25
20
  const pkg = require('../package.json');
26
21
 
27
- const DEFAULT_CONFIG_FILE = path.join(os.homedir(), '.cncjs-handwheel.config');
28
-
29
- const DEFAULTS = {
30
- cncjs: {
31
- port: null, // CNC controller port AS KNOWN TO CNCjs (e.g. /dev/ttyUSB0), NOT the pendant
32
- baudrate: 115200,
33
- controllerType: 'Grbl', // Grbl | Smoothie (TinyG: state is not mapped yet)
34
- socketAddress: 'localhost',
35
- socketPort: 8000,
36
- accessTokenLifetime: '30d',
37
- retryInterval: 5000, // ms before a failed or lost port open is retried (0 = never)
38
- openTimeout: 5000, // ms to wait for CNCjs to answer an open request
39
- maxOpenTries: 3, // unanswered open requests before the connection to CNCjs is rebuilt
40
- keepaliveMs: 30000, // repeat the open request this often to verify the attachment (0 = off)
41
- reopenOnClose: true // reopen the CNC port when it gets closed (e.g. from the CNCjs UI)
42
- },
43
- device: {
44
- path: '/dev/pendant', // the pendant's serial port (e.g. /dev/ttyACM0 or /dev/rfcomm0)
45
- baudRate: 115200,
46
- reconnectMs: 3000,
47
- settleMs: 2000, // ignore pendant input this long after opening the port
48
- // strictGcode: only forward a pendant line to the machine when it looks like gcode (words such as G21 X+1.5 F2000,
49
- // Grbl "$" commands, "%" lines for CNCjs) and keep anything else out of it: it is shown in the widget's log
50
- // as "[not gcode, not sent] ..." and counted as dropped. A log line that lost its leading ";" (or a
51
- // fragment of one) would otherwise be sent to the controller and answered with error:..
52
- strictGcode: true,
53
- send: true, // false: never write anything to the pendant (status, PONG, ERR)
54
-
55
- // Modem-control lines. The CH340 + auto-reset transistors wire DTR/RTS to EN/IO0, so on Linux
56
- // the DTR/RTS toggling around open/close can reset the ESP32 or drop it into download mode.
57
- hupcl: false, // do NOT drop DTR/RTS when the port is closed
58
- dtr: null, // true/false = force DTR right after open, null = leave alone
59
- rts: null, // true/false = force RTS right after open, null = leave alone
60
-
61
- // "Is the handwheel switched on?" for a USB-powered adapter that stays alive when the handwheel is
62
- // switched off. The handwheel drives one modem INPUT of the USB serial chip (CTS#, DSR# or DCD#),
63
- // and the bridge reads it. Off by default (line: null). USB only; there is no such line over Bluetooth.
64
- // line: 'cts' | 'dsr' | 'dcd' which input is wired to the handwheel
65
- // poweredWhen: 'clear' | 'set' the line state that means "switched on". The inputs are active low:
66
- // a pin driven HIGH reads as clear, a pin pulled LOW reads as set. 'clear' = high means on
67
- // pollMs: how often the line is read
68
- // debounceMs: a change must last this long before it counts (opening the port can reset the ESP32)
69
- power: { line: null, poweredWhen: 'clear', pollMs: 250, debounceMs: 1000 }
70
- },
71
- health: {
72
- windowMs: 900000 // the counters in the widget header (reconnects, errors, dropped) cover this long; /status also keeps lifetime totals
73
- },
74
- status: {
75
- format: 'grbl', // 'grbl' -> <Idle|MPos:..|WPos:..|FS:..> 'json' -> {"t":"status",...}
76
- intervalMs: 400, // unsolicited status line at least this often (also the pendant's "host alive" signal)
77
- minGapMs: 350, // minimum gap between two status lines (about 3 per second at most)
78
- pollAfterCommand: true, // ask CNCjs/Grbl for a fresh status report after every pendant command
79
- decimals: 3
80
- },
81
- http: { enabled: true, host: '127.0.0.1', port: 8001 },
82
-
83
- // translate (Grbl 1.1 only): rewrite "G21G91X+10F2000" into "$J=G21G91X+10F2000" so a pendant jog does not
84
- // leave CNCjs/Grbl stuck in relative mode (and so jogs go through Grbl's jog queue)
85
- // maxInFlight: at most this many gcode lines handed to CNCjs and not yet answered with ok/error. While the
86
- // limit is reached, jogs on the same axis and feed are merged into one longer jog (0 = no limit, no merging)
87
- // stallMs: if nothing is acknowledged for this long, assume lines were lost and start counting afresh
88
- // echo: tag jog lines sent to CNCjs with {echo: false} in their context. CNCjs passes the context on in its
89
- // 'serialport:write' event, so a console widget can skip them (see README); it changes nothing else
90
- jog: { translate: true, maxInFlight: 4, stallMs: 2000, echo: false },
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
-
98
- // pendant console lines ("; ...") are kept here for the widget instead of being sent to Grbl
99
- log: { max: 500 },
100
-
101
- verbose: false, // -v: log pendant events and commands
102
- trace: false // --trace: also log all controller traffic (everything CNCjs reads/writes)
103
- };
104
-
105
- // ---------------------------------------------------------------- config
106
22
  const program = new Command();
107
23
  program
108
24
  .name('cncjs-handwheel')
@@ -135,29 +51,6 @@ if (cli.widgetPath) {
135
51
  process.exit(0);
136
52
  }
137
53
 
138
- /**
139
- * Tells whether a value is a plain object (not null, not an array).
140
- *
141
- * @param {*} v - value to test
142
- * @returns {boolean}
143
- */
144
- const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
145
- /**
146
- * Recursively merges `extra` into a copy of `base`. Plain objects are merged key by key,
147
- * everything else (including arrays) is replaced. Neither argument is modified.
148
- *
149
- * @param {object} base - lower precedence values
150
- * @param {object} [extra] - higher precedence values
151
- * @returns {object} the merged copy
152
- */
153
- const deepMerge = (base, extra) => {
154
- const out = Object.assign({}, base);
155
- Object.keys(extra || {}).forEach((k) => {
156
- out[k] = isObj(extra[k]) && isObj(base[k]) ? deepMerge(base[k], extra[k]) : extra[k];
157
- });
158
- return out;
159
- };
160
-
161
54
  if (cli.list) {
162
55
  SerialPort.list().then((ports) => {
163
56
  ports.forEach((p) => console.log([p.path, p.manufacturer, p.vendorId && (p.vendorId + ':' + p.productId)]
@@ -166,1141 +59,12 @@ if (cli.list) {
166
59
  return;
167
60
  }
168
61
 
169
- // precedence (low -> high): defaults, "pendant" section of ~/.cncrc, config file, CLI
170
- let cfg = deepMerge(DEFAULTS, connectToCncjs.readCncrc().pendant);
171
- const cfgFile = cli.config || (fs.existsSync(DEFAULT_CONFIG_FILE) ? DEFAULT_CONFIG_FILE : null);
172
- if (cfgFile) {
173
- try {
174
- cfg = deepMerge(cfg, JSON.parse(fs.readFileSync(cfgFile, 'utf8')));
175
- } catch (err) {
176
- console.error('Cannot read config file ' + cfgFile + ': ' + err.message);
177
- process.exit(1);
178
- }
179
- }
180
- if (cli.port) cfg.cncjs.port = cli.port;
181
- if (cli.baudrate) cfg.cncjs.baudrate = cli.baudrate;
182
- if (cli.controllerType) cfg.cncjs.controllerType = cli.controllerType;
183
- if (cli.socketAddress) cfg.cncjs.socketAddress = cli.socketAddress;
184
- if (cli.socketPort) cfg.cncjs.socketPort = cli.socketPort;
185
- if (cli.pendantPort) cfg.device.path = cli.pendantPort;
186
- if (cli.pendantBaudrate) cfg.device.baudRate = cli.pendantBaudrate;
187
- if (cli.verbose) cfg.verbose = true;
188
- if (cli.trace) cfg.trace = true;
189
- if (cli.pendantSend === false) cfg.device.send = false;
190
- if (cli.jogTranslate === false) cfg.jog.translate = false;
191
-
192
- if (!cfg.cncjs.port) { console.error('Missing CNC controller port (cncjs.port / --port)'); process.exit(1); }
193
- if (!cfg.device.path) { console.error('Missing pendant port (device.path / --pendant-port). Try --list'); process.exit(1); }
194
- if (cfg.device.power.line) {
195
- cfg.device.power.line = String(cfg.device.power.line).toLowerCase();
196
- if (!['cts', 'dsr', 'dcd'].includes(cfg.device.power.line)) {
197
- console.error('device.power.line must be "cts", "dsr", "dcd" or null, not "' + cfg.device.power.line + '"');
198
- process.exit(1);
199
- }
200
- if (!['clear', 'set'].includes(cfg.device.power.poweredWhen)) {
201
- console.error('device.power.poweredWhen must be "clear" or "set", not "' + cfg.device.power.poweredWhen + '"');
202
- process.exit(1);
203
- }
204
- }
205
-
206
- // ---------------------------------------------------------------- state
207
- const store = { controller: { state: {}, settings: {} }, sender: { status: {} } };
208
-
209
- const health = {
210
- startedAt: Date.now(),
211
- pendant: { path: cfg.device.path, connected: false, lastRx: null, lastTx: null, rxLines: 0, txLines: 0,
212
- reconnects: 0, errors: 0, lastError: null, logLines: 0, garbageLines: 0, strayLines: 0, link: null, info: null,
213
- powered: null, powerError: null }, // powered: null = unknown or not configured, true / false = switched on / off
214
- cncjs: { socketConnected: false, portOpen: false, port: cfg.cncjs.port, controllerType: cfg.cncjs.controllerType,
215
- lastError: null, droppedCommands: 0, workflow: null },
216
- guard: { dropped: 0, spindle: 0, lastAt: null },
217
- jog: { sent: 0, merged: 0, discarded: 0, stalls: 0, cancels: 0, inFlight: 0, held: false, lastAt: null },
218
- lastCommand: null
219
- };
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
-
258
- /**
259
- * Logs to the console, but only when -v / verbose is on.
260
- *
261
- * @param {...*} args - what to print
262
- * @returns {void}
263
- */
264
- const log = (...args) => cfg.verbose && console.log(...args);
265
- let shuttingDown = false;
266
-
267
- // ---------------------------------------------------------------- CNCjs side
268
- const cncOpts = Object.assign({}, cfg.cncjs, { secret: cli.secret, verbose: cfg.trace });
269
- const socket = connectToCncjs(cncOpts, (err) => {
270
- if (err) {
271
- health.cncjs.lastError = err.message;
272
- console.error(err.message);
273
- }
274
- });
275
-
276
- socket.on('connect', () => { health.cncjs.socketConnected = true; });
277
- socket.on('disconnect', () => { health.cncjs.socketConnected = false; health.cncjs.portOpen = false; resetJogs(); setWorkflow(null); });
278
- socket.on('serialport:read', onControllerLine);
279
- socket.on('serialport:open', () => {
280
- if (!health.cncjs.portOpen) { lastWco = null; resetJogs(); } // a keepalive confirmation must not discard the work offset
281
- health.cncjs.portOpen = true;
282
- health.cncjs.lastError = null;
283
- });
284
- socket.on('serialport:close', () => { health.cncjs.portOpen = false; resetJogs(); setWorkflow(null); });
285
- socket.on('workflow:state', (state) => setWorkflow(typeof state === 'string' ? state : null));
286
-
287
- ['Grbl', 'Smoothie', 'TinyG'].forEach((type) => {
288
- let dumped = false;
289
- socket.on(type + ':state', (state) => {
290
- store.controller.state = state || {};
291
- if (activeState() !== 'Hold') spindleStopped = false; // Grbl switches the spindle back on when the hold ends
292
- const wco = state && state.status && state.status.wco;
293
- if (wco) lastWco = wco;
294
- sendStatus(false); // forward changes right away (rate limited by status.minGapMs)
295
- if (cfg.verbose && !dumped) { dumped = true; console.log(type + ':state sample', JSON.stringify(state)); }
296
- });
297
- socket.on(type + ':settings', (settings) => { store.controller.settings = settings || {}; });
298
- });
299
-
300
- socket.on('sender:status', (data) => { store.sender.status = data || {}; });
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
-
380
- let lastWco = null; // Grbl 1.1 only reports MPos *or* WPos, plus WCO now and then: WPos = MPos - WCO
381
- /**
382
- * Tells whether commands can currently reach the CNC controller
383
- * (CNCjs socket connected and the CNC port open).
384
- *
385
- * @returns {boolean}
386
- */
387
- const cncReady = () => socket.connected && health.cncjs.portOpen;
388
-
389
- /**
390
- * Records and reports a command that could not be sent (at most one console line per second).
391
- *
392
- * @param {string} name - the CNCjs command that was dropped
393
- * @param {Array} args - its arguments
394
- * @returns {void}
395
- */
396
- let lastDropWarn = 0;
397
- const fmtArgs = (args) => args.map((a) => (a !== null && typeof a === 'object' ? JSON.stringify(a) : a));
398
- function noteDropped(name, args) {
399
- health.cncjs.droppedCommands++;
400
- noteEvent('droppedCommands');
401
- const now = Date.now();
402
- if (now - lastDropWarn < 1000) return;
403
- lastDropWarn = now;
404
- console.warn('Dropped pendant command (' + [name].concat(fmtArgs(args)).join(' ') + '): ' +
405
- (socket.connected ? 'the CNC port is not open' : 'not connected to CNCjs') +
406
- ' [' + health.cncjs.droppedCommands + ' dropped so far]');
407
- }
408
-
409
- /**
410
- * Sends a command to the CNC controller through CNCjs and answers the pendant with a status line.
411
- * If CNCjs or the CNC port is not ready the command is dropped and the pendant gets
412
- * `ERR:CNCJS_NOT_READY` plus a status line.
413
- *
414
- * @param {string} name - CNCjs command, e.g. 'gcode', 'feedhold', 'cyclestart', 'reset'
415
- * @param {...*} args - command arguments, e.g. the gcode line
416
- * @returns {boolean} true if the command was sent
417
- */
418
- function sendCommand(name, ...args) {
419
- if (!cncReady()) {
420
- noteDropped(name, args);
421
- sendToPendant('ERR:CNCJS_NOT_READY');
422
- queueStatus();
423
- return false;
424
- }
425
- health.lastCommand = { at: Date.now(), name, args };
426
- log('pendant ->', name, ...fmtArgs(args));
427
- if (!socket.emit('command', cfg.cncjs.port, name, ...args)) {
428
- noteDropped(name, args);
429
- return false;
430
- }
431
- answerCommand();
432
- return true;
433
- }
434
-
435
- // Every command from the pendant is answered with a status line right away. The position in it is
436
- // what CNCjs knew at that moment; a fresh report is requested so the real position follows within
437
- // a few tens of ms (forwarded by the :state handler).
438
- let lastPoll = 0;
439
- /**
440
- * Answers a command from the pendant with a status line (within status.minGapMs, so a burst of
441
- * commands does not flood the pendant), and asks the controller for a fresh status report (at most
442
- * once per status.minGapMs) so the new position follows shortly after.
443
- *
444
- * @returns {void}
445
- */
446
- function answerCommand() {
447
- queueStatus();
448
- const now = Date.now();
449
- if (cfg.status.pollAfterCommand && now - lastPoll >= Math.max(50, cfg.status.minGapMs)) {
450
- lastPoll = now;
451
- socket.emit('command', cfg.cncjs.port, 'statusreport');
452
- }
453
- }
454
-
455
- // ---------------------------------------------------------------- pendant -> CNCjs
456
- // Everything from the pendant is LINE based (newline terminated) and must be printable ASCII.
457
- // Lines that contain anything else are dropped (an ESP32 that is booting or running at the wrong
458
- // baud rate spews binary garbage, which must never reach the CNC).
459
- // "!" feed hold "~" cycle start "^X" (0x18) soft reset "?" status request
460
- // each as a line of its own, e.g. "!\n". Reset is rate limited.
461
- // ";..." pendant console log entry (any text, ANSI colours stripped): kept in a ring buffer for the
462
- // widget (GET /log), never sent to CNCjs; with -v it is printed as "pendant log: ..."
463
- // lines dropped as non-text are reported with -v (escaped, at most one per second)
464
- // everything after a ";" that is not at the start of the line is a comment and is not sent ("\x18; Reset")
465
- // "$X" is sent as CNCjs's unlock command (a gcode line would be dropped in Alarm)
466
- // PING -> PONG, STATUS? -> immediate status line
467
- // anything that looks like gcode (or a Grbl $ command) -> gcode; any other text is kept out of the machine
468
- // (device.strictGcode, on by default) and shown in the widget log as "[not gcode, not sent] ..."
469
- // After the pendant port opens, input is ignored for device.settleMs so the boot output of an
470
- // ESP32 that was reset by the open is discarded.
471
- const logBuf = [];
472
- let logSeq = 0;
473
-
474
- /**
475
- * Appends a pendant console line to the ring buffer served at GET /log (capped at log.max entries).
476
- *
477
- * @param {string} text - the log text, without the leading ';'
478
- * @returns {void}
479
- */
480
- function addPendantLog(text) {
481
- logBuf.push({ id: ++logSeq, t: Date.now(), text });
482
- if (logBuf.length > cfg.log.max) logBuf.splice(0, logBuf.length - cfg.log.max);
483
- health.pendant.logLines = logSeq;
484
- log('pendant -> log:', text);
485
- }
486
-
487
- const PRINTABLE = /^[\x20-\x7e]+$/;
488
- const REALTIME = { '!': 'feedhold', '~': 'cyclestart', '\x18': 'reset' };
489
- let rxBuf = '';
490
- let skipLine = false;
491
- let ignoreUntil = 0;
492
- let lastReset = 0;
493
-
494
- /**
495
- * Handler for raw bytes from the pendant's serial port. Splits the stream into lines, drops overlong
496
- * lines, and ignores everything during the settle time after the port was opened.
497
- *
498
- * @param {Buffer} buf - chunk read from the serial port
499
- * @returns {void}
500
- */
501
- function onPendantData(buf) {
502
- const now = Date.now();
503
- if (health.pendant.powered === false) { // switched off: whatever the adapter's RX line picks up is noise
504
- rxBuf = '';
505
- skipLine = false;
506
- return;
507
- }
508
- health.pendant.lastRx = now;
509
- if (now < ignoreUntil) {
510
- rxBuf = '';
511
- skipLine = false;
512
- return;
513
- }
514
- const text = buf.toString('binary');
515
- for (let i = 0; i < text.length; i++) {
516
- const ch = text[i];
517
- if (ch === '\n' || ch === '\r') {
518
- const line = rxBuf.trim();
519
- const drop = skipLine;
520
- rxBuf = '';
521
- skipLine = false;
522
- if (drop) { health.pendant.garbageLines++; noteEvent('garbageLines'); }
523
- else if (line) onPendantLine(line);
524
- } else if (rxBuf.length < 256) {
525
- rxBuf += ch;
526
- } else {
527
- skipLine = true; // overlong line: drop it up to the next newline
528
- }
529
- }
530
- }
531
-
532
- // A gcode line: words (a letter and a number, a #parameter or a [expression]) with optional (comments) and spaces
533
- // between them, a Grbl "$" command (`$J=...`, `$H`, `$X`, `$$`, `$100=250`), or a "%" line for CNCjs (`%wait`).
534
- const GCODE_WORDS = /^(?:N\d+)?(?:[A-Z](?:[-+]?(?:\d+\.?\d*|\.\d+)|#\d+|\[[^\]]*\]))+$/;
535
- const GRBL_SYSTEM = /^\$[\w#$=.+\-]*$/;
536
-
537
- /**
538
- * Says whether a text line from the pendant can be sent to the machine as gcode.
539
- *
540
- * @param {string} line - trimmed, printable line
541
- * @returns {boolean}
542
- */
543
- function looksLikeGcode(line) {
544
- if (line[0] === '%') return true; // CNCjs's own statements (%wait, %x = ...)
545
- const compact = line.replace(/\([^)]*\)/g, '').replace(/\s+/g, '').toUpperCase(); // comments and blanks do not count
546
- if (!compact) return true; // only a comment: harmless
547
- return GRBL_SYSTEM.test(compact) || GCODE_WORDS.test(compact);
548
- }
549
-
550
- // Only modal words (G20/G21/G90/G91), axis words and a feed, no G0/G1/G2/G3 -> this is a jog.
551
- const JOG_RE = /^(?:G(?:20|21|90|91))+(?:[XYZABC][-+]?\d*\.?\d+|F\d*\.?\d+)+$/;
552
-
553
- /**
554
- * Turns a pendant jog such as `G21G91X+10F2000` into a Grbl jog command (`$J=G21G91X+10F2000`).
555
- * Lines that are not pure jogs (no axis word, or containing G0/G1/G2/G3 etc.) are returned unchanged.
556
- *
557
- * @param {string} line - gcode line from the pendant
558
- * @returns {string} the jog command, or the original line
559
- */
560
- function toJog(line) {
561
- const compact = line.replace(/\s+/g, '').toUpperCase();
562
- return JOG_RE.test(compact) && /[XYZABC]/.test(compact) ? '$J=' + compact : line;
563
- }
564
-
565
- const ANSI = /\x1b\[[0-9;]*[A-Za-z]/g;
566
- let lastDropLog = 0;
567
-
568
- /**
569
- * Counts a rejected (non-text) pendant line and, with -v, reports it escaped (at most once a second).
570
- *
571
- * @param {string} raw - the rejected line as received (binary string)
572
- * @returns {void}
573
- */
574
- function dropLine(raw) {
575
- health.pendant.garbageLines++;
576
- noteEvent('garbageLines');
577
- const now = Date.now();
578
- if (cfg.verbose && now - lastDropLog > 1000) {
579
- lastDropLog = now;
580
- console.log('pendant: dropped non-text line', JSON.stringify(raw.slice(0, 60)));
581
- }
582
- }
583
-
584
- /**
585
- * Parses the pendant's own status report and stores it for /status. Two spellings are accepted:
586
- * `[HW:bat=74,chg=0,eta=13200,st=ok]` and the same wrapped in a gcode message comment,
587
- * `(MSG, [HW:bat=74,...])`, which a controller reached directly ignores (and may echo as a message).
588
- * Keys (integers only): bat 0-100 (%), chg 1 while charging, eta seconds to full (charging) or empty,
589
- * st ok|warn|err, heap free heap memory in bytes, stk number of tasks close to using up their stack.
590
- * All are optional and unknown keys are ignored, so the firmware can grow. Never sent to the controller.
591
- *
592
- * @param {string} line - trimmed line from the pendant
593
- * @returns {boolean} true if the line was a pendant status report (valid or not)
594
- */
595
- function parsePendantReport(line) {
596
- const m = /^\[HW:([^\]]*)\]$/.exec(line) || /^\(\s*MSG\s*,\s*\[HW:([^\]]*)\]\s*\)$/i.exec(line);
597
- if (!m) return false;
598
- const info = {}; // each report replaces the last one: a key that is left out is unknown, not unchanged
599
- m[1].split(',').forEach((pair) => {
600
- const [k, v] = pair.split('=').map((x) => x.trim());
601
- const num = /^\d+$/.test(v) ? Number(v) : null;
602
- if (k === 'bat' && num !== null && num <= 100) info.bat = num;
603
- else if (k === 'chg' && (v === '0' || v === '1')) info.chg = v === '1';
604
- else if (k === 'eta' && num !== null) info.eta = num;
605
- else if (k === 'st' && /^(ok|warn|err)$/.test(v)) info.st = v;
606
- else if (k === 'heap' && num !== null) info.heap = num;
607
- else if (k === 'stk' && num !== null) info.stk = num;
608
- });
609
- info.at = Date.now();
610
- health.pendant.info = info;
611
- return true;
612
- }
613
-
614
- /**
615
- * Works out whether the pendant port is USB or Bluetooth (rfcomm), looking through the udev symlink
616
- * (/dev/pendant) at the real device node.
617
- *
618
- * @param {string} devPath - configured pendant port
619
- * @returns {?string} 'bluetooth', 'usb' or null if it cannot be told
620
- */
621
- function detectLink(devPath) {
622
- let real = devPath;
623
- try { real = fs.realpathSync(devPath); } catch (err) { /* keep the configured path */ }
624
- if (/rfcomm/i.test(real)) return 'bluetooth';
625
- if (/tty(USB|ACM)/i.test(real) || /usb/i.test(real)) return 'usb';
626
- return null;
627
- }
628
-
629
- /**
630
- * Handles one complete line from the pendant: realtime commands (! ~ ^X ?), console log entries
631
- * (; ...), PING / STATUS?, and otherwise gcode (jogs are translated to $J= for Grbl).
632
- *
633
- * @param {string} raw - the line without the line terminator (binary string)
634
- * @returns {void}
635
- */
636
- function onPendantLine(raw) {
637
- health.pendant.rxLines++;
638
- // As in gcode, everything after a ";" is a comment: the firmware writes e.g. "\x18; Reset the machine". Only the
639
- // part before it is the command. (A line that starts with ";" is a log entry, handled below.)
640
- const semi = raw.indexOf(';');
641
- if (semi > 0) {
642
- const head = raw.slice(0, semi).trim();
643
- if (head) {
644
- log('pendant -> comment ignored:', raw.slice(semi + 1).trim());
645
- raw = head;
646
- }
647
- }
648
- if (raw === '?') return sendStatus(true);
649
- // Grbl jog cancel: the raw byte 0x85 (also accepted as UTF-8, C2 85), or the text alias JOGCANCEL
650
- if (raw === '\x85' || raw === '\xc2\x85' || raw.toUpperCase() === 'JOGCANCEL') return cancelJog();
651
- if (REALTIME[raw]) {
652
- if (raw === '\x18') {
653
- const now = Date.now();
654
- if (now - lastReset < 2000) return;
655
- lastReset = now;
656
- }
657
- // stop means stop: jogs still held back must not fire after a feed hold or a reset
658
- if (raw === '!' || raw === '\x18') discardHeldJog();
659
- if (raw === '\x18') jog.inFlight = 0; // a soft reset flushes everything Grbl had not answered yet
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));
662
- }
663
- // decode as UTF-8, drop ANSI colour codes, tabs -> spaces
664
- let line = Buffer.from(raw, 'binary').toString('utf8').replace(ANSI, '').replace(/\t/g, ' ').trim();
665
- if (!line) return;
666
- if (line[0] === ';') {
667
- // console log entry from the pendant: any text is fine, it is never sent to the controller
668
- addPendantLog(line.replace(/^;\s?/, '').replace(/[\x00-\x1f\x7f]/g, ''));
669
- return;
670
- }
671
- if (!PRINTABLE.test(line)) {
672
- dropLine(raw);
673
- return;
674
- }
675
- if (parsePendantReport(line)) return;
676
- const upper = line.toUpperCase();
677
- if (upper === 'PING') return sendToPendant('PONG');
678
- if (upper === 'STATUS?') return sendStatus(true);
679
- if (cfg.device.strictGcode !== false && !looksLikeGcode(line)) {
680
- // Not gcode: most likely a log line that lost its ";" or a piece of one. Never hand it to the controller.
681
- health.pendant.garbageLines++;
682
- noteEvent('garbageLines');
683
- health.pendant.strayLines = (health.pendant.strayLines || 0) + 1;
684
- addPendantLog('[not gcode, not sent] ' + line.replace(/[\x00-\x1f\x7f]/g, ''));
685
- return;
686
- }
687
- if (cfg.jog.translate && cfg.cncjs.controllerType === 'Grbl') {
688
- line = toJog(line);
689
- }
690
- sendGcodeLine(line);
691
- }
692
-
693
- // ---------------------------------------------------------------- jog governor
694
- // CNCjs hands every gcode line it is given to Grbl without waiting for the previous one to be
695
- // answered. Grbl only has a 128 byte serial buffer (about 6 jog lines), and stops reading it while its
696
- // planner is full, so a fast wheel makes it lose characters: jogs vanish or turn into garbage.
697
- // The bridge therefore counts the lines it has handed to CNCjs minus the ok / error replies it sees,
698
- // and while jog.maxInFlight is reached it merges further jogs (same axis, feed and relative mode;
699
- // opposite directions cancel out) into one pending jog that is sent as soon as a reply frees a slot.
700
- const jog = { inFlight: 0, lastAck: 0, pending: null };
701
- const JOG_PARTS = /^\$J=((?:G(?:20|21|90|91))+)([XYZABC])([-+]?\d*\.?\d+)F(\d*\.?\d+)$/;
702
-
703
- /**
704
- * Splits a single-axis relative Grbl jog (`$J=G21G91Y-0.1F2000`) into its parts.
705
- *
706
- * @param {string} line - gcode line, already translated by toJog()
707
- * @returns {?{raw: string, prefix: string, axis: string, dist: number, feed: string}} null if the line
708
- * is not a jog that can be merged with others
709
- */
710
- function parseJog(line) {
711
- const m = JOG_PARTS.exec(line);
712
- if (!m) return null;
713
- const words = m[1].match(/G\d+/g);
714
- if (!words.includes('G91') || words.includes('G90')) return null;
715
- return { raw: line, prefix: m[1], axis: m[2], dist: Number(m[3]), feed: m[4] };
716
- }
717
-
718
- /**
719
- * Formats a signed jog distance without floating point noise, e.g. -0.1, +0.3, +10.
720
- *
721
- * @param {number} d - distance
722
- * @returns {string}
723
- */
724
- function fmtDist(d) {
725
- const s = Math.abs(d).toFixed(4).replace(/\.?0+$/, '');
726
- return (d < 0 ? '-' : '+') + (s || '0');
727
- }
728
-
729
- /**
730
- * Sends a gcode line to CNCjs and counts it as unanswered (when the jog governor is on). Jogs ($J=)
731
- * carry `{echo: false}` as context when jog.echo is off.
732
- *
733
- * @param {string} line - the gcode line
734
- * @returns {boolean} true if the line was sent
735
- */
736
- function writeGcode(line) {
737
- const quiet = !cfg.jog.echo && /^\$J=/.test(line);
738
- // "$X" as a gcode line would be dropped by CNCjs while the machine is in Alarm (its feeder refuses to send in Alarm
739
- // mode); the "unlock" command writes it straight to the port, which is what the Unlock button does.
740
- const sent = /^\$X$/i.test(line) ? sendCommand('unlock')
741
- : quiet ? sendCommand('gcode', line, { echo: false }) : sendCommand('gcode', line);
742
- if (!sent) return false;
743
- if (cfg.jog.maxInFlight > 0) {
744
- if (jog.inFlight === 0) jog.lastAck = Date.now();
745
- jog.inFlight++;
746
- health.jog.inFlight = jog.inFlight;
747
- }
748
- health.jog.sent++;
749
- return true;
750
- }
751
-
752
- /**
753
- * Sends a gcode line from the pendant: jogs go through the governor, everything else goes straight
754
- * out (after any held back jog, to keep the order).
755
- *
756
- * @param {string} line - the gcode line
757
- * @returns {boolean} true if the line was sent or held back
758
- */
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);
764
- const j = cfg.jog.maxInFlight > 0 ? parseJog(line) : null;
765
- if (j) return queueJog(j);
766
- flushJog(true);
767
- return writeGcode(line);
768
- }
769
-
770
- /**
771
- * Adds a jog to the pending one (same axis, feed and mode: distances add up, opposite jogs cancel;
772
- * anything else replaces it) and sends it if there is room.
773
- *
774
- * @param {object} j - jog from parseJog()
775
- * @returns {boolean} true
776
- */
777
- function queueJog(j) {
778
- health.jog.lastAt = Date.now(); // the wheel is being turned (the widget shows "Jog" for a moment)
779
- const p = jog.pending;
780
- if (p && p.prefix === j.prefix && p.axis === j.axis && p.feed === j.feed) {
781
- p.dist += j.dist;
782
- p.raw = null;
783
- health.jog.merged++;
784
- if (Math.abs(p.dist) < 1e-9) jog.pending = null;
785
- } else {
786
- if (p) health.jog.discarded++;
787
- jog.pending = j;
788
- }
789
- flushJog(false);
790
- health.jog.held = !!jog.pending;
791
- return true;
792
- }
793
-
794
- /**
795
- * Sends the pending jog if the limit allows (or when forced).
796
- *
797
- * @param {boolean} force - send even if jog.maxInFlight is reached
798
- * @returns {void}
799
- */
800
- function flushJog(force) {
801
- const p = jog.pending;
802
- if (!p) return;
803
- if (jobGuarded()) { discardHeldJog(); return; }
804
- if (!force && (cancelTimer || jog.inFlight >= cfg.jog.maxInFlight)) return;
805
- jog.pending = null;
806
- health.jog.held = false;
807
- writeGcode(p.raw || '$J=' + p.prefix + p.axis + fmtDist(p.dist) + 'F' + p.feed);
808
- }
809
-
810
- const CANCEL_SETTLE_DEFAULT_MS = 40;
811
- let cancelTimer = null;
812
-
813
- /**
814
- * Cancels the jog in progress (pendant line 0x85 or JOGCANCEL). Three steps, in this order:
815
- * 1. the jog held back by the governor is discarded;
816
- * 2. `feeder:stop` empties the CNCjs feeder queue right away, so no further jog line leaves for Grbl
817
- * (a Grbl jog cancel only flushes Grbl's planner, jogs still queued in CNCjs would continue);
818
- * 3. after jog.cancelSettleMs the `jogCancel` command (0x85) is sent. Grbl handles 0x85 the moment it
819
- * arrives, ahead of lines still unparsed in its serial buffer, so the short wait lets those lines
820
- * be parsed first; otherwise a long jog sent just before the cancel could start after it.
821
- * Jogs from the pendant that arrive during the wait are held and released after the cancel.
822
- * Lines CNCjs had already written to Grbl may still run (at most jog.maxInFlight short jogs).
823
- *
824
- * @returns {boolean} true if the cancel was started
825
- */
826
- function cancelJog() {
827
- health.jog.cancels++;
828
- if (cfg.cncjs.controllerType !== 'Grbl') {
829
- log('pendant -> jog cancel ignored: only supported for Grbl');
830
- return false;
831
- }
832
- discardHeldJog();
833
- if (!sendCommand('feeder:stop')) return false;
834
- jog.inFlight = 0; // lines removed from the feeder will never be answered
835
- health.jog.inFlight = 0;
836
- clearTimeout(cancelTimer);
837
- cancelTimer = setTimeout(() => {
838
- cancelTimer = null;
839
- sendCommand('jogCancel');
840
- flushJog(false);
841
- }, Number(cfg.jog.cancelSettleMs !== undefined ? cfg.jog.cancelSettleMs : CANCEL_SETTLE_DEFAULT_MS));
842
- return true;
843
- }
844
-
845
- /**
846
- * Throws away a jog that is being held back (after a feed hold or reset).
847
- *
848
- * @returns {void}
849
- */
850
- function discardHeldJog() {
851
- if (jog.pending) health.jog.discarded++;
852
- jog.pending = null;
853
- health.jog.held = false;
854
- }
855
-
856
- /**
857
- * Forgets all jog accounting (CNCjs connection or CNC port changed): nothing stale is replayed.
858
- *
859
- * @returns {void}
860
- */
861
- function resetJogs() {
862
- jog.inFlight = 0;
863
- jog.pending = null;
864
- health.jog.inFlight = 0;
865
- health.jog.held = false;
866
- }
867
-
868
- /**
869
- * Handles a line CNCjs read from the controller: every ok / error reply frees a slot and may release
870
- * the held jog.
871
- *
872
- * @param {*} data - the line (string) as emitted by CNCjs
873
- * @returns {void}
874
- */
875
- function onControllerLine(data) {
876
- const line = String(data === null || data === undefined ? '' : data).trim();
877
- if (line !== 'ok' && line.slice(0, 6).toLowerCase() !== 'error:') return;
878
- if (jog.inFlight > 0) jog.inFlight--;
879
- health.jog.inFlight = jog.inFlight;
880
- jog.lastAck = Date.now();
881
- flushJog(false);
882
- health.jog.held = !!jog.pending;
883
- }
884
-
885
- // Lines the controller never answers (lost in transit) would keep the counter up for good.
886
- const jogTimer = setInterval(() => {
887
- if (jog.inFlight > 0 && Date.now() - jog.lastAck > cfg.jog.stallMs) {
888
- health.jog.stalls++;
889
- console.warn('Controller did not acknowledge ' + jog.inFlight + ' gcode line(s) for ' + cfg.jog.stallMs +
890
- ' ms: they may have been lost. [' + health.jog.stalls + ' stall(s) so far]');
891
- jog.inFlight = 0;
892
- health.jog.inFlight = 0;
893
- }
894
- flushJog(false);
895
- }, 250);
896
-
897
- // ---------------------------------------------------------------- CNCjs -> pendant
898
- /**
899
- * Converts a value to a number, treating anything non-numeric as 0.
900
- *
901
- * @param {*} v
902
- * @returns {number}
903
- */
904
- const num = (v) => Number(v) || 0;
905
- /**
906
- * Subtracts two {x, y, z} positions (a - b).
907
- *
908
- * @param {{x: (number|string), y: (number|string), z: (number|string)}} a
909
- * @param {{x: (number|string), y: (number|string), z: (number|string)}} b
910
- * @returns {{x: number, y: number, z: number}}
911
- */
912
- const sub = (a, b) => ({ x: num(a.x) - num(b.x), y: num(a.y) - num(b.y), z: num(a.z) - num(b.z) });
913
- /**
914
- * Adds two {x, y, z} positions (a + b).
915
- *
916
- * @param {{x: (number|string), y: (number|string), z: (number|string)}} a
917
- * @param {{x: (number|string), y: (number|string), z: (number|string)}} b
918
- * @returns {{x: number, y: number, z: number}}
919
- */
920
- const add = (a, b) => ({ x: num(a.x) + num(b.x), y: num(a.y) + num(b.y), z: num(a.z) + num(b.z) });
921
-
922
- /**
923
- * Returns machine and work position. Grbl 1.1 reports only one of them plus the work coordinate
924
- * offset (WCO) now and then, so the missing one is derived: WPos = MPos - WCO.
925
- *
926
- * @param {object} st - the `status` object of the CNCjs controller state
927
- * @returns {{mpos: ?object, wpos: ?object}} positions, null where they cannot be determined yet
928
- */
929
- function positions(st) {
930
- const wco = st.wco || lastWco;
931
- let mpos = st.mpos || null;
932
- let wpos = st.wpos || null;
933
- if (!wpos && mpos && wco) wpos = sub(mpos, wco);
934
- if (!mpos && wpos && wco) mpos = add(wpos, wco);
935
- return { mpos, wpos };
936
- }
937
-
938
- /**
939
- * Builds the current machine status from the latest CNCjs controller and sender state.
940
- *
941
- * @returns {{connected: boolean, state: string, mpos: ?object, wpos: ?object, feed: ?number,
942
- * spindle: ?number, sender: object}}
943
- */
944
- function snapshot() {
945
- const connected = cncReady();
946
- const st = (store.controller.state && store.controller.state.status) || {};
947
- const pos = positions(st);
948
- const snd = store.sender.status || {};
949
- return {
950
- connected,
951
- state: connected ? (st.activeState || 'Unknown') : 'Disconnected',
952
- mpos: pos.mpos,
953
- wpos: pos.wpos,
954
- feed: st.feedrate !== undefined ? st.feedrate : null,
955
- spindle: st.spindle !== undefined ? st.spindle : null,
956
- sender: { name: snd.name || null, total: snd.total || 0, sent: snd.sent || 0,
957
- received: snd.received || 0, hold: !!snd.hold }
958
- };
959
- }
960
-
961
- /**
962
- * Formats a status snapshot as the line sent to the pendant, either Grbl style
963
- * (`<Idle|MPos:x,y,z|WPos:x,y,z|FS:feed,spindle>`) or JSON, depending on status.format.
964
- *
965
- * @param {object} s - snapshot from snapshot()
966
- * @returns {string} the status line without terminator
967
- */
968
- function formatStatus(s) {
969
- if (cfg.status.format === 'json') {
970
- return JSON.stringify(Object.assign({ t: 'status' }, s));
971
- }
972
- const d = cfg.status.decimals;
973
- const pos = (p) => [p.x, p.y, p.z].map((n) => (Number(n) || 0).toFixed(d)).join(',');
974
- const parts = [s.state];
975
- if (s.connected) {
976
- if (s.mpos) parts.push('MPos:' + pos(s.mpos));
977
- if (s.wpos) parts.push('WPos:' + pos(s.wpos));
978
- if (s.feed !== null) parts.push('FS:' + (Number(s.feed) || 0) + ',' + (Number(s.spindle) || 0));
979
- }
980
- return '<' + parts.join('|') + '>';
981
- }
982
-
983
- let lastLine = '';
984
- let lastStatusAt = 0;
985
- let statusQueued = false;
986
-
987
- /**
988
- * Sends the current status to the pendant if one is due: forced, at least every status.intervalMs,
989
- * when the values changed and status.minGapMs has passed, or when one was queued with queueStatus().
990
- *
991
- * @param {boolean} [force=false] - send regardless of timing
992
- * @returns {void}
993
- */
994
- function sendStatus(force) {
995
- if (!cfg.device.send) return;
996
- const line = formatStatus(snapshot());
997
- const now = Date.now();
998
- const gapOk = now - lastStatusAt >= cfg.status.minGapMs;
999
- const due = now - lastStatusAt >= cfg.status.intervalMs;
1000
- const changed = line !== lastLine && gapOk;
1001
- if (force || due || changed || (statusQueued && gapOk)) {
1002
- if (sendToPendant(line, changed)) {
1003
- lastLine = line;
1004
- lastStatusAt = now;
1005
- statusQueued = false;
1006
- }
1007
- }
1008
- }
1009
-
1010
- /**
1011
- * Asks for a status line to go to the pendant soon: now if status.minGapMs has passed since the last
1012
- * one, otherwise as soon as it has (the periodic timer sends it). Many requests in a row cost one line.
1013
- *
1014
- * @returns {void}
1015
- */
1016
- function queueStatus() {
1017
- statusQueued = true;
1018
- sendStatus(false);
1019
- }
1020
-
1021
- /**
1022
- * Writes one line to the pendant's serial port.
1023
- *
1024
- * @param {string} text - the line, without terminator (a newline is added)
1025
- * @param {boolean} [should_log=false] - print the line when -v is on
1026
- * @returns {boolean} false if the pendant port is not open
1027
- */
1028
- function sendToPendant(text, should_log=false) {
1029
- if (!cfg.device.send) return false;
1030
- const port = pendantPort;
1031
- if (!port || !port.isOpen || health.pendant.powered === false) return false;
1032
- if(should_log) log('cncjs -> ', 'pendant', text);
1033
- port.write(text + '\n', (err) => {
1034
- if (err) noteError(err);
1035
- });
1036
- health.pendant.lastTx = Date.now();
1037
- health.pendant.txLines++;
1038
- return true;
1039
- }
1040
-
1041
- const statusTimer = setInterval(() => sendStatus(false), Math.max(10, Math.min(100, cfg.status.minGapMs, cfg.status.intervalMs)));
1042
-
1043
- // ---------------------------------------------------------------- pendant serial link
1044
- let pendantPort = null;
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
1048
-
1049
- /**
1050
- * Records a pendant serial error in the health data and prints it.
1051
- *
1052
- * @param {Error} err
1053
- * @returns {void}
1054
- */
1055
- function noteError(err) {
1056
- health.pendant.errors++;
1057
- noteEvent('errors');
1058
- health.pendant.lastError = err.message;
1059
- console.error('Pendant error:', err.message);
1060
- }
1061
-
1062
- /**
1063
- * Schedules a reopen of the pendant serial port after device.reconnectMs (at most one pending).
1064
- *
1065
- * @returns {void}
1066
- */
1067
- function scheduleReconnect() {
1068
- if (shuttingDown || reconnectTimer) return;
1069
- if (downSince === null) downSince = Date.now();
1070
- reconnectTimer = setTimeout(() => {
1071
- reconnectTimer = null;
1072
- health.pendant.reconnects++;
1073
- noteEvent('reconnects');
1074
- openPendant();
1075
- }, cfg.device.reconnectMs);
1076
- }
1077
-
1078
- // ---------------------------------------------------------------- handwheel power (modem line)
1079
- let powerTimer = null;
1080
- let powerBusy = false;
1081
- let powerRaw = null; // last reading (true = on), not yet debounced
1082
- let powerSince = 0; // when powerRaw last changed
1083
-
1084
- /**
1085
- * Stops reading the power line and forgets what it said (the state is unknown while the port is closed).
1086
- *
1087
- * @returns {void}
1088
- */
1089
- function stopPowerWatch() {
1090
- clearInterval(powerTimer);
1091
- powerTimer = null;
1092
- powerBusy = false;
1093
- powerRaw = null;
1094
- health.pendant.powered = null;
1095
- }
1096
-
1097
- /**
1098
- * Records a debounced change of the handwheel's power state.
1099
- *
1100
- * @param {boolean} on - true if the handwheel is switched on
1101
- * @returns {void}
1102
- */
1103
- function setPowered(on) {
1104
- health.pendant.powered = on;
1105
- rxBuf = '';
1106
- skipLine = false;
1107
- if (on) {
1108
- // the ESP32 is booting: ignore its output like after opening the port
1109
- ignoreUntil = Date.now() + Number(cfg.device.settleMs || 0);
1110
- } else {
1111
- health.pendant.info = null; // a stale battery level is worse than none
1112
- discardHeldJog(); // switching the handwheel off must not let a held jog fire afterwards
1113
- }
1114
- console.log('Handwheel switched ' + (on ? 'on' : 'off'));
1115
- }
1116
-
1117
- /**
1118
- * Reads the modem line once and applies the debounce.
1119
- *
1120
- * @param {SerialPort} port - the open pendant port
1121
- * @returns {void}
1122
- */
1123
- function pollPower(port) {
1124
- if (powerBusy || !port.isOpen) return;
1125
- powerBusy = true;
1126
- port.get((err, signals) => {
1127
- powerBusy = false;
1128
- if (port !== pendantPort || !port.isOpen) return;
1129
- if (err) {
1130
- // e.g. Bluetooth (rfcomm) has no modem lines: say so once and stop asking
1131
- health.pendant.powerError = err.message;
1132
- console.error('Pendant power line cannot be read, power detection is off:', err.message);
1133
- stopPowerWatch();
1134
- return;
1135
- }
1136
- const set = !!(signals && signals[cfg.device.power.line]);
1137
- const on = cfg.device.power.poweredWhen === 'set' ? set : !set;
1138
- const now = Date.now();
1139
- if (on !== powerRaw) {
1140
- powerRaw = on;
1141
- powerSince = now;
1142
- }
1143
- if (health.pendant.powered !== on && now - powerSince >= Number(cfg.device.power.debounceMs || 0)) setPowered(on);
1144
- });
1145
- }
1146
-
1147
- /**
1148
- * Starts polling the configured modem line of the pendant's port (nothing happens if device.power.line is null).
1149
- *
1150
- * @param {SerialPort} port - the open pendant port
1151
- * @returns {void}
1152
- */
1153
- function startPowerWatch(port) {
1154
- stopPowerWatch();
1155
- health.pendant.powerError = null;
1156
- if (!cfg.device.power.line) return;
1157
- powerTimer = setInterval(() => pollPower(port), Math.max(50, Number(cfg.device.power.pollMs) || 250));
1158
- pollPower(port);
1159
- }
1160
-
1161
- /**
1162
- * Opens the pendant's serial port and wires up its events. Failures and closes schedule a reconnect.
1163
- * After a successful open, pendant input is ignored for device.settleMs and a status line is sent.
1164
- *
1165
- * @returns {void}
1166
- */
1167
- function openPendant() {
1168
- const port = new SerialPort({
1169
- path: cfg.device.path,
1170
- baudRate: Number(cfg.device.baudRate),
1171
- autoOpen: false,
1172
- dataBits: 8,
1173
- stopBits: 1,
1174
- parity: 'none',
1175
- rtscts: false,
1176
- xon: false,
1177
- xoff: false,
1178
- xany: false,
1179
- hupcl: !!cfg.device.hupcl
1180
- });
1181
- pendantPort = port;
1182
- port.on('data', onPendantData);
1183
- port.on('error', noteError);
1184
- port.on('close', () => {
1185
- health.pendant.connected = false;
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
1188
- stopPowerWatch();
1189
- if (!shuttingDown) console.log('Pendant port closed');
1190
- scheduleReconnect();
1191
- });
1192
- port.open((err) => {
1193
- if (err) {
1194
- noteError(err);
1195
- scheduleReconnect();
1196
- return;
1197
- }
1198
- rxBuf = '';
1199
- skipLine = false;
1200
- ignoreUntil = Date.now() + Number(cfg.device.settleMs || 0);
1201
- const lines = {};
1202
- if (cfg.device.dtr !== null && cfg.device.dtr !== undefined) lines.dtr = !!cfg.device.dtr;
1203
- if (cfg.device.rts !== null && cfg.device.rts !== undefined) lines.rts = !!cfg.device.rts;
1204
- if (Object.keys(lines).length) {
1205
- port.set(lines, (setErr) => { if (setErr) noteError(setErr); });
1206
- }
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;
1216
- health.pendant.link = detectLink(cfg.device.path);
1217
- health.pendant.lastError = null;
1218
- console.log('Pendant connected on ' + cfg.device.path);
1219
- startPowerWatch(port);
1220
- sendStatus(true);
1221
- });
1222
- }
1223
-
1224
- // ---------------------------------------------------------------- health endpoint
1225
- /**
1226
- * Builds the JSON served at GET /status: link health of the pendant and CNCjs, the last command
1227
- * sent, and the current machine status.
1228
- *
1229
- * @returns {object}
1230
- */
1231
- function healthReport() {
1232
- const now = Date.now();
1233
- const age = (t) => (t ? now - t : null);
1234
- return {
1235
- ok: health.pendant.connected && health.pendant.powered !== false && cncReady(),
1236
- version: pkg.version,
1237
- uptimeMs: now - health.startedAt,
1238
- pendant: Object.assign({}, health.pendant, { sendEnabled: !!cfg.device.send, powerDetect: !!cfg.device.power.line,
1239
- lastRxAgeMs: age(health.pendant.lastRx),
1240
- lastTxAgeMs: age(health.pendant.lastTx),
1241
- info: health.pendant.info && Object.assign({}, health.pendant.info, { ageMs: age(health.pendant.info.at) }) }),
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
- },
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) }),
1255
- lastCommand: health.lastCommand,
1256
- status: snapshot()
1257
- };
1258
- }
1259
-
1260
- let httpServer = null;
1261
- if (cfg.http.enabled) {
1262
- httpServer = http.createServer((req, res) => {
1263
- const url = new URL(req.url, 'http://localhost');
1264
- const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
1265
- if (url.pathname === '/' || url.pathname === '/status') {
1266
- res.writeHead(200, headers);
1267
- res.end(JSON.stringify(healthReport()));
1268
- } else if (url.pathname === '/log') {
1269
- // GET /log?since=<id> -> entries with id > since (poll with the last id you saw)
1270
- const since = Number(url.searchParams.get('since')) || 0;
1271
- res.writeHead(200, headers);
1272
- res.end(JSON.stringify({ last: logSeq, entries: logBuf.filter((e) => e.id > since) }));
1273
- } else {
1274
- res.writeHead(404);
1275
- res.end();
1276
- }
1277
- });
1278
- httpServer.on('error', (err) => console.error('Health endpoint error:', err.message));
1279
- httpServer.listen(cfg.http.port, cfg.http.host, () =>
1280
- console.log('Health endpoint on http://' + cfg.http.host + ':' + cfg.http.port + '/status'));
1281
- }
1282
-
1283
- // ---------------------------------------------------------------- lifecycle
1284
- /**
1285
- * Stops timers and closes the CNCjs socket, the pendant port and the HTTP server, then exits.
1286
- * Called on SIGINT / SIGTERM.
1287
- *
1288
- * @returns {void}
1289
- */
1290
- function shutdown() {
1291
- if (shuttingDown) return;
1292
- shuttingDown = true;
1293
- clearInterval(statusTimer);
1294
- clearInterval(powerTimer);
1295
- clearInterval(jogTimer);
1296
- clearTimeout(cancelTimer);
1297
- clearTimeout(reconnectTimer);
1298
- socket.close();
1299
- if (httpServer) httpServer.close();
1300
- if (pendantPort && pendantPort.isOpen) pendantPort.close();
1301
- setTimeout(() => process.exit(0), 300);
62
+ let cfg;
63
+ try {
64
+ ({ cfg } = loadConfig(cli, connectToCncjs.readCncrc().pendant));
65
+ } catch (err) {
66
+ console.error(err.message);
67
+ process.exit(1);
1302
68
  }
1303
- process.on('SIGINT', shutdown);
1304
- process.on('SIGTERM', shutdown);
1305
69
 
1306
- openPendant();
70
+ start({ cfg, cli, connectToCncjs, pkg });