cncjs-handwheel 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thor Schueler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # cncjs-handwheel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Bridge between CNCjs and a serial (USB or Bluetooth) ESP32 handwheel pendant. It runs on the same machine as CNCjs.
4
+
5
+ - pendant -> CNCjs: gcode lines, realtime commands, console log lines
6
+ - CNCjs -> pendant: status lines (state, MPos, WPos, feed/spindle), about 10 per second
7
+ - health and the pendant log as JSON on `http://127.0.0.1:8001` (for a CNCjs widget)
8
+
9
+ Requires Node 20 or newer and a CNCjs that uses socket.io 2.x (current CNCjs releases do).
10
+
11
+ ## Install
12
+
13
+ npm install -g cncjs-handwheel
14
+
15
+ Create the config (see below), then run it by hand to try it:
16
+
17
+ cncjs-handwheel --config ~/.cncjs-handwheel.config -v
18
+
19
+ `-v` logs pendant events and the commands sent to CNCjs, `--trace` also logs all controller traffic,
20
+ `--list` lists the serial ports.
21
+
22
+ ### Run as a service (systemd)
23
+
24
+ sudo env "PATH=$PATH" cncjs-handwheel install-service --user <user running CNCjs> --usb-port 1-2:1.0
25
+ sudo systemctl start cncjs-handwheel
26
+
27
+ - `--user` must be the user that runs CNCjs: the bridge reads the CNCjs secret from that user's `~/.cncrc`.
28
+ - `--usb-port` is optional. It is the USB port the pendant is plugged into, the first `KERNELS` value of
29
+ `udevadm info -a -n /dev/ttyUSBx`. It installs a udev rule that creates `/dev/pendant` and sets up the port so
30
+ that opening it does not reset the ESP32 through its auto-reset circuit. Replug the pendant afterwards.
31
+ - `sudo env "PATH=$PATH"` keeps an nvm-installed Node visible to root; with a system Node plain `sudo` works.
32
+ - The unit stores the absolute path of the Node that ran the command. After a Node upgrade run `install-service` again.
33
+ - `--dry-run` prints the unit and rule without changing anything.
34
+
35
+ Update: `npm install -g cncjs-handwheel@latest && sudo systemctl restart cncjs-handwheel`.
36
+ Remove: `sudo env "PATH=$PATH" cncjs-handwheel uninstall-service` (the config file stays).
37
+
38
+ journalctl -u cncjs-handwheel -f # logs
39
+ curl http://127.0.0.1:8001/status # health
40
+ curl "http://127.0.0.1:8001/log?since=0" # pendant console log
41
+
42
+ ## Configuration
43
+
44
+ Precedence, lowest to highest: defaults, the `pendant` section of `~/.cncrc`, `~/.cncjs-handwheel.config`
45
+ (or the file given with `--config`), command line options. CNCjs rewrites `.cncrc` itself, so a separate file is safer.
46
+ Start from `cncjs-pendant.config.example.json`.
47
+
48
+ | Key | Meaning |
49
+ |---|---|
50
+ | `cncjs.port` | CNC controller port as CNCjs knows it (not the pendant) |
51
+ | `cncjs.controllerType` | `Grbl` (Smoothie shares the state format) |
52
+ | `device.path` | pendant serial port, e.g. `/dev/pendant` |
53
+ | `device.baudRate`, `device.settleMs` | pendant baud rate; pendant input is ignored this long after opening |
54
+ | `device.hupcl`, `dtr`, `rts` | modem control line handling (the defaults are fine with the udev rule) |
55
+ | `status.intervalMs`, `status.minGapMs` | status line at least every 100 ms, and at most every 25 ms when values change |
56
+ | `status.pollAfterCommand` | ask Grbl for a fresh report after each pendant command |
57
+ | `status.format` | `grbl` or `json` |
58
+ | `jog.translate` | rewrite jogs like `G21G91X10F500` to `$J=...` so they do not leave Grbl in relative mode |
59
+ | `http` | health endpoint (`enabled`, `host`, `port`) |
60
+ | `log.max` | pendant log lines kept for the widget |
61
+
62
+ ## Pendant protocol
63
+
64
+ Newline-terminated text. Everything except log lines must be printable ASCII.
65
+
66
+ Pendant to bridge:
67
+
68
+ | Line | Effect |
69
+ |---|---|
70
+ | `G21G91X+10F2000` | jog (sent as `$J=...`); any other line is sent to the controller as gcode |
71
+ | `!` / `~` / `^X` (0x18) | feed hold / cycle start / reset, each as a line of its own (reset at most once per 2 s) |
72
+ | `?` or `STATUS?` | immediate status line |
73
+ | `PING` | answered with `PONG` |
74
+ | `; text` | console log entry for the widget; never sent to the controller |
75
+
76
+ Bridge to pendant:
77
+
78
+ | Line | Meaning |
79
+ |---|---|
80
+ | `<Idle\|MPos:x,y,z\|WPos:x,y,z\|FS:feed,spindle>` | status, after every command and at least every 100 ms |
81
+ | `<Disconnected>` | the bridge is up, but CNCjs or the CNC port is not |
82
+ | `ERR:CNCJS_NOT_READY` | a command was dropped because the CNC port is not open |
83
+ | `PONG` | answer to `PING` |
84
+
85
+ The status right after a command shows where the machine was at that moment; Grbl's `ok` only means the move was
86
+ queued. A fresh report follows within a few tens of milliseconds, and the 100 ms stream tracks the move.
87
+ If no line arrives for about 500 ms, treat the bridge as gone.
88
+
89
+ ## Troubleshooting
90
+
91
+ - **ESP32 reboots or enters download mode when the port is opened.** Linux raises DTR and RTS on the first open, and
92
+ the auto-reset circuit turns that into a reset. Use the udev rule from `--usb-port`. A capacitor of about 1 uF from
93
+ EN to GND on the board removes the problem at its source.
94
+ - **Nothing from the pendant.** Run with `-v`. Lines rejected as non-text are reported as `dropped non-text line`
95
+ and counted in `/status` (`pendant.garbageLines`); wrong baud rate and a rebooting ESP32 look like that.
96
+ - **`$$` and `$I` output at start.** Normal: CNCjs queries the controller when a client opens the CNC port.
97
+ - **No WPos.** Grbl reports the work offset only every 10-30 status reports; the first WPos can take a few seconds.
@@ -0,0 +1,659 @@
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), 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
+ },
37
+ device: {
38
+ path: '/dev/pendant', // the pendant's serial port (e.g. /dev/ttyACM0 or /dev/rfcomm0)
39
+ baudRate: 115200,
40
+ reconnectMs: 3000,
41
+ settleMs: 2000, // ignore pendant input this long after opening the port
42
+
43
+ // Modem-control lines. The CH340 + auto-reset transistors wire DTR/RTS to EN/IO0, so on Linux
44
+ // the DTR/RTS toggling around open/close can reset the ESP32 or drop it into download mode.
45
+ hupcl: false, // do NOT drop DTR/RTS when the port is closed
46
+ dtr: null, // true/false = force DTR right after open, null = leave alone
47
+ rts: null // true/false = force RTS right after open, null = leave alone
48
+ },
49
+ status: {
50
+ format: 'grbl', // 'grbl' -> <Idle|MPos:..|WPos:..|FS:..> 'json' -> {"t":"status",...}
51
+ intervalMs: 100, // unsolicited status line at least this often (also the pendant's "host alive" signal)
52
+ minGapMs: 25, // minimum gap between two status lines when the values change
53
+ pollAfterCommand: true, // ask CNCjs/Grbl for a fresh status report after every pendant command
54
+ decimals: 3
55
+ },
56
+ http: { enabled: true, host: '127.0.0.1', port: 8001 },
57
+
58
+ // Grbl 1.1 only: rewrite "G21G91X+10F2000" into "$J=G21G91X+10F2000" so a pendant jog does not
59
+ // leave CNCjs/Grbl stuck in relative mode (and so jogs go through Grbl's jog queue)
60
+ jog: { translate: true },
61
+
62
+ // pendant console lines ("; ...") are kept here for the widget instead of being sent to Grbl
63
+ log: { max: 500 },
64
+
65
+ verbose: false, // -v: log pendant events and commands
66
+ trace: false // --trace: also log all controller traffic (everything CNCjs reads/writes)
67
+ };
68
+
69
+ // ---------------------------------------------------------------- config
70
+ const program = new Command();
71
+ program
72
+ .name('cncjs-handwheel')
73
+ .version(pkg.version)
74
+ .option('-l, --list', 'list available serial ports then exit')
75
+ .option('-c, --config <file>', 'config file (default: ' + DEFAULT_CONFIG_FILE + ' if present)')
76
+ .option('-s, --secret <secret>', 'CNCjs secret (default: $CNCJS_SECRET or ~/.cncrc)')
77
+ .option('-p, --port <port>', 'CNC controller port as known to CNCjs, e.g. /dev/ttyUSB0')
78
+ .option('-b, --baudrate <baudrate>', 'CNC controller baud rate')
79
+ .option('--controller-type <type>', 'Grbl|Smoothie')
80
+ .option('--socket-address <address>', 'CNCjs host')
81
+ .option('--socket-port <port>', 'CNCjs port')
82
+ .option('--pendant-port <path>', 'serial port of the pendant')
83
+ .option('--pendant-baudrate <baudrate>', 'baud rate of the pendant')
84
+ .option('-v, --verbose', 'log pendant events and the commands sent to CNCjs')
85
+ .option('--trace', 'also log all controller traffic (very noisy)');
86
+ program.parse(process.argv);
87
+ const cli = program.opts();
88
+
89
+ /**
90
+ * Tells whether a value is a plain object (not null, not an array).
91
+ *
92
+ * @param {*} v - value to test
93
+ * @returns {boolean}
94
+ */
95
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
96
+ /**
97
+ * Recursively merges `extra` into a copy of `base`. Plain objects are merged key by key,
98
+ * everything else (including arrays) is replaced. Neither argument is modified.
99
+ *
100
+ * @param {object} base - lower precedence values
101
+ * @param {object} [extra] - higher precedence values
102
+ * @returns {object} the merged copy
103
+ */
104
+ const deepMerge = (base, extra) => {
105
+ const out = Object.assign({}, base);
106
+ Object.keys(extra || {}).forEach((k) => {
107
+ out[k] = isObj(extra[k]) && isObj(base[k]) ? deepMerge(base[k], extra[k]) : extra[k];
108
+ });
109
+ return out;
110
+ };
111
+
112
+ if (cli.list) {
113
+ SerialPort.list().then((ports) => {
114
+ ports.forEach((p) => console.log([p.path, p.manufacturer, p.vendorId && (p.vendorId + ':' + p.productId)]
115
+ .filter(Boolean).join(' ')));
116
+ }).catch((err) => { console.error(err); process.exit(1); });
117
+ return;
118
+ }
119
+
120
+ // precedence (low -> high): defaults, "pendant" section of ~/.cncrc, config file, CLI
121
+ let cfg = deepMerge(DEFAULTS, connectToCncjs.readCncrc().pendant);
122
+ const cfgFile = cli.config || (fs.existsSync(DEFAULT_CONFIG_FILE) ? DEFAULT_CONFIG_FILE : null);
123
+ if (cfgFile) {
124
+ try {
125
+ cfg = deepMerge(cfg, JSON.parse(fs.readFileSync(cfgFile, 'utf8')));
126
+ } catch (err) {
127
+ console.error('Cannot read config file ' + cfgFile + ': ' + err.message);
128
+ process.exit(1);
129
+ }
130
+ }
131
+ if (cli.port) cfg.cncjs.port = cli.port;
132
+ if (cli.baudrate) cfg.cncjs.baudrate = cli.baudrate;
133
+ if (cli.controllerType) cfg.cncjs.controllerType = cli.controllerType;
134
+ if (cli.socketAddress) cfg.cncjs.socketAddress = cli.socketAddress;
135
+ if (cli.socketPort) cfg.cncjs.socketPort = cli.socketPort;
136
+ if (cli.pendantPort) cfg.device.path = cli.pendantPort;
137
+ if (cli.pendantBaudrate) cfg.device.baudRate = cli.pendantBaudrate;
138
+ if (cli.verbose) cfg.verbose = true;
139
+ if (cli.trace) cfg.trace = true;
140
+
141
+ if (!cfg.cncjs.port) { console.error('Missing CNC controller port (cncjs.port / --port)'); process.exit(1); }
142
+ if (!cfg.device.path) { console.error('Missing pendant port (device.path / --pendant-port). Try --list'); process.exit(1); }
143
+
144
+ // ---------------------------------------------------------------- state
145
+ const store = { controller: { state: {}, settings: {} }, sender: { status: {} } };
146
+
147
+ const health = {
148
+ startedAt: Date.now(),
149
+ 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 },
151
+ cncjs: { socketConnected: false, portOpen: false, port: cfg.cncjs.port, controllerType: cfg.cncjs.controllerType,
152
+ lastError: null },
153
+ lastCommand: null
154
+ };
155
+
156
+ /**
157
+ * Logs to the console, but only when -v / verbose is on.
158
+ *
159
+ * @param {...*} args - what to print
160
+ * @returns {void}
161
+ */
162
+ const log = (...args) => cfg.verbose && console.log(...args);
163
+ let shuttingDown = false;
164
+
165
+ // ---------------------------------------------------------------- CNCjs side
166
+ const cncOpts = Object.assign({}, cfg.cncjs, { secret: cli.secret, verbose: cfg.trace });
167
+ const socket = connectToCncjs(cncOpts, (err) => {
168
+ if (err) {
169
+ health.cncjs.lastError = err.message;
170
+ console.error(err.message);
171
+ }
172
+ });
173
+
174
+ socket.on('connect', () => { health.cncjs.socketConnected = true; });
175
+ socket.on('disconnect', () => { health.cncjs.socketConnected = false; health.cncjs.portOpen = false; });
176
+ socket.on('serialport:open', () => { health.cncjs.portOpen = true; health.cncjs.lastError = null; lastWco = null; });
177
+ socket.on('serialport:close', () => { health.cncjs.portOpen = false; });
178
+
179
+ ['Grbl', 'Smoothie', 'TinyG'].forEach((type) => {
180
+ let dumped = false;
181
+ socket.on(type + ':state', (state) => {
182
+ store.controller.state = state || {};
183
+ const wco = state && state.status && state.status.wco;
184
+ if (wco) lastWco = wco;
185
+ sendStatus(false); // forward changes right away (rate limited by status.minGapMs)
186
+ if (cfg.verbose && !dumped) { dumped = true; console.log(type + ':state sample', JSON.stringify(state)); }
187
+ });
188
+ socket.on(type + ':settings', (settings) => { store.controller.settings = settings || {}; });
189
+ });
190
+
191
+ socket.on('sender:status', (data) => { store.sender.status = data || {}; });
192
+
193
+ let lastWco = null; // Grbl 1.1 only reports MPos *or* WPos, plus WCO now and then: WPos = MPos - WCO
194
+ /**
195
+ * Tells whether commands can currently reach the CNC controller
196
+ * (CNCjs socket connected and the CNC port open).
197
+ *
198
+ * @returns {boolean}
199
+ */
200
+ const cncReady = () => health.cncjs.socketConnected && health.cncjs.portOpen;
201
+
202
+ /**
203
+ * Sends a command to the CNC controller through CNCjs and answers the pendant with a status line.
204
+ * If CNCjs or the CNC port is not ready the command is dropped and the pendant gets
205
+ * `ERR:CNCJS_NOT_READY` plus a status line.
206
+ *
207
+ * @param {string} name - CNCjs command, e.g. 'gcode', 'feedhold', 'cyclestart', 'reset'
208
+ * @param {...*} args - command arguments, e.g. the gcode line
209
+ * @returns {boolean} true if the command was sent
210
+ */
211
+ function sendCommand(name, ...args) {
212
+ if (!cncReady()) {
213
+ sendToPendant('ERR:CNCJS_NOT_READY');
214
+ sendStatus(true);
215
+ return false;
216
+ }
217
+ health.lastCommand = { at: Date.now(), name, args };
218
+ log('pendant ->', name, ...args);
219
+ socket.emit('command', cfg.cncjs.port, name, ...args);
220
+ answerCommand();
221
+ return true;
222
+ }
223
+
224
+ // Every command from the pendant is answered with a status line right away. The position in it is
225
+ // what CNCjs knew at that moment; a fresh report is requested so the real position follows within
226
+ // a few tens of ms (forwarded by the :state handler).
227
+ let lastPoll = 0;
228
+ /**
229
+ * Answers a command from the pendant with a status line right away, and asks the controller for a
230
+ * fresh status report (at most every 50 ms) so the new position follows shortly after.
231
+ *
232
+ * @returns {void}
233
+ */
234
+ function answerCommand() {
235
+ sendStatus(true);
236
+ const now = Date.now();
237
+ if (cfg.status.pollAfterCommand && now - lastPoll >= 50) {
238
+ lastPoll = now;
239
+ socket.emit('command', cfg.cncjs.port, 'statusreport');
240
+ }
241
+ }
242
+
243
+ // ---------------------------------------------------------------- pendant -> CNCjs
244
+ // Everything from the pendant is LINE based (newline terminated) and must be printable ASCII.
245
+ // Lines that contain anything else are dropped (an ESP32 that is booting or running at the wrong
246
+ // baud rate spews binary garbage, which must never reach the CNC).
247
+ // "!" feed hold "~" cycle start "^X" (0x18) soft reset "?" status request
248
+ // each as a line of its own, e.g. "!\n". Reset is rate limited.
249
+ // ";..." pendant console log entry (any text, ANSI colours stripped): kept in a ring buffer for the
250
+ // widget (GET /log), never sent to CNCjs; with -v it is printed as "pendant log: ..."
251
+ // lines dropped as non-text are reported with -v (escaped, at most one per second)
252
+ // PING -> PONG, STATUS? -> immediate status line
253
+ // anything else -> gcode
254
+ // After the pendant port opens, input is ignored for device.settleMs so the boot output of an
255
+ // ESP32 that was reset by the open is discarded.
256
+ const logBuf = [];
257
+ let logSeq = 0;
258
+
259
+ /**
260
+ * Appends a pendant console line to the ring buffer served at GET /log (capped at log.max entries).
261
+ *
262
+ * @param {string} text - the log text, without the leading ';'
263
+ * @returns {void}
264
+ */
265
+ function addPendantLog(text) {
266
+ logBuf.push({ id: ++logSeq, t: Date.now(), text });
267
+ if (logBuf.length > cfg.log.max) logBuf.splice(0, logBuf.length - cfg.log.max);
268
+ health.pendant.logLines = logSeq;
269
+ log('pendant -> log:', text);
270
+ }
271
+
272
+ const PRINTABLE = /^[\x20-\x7e]+$/;
273
+ const REALTIME = { '!': 'feedhold', '~': 'cyclestart', '\x18': 'reset' };
274
+ let rxBuf = '';
275
+ let skipLine = false;
276
+ let ignoreUntil = 0;
277
+ let lastReset = 0;
278
+
279
+ /**
280
+ * Handler for raw bytes from the pendant's serial port. Splits the stream into lines, drops overlong
281
+ * lines, and ignores everything during the settle time after the port was opened.
282
+ *
283
+ * @param {Buffer} buf - chunk read from the serial port
284
+ * @returns {void}
285
+ */
286
+ function onPendantData(buf) {
287
+ const now = Date.now();
288
+ health.pendant.lastRx = now;
289
+ if (now < ignoreUntil) {
290
+ rxBuf = '';
291
+ skipLine = false;
292
+ return;
293
+ }
294
+ const text = buf.toString('binary');
295
+ for (let i = 0; i < text.length; i++) {
296
+ const ch = text[i];
297
+ if (ch === '\n' || ch === '\r') {
298
+ const line = rxBuf.trim();
299
+ const drop = skipLine;
300
+ rxBuf = '';
301
+ skipLine = false;
302
+ if (drop) health.pendant.garbageLines++;
303
+ else if (line) onPendantLine(line);
304
+ } else if (rxBuf.length < 256) {
305
+ rxBuf += ch;
306
+ } else {
307
+ skipLine = true; // overlong line: drop it up to the next newline
308
+ }
309
+ }
310
+ }
311
+
312
+ // Only modal words (G20/G21/G90/G91), axis words and a feed, no G0/G1/G2/G3 -> this is a jog.
313
+ const JOG_RE = /^(?:G(?:20|21|90|91))+(?:[XYZABC][-+]?\d*\.?\d+|F\d*\.?\d+)+$/;
314
+
315
+ /**
316
+ * Turns a pendant jog such as `G21G91X+10F2000` into a Grbl jog command (`$J=G21G91X+10F2000`).
317
+ * Lines that are not pure jogs (no axis word, or containing G0/G1/G2/G3 etc.) are returned unchanged.
318
+ *
319
+ * @param {string} line - gcode line from the pendant
320
+ * @returns {string} the jog command, or the original line
321
+ */
322
+ function toJog(line) {
323
+ const compact = line.replace(/\s+/g, '').toUpperCase();
324
+ return JOG_RE.test(compact) && /[XYZABC]/.test(compact) ? '$J=' + compact : line;
325
+ }
326
+
327
+ const ANSI = /\x1b\[[0-9;]*[A-Za-z]/g;
328
+ let lastDropLog = 0;
329
+
330
+ /**
331
+ * Counts a rejected (non-text) pendant line and, with -v, reports it escaped (at most once a second).
332
+ *
333
+ * @param {string} raw - the rejected line as received (binary string)
334
+ * @returns {void}
335
+ */
336
+ function dropLine(raw) {
337
+ health.pendant.garbageLines++;
338
+ const now = Date.now();
339
+ if (cfg.verbose && now - lastDropLog > 1000) {
340
+ lastDropLog = now;
341
+ console.log('pendant: dropped non-text line', JSON.stringify(raw.slice(0, 60)));
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Handles one complete line from the pendant: realtime commands (! ~ ^X ?), console log entries
347
+ * (; ...), PING / STATUS?, and otherwise gcode (jogs are translated to $J= for Grbl).
348
+ *
349
+ * @param {string} raw - the line without the line terminator (binary string)
350
+ * @returns {void}
351
+ */
352
+ function onPendantLine(raw) {
353
+ health.pendant.rxLines++;
354
+ if (raw === '?') return sendStatus(true);
355
+ if (REALTIME[raw]) {
356
+ if (raw === '\x18') {
357
+ const now = Date.now();
358
+ if (now - lastReset < 2000) return;
359
+ lastReset = now;
360
+ }
361
+ return sendCommand(REALTIME[raw]);
362
+ }
363
+ // decode as UTF-8, drop ANSI colour codes, tabs -> spaces
364
+ let line = Buffer.from(raw, 'binary').toString('utf8').replace(ANSI, '').replace(/\t/g, ' ').trim();
365
+ if (!line) return;
366
+ if (line[0] === ';') {
367
+ // console log entry from the pendant: any text is fine, it is never sent to the controller
368
+ addPendantLog(line.replace(/^;\s?/, '').replace(/[\x00-\x1f\x7f]/g, ''));
369
+ return;
370
+ }
371
+ if (!PRINTABLE.test(line)) {
372
+ dropLine(raw);
373
+ return;
374
+ }
375
+ const upper = line.toUpperCase();
376
+ if (upper === 'PING') return sendToPendant('PONG');
377
+ if (upper === 'STATUS?') return sendStatus(true);
378
+ if (cfg.jog.translate && cfg.cncjs.controllerType === 'Grbl') {
379
+ line = toJog(line);
380
+ }
381
+ sendCommand('gcode', line);
382
+ }
383
+
384
+ // ---------------------------------------------------------------- CNCjs -> pendant
385
+ /**
386
+ * Converts a value to a number, treating anything non-numeric as 0.
387
+ *
388
+ * @param {*} v
389
+ * @returns {number}
390
+ */
391
+ const num = (v) => Number(v) || 0;
392
+ /**
393
+ * Subtracts two {x, y, z} positions (a - b).
394
+ *
395
+ * @param {{x: (number|string), y: (number|string), z: (number|string)}} a
396
+ * @param {{x: (number|string), y: (number|string), z: (number|string)}} b
397
+ * @returns {{x: number, y: number, z: number}}
398
+ */
399
+ 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) });
400
+ /**
401
+ * Adds two {x, y, z} positions (a + b).
402
+ *
403
+ * @param {{x: (number|string), y: (number|string), z: (number|string)}} a
404
+ * @param {{x: (number|string), y: (number|string), z: (number|string)}} b
405
+ * @returns {{x: number, y: number, z: number}}
406
+ */
407
+ 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) });
408
+
409
+ /**
410
+ * Returns machine and work position. Grbl 1.1 reports only one of them plus the work coordinate
411
+ * offset (WCO) now and then, so the missing one is derived: WPos = MPos - WCO.
412
+ *
413
+ * @param {object} st - the `status` object of the CNCjs controller state
414
+ * @returns {{mpos: ?object, wpos: ?object}} positions, null where they cannot be determined yet
415
+ */
416
+ function positions(st) {
417
+ const wco = st.wco || lastWco;
418
+ let mpos = st.mpos || null;
419
+ let wpos = st.wpos || null;
420
+ if (!wpos && mpos && wco) wpos = sub(mpos, wco);
421
+ if (!mpos && wpos && wco) mpos = add(wpos, wco);
422
+ return { mpos, wpos };
423
+ }
424
+
425
+ /**
426
+ * Builds the current machine status from the latest CNCjs controller and sender state.
427
+ *
428
+ * @returns {{connected: boolean, state: string, mpos: ?object, wpos: ?object, feed: ?number,
429
+ * spindle: ?number, sender: object}}
430
+ */
431
+ function snapshot() {
432
+ const connected = cncReady();
433
+ const st = (store.controller.state && store.controller.state.status) || {};
434
+ const pos = positions(st);
435
+ const snd = store.sender.status || {};
436
+ return {
437
+ connected,
438
+ state: connected ? (st.activeState || 'Unknown') : 'Disconnected',
439
+ mpos: pos.mpos,
440
+ wpos: pos.wpos,
441
+ feed: st.feedrate !== undefined ? st.feedrate : null,
442
+ spindle: st.spindle !== undefined ? st.spindle : null,
443
+ sender: { name: snd.name || null, total: snd.total || 0, sent: snd.sent || 0,
444
+ received: snd.received || 0, hold: !!snd.hold }
445
+ };
446
+ }
447
+
448
+ /**
449
+ * Formats a status snapshot as the line sent to the pendant, either Grbl style
450
+ * (`<Idle|MPos:x,y,z|WPos:x,y,z|FS:feed,spindle>`) or JSON, depending on status.format.
451
+ *
452
+ * @param {object} s - snapshot from snapshot()
453
+ * @returns {string} the status line without terminator
454
+ */
455
+ function formatStatus(s) {
456
+ if (cfg.status.format === 'json') {
457
+ return JSON.stringify(Object.assign({ t: 'status' }, s));
458
+ }
459
+ const d = cfg.status.decimals;
460
+ const pos = (p) => [p.x, p.y, p.z].map((n) => (Number(n) || 0).toFixed(d)).join(',');
461
+ const parts = [s.state];
462
+ if (s.connected) {
463
+ if (s.mpos) parts.push('MPos:' + pos(s.mpos));
464
+ if (s.wpos) parts.push('WPos:' + pos(s.wpos));
465
+ if (s.feed !== null) parts.push('FS:' + (Number(s.feed) || 0) + ',' + (Number(s.spindle) || 0));
466
+ }
467
+ return '<' + parts.join('|') + '>';
468
+ }
469
+
470
+ let lastLine = '';
471
+ let lastStatusAt = 0;
472
+
473
+ /**
474
+ * Sends the current status to the pendant if one is due: forced, at least every status.intervalMs,
475
+ * or when the values changed and status.minGapMs has passed.
476
+ *
477
+ * @param {boolean} [force=false] - send regardless of timing
478
+ * @returns {void}
479
+ */
480
+ function sendStatus(force) {
481
+ const line = formatStatus(snapshot());
482
+ const now = Date.now();
483
+ const due = now - lastStatusAt >= cfg.status.intervalMs;
484
+ const changed = line !== lastLine && now - lastStatusAt >= cfg.status.minGapMs;
485
+ if (force || due || changed) {
486
+ if (sendToPendant(line, changed)) {
487
+ lastLine = line;
488
+ lastStatusAt = now;
489
+ }
490
+ }
491
+ }
492
+
493
+ /**
494
+ * Writes one line to the pendant's serial port.
495
+ *
496
+ * @param {string} text - the line, without terminator (a newline is added)
497
+ * @param {boolean} [shouldLog=true] - print the line when -v is on
498
+ * @returns {boolean} false if the pendant port is not open
499
+ */
500
+ function sendToPendant(text, shouldLog=true) {
501
+ const port = pendantPort;
502
+ if (!port || !port.isOpen) return false;
503
+ if(shouldLog) log('cncjs -> ', 'pendant', text);
504
+ port.write(text + '\n', (err) => {
505
+ if (err) noteError(err);
506
+ });
507
+ health.pendant.lastTx = Date.now();
508
+ health.pendant.txLines++;
509
+ return true;
510
+ }
511
+
512
+ const statusTimer = setInterval(() => sendStatus(false), Math.max(10, Math.min(cfg.status.minGapMs, cfg.status.intervalMs)));
513
+
514
+ // ---------------------------------------------------------------- pendant serial link
515
+ let pendantPort = null;
516
+ let reconnectTimer = null;
517
+
518
+ /**
519
+ * Records a pendant serial error in the health data and prints it.
520
+ *
521
+ * @param {Error} err
522
+ * @returns {void}
523
+ */
524
+ function noteError(err) {
525
+ health.pendant.errors++;
526
+ health.pendant.lastError = err.message;
527
+ console.error('Pendant error:', err.message);
528
+ }
529
+
530
+ /**
531
+ * Schedules a reopen of the pendant serial port after device.reconnectMs (at most one pending).
532
+ *
533
+ * @returns {void}
534
+ */
535
+ function scheduleReconnect() {
536
+ if (shuttingDown || reconnectTimer) return;
537
+ reconnectTimer = setTimeout(() => {
538
+ reconnectTimer = null;
539
+ health.pendant.reconnects++;
540
+ openPendant();
541
+ }, cfg.device.reconnectMs);
542
+ }
543
+
544
+ /**
545
+ * Opens the pendant's serial port and wires up its events. Failures and closes schedule a reconnect.
546
+ * After a successful open, pendant input is ignored for device.settleMs and a status line is sent.
547
+ *
548
+ * @returns {void}
549
+ */
550
+ function openPendant() {
551
+ const port = new SerialPort({
552
+ path: cfg.device.path,
553
+ baudRate: Number(cfg.device.baudRate),
554
+ autoOpen: false,
555
+ dataBits: 8,
556
+ stopBits: 1,
557
+ parity: 'none',
558
+ rtscts: false,
559
+ xon: false,
560
+ xoff: false,
561
+ xany: false,
562
+ hupcl: !!cfg.device.hupcl
563
+ });
564
+ pendantPort = port;
565
+ port.on('data', onPendantData);
566
+ port.on('error', noteError);
567
+ port.on('close', () => {
568
+ health.pendant.connected = false;
569
+ if (!shuttingDown) console.log('Pendant port closed');
570
+ scheduleReconnect();
571
+ });
572
+ port.open((err) => {
573
+ if (err) {
574
+ noteError(err);
575
+ scheduleReconnect();
576
+ return;
577
+ }
578
+ rxBuf = '';
579
+ skipLine = false;
580
+ ignoreUntil = Date.now() + Number(cfg.device.settleMs || 0);
581
+ const lines = {};
582
+ if (cfg.device.dtr !== null && cfg.device.dtr !== undefined) lines.dtr = !!cfg.device.dtr;
583
+ if (cfg.device.rts !== null && cfg.device.rts !== undefined) lines.rts = !!cfg.device.rts;
584
+ if (Object.keys(lines).length) {
585
+ port.set(lines, (setErr) => { if (setErr) noteError(setErr); });
586
+ }
587
+ health.pendant.connected = true;
588
+ health.pendant.lastError = null;
589
+ console.log('Pendant connected on ' + cfg.device.path);
590
+ sendStatus(true);
591
+ });
592
+ }
593
+
594
+ // ---------------------------------------------------------------- health endpoint
595
+ /**
596
+ * Builds the JSON served at GET /status: link health of the pendant and CNCjs, the last command
597
+ * sent, and the current machine status.
598
+ *
599
+ * @returns {object}
600
+ */
601
+ function healthReport() {
602
+ const now = Date.now();
603
+ const age = (t) => (t ? now - t : null);
604
+ return {
605
+ ok: health.pendant.connected && cncReady(),
606
+ version: pkg.version,
607
+ uptimeMs: now - health.startedAt,
608
+ pendant: Object.assign({}, health.pendant, { lastRxAgeMs: age(health.pendant.lastRx),
609
+ lastTxAgeMs: age(health.pendant.lastTx) }),
610
+ cncjs: health.cncjs,
611
+ lastCommand: health.lastCommand,
612
+ status: snapshot()
613
+ };
614
+ }
615
+
616
+ let httpServer = null;
617
+ if (cfg.http.enabled) {
618
+ httpServer = http.createServer((req, res) => {
619
+ const url = new URL(req.url, 'http://localhost');
620
+ const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
621
+ if (url.pathname === '/' || url.pathname === '/status') {
622
+ res.writeHead(200, headers);
623
+ res.end(JSON.stringify(healthReport()));
624
+ } else if (url.pathname === '/log') {
625
+ // GET /log?since=<id> -> entries with id > since (poll with the last id you saw)
626
+ const since = Number(url.searchParams.get('since')) || 0;
627
+ res.writeHead(200, headers);
628
+ res.end(JSON.stringify({ last: logSeq, entries: logBuf.filter((e) => e.id > since) }));
629
+ } else {
630
+ res.writeHead(404);
631
+ res.end();
632
+ }
633
+ });
634
+ httpServer.on('error', (err) => console.error('Health endpoint error:', err.message));
635
+ httpServer.listen(cfg.http.port, cfg.http.host, () =>
636
+ console.log('Health endpoint on http://' + cfg.http.host + ':' + cfg.http.port + '/status'));
637
+ }
638
+
639
+ // ---------------------------------------------------------------- lifecycle
640
+ /**
641
+ * Stops timers and closes the CNCjs socket, the pendant port and the HTTP server, then exits.
642
+ * Called on SIGINT / SIGTERM.
643
+ *
644
+ * @returns {void}
645
+ */
646
+ function shutdown() {
647
+ if (shuttingDown) return;
648
+ shuttingDown = true;
649
+ clearInterval(statusTimer);
650
+ clearTimeout(reconnectTimer);
651
+ socket.close();
652
+ if (httpServer) httpServer.close();
653
+ if (pendantPort && pendantPort.isOpen) pendantPort.close();
654
+ setTimeout(() => process.exit(0), 300);
655
+ }
656
+ process.on('SIGINT', shutdown);
657
+ process.on('SIGTERM', shutdown);
658
+
659
+ openPendant();
package/index.js ADDED
@@ -0,0 +1,163 @@
1
+ 'use strict';
2
+
3
+ // CNCjs client helper (adapted from cncjs-pendant-keyboard/index.js).
4
+ //
5
+ // Differences from the original:
6
+ // - returns the socket immediately and keeps the connection alive:
7
+ // re-opens the CNC port after (re)connects and retries if the open fails
8
+ // - generates a fresh access token on every reconnect attempt, so a
9
+ // long-running daemon never ends up with an expired token
10
+ // - no implicit global `socket`; uses 'disconnect' (socket.io has no 'close')
11
+ // - controller read/write logging only when options.verbose is set
12
+ // - callback(err) is called for open errors, callback(null, socket) on every
13
+ // successful port open
14
+
15
+ const fs = require('fs');
16
+ const path = require('path');
17
+ const io = require('socket.io-client');
18
+ const jwt = require('jsonwebtoken');
19
+ const get = require('lodash.get');
20
+
21
+ /**
22
+ * Returns the current user's home directory.
23
+ *
24
+ * @returns {string|undefined} $HOME (or %USERPROFILE% on Windows)
25
+ */
26
+ const getUserHome = () => process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
27
+
28
+ /**
29
+ * Signs a CNCjs access token.
30
+ *
31
+ * @param {object} payload - token payload, e.g. { id: '', name: 'cncjs-handwheel' }
32
+ * @param {string} secret - the CNCjs secret
33
+ * @param {string|number} expiration - token lifetime understood by jsonwebtoken, e.g. '30d'
34
+ * @returns {string} the signed JWT
35
+ */
36
+ const generateAccessToken = (payload, secret, expiration) =>
37
+ jwt.sign(payload, secret, { expiresIn: expiration });
38
+
39
+ /**
40
+ * Reads and parses the CNCjs configuration file.
41
+ *
42
+ * @param {string} [file] - path of the file (default: ~/.cncrc)
43
+ * @returns {object} the parsed config, or {} if the file is missing or invalid
44
+ */
45
+ const readCncrc = (file) => {
46
+ try {
47
+ return JSON.parse(fs.readFileSync(file || path.resolve(getUserHome(), '.cncrc'), 'utf8'));
48
+ } catch (err) {
49
+ return {};
50
+ }
51
+ };
52
+
53
+ /**
54
+ * Connects to the CNCjs server, opens (or attaches to) the CNC serial port and keeps both alive.
55
+ * Reconnects automatically (with a fresh access token) and retries failed port opens.
56
+ *
57
+ * @param {object} options
58
+ * @param {string} options.port - CNC controller port as known to CNCjs, e.g. /dev/ttyUSB0
59
+ * @param {string} [options.secret] - CNCjs secret (default: $CNCJS_SECRET, then ~/.cncrc)
60
+ * @param {number} [options.baudrate=115200] - CNC controller baud rate
61
+ * @param {string} [options.socketAddress='localhost'] - CNCjs host
62
+ * @param {number} [options.socketPort=8000] - CNCjs port
63
+ * @param {string} [options.controllerType='Grbl'] - Grbl | Smoothie | TinyG
64
+ * @param {string} [options.accessTokenLifetime='30d'] - lifetime of each generated token
65
+ * @param {number} [options.retryInterval=5000] - ms between port open retries, 0 = never retry
66
+ * @param {boolean} [options.verbose=false] - log all serialport:read / serialport:write traffic
67
+ * @param {function(Error|null, object=)} [callback] - called with (null, socket) on every successful
68
+ * port open and with (err) on every failed one
69
+ * @returns {object} the socket.io client socket (stays valid across reconnects)
70
+ */
71
+ module.exports = function(options, callback) {
72
+ options = options || {};
73
+ callback = callback || function() {};
74
+ options.secret = get(options, 'secret', process.env['CNCJS_SECRET']);
75
+ options.baudrate = get(options, 'baudrate', 115200);
76
+ options.socketAddress = get(options, 'socketAddress', 'localhost');
77
+ options.socketPort = get(options, 'socketPort', 8000);
78
+ options.controllerType = get(options, 'controllerType', 'Grbl');
79
+ options.accessTokenLifetime = get(options, 'accessTokenLifetime', '30d');
80
+ options.retryInterval = get(options, 'retryInterval', 5000); // ms, 0 = never retry
81
+ options.verbose = get(options, 'verbose', false);
82
+
83
+ if (!options.secret) {
84
+ options.secret = readCncrc().secret;
85
+ if (!options.secret) {
86
+ console.error('No CNCjs secret found. Use --secret, $CNCJS_SECRET or ~/.cncrc');
87
+ process.exit(1);
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Creates a fresh access token for the connection (called on connect and on every reconnect attempt).
93
+ *
94
+ * @returns {string} the signed JWT
95
+ */
96
+ const makeToken = () =>
97
+ generateAccessToken({ id: '', name: 'cncjs-handwheel' }, options.secret, options.accessTokenLifetime);
98
+ const address = 'ws://' + options.socketAddress + ':' + options.socketPort;
99
+
100
+ const socket = io.connect(address, { query: 'token=' + makeToken() });
101
+ let retryTimer = null;
102
+
103
+ /**
104
+ * Asks CNCjs to open the CNC port. If the port is already open (e.g. by the CNCjs UI) this
105
+ * attaches the pendant connection to it.
106
+ *
107
+ * @returns {void}
108
+ */
109
+ const openPort = () => {
110
+ socket.emit('open', options.port, {
111
+ baudrate: Number(options.baudrate),
112
+ controllerType: options.controllerType
113
+ });
114
+ };
115
+
116
+ // socket.io-client v2 reuses the original query on reconnect; refresh it.
117
+ socket.on('reconnect_attempt', () => {
118
+ socket.io.opts.query = 'token=' + makeToken();
119
+ });
120
+
121
+ socket.on('connect', () => {
122
+ console.log('Connected to ' + address);
123
+ openPort(); // attaches to the port if the CNCjs UI already opened it
124
+ });
125
+
126
+ socket.on('error', (err) => {
127
+ console.error('Connection error:', err && err.message ? err.message : err);
128
+ });
129
+
130
+ socket.on('disconnect', () => {
131
+ console.log('Disconnected from ' + address);
132
+ });
133
+
134
+ socket.on('serialport:open', (data) => {
135
+ data = data || {};
136
+ clearTimeout(retryTimer);
137
+ console.log('Connected to port "' + data.port + '" (Baud rate: ' + data.baudrate + ')');
138
+ callback(null, socket);
139
+ });
140
+
141
+ socket.on('serialport:error', (data) => {
142
+ data = data || {};
143
+ callback(new Error('Error opening serial port "' + data.port + '"'));
144
+ if (options.retryInterval > 0) {
145
+ clearTimeout(retryTimer);
146
+ retryTimer = setTimeout(() => {
147
+ if (socket.connected) {
148
+ openPort();
149
+ }
150
+ }, options.retryInterval);
151
+ }
152
+ });
153
+
154
+ if (options.verbose) {
155
+ socket.on('serialport:read', (data) => console.log('<', (data || '').trim()));
156
+ socket.on('serialport:write', (data) => console.log('>', (data || '').trim()));
157
+ }
158
+
159
+ return socket;
160
+ };
161
+
162
+ /** Exposed so callers can read other sections (e.g. `pendant`) of ~/.cncrc. */
163
+ module.exports.readCncrc = readCncrc;
package/lib/service.js ADDED
@@ -0,0 +1,234 @@
1
+ 'use strict';
2
+
3
+ // "<command> install-service" / "<command> uninstall-service"
4
+ // Sets up (or removes) a systemd unit and, optionally, a udev rule for the pendant.
5
+ // All names and paths are derived from package.json and the running Node, so a package rename
6
+ // carries through and the unit never depends on PATH (nvm installs work).
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const { execFileSync } = require('child_process');
11
+ const pkg = require('../package.json');
12
+
13
+ const NAME = pkg.name.replace(/^@[^/]+\//, '');
14
+ const COMMAND = typeof pkg.bin === 'string' ? NAME : Object.keys(pkg.bin)[0];
15
+ const BIN = path.resolve(__dirname, '..', typeof pkg.bin === 'string' ? pkg.bin : Object.values(pkg.bin)[0]);
16
+ const NODE = process.execPath;
17
+ const UNIT_PATH = '/etc/systemd/system/' + NAME + '.service';
18
+ const RULE_PATH = '/etc/udev/rules.d/99-' + NAME + '.rules';
19
+
20
+ /**
21
+ * Prints an error message and exits with status 1.
22
+ *
23
+ * @param {string} msg - the message to print to stderr
24
+ * @returns {never}
25
+ */
26
+ const die = (msg) => { console.error(msg); process.exit(1); };
27
+ /**
28
+ * Quotes a path for use in a systemd ExecStart line when it contains whitespace.
29
+ *
30
+ * @param {string} s - the path
31
+ * @returns {string} the path, wrapped in double quotes if needed
32
+ */
33
+ const quote = (s) => (/\s/.test(s) ? '"' + s + '"' : s);
34
+
35
+ /**
36
+ * Prints the help text for the install-service / uninstall-service subcommands.
37
+ *
38
+ * @returns {void}
39
+ */
40
+ function usage() {
41
+ console.log([
42
+ 'Usage: sudo env "PATH=$PATH" ' + COMMAND + ' install-service [options]',
43
+ ' sudo env "PATH=$PATH" ' + COMMAND + ' uninstall-service',
44
+ '',
45
+ ' --user USER user the service runs as; must be the user that runs CNCjs, because the',
46
+ ' secret is read from that user\'s ~/.cncrc (default: $SUDO_USER)',
47
+ ' --usb-port PORT USB port the pendant is plugged into: the first KERNELS value of',
48
+ ' "udevadm info -a -n /dev/ttyUSBx", e.g. 1-2:1.0. Installs a udev rule that',
49
+ ' creates /dev/pendant and sets the port up so opening it does not reset the ESP32.',
50
+ ' --start start the service now (otherwise edit the config first)',
51
+ ' --dry-run print what would be written, change nothing (no root needed)'
52
+ ].join('\n'));
53
+ }
54
+
55
+ /**
56
+ * Parses the options that follow the subcommand. Exits with an error on an unknown option.
57
+ *
58
+ * @param {string[]} argv - arguments after the subcommand
59
+ * @returns {{user: (string|undefined), usbPort: (string|undefined), start: (boolean|undefined),
60
+ * dryRun: (boolean|undefined), help: (boolean|undefined)}}
61
+ */
62
+ function parseArgs(argv) {
63
+ const o = {};
64
+ for (let i = 0; i < argv.length; i++) {
65
+ const a = argv[i];
66
+ if (a === '--user') o.user = argv[++i];
67
+ else if (a === '--usb-port') o.usbPort = argv[++i];
68
+ else if (a === '--start') o.start = true;
69
+ else if (a === '--dry-run') o.dryRun = true;
70
+ else if (a === '-h' || a === '--help') o.help = true;
71
+ else die('Unknown option: ' + a);
72
+ }
73
+ return o;
74
+ }
75
+
76
+ /**
77
+ * Finds the group that grants access to serial ports on this system ('dialout' on Debian and
78
+ * Raspberry Pi OS, 'uucp' on Arch).
79
+ *
80
+ * @returns {?string} the group name, or null if neither exists
81
+ */
82
+ function serialGroup() {
83
+ try {
84
+ const groups = fs.readFileSync('/etc/group', 'utf8');
85
+ return ['dialout', 'uucp'].find((g) => new RegExp('^' + g + ':', 'm').test(groups)) || null;
86
+ } catch (err) {
87
+ return null;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * Runs an external command with its output shown to the user.
93
+ *
94
+ * @param {string} cmd - the executable, e.g. 'systemctl'
95
+ * @param {string[]} args - its arguments
96
+ * @param {boolean} [tolerate=false] - when true a failure is ignored, otherwise the process exits
97
+ * @returns {void}
98
+ */
99
+ function run(cmd, args, tolerate) {
100
+ try {
101
+ execFileSync(cmd, args, { stdio: 'inherit' });
102
+ } catch (err) {
103
+ if (!tolerate) die(cmd + ' ' + args.join(' ') + ' failed');
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Builds the text of the systemd unit. The unit runs the bridge with the absolute path of the Node
109
+ * that executed this command, so it does not depend on PATH (nvm installs work). Config is found
110
+ * the same way as when the bridge is started by hand, through the service user's home directory.
111
+ *
112
+ * @param {string} user - user the service runs as
113
+ * @param {?string} group - supplementary group for serial port access, or null
114
+ * @returns {string} the unit file content
115
+ */
116
+ function unitText(user, group) {
117
+ return [
118
+ '[Unit]',
119
+ 'Description=' + (pkg.description || NAME),
120
+ 'After=network-online.target',
121
+ 'Wants=network-online.target',
122
+ '',
123
+ '[Service]',
124
+ 'Type=simple',
125
+ 'User=' + user,
126
+ group ? 'SupplementaryGroups=' + group : null,
127
+ 'ExecStart=' + quote(NODE) + ' ' + quote(BIN),
128
+ 'Restart=always',
129
+ 'RestartSec=3',
130
+ 'NoNewPrivileges=true',
131
+ 'ProtectSystem=full',
132
+ 'ProtectHome=read-only',
133
+ 'PrivateTmp=true',
134
+ '',
135
+ '[Install]',
136
+ 'WantedBy=multi-user.target',
137
+ ''
138
+ ].filter((l) => l !== null).join('\n');
139
+ }
140
+
141
+ /**
142
+ * Builds the text of the udev rule for the pendant. The rule matches by USB port (so it never touches
143
+ * the CNC controller's identical CH340), creates /dev/pendant, keeps ModemManager away, and sets the
144
+ * port up without hangup-on-close so that opening it does not reset the ESP32.
145
+ *
146
+ * @param {string} usbPort - the KERNELS value of the pendant's USB port, e.g. '1-2:1.0'
147
+ * @returns {string} the rule file content
148
+ */
149
+ function ruleText(usbPort) {
150
+ return [
151
+ '# ' + NAME + ': stable /dev/pendant name, no ModemManager probing, and a port setup that does not',
152
+ '# drop DTR/RTS (which would reset the ESP32 through its auto-reset circuit).',
153
+ 'SUBSYSTEM=="tty", ACTION=="add", KERNELS=="' + usbPort + '", SYMLINK+="pendant", ' +
154
+ 'ENV{ID_MM_DEVICE_IGNORE}="1", RUN+="/bin/stty -F /dev/%k 115200 raw -echo -crtscts -hupcl"',
155
+ ''
156
+ ].join('\n');
157
+ }
158
+
159
+ /**
160
+ * Installs the systemd unit (and optionally the udev rule), reloads systemd and enables the service.
161
+ * Needs root unless --dry-run is given, in which case the files are only printed.
162
+ *
163
+ * @param {object} o - parsed options from parseArgs()
164
+ * @returns {void}
165
+ */
166
+ function install(o) {
167
+ const user = o.user || process.env.SUDO_USER;
168
+ if (!user || user === 'root') die('Cannot tell which user should run the service. Use --user USER (the user running CNCjs).');
169
+ if (o.usbPort && !/^[0-9]+-[0-9.]+:[0-9.]+$/.test(o.usbPort)) die('--usb-port should look like 1-2:1.0');
170
+ if (!o.dryRun) {
171
+ if (typeof process.getuid === 'function' && process.getuid() !== 0) {
172
+ die('Needs root: sudo env "PATH=$PATH" ' + COMMAND + ' install-service ...');
173
+ }
174
+ try { execFileSync('id', ['-u', user], { stdio: 'ignore' }); } catch (err) { die('No such user: ' + user); }
175
+ }
176
+ const group = serialGroup();
177
+ const unit = unitText(user, group);
178
+ const rule = o.usbPort ? ruleText(o.usbPort) : null;
179
+
180
+ if (o.dryRun) {
181
+ console.log('# ' + UNIT_PATH + '\n' + unit);
182
+ if (rule) console.log('# ' + RULE_PATH + '\n' + rule);
183
+ return;
184
+ }
185
+
186
+ fs.writeFileSync(UNIT_PATH, unit);
187
+ console.log('Wrote ' + UNIT_PATH);
188
+ if (rule) {
189
+ fs.writeFileSync(RULE_PATH, rule);
190
+ run('udevadm', ['control', '--reload'], true);
191
+ console.log('Wrote ' + RULE_PATH + ' (replug the pendant, then use /dev/pendant as the pendant port)');
192
+ }
193
+ run('systemctl', ['daemon-reload']);
194
+ run('systemctl', ['enable', NAME]);
195
+ if (o.start) {
196
+ run('systemctl', ['restart', NAME]);
197
+ console.log('Started.');
198
+ } else {
199
+ console.log('Not started yet. Create the config (see the example in ' + path.resolve(__dirname, '..') +
200
+ '), then: sudo systemctl start ' + NAME);
201
+ }
202
+ console.log('Logs: journalctl -u ' + NAME + ' -f');
203
+ }
204
+
205
+ /**
206
+ * Stops and disables the service and removes the unit and the udev rule. The config file is kept.
207
+ * Needs root.
208
+ *
209
+ * @returns {void}
210
+ */
211
+ function uninstall() {
212
+ if (typeof process.getuid === 'function' && process.getuid() !== 0) {
213
+ die('Needs root: sudo env "PATH=$PATH" ' + COMMAND + ' uninstall-service');
214
+ }
215
+ run('systemctl', ['disable', '--now', NAME], true);
216
+ [UNIT_PATH, RULE_PATH].forEach((f) => { try { fs.unlinkSync(f); console.log('Removed ' + f); } catch (err) { /* not there */ } });
217
+ run('systemctl', ['daemon-reload'], true);
218
+ run('udevadm', ['control', '--reload'], true);
219
+ console.log('Done. The config file was left in place.');
220
+ }
221
+
222
+ /**
223
+ * Entry point for the install-service / uninstall-service subcommands.
224
+ *
225
+ * @param {string} cmd - 'install-service' or 'uninstall-service'
226
+ * @param {string[]} argv - the arguments after the subcommand
227
+ * @returns {void}
228
+ */
229
+ module.exports = function(cmd, argv) {
230
+ const o = parseArgs(argv);
231
+ if (o.help) return usage();
232
+ if (cmd === 'uninstall-service') return uninstall();
233
+ return install(o);
234
+ };
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "cncjs-handwheel",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "CNCjs pendant bridge for a serial (USB/Bluetooth) ESP32 CNC handwheel",
5
+ "keywords": [
6
+ "cncjs",
7
+ "pendant",
8
+ "handwheel",
9
+ "grbl",
10
+ "esp32",
11
+ "cnc"
12
+ ],
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/thor-schueler/CNCjs-Handwheel.git"
17
+ },
18
+ "author": "theRealThor",
19
+ "main": "index.js",
20
+ "bin": {
21
+ "cncjs-handwheel": "bin/cncjs-handwheel"
22
+ },
23
+ "files": [
24
+ "bin",
25
+ "lib",
26
+ "index.js",
27
+ "cncjs-pendant.config.example.json"
28
+ ],
29
+ "scripts": {
30
+ "start": "node bin/cncjs-handwheel",
31
+ "check": "node --check index.js && node --check bin/cncjs-handwheel && node --check lib/service.js",
32
+ "prepublishOnly": "npm run check"
33
+ },
34
+ "engines": {
35
+ "node": ">=20"
36
+ },
37
+ "dependencies": {
38
+ "commander": "^9.5.0",
39
+ "jsonwebtoken": "^9.0.0",
40
+ "lodash.get": "^4.4.2",
41
+ "serialport": "^13.0.0",
42
+ "socket.io-client": "^2.5.0"
43
+ }
44
+ }