cncjs-handwheel 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -8
- package/bin/cncjs-handwheel +349 -30
- package/cncjs-handwheel.config.example.json +40 -0
- package/index.js +311 -62
- package/lib/service.js +109 -8
- package/package.json +6 -3
- package/widget/dist/assets/index-DjeoyRHc.css +1 -0
- package/widget/dist/assets/index-rdV6NzC9.js +40 -0
- package/widget/dist/index.html +13 -0
package/bin/cncjs-handwheel
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
// Health/status of both links is exposed as JSON on http://127.0.0.1:8001/status (configurable).
|
|
8
8
|
// Pendant logs can be accessed on http://127.0.0.1:8001/log (configurable)
|
|
9
9
|
|
|
10
|
-
// "install-service" / "uninstall-service": set up the systemd unit (and udev rule), then exit
|
|
10
|
+
// "install-service" / "uninstall-service": set up the systemd unit (and udev rule or Bluetooth binding), then exit
|
|
11
11
|
const subcommand = process.argv[2];
|
|
12
12
|
if (subcommand === 'install-service' || subcommand === 'uninstall-service') {
|
|
13
13
|
require('../lib/service')(subcommand, process.argv.slice(3));
|
|
@@ -32,13 +32,19 @@ const DEFAULTS = {
|
|
|
32
32
|
controllerType: 'Grbl', // Grbl | Smoothie (TinyG: state is not mapped yet)
|
|
33
33
|
socketAddress: 'localhost',
|
|
34
34
|
socketPort: 8000,
|
|
35
|
-
accessTokenLifetime: '30d'
|
|
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)
|
|
36
41
|
},
|
|
37
42
|
device: {
|
|
38
43
|
path: '/dev/pendant', // the pendant's serial port (e.g. /dev/ttyACM0 or /dev/rfcomm0)
|
|
39
44
|
baudRate: 115200,
|
|
40
45
|
reconnectMs: 3000,
|
|
41
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)
|
|
42
48
|
|
|
43
49
|
// Modem-control lines. The CH340 + auto-reset transistors wire DTR/RTS to EN/IO0, so on Linux
|
|
44
50
|
// the DTR/RTS toggling around open/close can reset the ESP32 or drop it into download mode.
|
|
@@ -48,16 +54,21 @@ const DEFAULTS = {
|
|
|
48
54
|
},
|
|
49
55
|
status: {
|
|
50
56
|
format: 'grbl', // 'grbl' -> <Idle|MPos:..|WPos:..|FS:..> 'json' -> {"t":"status",...}
|
|
51
|
-
intervalMs:
|
|
52
|
-
minGapMs:
|
|
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)
|
|
53
59
|
pollAfterCommand: true, // ask CNCjs/Grbl for a fresh status report after every pendant command
|
|
54
60
|
decimals: 3
|
|
55
61
|
},
|
|
56
62
|
http: { enabled: true, host: '127.0.0.1', port: 8001 },
|
|
57
63
|
|
|
58
|
-
// Grbl 1.1 only: rewrite "G21G91X+10F2000" into "$J=G21G91X+10F2000" so a pendant jog does not
|
|
64
|
+
// translate (Grbl 1.1 only): rewrite "G21G91X+10F2000" into "$J=G21G91X+10F2000" so a pendant jog does not
|
|
59
65
|
// leave CNCjs/Grbl stuck in relative mode (and so jogs go through Grbl's jog queue)
|
|
60
|
-
|
|
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 },
|
|
61
72
|
|
|
62
73
|
// pendant console lines ("; ...") are kept here for the widget instead of being sent to Grbl
|
|
63
74
|
log: { max: 500 },
|
|
@@ -72,6 +83,7 @@ program
|
|
|
72
83
|
.name('cncjs-handwheel')
|
|
73
84
|
.version(pkg.version)
|
|
74
85
|
.option('-l, --list', 'list available serial ports then exit')
|
|
86
|
+
.option('--widget-path', 'print the directory of the built CNCjs widget (for cncjs --mount) then exit')
|
|
75
87
|
.option('-c, --config <file>', 'config file (default: ' + DEFAULT_CONFIG_FILE + ' if present)')
|
|
76
88
|
.option('-s, --secret <secret>', 'CNCjs secret (default: $CNCJS_SECRET or ~/.cncrc)')
|
|
77
89
|
.option('-p, --port <port>', 'CNC controller port as known to CNCjs, e.g. /dev/ttyUSB0')
|
|
@@ -82,10 +94,22 @@ program
|
|
|
82
94
|
.option('--pendant-port <path>', 'serial port of the pendant')
|
|
83
95
|
.option('--pendant-baudrate <baudrate>', 'baud rate of the pendant')
|
|
84
96
|
.option('-v, --verbose', 'log pendant events and the commands sent to CNCjs')
|
|
85
|
-
.option('--trace', 'also log all controller traffic (very noisy)')
|
|
97
|
+
.option('--trace', 'also log all controller traffic (very noisy)')
|
|
98
|
+
.option('--no-pendant-send', 'do not write anything to the pendant (same as device.send: false)')
|
|
99
|
+
.option('--no-jog-translate', 'send pendant jogs as plain gcode instead of $J= (same as jog.translate: false)');
|
|
86
100
|
program.parse(process.argv);
|
|
87
101
|
const cli = program.opts();
|
|
88
102
|
|
|
103
|
+
if (cli.widgetPath) {
|
|
104
|
+
const dir = path.join(__dirname, '..', 'widget', 'dist');
|
|
105
|
+
if (!fs.existsSync(path.join(dir, 'index.html'))) {
|
|
106
|
+
console.error('The widget is not built: ' + dir + ' has no index.html. Run `npm run build:widget` in the package directory.');
|
|
107
|
+
process.exit(1);
|
|
108
|
+
}
|
|
109
|
+
console.log(dir);
|
|
110
|
+
process.exit(0);
|
|
111
|
+
}
|
|
112
|
+
|
|
89
113
|
/**
|
|
90
114
|
* Tells whether a value is a plain object (not null, not an array).
|
|
91
115
|
*
|
|
@@ -137,6 +161,8 @@ if (cli.pendantPort) cfg.device.path = cli.pendantPort;
|
|
|
137
161
|
if (cli.pendantBaudrate) cfg.device.baudRate = cli.pendantBaudrate;
|
|
138
162
|
if (cli.verbose) cfg.verbose = true;
|
|
139
163
|
if (cli.trace) cfg.trace = true;
|
|
164
|
+
if (cli.pendantSend === false) cfg.device.send = false;
|
|
165
|
+
if (cli.jogTranslate === false) cfg.jog.translate = false;
|
|
140
166
|
|
|
141
167
|
if (!cfg.cncjs.port) { console.error('Missing CNC controller port (cncjs.port / --port)'); process.exit(1); }
|
|
142
168
|
if (!cfg.device.path) { console.error('Missing pendant port (device.path / --pendant-port). Try --list'); process.exit(1); }
|
|
@@ -147,9 +173,10 @@ const store = { controller: { state: {}, settings: {} }, sender: { status: {} }
|
|
|
147
173
|
const health = {
|
|
148
174
|
startedAt: Date.now(),
|
|
149
175
|
pendant: { path: cfg.device.path, connected: false, lastRx: null, lastTx: null, rxLines: 0, txLines: 0,
|
|
150
|
-
reconnects: 0, errors: 0, lastError: null, logLines: 0, garbageLines: 0 },
|
|
176
|
+
reconnects: 0, errors: 0, lastError: null, logLines: 0, garbageLines: 0, link: null, info: null },
|
|
151
177
|
cncjs: { socketConnected: false, portOpen: false, port: cfg.cncjs.port, controllerType: cfg.cncjs.controllerType,
|
|
152
|
-
lastError: null },
|
|
178
|
+
lastError: null, droppedCommands: 0 },
|
|
179
|
+
jog: { sent: 0, merged: 0, discarded: 0, stalls: 0, cancels: 0, inFlight: 0, held: false, lastAt: null },
|
|
153
180
|
lastCommand: null
|
|
154
181
|
};
|
|
155
182
|
|
|
@@ -172,9 +199,14 @@ const socket = connectToCncjs(cncOpts, (err) => {
|
|
|
172
199
|
});
|
|
173
200
|
|
|
174
201
|
socket.on('connect', () => { health.cncjs.socketConnected = true; });
|
|
175
|
-
socket.on('disconnect', () => { health.cncjs.socketConnected = false; health.cncjs.portOpen = false; });
|
|
176
|
-
socket.on('serialport:
|
|
177
|
-
socket.on('serialport:
|
|
202
|
+
socket.on('disconnect', () => { health.cncjs.socketConnected = false; health.cncjs.portOpen = false; resetJogs(); });
|
|
203
|
+
socket.on('serialport:read', onControllerLine);
|
|
204
|
+
socket.on('serialport:open', () => {
|
|
205
|
+
if (!health.cncjs.portOpen) { lastWco = null; resetJogs(); } // a keepalive confirmation must not discard the work offset
|
|
206
|
+
health.cncjs.portOpen = true;
|
|
207
|
+
health.cncjs.lastError = null;
|
|
208
|
+
});
|
|
209
|
+
socket.on('serialport:close', () => { health.cncjs.portOpen = false; resetJogs(); });
|
|
178
210
|
|
|
179
211
|
['Grbl', 'Smoothie', 'TinyG'].forEach((type) => {
|
|
180
212
|
let dumped = false;
|
|
@@ -197,7 +229,26 @@ let lastWco = null; // Grbl 1.1 only reports MPos *or* WPos, plus WCO now and th
|
|
|
197
229
|
*
|
|
198
230
|
* @returns {boolean}
|
|
199
231
|
*/
|
|
200
|
-
const cncReady = () =>
|
|
232
|
+
const cncReady = () => socket.connected && health.cncjs.portOpen;
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Records and reports a command that could not be sent (at most one console line per second).
|
|
236
|
+
*
|
|
237
|
+
* @param {string} name - the CNCjs command that was dropped
|
|
238
|
+
* @param {Array} args - its arguments
|
|
239
|
+
* @returns {void}
|
|
240
|
+
*/
|
|
241
|
+
let lastDropWarn = 0;
|
|
242
|
+
const fmtArgs = (args) => args.map((a) => (a !== null && typeof a === 'object' ? JSON.stringify(a) : a));
|
|
243
|
+
function noteDropped(name, args) {
|
|
244
|
+
health.cncjs.droppedCommands++;
|
|
245
|
+
const now = Date.now();
|
|
246
|
+
if (now - lastDropWarn < 1000) return;
|
|
247
|
+
lastDropWarn = now;
|
|
248
|
+
console.warn('Dropped pendant command (' + [name].concat(fmtArgs(args)).join(' ') + '): ' +
|
|
249
|
+
(socket.connected ? 'the CNC port is not open' : 'not connected to CNCjs') +
|
|
250
|
+
' [' + health.cncjs.droppedCommands + ' dropped so far]');
|
|
251
|
+
}
|
|
201
252
|
|
|
202
253
|
/**
|
|
203
254
|
* Sends a command to the CNC controller through CNCjs and answers the pendant with a status line.
|
|
@@ -210,13 +261,17 @@ const cncReady = () => health.cncjs.socketConnected && health.cncjs.portOpen;
|
|
|
210
261
|
*/
|
|
211
262
|
function sendCommand(name, ...args) {
|
|
212
263
|
if (!cncReady()) {
|
|
264
|
+
noteDropped(name, args);
|
|
213
265
|
sendToPendant('ERR:CNCJS_NOT_READY');
|
|
214
|
-
|
|
266
|
+
queueStatus();
|
|
215
267
|
return false;
|
|
216
268
|
}
|
|
217
269
|
health.lastCommand = { at: Date.now(), name, args };
|
|
218
|
-
log('pendant ->', name, ...args);
|
|
219
|
-
socket.emit('command', cfg.cncjs.port, name, ...args)
|
|
270
|
+
log('pendant ->', name, ...fmtArgs(args));
|
|
271
|
+
if (!socket.emit('command', cfg.cncjs.port, name, ...args)) {
|
|
272
|
+
noteDropped(name, args);
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
220
275
|
answerCommand();
|
|
221
276
|
return true;
|
|
222
277
|
}
|
|
@@ -226,15 +281,16 @@ function sendCommand(name, ...args) {
|
|
|
226
281
|
// a few tens of ms (forwarded by the :state handler).
|
|
227
282
|
let lastPoll = 0;
|
|
228
283
|
/**
|
|
229
|
-
* Answers a command from the pendant with a status line
|
|
230
|
-
*
|
|
284
|
+
* Answers a command from the pendant with a status line (within status.minGapMs, so a burst of
|
|
285
|
+
* commands does not flood the pendant), and asks the controller for a fresh status report (at most
|
|
286
|
+
* once per status.minGapMs) so the new position follows shortly after.
|
|
231
287
|
*
|
|
232
288
|
* @returns {void}
|
|
233
289
|
*/
|
|
234
290
|
function answerCommand() {
|
|
235
|
-
|
|
291
|
+
queueStatus();
|
|
236
292
|
const now = Date.now();
|
|
237
|
-
if (cfg.status.pollAfterCommand && now - lastPoll >= 50) {
|
|
293
|
+
if (cfg.status.pollAfterCommand && now - lastPoll >= Math.max(50, cfg.status.minGapMs)) {
|
|
238
294
|
lastPoll = now;
|
|
239
295
|
socket.emit('command', cfg.cncjs.port, 'statusreport');
|
|
240
296
|
}
|
|
@@ -342,6 +398,46 @@ function dropLine(raw) {
|
|
|
342
398
|
}
|
|
343
399
|
}
|
|
344
400
|
|
|
401
|
+
/**
|
|
402
|
+
* Parses the pendant's own status report `[HW:bat=74,chg=0,eta=13200,st=ok]` and stores it for /status.
|
|
403
|
+
* Keys: bat 0-100 (%), chg 1 while charging, eta seconds to full (charging) or empty, st ok|warn|err.
|
|
404
|
+
* All are optional and unknown keys are ignored, so the firmware can grow. Never sent to the controller.
|
|
405
|
+
*
|
|
406
|
+
* @param {string} line - trimmed line from the pendant
|
|
407
|
+
* @returns {boolean} true if the line was a pendant status report (valid or not)
|
|
408
|
+
*/
|
|
409
|
+
function parsePendantReport(line) {
|
|
410
|
+
const m = /^\[HW:([^\]]*)\]$/.exec(line);
|
|
411
|
+
if (!m) return false;
|
|
412
|
+
const info = {}; // each report replaces the last one: a key that is left out is unknown, not unchanged
|
|
413
|
+
m[1].split(',').forEach((pair) => {
|
|
414
|
+
const [k, v] = pair.split('=').map((x) => x.trim());
|
|
415
|
+
const num = /^\d+$/.test(v) ? Number(v) : null;
|
|
416
|
+
if (k === 'bat' && num !== null && num <= 100) info.bat = num;
|
|
417
|
+
else if (k === 'chg' && (v === '0' || v === '1')) info.chg = v === '1';
|
|
418
|
+
else if (k === 'eta' && num !== null) info.eta = num;
|
|
419
|
+
else if (k === 'st' && /^(ok|warn|err)$/.test(v)) info.st = v;
|
|
420
|
+
});
|
|
421
|
+
info.at = Date.now();
|
|
422
|
+
health.pendant.info = info;
|
|
423
|
+
return true;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/**
|
|
427
|
+
* Works out whether the pendant port is USB or Bluetooth (rfcomm), looking through the udev symlink
|
|
428
|
+
* (/dev/pendant) at the real device node.
|
|
429
|
+
*
|
|
430
|
+
* @param {string} devPath - configured pendant port
|
|
431
|
+
* @returns {?string} 'bluetooth', 'usb' or null if it cannot be told
|
|
432
|
+
*/
|
|
433
|
+
function detectLink(devPath) {
|
|
434
|
+
let real = devPath;
|
|
435
|
+
try { real = fs.realpathSync(devPath); } catch (err) { /* keep the configured path */ }
|
|
436
|
+
if (/rfcomm/i.test(real)) return 'bluetooth';
|
|
437
|
+
if (/tty(USB|ACM)/i.test(real) || /usb/i.test(real)) return 'usb';
|
|
438
|
+
return null;
|
|
439
|
+
}
|
|
440
|
+
|
|
345
441
|
/**
|
|
346
442
|
* Handles one complete line from the pendant: realtime commands (! ~ ^X ?), console log entries
|
|
347
443
|
* (; ...), PING / STATUS?, and otherwise gcode (jogs are translated to $J= for Grbl).
|
|
@@ -352,12 +448,17 @@ function dropLine(raw) {
|
|
|
352
448
|
function onPendantLine(raw) {
|
|
353
449
|
health.pendant.rxLines++;
|
|
354
450
|
if (raw === '?') return sendStatus(true);
|
|
451
|
+
// Grbl jog cancel: the raw byte 0x85 (also accepted as UTF-8, C2 85), or the text alias JOGCANCEL
|
|
452
|
+
if (raw === '\x85' || raw === '\xc2\x85' || raw.toUpperCase() === 'JOGCANCEL') return cancelJog();
|
|
355
453
|
if (REALTIME[raw]) {
|
|
356
454
|
if (raw === '\x18') {
|
|
357
455
|
const now = Date.now();
|
|
358
456
|
if (now - lastReset < 2000) return;
|
|
359
457
|
lastReset = now;
|
|
360
458
|
}
|
|
459
|
+
// stop means stop: jogs still held back must not fire after a feed hold or a reset
|
|
460
|
+
if (raw === '!' || raw === '\x18') discardHeldJog();
|
|
461
|
+
if (raw === '\x18') jog.inFlight = 0; // a soft reset flushes everything Grbl had not answered yet
|
|
361
462
|
return sendCommand(REALTIME[raw]);
|
|
362
463
|
}
|
|
363
464
|
// decode as UTF-8, drop ANSI colour codes, tabs -> spaces
|
|
@@ -372,15 +473,211 @@ function onPendantLine(raw) {
|
|
|
372
473
|
dropLine(raw);
|
|
373
474
|
return;
|
|
374
475
|
}
|
|
476
|
+
if (parsePendantReport(line)) return;
|
|
375
477
|
const upper = line.toUpperCase();
|
|
376
478
|
if (upper === 'PING') return sendToPendant('PONG');
|
|
377
479
|
if (upper === 'STATUS?') return sendStatus(true);
|
|
378
480
|
if (cfg.jog.translate && cfg.cncjs.controllerType === 'Grbl') {
|
|
379
481
|
line = toJog(line);
|
|
380
482
|
}
|
|
381
|
-
|
|
483
|
+
sendGcodeLine(line);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// ---------------------------------------------------------------- jog governor
|
|
487
|
+
// CNCjs hands every gcode line it is given to Grbl without waiting for the previous one to be
|
|
488
|
+
// answered. Grbl only has a 128 byte serial buffer (about 6 jog lines), and stops reading it while its
|
|
489
|
+
// planner is full, so a fast wheel makes it lose characters: jogs vanish or turn into garbage.
|
|
490
|
+
// The bridge therefore counts the lines it has handed to CNCjs minus the ok / error replies it sees,
|
|
491
|
+
// and while jog.maxInFlight is reached it merges further jogs (same axis, feed and relative mode;
|
|
492
|
+
// opposite directions cancel out) into one pending jog that is sent as soon as a reply frees a slot.
|
|
493
|
+
const jog = { inFlight: 0, lastAck: 0, pending: null };
|
|
494
|
+
const JOG_PARTS = /^\$J=((?:G(?:20|21|90|91))+)([XYZABC])([-+]?\d*\.?\d+)F(\d*\.?\d+)$/;
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Splits a single-axis relative Grbl jog (`$J=G21G91Y-0.1F2000`) into its parts.
|
|
498
|
+
*
|
|
499
|
+
* @param {string} line - gcode line, already translated by toJog()
|
|
500
|
+
* @returns {?{raw: string, prefix: string, axis: string, dist: number, feed: string}} null if the line
|
|
501
|
+
* is not a jog that can be merged with others
|
|
502
|
+
*/
|
|
503
|
+
function parseJog(line) {
|
|
504
|
+
const m = JOG_PARTS.exec(line);
|
|
505
|
+
if (!m) return null;
|
|
506
|
+
const words = m[1].match(/G\d+/g);
|
|
507
|
+
if (!words.includes('G91') || words.includes('G90')) return null;
|
|
508
|
+
return { raw: line, prefix: m[1], axis: m[2], dist: Number(m[3]), feed: m[4] };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Formats a signed jog distance without floating point noise, e.g. -0.1, +0.3, +10.
|
|
513
|
+
*
|
|
514
|
+
* @param {number} d - distance
|
|
515
|
+
* @returns {string}
|
|
516
|
+
*/
|
|
517
|
+
function fmtDist(d) {
|
|
518
|
+
const s = Math.abs(d).toFixed(4).replace(/\.?0+$/, '');
|
|
519
|
+
return (d < 0 ? '-' : '+') + (s || '0');
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* Sends a gcode line to CNCjs and counts it as unanswered (when the jog governor is on). Jogs ($J=)
|
|
524
|
+
* carry `{echo: false}` as context when jog.echo is off.
|
|
525
|
+
*
|
|
526
|
+
* @param {string} line - the gcode line
|
|
527
|
+
* @returns {boolean} true if the line was sent
|
|
528
|
+
*/
|
|
529
|
+
function writeGcode(line) {
|
|
530
|
+
const quiet = !cfg.jog.echo && /^\$J=/.test(line);
|
|
531
|
+
if (!(quiet ? sendCommand('gcode', line, { echo: false }) : sendCommand('gcode', line))) return false;
|
|
532
|
+
if (cfg.jog.maxInFlight > 0) {
|
|
533
|
+
if (jog.inFlight === 0) jog.lastAck = Date.now();
|
|
534
|
+
jog.inFlight++;
|
|
535
|
+
health.jog.inFlight = jog.inFlight;
|
|
536
|
+
}
|
|
537
|
+
health.jog.sent++;
|
|
538
|
+
return true;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Sends a gcode line from the pendant: jogs go through the governor, everything else goes straight
|
|
543
|
+
* out (after any held back jog, to keep the order).
|
|
544
|
+
*
|
|
545
|
+
* @param {string} line - the gcode line
|
|
546
|
+
* @returns {boolean} true if the line was sent or held back
|
|
547
|
+
*/
|
|
548
|
+
function sendGcodeLine(line) {
|
|
549
|
+
const j = cfg.jog.maxInFlight > 0 ? parseJog(line) : null;
|
|
550
|
+
if (j) return queueJog(j);
|
|
551
|
+
flushJog(true);
|
|
552
|
+
return writeGcode(line);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Adds a jog to the pending one (same axis, feed and mode: distances add up, opposite jogs cancel;
|
|
557
|
+
* anything else replaces it) and sends it if there is room.
|
|
558
|
+
*
|
|
559
|
+
* @param {object} j - jog from parseJog()
|
|
560
|
+
* @returns {boolean} true
|
|
561
|
+
*/
|
|
562
|
+
function queueJog(j) {
|
|
563
|
+
health.jog.lastAt = Date.now(); // the wheel is being turned (the widget shows "Jog" for a moment)
|
|
564
|
+
const p = jog.pending;
|
|
565
|
+
if (p && p.prefix === j.prefix && p.axis === j.axis && p.feed === j.feed) {
|
|
566
|
+
p.dist += j.dist;
|
|
567
|
+
p.raw = null;
|
|
568
|
+
health.jog.merged++;
|
|
569
|
+
if (Math.abs(p.dist) < 1e-9) jog.pending = null;
|
|
570
|
+
} else {
|
|
571
|
+
if (p) health.jog.discarded++;
|
|
572
|
+
jog.pending = j;
|
|
573
|
+
}
|
|
574
|
+
flushJog(false);
|
|
575
|
+
health.jog.held = !!jog.pending;
|
|
576
|
+
return true;
|
|
382
577
|
}
|
|
383
578
|
|
|
579
|
+
/**
|
|
580
|
+
* Sends the pending jog if the limit allows (or when forced).
|
|
581
|
+
*
|
|
582
|
+
* @param {boolean} force - send even if jog.maxInFlight is reached
|
|
583
|
+
* @returns {void}
|
|
584
|
+
*/
|
|
585
|
+
function flushJog(force) {
|
|
586
|
+
const p = jog.pending;
|
|
587
|
+
if (!p) return;
|
|
588
|
+
if (!force && (cancelTimer || jog.inFlight >= cfg.jog.maxInFlight)) return;
|
|
589
|
+
jog.pending = null;
|
|
590
|
+
health.jog.held = false;
|
|
591
|
+
writeGcode(p.raw || '$J=' + p.prefix + p.axis + fmtDist(p.dist) + 'F' + p.feed);
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const CANCEL_SETTLE_DEFAULT_MS = 40;
|
|
595
|
+
let cancelTimer = null;
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Cancels the jog in progress (pendant line 0x85 or JOGCANCEL). Three steps, in this order:
|
|
599
|
+
* 1. the jog held back by the governor is discarded;
|
|
600
|
+
* 2. `feeder:stop` empties the CNCjs feeder queue right away, so no further jog line leaves for Grbl
|
|
601
|
+
* (a Grbl jog cancel only flushes Grbl's planner, jogs still queued in CNCjs would continue);
|
|
602
|
+
* 3. after jog.cancelSettleMs the `jogCancel` command (0x85) is sent. Grbl handles 0x85 the moment it
|
|
603
|
+
* arrives, ahead of lines still unparsed in its serial buffer, so the short wait lets those lines
|
|
604
|
+
* be parsed first; otherwise a long jog sent just before the cancel could start after it.
|
|
605
|
+
* Jogs from the pendant that arrive during the wait are held and released after the cancel.
|
|
606
|
+
* Lines CNCjs had already written to Grbl may still run (at most jog.maxInFlight short jogs).
|
|
607
|
+
*
|
|
608
|
+
* @returns {boolean} true if the cancel was started
|
|
609
|
+
*/
|
|
610
|
+
function cancelJog() {
|
|
611
|
+
health.jog.cancels++;
|
|
612
|
+
if (cfg.cncjs.controllerType !== 'Grbl') {
|
|
613
|
+
log('pendant -> jog cancel ignored: only supported for Grbl');
|
|
614
|
+
return false;
|
|
615
|
+
}
|
|
616
|
+
discardHeldJog();
|
|
617
|
+
if (!sendCommand('feeder:stop')) return false;
|
|
618
|
+
jog.inFlight = 0; // lines removed from the feeder will never be answered
|
|
619
|
+
health.jog.inFlight = 0;
|
|
620
|
+
clearTimeout(cancelTimer);
|
|
621
|
+
cancelTimer = setTimeout(() => {
|
|
622
|
+
cancelTimer = null;
|
|
623
|
+
sendCommand('jogCancel');
|
|
624
|
+
flushJog(false);
|
|
625
|
+
}, Number(cfg.jog.cancelSettleMs !== undefined ? cfg.jog.cancelSettleMs : CANCEL_SETTLE_DEFAULT_MS));
|
|
626
|
+
return true;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Throws away a jog that is being held back (after a feed hold or reset).
|
|
631
|
+
*
|
|
632
|
+
* @returns {void}
|
|
633
|
+
*/
|
|
634
|
+
function discardHeldJog() {
|
|
635
|
+
if (jog.pending) health.jog.discarded++;
|
|
636
|
+
jog.pending = null;
|
|
637
|
+
health.jog.held = false;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Forgets all jog accounting (CNCjs connection or CNC port changed): nothing stale is replayed.
|
|
642
|
+
*
|
|
643
|
+
* @returns {void}
|
|
644
|
+
*/
|
|
645
|
+
function resetJogs() {
|
|
646
|
+
jog.inFlight = 0;
|
|
647
|
+
jog.pending = null;
|
|
648
|
+
health.jog.inFlight = 0;
|
|
649
|
+
health.jog.held = false;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/**
|
|
653
|
+
* Handles a line CNCjs read from the controller: every ok / error reply frees a slot and may release
|
|
654
|
+
* the held jog.
|
|
655
|
+
*
|
|
656
|
+
* @param {*} data - the line (string) as emitted by CNCjs
|
|
657
|
+
* @returns {void}
|
|
658
|
+
*/
|
|
659
|
+
function onControllerLine(data) {
|
|
660
|
+
const line = String(data === null || data === undefined ? '' : data).trim();
|
|
661
|
+
if (line !== 'ok' && line.slice(0, 6).toLowerCase() !== 'error:') return;
|
|
662
|
+
if (jog.inFlight > 0) jog.inFlight--;
|
|
663
|
+
health.jog.inFlight = jog.inFlight;
|
|
664
|
+
jog.lastAck = Date.now();
|
|
665
|
+
flushJog(false);
|
|
666
|
+
health.jog.held = !!jog.pending;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
// Lines the controller never answers (lost in transit) would keep the counter up for good.
|
|
670
|
+
const jogTimer = setInterval(() => {
|
|
671
|
+
if (jog.inFlight > 0 && Date.now() - jog.lastAck > cfg.jog.stallMs) {
|
|
672
|
+
health.jog.stalls++;
|
|
673
|
+
console.warn('Controller did not acknowledge ' + jog.inFlight + ' gcode line(s) for ' + cfg.jog.stallMs +
|
|
674
|
+
' ms: they may have been lost. [' + health.jog.stalls + ' stall(s) so far]');
|
|
675
|
+
jog.inFlight = 0;
|
|
676
|
+
health.jog.inFlight = 0;
|
|
677
|
+
}
|
|
678
|
+
flushJog(false);
|
|
679
|
+
}, 250);
|
|
680
|
+
|
|
384
681
|
// ---------------------------------------------------------------- CNCjs -> pendant
|
|
385
682
|
/**
|
|
386
683
|
* Converts a value to a number, treating anything non-numeric as 0.
|
|
@@ -469,38 +766,54 @@ function formatStatus(s) {
|
|
|
469
766
|
|
|
470
767
|
let lastLine = '';
|
|
471
768
|
let lastStatusAt = 0;
|
|
769
|
+
let statusQueued = false;
|
|
472
770
|
|
|
473
771
|
/**
|
|
474
772
|
* Sends the current status to the pendant if one is due: forced, at least every status.intervalMs,
|
|
475
|
-
*
|
|
773
|
+
* when the values changed and status.minGapMs has passed, or when one was queued with queueStatus().
|
|
476
774
|
*
|
|
477
775
|
* @param {boolean} [force=false] - send regardless of timing
|
|
478
776
|
* @returns {void}
|
|
479
777
|
*/
|
|
480
778
|
function sendStatus(force) {
|
|
779
|
+
if (!cfg.device.send) return;
|
|
481
780
|
const line = formatStatus(snapshot());
|
|
482
781
|
const now = Date.now();
|
|
782
|
+
const gapOk = now - lastStatusAt >= cfg.status.minGapMs;
|
|
483
783
|
const due = now - lastStatusAt >= cfg.status.intervalMs;
|
|
484
|
-
const changed = line !== lastLine &&
|
|
485
|
-
if (force || due || changed) {
|
|
784
|
+
const changed = line !== lastLine && gapOk;
|
|
785
|
+
if (force || due || changed || (statusQueued && gapOk)) {
|
|
486
786
|
if (sendToPendant(line, changed)) {
|
|
487
787
|
lastLine = line;
|
|
488
788
|
lastStatusAt = now;
|
|
789
|
+
statusQueued = false;
|
|
489
790
|
}
|
|
490
791
|
}
|
|
491
792
|
}
|
|
492
793
|
|
|
794
|
+
/**
|
|
795
|
+
* Asks for a status line to go to the pendant soon: now if status.minGapMs has passed since the last
|
|
796
|
+
* one, otherwise as soon as it has (the periodic timer sends it). Many requests in a row cost one line.
|
|
797
|
+
*
|
|
798
|
+
* @returns {void}
|
|
799
|
+
*/
|
|
800
|
+
function queueStatus() {
|
|
801
|
+
statusQueued = true;
|
|
802
|
+
sendStatus(false);
|
|
803
|
+
}
|
|
804
|
+
|
|
493
805
|
/**
|
|
494
806
|
* Writes one line to the pendant's serial port.
|
|
495
807
|
*
|
|
496
808
|
* @param {string} text - the line, without terminator (a newline is added)
|
|
497
|
-
* @param {boolean} [
|
|
809
|
+
* @param {boolean} [should_log=false] - print the line when -v is on
|
|
498
810
|
* @returns {boolean} false if the pendant port is not open
|
|
499
811
|
*/
|
|
500
|
-
function sendToPendant(text,
|
|
812
|
+
function sendToPendant(text, should_log=false) {
|
|
813
|
+
if (!cfg.device.send) return false;
|
|
501
814
|
const port = pendantPort;
|
|
502
815
|
if (!port || !port.isOpen) return false;
|
|
503
|
-
if(
|
|
816
|
+
if(should_log) log('cncjs -> ', 'pendant', text);
|
|
504
817
|
port.write(text + '\n', (err) => {
|
|
505
818
|
if (err) noteError(err);
|
|
506
819
|
});
|
|
@@ -509,7 +822,7 @@ function sendToPendant(text, shouldLog=true) {
|
|
|
509
822
|
return true;
|
|
510
823
|
}
|
|
511
824
|
|
|
512
|
-
const statusTimer = setInterval(() => sendStatus(false), Math.max(10, Math.min(cfg.status.minGapMs, cfg.status.intervalMs)));
|
|
825
|
+
const statusTimer = setInterval(() => sendStatus(false), Math.max(10, Math.min(100, cfg.status.minGapMs, cfg.status.intervalMs)));
|
|
513
826
|
|
|
514
827
|
// ---------------------------------------------------------------- pendant serial link
|
|
515
828
|
let pendantPort = null;
|
|
@@ -566,6 +879,7 @@ function openPendant() {
|
|
|
566
879
|
port.on('error', noteError);
|
|
567
880
|
port.on('close', () => {
|
|
568
881
|
health.pendant.connected = false;
|
|
882
|
+
health.pendant.info = null; // a stale battery level is worse than none
|
|
569
883
|
if (!shuttingDown) console.log('Pendant port closed');
|
|
570
884
|
scheduleReconnect();
|
|
571
885
|
});
|
|
@@ -585,6 +899,7 @@ function openPendant() {
|
|
|
585
899
|
port.set(lines, (setErr) => { if (setErr) noteError(setErr); });
|
|
586
900
|
}
|
|
587
901
|
health.pendant.connected = true;
|
|
902
|
+
health.pendant.link = detectLink(cfg.device.path);
|
|
588
903
|
health.pendant.lastError = null;
|
|
589
904
|
console.log('Pendant connected on ' + cfg.device.path);
|
|
590
905
|
sendStatus(true);
|
|
@@ -605,9 +920,11 @@ function healthReport() {
|
|
|
605
920
|
ok: health.pendant.connected && cncReady(),
|
|
606
921
|
version: pkg.version,
|
|
607
922
|
uptimeMs: now - health.startedAt,
|
|
608
|
-
pendant: Object.assign({}, health.pendant, { lastRxAgeMs: age(health.pendant.lastRx),
|
|
609
|
-
lastTxAgeMs: age(health.pendant.lastTx)
|
|
923
|
+
pendant: Object.assign({}, health.pendant, { sendEnabled: !!cfg.device.send, lastRxAgeMs: age(health.pendant.lastRx),
|
|
924
|
+
lastTxAgeMs: age(health.pendant.lastTx),
|
|
925
|
+
info: health.pendant.info && Object.assign({}, health.pendant.info, { ageMs: age(health.pendant.info.at) }) }),
|
|
610
926
|
cncjs: health.cncjs,
|
|
927
|
+
jog: Object.assign({}, health.jog, { lastAgeMs: age(health.jog.lastAt) }),
|
|
611
928
|
lastCommand: health.lastCommand,
|
|
612
929
|
status: snapshot()
|
|
613
930
|
};
|
|
@@ -647,6 +964,8 @@ function shutdown() {
|
|
|
647
964
|
if (shuttingDown) return;
|
|
648
965
|
shuttingDown = true;
|
|
649
966
|
clearInterval(statusTimer);
|
|
967
|
+
clearInterval(jogTimer);
|
|
968
|
+
clearTimeout(cancelTimer);
|
|
650
969
|
clearTimeout(reconnectTimer);
|
|
651
970
|
socket.close();
|
|
652
971
|
if (httpServer) httpServer.close();
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"cncjs": {
|
|
3
|
+
"port": "/dev/ttyUSB0",
|
|
4
|
+
"baudrate": 115200,
|
|
5
|
+
"controllerType": "Grbl",
|
|
6
|
+
"socketAddress": "localhost",
|
|
7
|
+
"socketPort": 8000,
|
|
8
|
+
"retryInterval": 5000,
|
|
9
|
+
"openTimeout": 5000,
|
|
10
|
+
"maxOpenTries": 3,
|
|
11
|
+
"keepaliveMs": 30000,
|
|
12
|
+
"reopenOnClose": true
|
|
13
|
+
},
|
|
14
|
+
"device": {
|
|
15
|
+
"path": "/dev/pendant",
|
|
16
|
+
"baudRate": 115200,
|
|
17
|
+
"reconnectMs": 3000,
|
|
18
|
+
"settleMs": 2000,
|
|
19
|
+
"send": true,
|
|
20
|
+
"hupcl": false,
|
|
21
|
+
"dtr": null,
|
|
22
|
+
"rts": null
|
|
23
|
+
},
|
|
24
|
+
"status": {
|
|
25
|
+
"format": "grbl",
|
|
26
|
+
"intervalMs": 400,
|
|
27
|
+
"minGapMs": 350,
|
|
28
|
+
"pollAfterCommand": false,
|
|
29
|
+
"decimals": 3
|
|
30
|
+
},
|
|
31
|
+
"jog": {
|
|
32
|
+
"translate": true,
|
|
33
|
+
"maxInFlight": 4,
|
|
34
|
+
"stallMs": 2000,
|
|
35
|
+
"cancelSettleMs": 40,
|
|
36
|
+
"echo": false
|
|
37
|
+
},
|
|
38
|
+
"http": { "enabled": true, "host": "127.0.0.1", "port": 8001 },
|
|
39
|
+
"log": { "max": 500 }
|
|
40
|
+
}
|