cncjs-handwheel 0.0.0-stage → 0.2.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.
@@ -0,0 +1,922 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
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)
9
+
10
+ // "install-service" / "uninstall-service": set up the systemd unit (and udev rule or Bluetooth binding), then exit
11
+ const subcommand = process.argv[2];
12
+ if (subcommand === 'install-service' || subcommand === 'uninstall-service') {
13
+ require('../lib/service')(subcommand, process.argv.slice(3));
14
+ return;
15
+ }
16
+
17
+ const fs = require('fs');
18
+ const os = require('os');
19
+ const path = require('path');
20
+ const http = require('http');
21
+ const { Command } = require('commander');
22
+ const { SerialPort } = require('serialport');
23
+ const connectToCncjs = require('../index');
24
+ const pkg = require('../package.json');
25
+
26
+ const DEFAULT_CONFIG_FILE = path.join(os.homedir(), '.cncjs-handwheel.config');
27
+
28
+ const DEFAULTS = {
29
+ cncjs: {
30
+ port: null, // CNC controller port AS KNOWN TO CNCjs (e.g. /dev/ttyUSB0), NOT the pendant
31
+ baudrate: 115200,
32
+ controllerType: 'Grbl', // Grbl | Smoothie (TinyG: state is not mapped yet)
33
+ socketAddress: 'localhost',
34
+ socketPort: 8000,
35
+ accessTokenLifetime: '30d',
36
+ retryInterval: 5000, // ms before a failed or lost port open is retried (0 = never)
37
+ openTimeout: 5000, // ms to wait for CNCjs to answer an open request
38
+ maxOpenTries: 3, // unanswered open requests before the connection to CNCjs is rebuilt
39
+ keepaliveMs: 30000, // repeat the open request this often to verify the attachment (0 = off)
40
+ reopenOnClose: true // reopen the CNC port when it gets closed (e.g. from the CNCjs UI)
41
+ },
42
+ device: {
43
+ path: '/dev/pendant', // the pendant's serial port (e.g. /dev/ttyACM0 or /dev/rfcomm0)
44
+ baudRate: 115200,
45
+ reconnectMs: 3000,
46
+ settleMs: 2000, // ignore pendant input this long after opening the port
47
+ send: true, // false: never write anything to the pendant (status, PONG, ERR)
48
+
49
+ // Modem-control lines. The CH340 + auto-reset transistors wire DTR/RTS to EN/IO0, so on Linux
50
+ // the DTR/RTS toggling around open/close can reset the ESP32 or drop it into download mode.
51
+ hupcl: false, // do NOT drop DTR/RTS when the port is closed
52
+ dtr: null, // true/false = force DTR right after open, null = leave alone
53
+ rts: null // true/false = force RTS right after open, null = leave alone
54
+ },
55
+ status: {
56
+ format: 'grbl', // 'grbl' -> <Idle|MPos:..|WPos:..|FS:..> 'json' -> {"t":"status",...}
57
+ intervalMs: 400, // unsolicited status line at least this often (also the pendant's "host alive" signal)
58
+ minGapMs: 350, // minimum gap between two status lines (about 3 per second at most)
59
+ pollAfterCommand: true, // ask CNCjs/Grbl for a fresh status report after every pendant command
60
+ decimals: 3
61
+ },
62
+ http: { enabled: true, host: '127.0.0.1', port: 8001 },
63
+
64
+ // translate (Grbl 1.1 only): rewrite "G21G91X+10F2000" into "$J=G21G91X+10F2000" so a pendant jog does not
65
+ // leave CNCjs/Grbl stuck in relative mode (and so jogs go through Grbl's jog queue)
66
+ // maxInFlight: at most this many gcode lines handed to CNCjs and not yet answered with ok/error. While the
67
+ // limit is reached, jogs on the same axis and feed are merged into one longer jog (0 = no limit, no merging)
68
+ // stallMs: if nothing is acknowledged for this long, assume lines were lost and start counting afresh
69
+ // echo: tag jog lines sent to CNCjs with {echo: false} in their context. CNCjs passes the context on in its
70
+ // 'serialport:write' event, so a console widget can skip them (see README); it changes nothing else
71
+ jog: { translate: true, maxInFlight: 4, stallMs: 2000, echo: false },
72
+
73
+ // pendant console lines ("; ...") are kept here for the widget instead of being sent to Grbl
74
+ log: { max: 500 },
75
+
76
+ verbose: false, // -v: log pendant events and commands
77
+ trace: false // --trace: also log all controller traffic (everything CNCjs reads/writes)
78
+ };
79
+
80
+ // ---------------------------------------------------------------- config
81
+ const program = new Command();
82
+ program
83
+ .name('cncjs-handwheel')
84
+ .version(pkg.version)
85
+ .option('-l, --list', 'list available serial ports then exit')
86
+ .option('-c, --config <file>', 'config file (default: ' + DEFAULT_CONFIG_FILE + ' if present)')
87
+ .option('-s, --secret <secret>', 'CNCjs secret (default: $CNCJS_SECRET or ~/.cncrc)')
88
+ .option('-p, --port <port>', 'CNC controller port as known to CNCjs, e.g. /dev/ttyUSB0')
89
+ .option('-b, --baudrate <baudrate>', 'CNC controller baud rate')
90
+ .option('--controller-type <type>', 'Grbl|Smoothie')
91
+ .option('--socket-address <address>', 'CNCjs host')
92
+ .option('--socket-port <port>', 'CNCjs port')
93
+ .option('--pendant-port <path>', 'serial port of the pendant')
94
+ .option('--pendant-baudrate <baudrate>', 'baud rate of the pendant')
95
+ .option('-v, --verbose', 'log pendant events and the commands sent to CNCjs')
96
+ .option('--trace', 'also log all controller traffic (very noisy)')
97
+ .option('--no-pendant-send', 'do not write anything to the pendant (same as device.send: false)')
98
+ .option('--no-jog-translate', 'send pendant jogs as plain gcode instead of $J= (same as jog.translate: false)');
99
+ program.parse(process.argv);
100
+ const cli = program.opts();
101
+
102
+ /**
103
+ * Tells whether a value is a plain object (not null, not an array).
104
+ *
105
+ * @param {*} v - value to test
106
+ * @returns {boolean}
107
+ */
108
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
109
+ /**
110
+ * Recursively merges `extra` into a copy of `base`. Plain objects are merged key by key,
111
+ * everything else (including arrays) is replaced. Neither argument is modified.
112
+ *
113
+ * @param {object} base - lower precedence values
114
+ * @param {object} [extra] - higher precedence values
115
+ * @returns {object} the merged copy
116
+ */
117
+ const deepMerge = (base, extra) => {
118
+ const out = Object.assign({}, base);
119
+ Object.keys(extra || {}).forEach((k) => {
120
+ out[k] = isObj(extra[k]) && isObj(base[k]) ? deepMerge(base[k], extra[k]) : extra[k];
121
+ });
122
+ return out;
123
+ };
124
+
125
+ if (cli.list) {
126
+ SerialPort.list().then((ports) => {
127
+ ports.forEach((p) => console.log([p.path, p.manufacturer, p.vendorId && (p.vendorId + ':' + p.productId)]
128
+ .filter(Boolean).join(' ')));
129
+ }).catch((err) => { console.error(err); process.exit(1); });
130
+ return;
131
+ }
132
+
133
+ // precedence (low -> high): defaults, "pendant" section of ~/.cncrc, config file, CLI
134
+ let cfg = deepMerge(DEFAULTS, connectToCncjs.readCncrc().pendant);
135
+ const cfgFile = cli.config || (fs.existsSync(DEFAULT_CONFIG_FILE) ? DEFAULT_CONFIG_FILE : null);
136
+ if (cfgFile) {
137
+ try {
138
+ cfg = deepMerge(cfg, JSON.parse(fs.readFileSync(cfgFile, 'utf8')));
139
+ } catch (err) {
140
+ console.error('Cannot read config file ' + cfgFile + ': ' + err.message);
141
+ process.exit(1);
142
+ }
143
+ }
144
+ if (cli.port) cfg.cncjs.port = cli.port;
145
+ if (cli.baudrate) cfg.cncjs.baudrate = cli.baudrate;
146
+ if (cli.controllerType) cfg.cncjs.controllerType = cli.controllerType;
147
+ if (cli.socketAddress) cfg.cncjs.socketAddress = cli.socketAddress;
148
+ if (cli.socketPort) cfg.cncjs.socketPort = cli.socketPort;
149
+ if (cli.pendantPort) cfg.device.path = cli.pendantPort;
150
+ if (cli.pendantBaudrate) cfg.device.baudRate = cli.pendantBaudrate;
151
+ if (cli.verbose) cfg.verbose = true;
152
+ if (cli.trace) cfg.trace = true;
153
+ if (cli.pendantSend === false) cfg.device.send = false;
154
+ if (cli.jogTranslate === false) cfg.jog.translate = false;
155
+
156
+ if (!cfg.cncjs.port) { console.error('Missing CNC controller port (cncjs.port / --port)'); process.exit(1); }
157
+ if (!cfg.device.path) { console.error('Missing pendant port (device.path / --pendant-port). Try --list'); process.exit(1); }
158
+
159
+ // ---------------------------------------------------------------- state
160
+ const store = { controller: { state: {}, settings: {} }, sender: { status: {} } };
161
+
162
+ const health = {
163
+ startedAt: Date.now(),
164
+ pendant: { path: cfg.device.path, connected: false, lastRx: null, lastTx: null, rxLines: 0, txLines: 0,
165
+ reconnects: 0, errors: 0, lastError: null, logLines: 0, garbageLines: 0 },
166
+ cncjs: { socketConnected: false, portOpen: false, port: cfg.cncjs.port, controllerType: cfg.cncjs.controllerType,
167
+ lastError: null, droppedCommands: 0 },
168
+ jog: { sent: 0, merged: 0, discarded: 0, stalls: 0, cancels: 0, inFlight: 0, held: false },
169
+ lastCommand: null
170
+ };
171
+
172
+ /**
173
+ * Logs to the console, but only when -v / verbose is on.
174
+ *
175
+ * @param {...*} args - what to print
176
+ * @returns {void}
177
+ */
178
+ const log = (...args) => cfg.verbose && console.log(...args);
179
+ let shuttingDown = false;
180
+
181
+ // ---------------------------------------------------------------- CNCjs side
182
+ const cncOpts = Object.assign({}, cfg.cncjs, { secret: cli.secret, verbose: cfg.trace });
183
+ const socket = connectToCncjs(cncOpts, (err) => {
184
+ if (err) {
185
+ health.cncjs.lastError = err.message;
186
+ console.error(err.message);
187
+ }
188
+ });
189
+
190
+ socket.on('connect', () => { health.cncjs.socketConnected = true; });
191
+ socket.on('disconnect', () => { health.cncjs.socketConnected = false; health.cncjs.portOpen = false; resetJogs(); });
192
+ socket.on('serialport:read', onControllerLine);
193
+ socket.on('serialport:open', () => {
194
+ if (!health.cncjs.portOpen) { lastWco = null; resetJogs(); } // a keepalive confirmation must not discard the work offset
195
+ health.cncjs.portOpen = true;
196
+ health.cncjs.lastError = null;
197
+ });
198
+ socket.on('serialport:close', () => { health.cncjs.portOpen = false; resetJogs(); });
199
+
200
+ ['Grbl', 'Smoothie', 'TinyG'].forEach((type) => {
201
+ let dumped = false;
202
+ socket.on(type + ':state', (state) => {
203
+ store.controller.state = state || {};
204
+ const wco = state && state.status && state.status.wco;
205
+ if (wco) lastWco = wco;
206
+ sendStatus(false); // forward changes right away (rate limited by status.minGapMs)
207
+ if (cfg.verbose && !dumped) { dumped = true; console.log(type + ':state sample', JSON.stringify(state)); }
208
+ });
209
+ socket.on(type + ':settings', (settings) => { store.controller.settings = settings || {}; });
210
+ });
211
+
212
+ socket.on('sender:status', (data) => { store.sender.status = data || {}; });
213
+
214
+ let lastWco = null; // Grbl 1.1 only reports MPos *or* WPos, plus WCO now and then: WPos = MPos - WCO
215
+ /**
216
+ * Tells whether commands can currently reach the CNC controller
217
+ * (CNCjs socket connected and the CNC port open).
218
+ *
219
+ * @returns {boolean}
220
+ */
221
+ const cncReady = () => socket.connected && health.cncjs.portOpen;
222
+
223
+ /**
224
+ * Records and reports a command that could not be sent (at most one console line per second).
225
+ *
226
+ * @param {string} name - the CNCjs command that was dropped
227
+ * @param {Array} args - its arguments
228
+ * @returns {void}
229
+ */
230
+ let lastDropWarn = 0;
231
+ const fmtArgs = (args) => args.map((a) => (a !== null && typeof a === 'object' ? JSON.stringify(a) : a));
232
+ function noteDropped(name, args) {
233
+ health.cncjs.droppedCommands++;
234
+ const now = Date.now();
235
+ if (now - lastDropWarn < 1000) return;
236
+ lastDropWarn = now;
237
+ console.warn('Dropped pendant command (' + [name].concat(fmtArgs(args)).join(' ') + '): ' +
238
+ (socket.connected ? 'the CNC port is not open' : 'not connected to CNCjs') +
239
+ ' [' + health.cncjs.droppedCommands + ' dropped so far]');
240
+ }
241
+
242
+ /**
243
+ * Sends a command to the CNC controller through CNCjs and answers the pendant with a status line.
244
+ * If CNCjs or the CNC port is not ready the command is dropped and the pendant gets
245
+ * `ERR:CNCJS_NOT_READY` plus a status line.
246
+ *
247
+ * @param {string} name - CNCjs command, e.g. 'gcode', 'feedhold', 'cyclestart', 'reset'
248
+ * @param {...*} args - command arguments, e.g. the gcode line
249
+ * @returns {boolean} true if the command was sent
250
+ */
251
+ function sendCommand(name, ...args) {
252
+ if (!cncReady()) {
253
+ noteDropped(name, args);
254
+ sendToPendant('ERR:CNCJS_NOT_READY');
255
+ queueStatus();
256
+ return false;
257
+ }
258
+ health.lastCommand = { at: Date.now(), name, args };
259
+ log('pendant ->', name, ...fmtArgs(args));
260
+ if (!socket.emit('command', cfg.cncjs.port, name, ...args)) {
261
+ noteDropped(name, args);
262
+ return false;
263
+ }
264
+ answerCommand();
265
+ return true;
266
+ }
267
+
268
+ // Every command from the pendant is answered with a status line right away. The position in it is
269
+ // what CNCjs knew at that moment; a fresh report is requested so the real position follows within
270
+ // a few tens of ms (forwarded by the :state handler).
271
+ let lastPoll = 0;
272
+ /**
273
+ * Answers a command from the pendant with a status line (within status.minGapMs, so a burst of
274
+ * commands does not flood the pendant), and asks the controller for a fresh status report (at most
275
+ * once per status.minGapMs) so the new position follows shortly after.
276
+ *
277
+ * @returns {void}
278
+ */
279
+ function answerCommand() {
280
+ queueStatus();
281
+ const now = Date.now();
282
+ if (cfg.status.pollAfterCommand && now - lastPoll >= Math.max(50, cfg.status.minGapMs)) {
283
+ lastPoll = now;
284
+ socket.emit('command', cfg.cncjs.port, 'statusreport');
285
+ }
286
+ }
287
+
288
+ // ---------------------------------------------------------------- pendant -> CNCjs
289
+ // Everything from the pendant is LINE based (newline terminated) and must be printable ASCII.
290
+ // Lines that contain anything else are dropped (an ESP32 that is booting or running at the wrong
291
+ // baud rate spews binary garbage, which must never reach the CNC).
292
+ // "!" feed hold "~" cycle start "^X" (0x18) soft reset "?" status request
293
+ // each as a line of its own, e.g. "!\n". Reset is rate limited.
294
+ // ";..." pendant console log entry (any text, ANSI colours stripped): kept in a ring buffer for the
295
+ // widget (GET /log), never sent to CNCjs; with -v it is printed as "pendant log: ..."
296
+ // lines dropped as non-text are reported with -v (escaped, at most one per second)
297
+ // PING -> PONG, STATUS? -> immediate status line
298
+ // anything else -> gcode
299
+ // After the pendant port opens, input is ignored for device.settleMs so the boot output of an
300
+ // ESP32 that was reset by the open is discarded.
301
+ const logBuf = [];
302
+ let logSeq = 0;
303
+
304
+ /**
305
+ * Appends a pendant console line to the ring buffer served at GET /log (capped at log.max entries).
306
+ *
307
+ * @param {string} text - the log text, without the leading ';'
308
+ * @returns {void}
309
+ */
310
+ function addPendantLog(text) {
311
+ logBuf.push({ id: ++logSeq, t: Date.now(), text });
312
+ if (logBuf.length > cfg.log.max) logBuf.splice(0, logBuf.length - cfg.log.max);
313
+ health.pendant.logLines = logSeq;
314
+ log('pendant -> log:', text);
315
+ }
316
+
317
+ const PRINTABLE = /^[\x20-\x7e]+$/;
318
+ const REALTIME = { '!': 'feedhold', '~': 'cyclestart', '\x18': 'reset' };
319
+ let rxBuf = '';
320
+ let skipLine = false;
321
+ let ignoreUntil = 0;
322
+ let lastReset = 0;
323
+
324
+ /**
325
+ * Handler for raw bytes from the pendant's serial port. Splits the stream into lines, drops overlong
326
+ * lines, and ignores everything during the settle time after the port was opened.
327
+ *
328
+ * @param {Buffer} buf - chunk read from the serial port
329
+ * @returns {void}
330
+ */
331
+ function onPendantData(buf) {
332
+ const now = Date.now();
333
+ health.pendant.lastRx = now;
334
+ if (now < ignoreUntil) {
335
+ rxBuf = '';
336
+ skipLine = false;
337
+ return;
338
+ }
339
+ const text = buf.toString('binary');
340
+ for (let i = 0; i < text.length; i++) {
341
+ const ch = text[i];
342
+ if (ch === '\n' || ch === '\r') {
343
+ const line = rxBuf.trim();
344
+ const drop = skipLine;
345
+ rxBuf = '';
346
+ skipLine = false;
347
+ if (drop) health.pendant.garbageLines++;
348
+ else if (line) onPendantLine(line);
349
+ } else if (rxBuf.length < 256) {
350
+ rxBuf += ch;
351
+ } else {
352
+ skipLine = true; // overlong line: drop it up to the next newline
353
+ }
354
+ }
355
+ }
356
+
357
+ // Only modal words (G20/G21/G90/G91), axis words and a feed, no G0/G1/G2/G3 -> this is a jog.
358
+ const JOG_RE = /^(?:G(?:20|21|90|91))+(?:[XYZABC][-+]?\d*\.?\d+|F\d*\.?\d+)+$/;
359
+
360
+ /**
361
+ * Turns a pendant jog such as `G21G91X+10F2000` into a Grbl jog command (`$J=G21G91X+10F2000`).
362
+ * Lines that are not pure jogs (no axis word, or containing G0/G1/G2/G3 etc.) are returned unchanged.
363
+ *
364
+ * @param {string} line - gcode line from the pendant
365
+ * @returns {string} the jog command, or the original line
366
+ */
367
+ function toJog(line) {
368
+ const compact = line.replace(/\s+/g, '').toUpperCase();
369
+ return JOG_RE.test(compact) && /[XYZABC]/.test(compact) ? '$J=' + compact : line;
370
+ }
371
+
372
+ const ANSI = /\x1b\[[0-9;]*[A-Za-z]/g;
373
+ let lastDropLog = 0;
374
+
375
+ /**
376
+ * Counts a rejected (non-text) pendant line and, with -v, reports it escaped (at most once a second).
377
+ *
378
+ * @param {string} raw - the rejected line as received (binary string)
379
+ * @returns {void}
380
+ */
381
+ function dropLine(raw) {
382
+ health.pendant.garbageLines++;
383
+ const now = Date.now();
384
+ if (cfg.verbose && now - lastDropLog > 1000) {
385
+ lastDropLog = now;
386
+ console.log('pendant: dropped non-text line', JSON.stringify(raw.slice(0, 60)));
387
+ }
388
+ }
389
+
390
+ /**
391
+ * Handles one complete line from the pendant: realtime commands (! ~ ^X ?), console log entries
392
+ * (; ...), PING / STATUS?, and otherwise gcode (jogs are translated to $J= for Grbl).
393
+ *
394
+ * @param {string} raw - the line without the line terminator (binary string)
395
+ * @returns {void}
396
+ */
397
+ function onPendantLine(raw) {
398
+ health.pendant.rxLines++;
399
+ if (raw === '?') return sendStatus(true);
400
+ // Grbl jog cancel: the raw byte 0x85 (also accepted as UTF-8, C2 85), or the text alias JOGCANCEL
401
+ if (raw === '\x85' || raw === '\xc2\x85' || raw.toUpperCase() === 'JOGCANCEL') return cancelJog();
402
+ if (REALTIME[raw]) {
403
+ if (raw === '\x18') {
404
+ const now = Date.now();
405
+ if (now - lastReset < 2000) return;
406
+ lastReset = now;
407
+ }
408
+ // stop means stop: jogs still held back must not fire after a feed hold or a reset
409
+ if (raw === '!' || raw === '\x18') discardHeldJog();
410
+ if (raw === '\x18') jog.inFlight = 0; // a soft reset flushes everything Grbl had not answered yet
411
+ return sendCommand(REALTIME[raw]);
412
+ }
413
+ // decode as UTF-8, drop ANSI colour codes, tabs -> spaces
414
+ let line = Buffer.from(raw, 'binary').toString('utf8').replace(ANSI, '').replace(/\t/g, ' ').trim();
415
+ if (!line) return;
416
+ if (line[0] === ';') {
417
+ // console log entry from the pendant: any text is fine, it is never sent to the controller
418
+ addPendantLog(line.replace(/^;\s?/, '').replace(/[\x00-\x1f\x7f]/g, ''));
419
+ return;
420
+ }
421
+ if (!PRINTABLE.test(line)) {
422
+ dropLine(raw);
423
+ return;
424
+ }
425
+ const upper = line.toUpperCase();
426
+ if (upper === 'PING') return sendToPendant('PONG');
427
+ if (upper === 'STATUS?') return sendStatus(true);
428
+ if (cfg.jog.translate && cfg.cncjs.controllerType === 'Grbl') {
429
+ line = toJog(line);
430
+ }
431
+ sendGcodeLine(line);
432
+ }
433
+
434
+ // ---------------------------------------------------------------- jog governor
435
+ // CNCjs hands every gcode line it is given to Grbl without waiting for the previous one to be
436
+ // answered. Grbl only has a 128 byte serial buffer (about 6 jog lines), and stops reading it while its
437
+ // planner is full, so a fast wheel makes it lose characters: jogs vanish or turn into garbage.
438
+ // The bridge therefore counts the lines it has handed to CNCjs minus the ok / error replies it sees,
439
+ // and while jog.maxInFlight is reached it merges further jogs (same axis, feed and relative mode;
440
+ // opposite directions cancel out) into one pending jog that is sent as soon as a reply frees a slot.
441
+ const jog = { inFlight: 0, lastAck: 0, pending: null };
442
+ const JOG_PARTS = /^\$J=((?:G(?:20|21|90|91))+)([XYZABC])([-+]?\d*\.?\d+)F(\d*\.?\d+)$/;
443
+
444
+ /**
445
+ * Splits a single-axis relative Grbl jog (`$J=G21G91Y-0.1F2000`) into its parts.
446
+ *
447
+ * @param {string} line - gcode line, already translated by toJog()
448
+ * @returns {?{raw: string, prefix: string, axis: string, dist: number, feed: string}} null if the line
449
+ * is not a jog that can be merged with others
450
+ */
451
+ function parseJog(line) {
452
+ const m = JOG_PARTS.exec(line);
453
+ if (!m) return null;
454
+ const words = m[1].match(/G\d+/g);
455
+ if (!words.includes('G91') || words.includes('G90')) return null;
456
+ return { raw: line, prefix: m[1], axis: m[2], dist: Number(m[3]), feed: m[4] };
457
+ }
458
+
459
+ /**
460
+ * Formats a signed jog distance without floating point noise, e.g. -0.1, +0.3, +10.
461
+ *
462
+ * @param {number} d - distance
463
+ * @returns {string}
464
+ */
465
+ function fmtDist(d) {
466
+ const s = Math.abs(d).toFixed(4).replace(/\.?0+$/, '');
467
+ return (d < 0 ? '-' : '+') + (s || '0');
468
+ }
469
+
470
+ /**
471
+ * Sends a gcode line to CNCjs and counts it as unanswered (when the jog governor is on). Jogs ($J=)
472
+ * carry `{echo: false}` as context when jog.echo is off.
473
+ *
474
+ * @param {string} line - the gcode line
475
+ * @returns {boolean} true if the line was sent
476
+ */
477
+ function writeGcode(line) {
478
+ const quiet = !cfg.jog.echo && /^\$J=/.test(line);
479
+ if (!(quiet ? sendCommand('gcode', line, { echo: false }) : sendCommand('gcode', line))) return false;
480
+ if (cfg.jog.maxInFlight > 0) {
481
+ if (jog.inFlight === 0) jog.lastAck = Date.now();
482
+ jog.inFlight++;
483
+ health.jog.inFlight = jog.inFlight;
484
+ }
485
+ health.jog.sent++;
486
+ return true;
487
+ }
488
+
489
+ /**
490
+ * Sends a gcode line from the pendant: jogs go through the governor, everything else goes straight
491
+ * out (after any held back jog, to keep the order).
492
+ *
493
+ * @param {string} line - the gcode line
494
+ * @returns {boolean} true if the line was sent or held back
495
+ */
496
+ function sendGcodeLine(line) {
497
+ const j = cfg.jog.maxInFlight > 0 ? parseJog(line) : null;
498
+ if (j) return queueJog(j);
499
+ flushJog(true);
500
+ return writeGcode(line);
501
+ }
502
+
503
+ /**
504
+ * Adds a jog to the pending one (same axis, feed and mode: distances add up, opposite jogs cancel;
505
+ * anything else replaces it) and sends it if there is room.
506
+ *
507
+ * @param {object} j - jog from parseJog()
508
+ * @returns {boolean} true
509
+ */
510
+ function queueJog(j) {
511
+ const p = jog.pending;
512
+ if (p && p.prefix === j.prefix && p.axis === j.axis && p.feed === j.feed) {
513
+ p.dist += j.dist;
514
+ p.raw = null;
515
+ health.jog.merged++;
516
+ if (Math.abs(p.dist) < 1e-9) jog.pending = null;
517
+ } else {
518
+ if (p) health.jog.discarded++;
519
+ jog.pending = j;
520
+ }
521
+ flushJog(false);
522
+ health.jog.held = !!jog.pending;
523
+ return true;
524
+ }
525
+
526
+ /**
527
+ * Sends the pending jog if the limit allows (or when forced).
528
+ *
529
+ * @param {boolean} force - send even if jog.maxInFlight is reached
530
+ * @returns {void}
531
+ */
532
+ function flushJog(force) {
533
+ const p = jog.pending;
534
+ if (!p) return;
535
+ if (!force && (cancelTimer || jog.inFlight >= cfg.jog.maxInFlight)) return;
536
+ jog.pending = null;
537
+ health.jog.held = false;
538
+ writeGcode(p.raw || '$J=' + p.prefix + p.axis + fmtDist(p.dist) + 'F' + p.feed);
539
+ }
540
+
541
+ const CANCEL_SETTLE_DEFAULT_MS = 40;
542
+ let cancelTimer = null;
543
+
544
+ /**
545
+ * Cancels the jog in progress (pendant line 0x85 or JOGCANCEL). Three steps, in this order:
546
+ * 1. the jog held back by the governor is discarded;
547
+ * 2. `feeder:stop` empties the CNCjs feeder queue right away, so no further jog line leaves for Grbl
548
+ * (a Grbl jog cancel only flushes Grbl's planner, jogs still queued in CNCjs would continue);
549
+ * 3. after jog.cancelSettleMs the `jogCancel` command (0x85) is sent. Grbl handles 0x85 the moment it
550
+ * arrives, ahead of lines still unparsed in its serial buffer, so the short wait lets those lines
551
+ * be parsed first; otherwise a long jog sent just before the cancel could start after it.
552
+ * Jogs from the pendant that arrive during the wait are held and released after the cancel.
553
+ * Lines CNCjs had already written to Grbl may still run (at most jog.maxInFlight short jogs).
554
+ *
555
+ * @returns {boolean} true if the cancel was started
556
+ */
557
+ function cancelJog() {
558
+ health.jog.cancels++;
559
+ if (cfg.cncjs.controllerType !== 'Grbl') {
560
+ log('pendant -> jog cancel ignored: only supported for Grbl');
561
+ return false;
562
+ }
563
+ discardHeldJog();
564
+ if (!sendCommand('feeder:stop')) return false;
565
+ jog.inFlight = 0; // lines removed from the feeder will never be answered
566
+ health.jog.inFlight = 0;
567
+ clearTimeout(cancelTimer);
568
+ cancelTimer = setTimeout(() => {
569
+ cancelTimer = null;
570
+ sendCommand('jogCancel');
571
+ flushJog(false);
572
+ }, Number(cfg.jog.cancelSettleMs !== undefined ? cfg.jog.cancelSettleMs : CANCEL_SETTLE_DEFAULT_MS));
573
+ return true;
574
+ }
575
+
576
+ /**
577
+ * Throws away a jog that is being held back (after a feed hold or reset).
578
+ *
579
+ * @returns {void}
580
+ */
581
+ function discardHeldJog() {
582
+ if (jog.pending) health.jog.discarded++;
583
+ jog.pending = null;
584
+ health.jog.held = false;
585
+ }
586
+
587
+ /**
588
+ * Forgets all jog accounting (CNCjs connection or CNC port changed): nothing stale is replayed.
589
+ *
590
+ * @returns {void}
591
+ */
592
+ function resetJogs() {
593
+ jog.inFlight = 0;
594
+ jog.pending = null;
595
+ health.jog.inFlight = 0;
596
+ health.jog.held = false;
597
+ }
598
+
599
+ /**
600
+ * Handles a line CNCjs read from the controller: every ok / error reply frees a slot and may release
601
+ * the held jog.
602
+ *
603
+ * @param {*} data - the line (string) as emitted by CNCjs
604
+ * @returns {void}
605
+ */
606
+ function onControllerLine(data) {
607
+ const line = String(data === null || data === undefined ? '' : data).trim();
608
+ if (line !== 'ok' && line.slice(0, 6).toLowerCase() !== 'error:') return;
609
+ if (jog.inFlight > 0) jog.inFlight--;
610
+ health.jog.inFlight = jog.inFlight;
611
+ jog.lastAck = Date.now();
612
+ flushJog(false);
613
+ health.jog.held = !!jog.pending;
614
+ }
615
+
616
+ // Lines the controller never answers (lost in transit) would keep the counter up for good.
617
+ const jogTimer = setInterval(() => {
618
+ if (jog.inFlight > 0 && Date.now() - jog.lastAck > cfg.jog.stallMs) {
619
+ health.jog.stalls++;
620
+ console.warn('Controller did not acknowledge ' + jog.inFlight + ' gcode line(s) for ' + cfg.jog.stallMs +
621
+ ' ms: they may have been lost. [' + health.jog.stalls + ' stall(s) so far]');
622
+ jog.inFlight = 0;
623
+ health.jog.inFlight = 0;
624
+ }
625
+ flushJog(false);
626
+ }, 250);
627
+
628
+ // ---------------------------------------------------------------- CNCjs -> pendant
629
+ /**
630
+ * Converts a value to a number, treating anything non-numeric as 0.
631
+ *
632
+ * @param {*} v
633
+ * @returns {number}
634
+ */
635
+ const num = (v) => Number(v) || 0;
636
+ /**
637
+ * Subtracts two {x, y, z} positions (a - b).
638
+ *
639
+ * @param {{x: (number|string), y: (number|string), z: (number|string)}} a
640
+ * @param {{x: (number|string), y: (number|string), z: (number|string)}} b
641
+ * @returns {{x: number, y: number, z: number}}
642
+ */
643
+ 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) });
644
+ /**
645
+ * Adds two {x, y, z} positions (a + b).
646
+ *
647
+ * @param {{x: (number|string), y: (number|string), z: (number|string)}} a
648
+ * @param {{x: (number|string), y: (number|string), z: (number|string)}} b
649
+ * @returns {{x: number, y: number, z: number}}
650
+ */
651
+ 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) });
652
+
653
+ /**
654
+ * Returns machine and work position. Grbl 1.1 reports only one of them plus the work coordinate
655
+ * offset (WCO) now and then, so the missing one is derived: WPos = MPos - WCO.
656
+ *
657
+ * @param {object} st - the `status` object of the CNCjs controller state
658
+ * @returns {{mpos: ?object, wpos: ?object}} positions, null where they cannot be determined yet
659
+ */
660
+ function positions(st) {
661
+ const wco = st.wco || lastWco;
662
+ let mpos = st.mpos || null;
663
+ let wpos = st.wpos || null;
664
+ if (!wpos && mpos && wco) wpos = sub(mpos, wco);
665
+ if (!mpos && wpos && wco) mpos = add(wpos, wco);
666
+ return { mpos, wpos };
667
+ }
668
+
669
+ /**
670
+ * Builds the current machine status from the latest CNCjs controller and sender state.
671
+ *
672
+ * @returns {{connected: boolean, state: string, mpos: ?object, wpos: ?object, feed: ?number,
673
+ * spindle: ?number, sender: object}}
674
+ */
675
+ function snapshot() {
676
+ const connected = cncReady();
677
+ const st = (store.controller.state && store.controller.state.status) || {};
678
+ const pos = positions(st);
679
+ const snd = store.sender.status || {};
680
+ return {
681
+ connected,
682
+ state: connected ? (st.activeState || 'Unknown') : 'Disconnected',
683
+ mpos: pos.mpos,
684
+ wpos: pos.wpos,
685
+ feed: st.feedrate !== undefined ? st.feedrate : null,
686
+ spindle: st.spindle !== undefined ? st.spindle : null,
687
+ sender: { name: snd.name || null, total: snd.total || 0, sent: snd.sent || 0,
688
+ received: snd.received || 0, hold: !!snd.hold }
689
+ };
690
+ }
691
+
692
+ /**
693
+ * Formats a status snapshot as the line sent to the pendant, either Grbl style
694
+ * (`<Idle|MPos:x,y,z|WPos:x,y,z|FS:feed,spindle>`) or JSON, depending on status.format.
695
+ *
696
+ * @param {object} s - snapshot from snapshot()
697
+ * @returns {string} the status line without terminator
698
+ */
699
+ function formatStatus(s) {
700
+ if (cfg.status.format === 'json') {
701
+ return JSON.stringify(Object.assign({ t: 'status' }, s));
702
+ }
703
+ const d = cfg.status.decimals;
704
+ const pos = (p) => [p.x, p.y, p.z].map((n) => (Number(n) || 0).toFixed(d)).join(',');
705
+ const parts = [s.state];
706
+ if (s.connected) {
707
+ if (s.mpos) parts.push('MPos:' + pos(s.mpos));
708
+ if (s.wpos) parts.push('WPos:' + pos(s.wpos));
709
+ if (s.feed !== null) parts.push('FS:' + (Number(s.feed) || 0) + ',' + (Number(s.spindle) || 0));
710
+ }
711
+ return '<' + parts.join('|') + '>';
712
+ }
713
+
714
+ let lastLine = '';
715
+ let lastStatusAt = 0;
716
+ let statusQueued = false;
717
+
718
+ /**
719
+ * Sends the current status to the pendant if one is due: forced, at least every status.intervalMs,
720
+ * when the values changed and status.minGapMs has passed, or when one was queued with queueStatus().
721
+ *
722
+ * @param {boolean} [force=false] - send regardless of timing
723
+ * @returns {void}
724
+ */
725
+ function sendStatus(force) {
726
+ if (!cfg.device.send) return;
727
+ const line = formatStatus(snapshot());
728
+ const now = Date.now();
729
+ const gapOk = now - lastStatusAt >= cfg.status.minGapMs;
730
+ const due = now - lastStatusAt >= cfg.status.intervalMs;
731
+ const changed = line !== lastLine && gapOk;
732
+ if (force || due || changed || (statusQueued && gapOk)) {
733
+ if (sendToPendant(line, changed)) {
734
+ lastLine = line;
735
+ lastStatusAt = now;
736
+ statusQueued = false;
737
+ }
738
+ }
739
+ }
740
+
741
+ /**
742
+ * Asks for a status line to go to the pendant soon: now if status.minGapMs has passed since the last
743
+ * one, otherwise as soon as it has (the periodic timer sends it). Many requests in a row cost one line.
744
+ *
745
+ * @returns {void}
746
+ */
747
+ function queueStatus() {
748
+ statusQueued = true;
749
+ sendStatus(false);
750
+ }
751
+
752
+ /**
753
+ * Writes one line to the pendant's serial port.
754
+ *
755
+ * @param {string} text - the line, without terminator (a newline is added)
756
+ * @param {boolean} [should_log=false] - print the line when -v is on
757
+ * @returns {boolean} false if the pendant port is not open
758
+ */
759
+ function sendToPendant(text, should_log=false) {
760
+ if (!cfg.device.send) return false;
761
+ const port = pendantPort;
762
+ if (!port || !port.isOpen) return false;
763
+ if(should_log) log('cncjs -> ', 'pendant', text);
764
+ port.write(text + '\n', (err) => {
765
+ if (err) noteError(err);
766
+ });
767
+ health.pendant.lastTx = Date.now();
768
+ health.pendant.txLines++;
769
+ return true;
770
+ }
771
+
772
+ const statusTimer = setInterval(() => sendStatus(false), Math.max(10, Math.min(100, cfg.status.minGapMs, cfg.status.intervalMs)));
773
+
774
+ // ---------------------------------------------------------------- pendant serial link
775
+ let pendantPort = null;
776
+ let reconnectTimer = null;
777
+
778
+ /**
779
+ * Records a pendant serial error in the health data and prints it.
780
+ *
781
+ * @param {Error} err
782
+ * @returns {void}
783
+ */
784
+ function noteError(err) {
785
+ health.pendant.errors++;
786
+ health.pendant.lastError = err.message;
787
+ console.error('Pendant error:', err.message);
788
+ }
789
+
790
+ /**
791
+ * Schedules a reopen of the pendant serial port after device.reconnectMs (at most one pending).
792
+ *
793
+ * @returns {void}
794
+ */
795
+ function scheduleReconnect() {
796
+ if (shuttingDown || reconnectTimer) return;
797
+ reconnectTimer = setTimeout(() => {
798
+ reconnectTimer = null;
799
+ health.pendant.reconnects++;
800
+ openPendant();
801
+ }, cfg.device.reconnectMs);
802
+ }
803
+
804
+ /**
805
+ * Opens the pendant's serial port and wires up its events. Failures and closes schedule a reconnect.
806
+ * After a successful open, pendant input is ignored for device.settleMs and a status line is sent.
807
+ *
808
+ * @returns {void}
809
+ */
810
+ function openPendant() {
811
+ const port = new SerialPort({
812
+ path: cfg.device.path,
813
+ baudRate: Number(cfg.device.baudRate),
814
+ autoOpen: false,
815
+ dataBits: 8,
816
+ stopBits: 1,
817
+ parity: 'none',
818
+ rtscts: false,
819
+ xon: false,
820
+ xoff: false,
821
+ xany: false,
822
+ hupcl: !!cfg.device.hupcl
823
+ });
824
+ pendantPort = port;
825
+ port.on('data', onPendantData);
826
+ port.on('error', noteError);
827
+ port.on('close', () => {
828
+ health.pendant.connected = false;
829
+ if (!shuttingDown) console.log('Pendant port closed');
830
+ scheduleReconnect();
831
+ });
832
+ port.open((err) => {
833
+ if (err) {
834
+ noteError(err);
835
+ scheduleReconnect();
836
+ return;
837
+ }
838
+ rxBuf = '';
839
+ skipLine = false;
840
+ ignoreUntil = Date.now() + Number(cfg.device.settleMs || 0);
841
+ const lines = {};
842
+ if (cfg.device.dtr !== null && cfg.device.dtr !== undefined) lines.dtr = !!cfg.device.dtr;
843
+ if (cfg.device.rts !== null && cfg.device.rts !== undefined) lines.rts = !!cfg.device.rts;
844
+ if (Object.keys(lines).length) {
845
+ port.set(lines, (setErr) => { if (setErr) noteError(setErr); });
846
+ }
847
+ health.pendant.connected = true;
848
+ health.pendant.lastError = null;
849
+ console.log('Pendant connected on ' + cfg.device.path);
850
+ sendStatus(true);
851
+ });
852
+ }
853
+
854
+ // ---------------------------------------------------------------- health endpoint
855
+ /**
856
+ * Builds the JSON served at GET /status: link health of the pendant and CNCjs, the last command
857
+ * sent, and the current machine status.
858
+ *
859
+ * @returns {object}
860
+ */
861
+ function healthReport() {
862
+ const now = Date.now();
863
+ const age = (t) => (t ? now - t : null);
864
+ return {
865
+ ok: health.pendant.connected && cncReady(),
866
+ version: pkg.version,
867
+ uptimeMs: now - health.startedAt,
868
+ pendant: Object.assign({}, health.pendant, { sendEnabled: !!cfg.device.send, lastRxAgeMs: age(health.pendant.lastRx),
869
+ lastTxAgeMs: age(health.pendant.lastTx) }),
870
+ cncjs: health.cncjs,
871
+ jog: health.jog,
872
+ lastCommand: health.lastCommand,
873
+ status: snapshot()
874
+ };
875
+ }
876
+
877
+ let httpServer = null;
878
+ if (cfg.http.enabled) {
879
+ httpServer = http.createServer((req, res) => {
880
+ const url = new URL(req.url, 'http://localhost');
881
+ const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
882
+ if (url.pathname === '/' || url.pathname === '/status') {
883
+ res.writeHead(200, headers);
884
+ res.end(JSON.stringify(healthReport()));
885
+ } else if (url.pathname === '/log') {
886
+ // GET /log?since=<id> -> entries with id > since (poll with the last id you saw)
887
+ const since = Number(url.searchParams.get('since')) || 0;
888
+ res.writeHead(200, headers);
889
+ res.end(JSON.stringify({ last: logSeq, entries: logBuf.filter((e) => e.id > since) }));
890
+ } else {
891
+ res.writeHead(404);
892
+ res.end();
893
+ }
894
+ });
895
+ httpServer.on('error', (err) => console.error('Health endpoint error:', err.message));
896
+ httpServer.listen(cfg.http.port, cfg.http.host, () =>
897
+ console.log('Health endpoint on http://' + cfg.http.host + ':' + cfg.http.port + '/status'));
898
+ }
899
+
900
+ // ---------------------------------------------------------------- lifecycle
901
+ /**
902
+ * Stops timers and closes the CNCjs socket, the pendant port and the HTTP server, then exits.
903
+ * Called on SIGINT / SIGTERM.
904
+ *
905
+ * @returns {void}
906
+ */
907
+ function shutdown() {
908
+ if (shuttingDown) return;
909
+ shuttingDown = true;
910
+ clearInterval(statusTimer);
911
+ clearInterval(jogTimer);
912
+ clearTimeout(cancelTimer);
913
+ clearTimeout(reconnectTimer);
914
+ socket.close();
915
+ if (httpServer) httpServer.close();
916
+ if (pendantPort && pendantPort.isOpen) pendantPort.close();
917
+ setTimeout(() => process.exit(0), 300);
918
+ }
919
+ process.on('SIGINT', shutdown);
920
+ process.on('SIGTERM', shutdown);
921
+
922
+ openPendant();