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