cncjs-handwheel 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -8
- package/bin/cncjs-handwheel +349 -30
- package/cncjs-handwheel.config.example.json +40 -0
- package/index.js +311 -62
- package/lib/service.js +109 -8
- package/package.json +6 -3
- package/widget/dist/assets/index-DjeoyRHc.css +1 -0
- package/widget/dist/assets/index-rdV6NzC9.js +40 -0
- package/widget/dist/index.html +13 -0
package/index.js
CHANGED
|
@@ -3,15 +3,22 @@
|
|
|
3
3
|
// CNCjs client helper (adapted from cncjs-pendant-keyboard/index.js).
|
|
4
4
|
//
|
|
5
5
|
// Differences from the original:
|
|
6
|
-
// - returns
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
10
|
-
//
|
|
11
|
-
//
|
|
12
|
-
//
|
|
13
|
-
//
|
|
6
|
+
// - returns a connection object immediately and keeps the connection alive by itself:
|
|
7
|
+
// * every (re)connect builds a brand new socket.io client with a fresh access token,
|
|
8
|
+
// so no stale socket.io state or expired token can survive a CNCjs restart
|
|
9
|
+
// * after each connect the CNC port is opened (or attached to) and the answer is
|
|
10
|
+
// verified; no answer -> ask again -> still no answer -> rebuild the connection
|
|
11
|
+
// * a periodic keepalive repeats the open request, which detects (and repairs) a server
|
|
12
|
+
// that has forgotten this client
|
|
13
|
+
// * a failed port open is retried every options.retryInterval, a port that is closed
|
|
14
|
+
// behind our back is reopened (options.reopenOnClose)
|
|
15
|
+
// - nothing is buffered while disconnected: emit() returns false instead of replaying stale
|
|
16
|
+
// commands after the reconnect (socket.io would otherwise do exactly that)
|
|
17
|
+
// - lifecycle events are always logged; controller traffic only with options.verbose
|
|
18
|
+
// - callback(err) is called for open errors, callback(null, connection) on every successful
|
|
19
|
+
// port open
|
|
14
20
|
|
|
21
|
+
const EventEmitter = require('events');
|
|
15
22
|
const fs = require('fs');
|
|
16
23
|
const path = require('path');
|
|
17
24
|
const io = require('socket.io-client');
|
|
@@ -52,7 +59,12 @@ const readCncrc = (file) => {
|
|
|
52
59
|
|
|
53
60
|
/**
|
|
54
61
|
* Connects to the CNCjs server, opens (or attaches to) the CNC serial port and keeps both alive.
|
|
55
|
-
*
|
|
62
|
+
*
|
|
63
|
+
* The returned connection has the parts of the socket.io client API the bridge needs:
|
|
64
|
+
* `on`, `once`, `off`, `emit`, `close` and the read-only properties `connected` and `portOpen`.
|
|
65
|
+
* It stays valid across reconnects (the socket.io client underneath is replaced on every reconnect).
|
|
66
|
+
* Events from the server are delivered to `on` listeners; `connect` and `disconnect` are emitted
|
|
67
|
+
* on every (re)connect / loss of the connection.
|
|
56
68
|
*
|
|
57
69
|
* @param {object} options
|
|
58
70
|
* @param {string} options.port - CNC controller port as known to CNCjs, e.g. /dev/ttyUSB0
|
|
@@ -62,11 +74,18 @@ const readCncrc = (file) => {
|
|
|
62
74
|
* @param {number} [options.socketPort=8000] - CNCjs port
|
|
63
75
|
* @param {string} [options.controllerType='Grbl'] - Grbl | Smoothie | TinyG
|
|
64
76
|
* @param {string} [options.accessTokenLifetime='30d'] - lifetime of each generated token
|
|
65
|
-
* @param {number} [options.retryInterval=5000] - ms
|
|
77
|
+
* @param {number} [options.retryInterval=5000] - ms before a failed or lost port open is retried, 0 = never
|
|
78
|
+
* @param {number} [options.openTimeout=5000] - ms to wait for CNCjs to answer an open request
|
|
79
|
+
* @param {number} [options.maxOpenTries=3] - unanswered open requests before the connection is rebuilt
|
|
80
|
+
* @param {number} [options.keepaliveMs=30000] - interval of the keepalive open request, 0 = off
|
|
81
|
+
* @param {boolean} [options.reopenOnClose=true] - reopen the port when it was closed (e.g. from the CNCjs UI)
|
|
82
|
+
* @param {number} [options.reconnectMin=1000] - first delay (ms) before rebuilding a lost connection
|
|
83
|
+
* @param {number} [options.reconnectMax=10000] - maximum delay (ms) between rebuilds
|
|
66
84
|
* @param {boolean} [options.verbose=false] - log all serialport:read / serialport:write traffic
|
|
67
|
-
* @param {function(Error|null, object=)} [callback] - called with (null,
|
|
68
|
-
*
|
|
69
|
-
* @returns {
|
|
85
|
+
* @param {function(Error|null, object=)} [callback] - called with (null, connection) on every
|
|
86
|
+
* answered open request and with (err) on every failed one
|
|
87
|
+
* @returns {{connected: boolean, portOpen: boolean, on: function, once: function, off: function,
|
|
88
|
+
* emit: function(...*): boolean, close: function}} the connection
|
|
70
89
|
*/
|
|
71
90
|
module.exports = function(options, callback) {
|
|
72
91
|
options = options || {};
|
|
@@ -77,7 +96,13 @@ module.exports = function(options, callback) {
|
|
|
77
96
|
options.socketPort = get(options, 'socketPort', 8000);
|
|
78
97
|
options.controllerType = get(options, 'controllerType', 'Grbl');
|
|
79
98
|
options.accessTokenLifetime = get(options, 'accessTokenLifetime', '30d');
|
|
80
|
-
options.retryInterval = get(options, 'retryInterval', 5000);
|
|
99
|
+
options.retryInterval = get(options, 'retryInterval', 5000);
|
|
100
|
+
options.openTimeout = get(options, 'openTimeout', 5000);
|
|
101
|
+
options.maxOpenTries = get(options, 'maxOpenTries', 3);
|
|
102
|
+
options.keepaliveMs = get(options, 'keepaliveMs', 30000);
|
|
103
|
+
options.reopenOnClose = get(options, 'reopenOnClose', true);
|
|
104
|
+
options.reconnectMin = get(options, 'reconnectMin', 1000);
|
|
105
|
+
options.reconnectMax = get(options, 'reconnectMax', 10000);
|
|
81
106
|
options.verbose = get(options, 'verbose', false);
|
|
82
107
|
|
|
83
108
|
if (!options.secret) {
|
|
@@ -88,76 +113,300 @@ module.exports = function(options, callback) {
|
|
|
88
113
|
}
|
|
89
114
|
}
|
|
90
115
|
|
|
116
|
+
const address = 'ws://' + options.socketAddress + ':' + options.socketPort;
|
|
117
|
+
const bus = new EventEmitter(); // where the listeners of the returned connection are attached
|
|
118
|
+
|
|
119
|
+
let socket = null; // the current socket.io client
|
|
120
|
+
let generation = 0; // bumped whenever the current socket is replaced; stale sockets are ignored
|
|
121
|
+
let connected = false; // the current socket is connected to CNCjs
|
|
122
|
+
let portOpen = false; // CNCjs has confirmed that the CNC port is open and we are attached to it
|
|
123
|
+
let openTries = 0; // unanswered open requests since the last answer
|
|
124
|
+
let backoff = options.reconnectMin;
|
|
125
|
+
let closed = false;
|
|
126
|
+
let openTimer = null;
|
|
127
|
+
let rebuildTimer = null;
|
|
128
|
+
let keepaliveTimer = null;
|
|
129
|
+
|
|
91
130
|
/**
|
|
92
|
-
* Creates a fresh access token
|
|
131
|
+
* Creates a fresh access token (a new one for every new socket).
|
|
93
132
|
*
|
|
94
133
|
* @returns {string} the signed JWT
|
|
95
134
|
*/
|
|
96
135
|
const makeToken = () =>
|
|
97
136
|
generateAccessToken({ id: '', name: 'cncjs-handwheel' }, options.secret, options.accessTokenLifetime);
|
|
98
|
-
const address = 'ws://' + options.socketAddress + ':' + options.socketPort;
|
|
99
137
|
|
|
100
|
-
|
|
101
|
-
|
|
138
|
+
/**
|
|
139
|
+
* Extracts a printable message from a socket.io error value.
|
|
140
|
+
*
|
|
141
|
+
* @param {*} err - Error, string or anything else
|
|
142
|
+
* @returns {string}
|
|
143
|
+
*/
|
|
144
|
+
const errText = (err) => (err && err.message ? err.message : String(err));
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Records whether the CNC port is open and logs the transitions (not every confirmation).
|
|
148
|
+
*
|
|
149
|
+
* @param {boolean} value
|
|
150
|
+
* @param {object} [data] - the serialport:open payload, for the log line
|
|
151
|
+
* @returns {void}
|
|
152
|
+
*/
|
|
153
|
+
function setPortOpen(value, data) {
|
|
154
|
+
if (value === portOpen) return;
|
|
155
|
+
portOpen = value;
|
|
156
|
+
if (value) {
|
|
157
|
+
data = data || {};
|
|
158
|
+
console.log('Connected to port "' + (data.port || options.port) + '" (Baud rate: ' +
|
|
159
|
+
(data.baudrate || options.baudrate) + ')');
|
|
160
|
+
} else {
|
|
161
|
+
console.log('CNC port "' + options.port + '" is not open');
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Stops the open / keepalive timers (not the rebuild timer).
|
|
167
|
+
*
|
|
168
|
+
* @returns {void}
|
|
169
|
+
*/
|
|
170
|
+
function stopOpenTimers() {
|
|
171
|
+
clearTimeout(openTimer);
|
|
172
|
+
clearInterval(keepaliveTimer);
|
|
173
|
+
openTimer = null;
|
|
174
|
+
keepaliveTimer = null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Marks the connection as lost and tells the listeners (once per connect).
|
|
179
|
+
*
|
|
180
|
+
* @param {string} reason - why, for the listeners and the log
|
|
181
|
+
* @returns {void}
|
|
182
|
+
*/
|
|
183
|
+
function markDisconnected(reason) {
|
|
184
|
+
stopOpenTimers();
|
|
185
|
+
const was = connected;
|
|
186
|
+
connected = false;
|
|
187
|
+
portOpen = false;
|
|
188
|
+
if (was) {
|
|
189
|
+
console.log('Disconnected from ' + address + ' (' + reason + ')');
|
|
190
|
+
bus.emit('disconnect', reason);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Throws the current socket away. Everything it still emits is ignored afterwards.
|
|
196
|
+
*
|
|
197
|
+
* @returns {void}
|
|
198
|
+
*/
|
|
199
|
+
function teardown() {
|
|
200
|
+
generation++;
|
|
201
|
+
const old = socket;
|
|
202
|
+
socket = null;
|
|
203
|
+
if (old) {
|
|
204
|
+
try { old.close(); } catch (err) { /* already gone */ }
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Schedules building a new socket (exponential backoff, at most one pending).
|
|
210
|
+
*
|
|
211
|
+
* @param {string} reason - why, for the log
|
|
212
|
+
* @returns {void}
|
|
213
|
+
*/
|
|
214
|
+
function scheduleRebuild(reason) {
|
|
215
|
+
if (closed) return;
|
|
216
|
+
markDisconnected(reason);
|
|
217
|
+
teardown();
|
|
218
|
+
if (rebuildTimer) return;
|
|
219
|
+
const delay = backoff;
|
|
220
|
+
backoff = Math.min(backoff * 2, options.reconnectMax);
|
|
221
|
+
console.log('Reconnecting to ' + address + ' in ' + (delay / 1000) + ' s (' + reason + ')');
|
|
222
|
+
rebuildTimer = setTimeout(() => { rebuildTimer = null; build(); }, delay);
|
|
223
|
+
}
|
|
102
224
|
|
|
103
225
|
/**
|
|
104
|
-
* Asks CNCjs to open the CNC port
|
|
105
|
-
*
|
|
226
|
+
* Asks CNCjs to open the CNC port, or to attach this client to it if it is already open
|
|
227
|
+
* (for example opened by the CNCjs UI). CNCjs answers with serialport:open or serialport:error;
|
|
228
|
+
* if it answers neither the request is repeated and finally the connection is rebuilt.
|
|
106
229
|
*
|
|
107
230
|
* @returns {void}
|
|
108
231
|
*/
|
|
109
|
-
|
|
232
|
+
function requestOpen() {
|
|
233
|
+
if (closed || !socket || !connected) return;
|
|
234
|
+
clearTimeout(openTimer);
|
|
235
|
+
openTries++;
|
|
110
236
|
socket.emit('open', options.port, {
|
|
111
237
|
baudrate: Number(options.baudrate),
|
|
112
238
|
controllerType: options.controllerType
|
|
113
239
|
});
|
|
114
|
-
|
|
240
|
+
openTimer = setTimeout(onOpenTimeout, options.openTimeout);
|
|
241
|
+
}
|
|
115
242
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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);
|
|
243
|
+
/**
|
|
244
|
+
* No answer to an open request within options.openTimeout: ask again, or rebuild the connection
|
|
245
|
+
* after options.maxOpenTries unanswered requests.
|
|
246
|
+
*
|
|
247
|
+
* @returns {void}
|
|
248
|
+
*/
|
|
249
|
+
function onOpenTimeout() {
|
|
250
|
+
openTimer = null;
|
|
251
|
+
if (closed || !connected) return;
|
|
252
|
+
if (openTries >= options.maxOpenTries) {
|
|
253
|
+
console.error('CNCjs did not answer ' + openTries + ' open requests for "' + options.port + '"');
|
|
254
|
+
scheduleRebuild('no answer to open request');
|
|
255
|
+
return;
|
|
151
256
|
}
|
|
152
|
-
|
|
257
|
+
console.warn('No answer from CNCjs to the open request for "' + options.port + '" (' + openTries + '/' +
|
|
258
|
+
options.maxOpenTries + '), asking again');
|
|
259
|
+
requestOpen();
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Retries the port open after options.retryInterval (used after an error or a close).
|
|
264
|
+
*
|
|
265
|
+
* @returns {void}
|
|
266
|
+
*/
|
|
267
|
+
function retryOpenLater() {
|
|
268
|
+
clearTimeout(openTimer);
|
|
269
|
+
openTimer = null;
|
|
270
|
+
if (options.retryInterval <= 0 || closed || !connected) return;
|
|
271
|
+
openTimer = setTimeout(() => {
|
|
272
|
+
openTimer = null;
|
|
273
|
+
openTries = 0;
|
|
274
|
+
requestOpen();
|
|
275
|
+
}, options.retryInterval);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Builds a new socket.io client and wires it up. The previous socket (if any) is discarded.
|
|
280
|
+
*
|
|
281
|
+
* @returns {void}
|
|
282
|
+
*/
|
|
283
|
+
function build() {
|
|
284
|
+
if (closed) return;
|
|
285
|
+
clearTimeout(rebuildTimer);
|
|
286
|
+
rebuildTimer = null;
|
|
287
|
+
markDisconnected('rebuilding the connection');
|
|
288
|
+
teardown();
|
|
289
|
+
|
|
290
|
+
const gen = ++generation;
|
|
291
|
+
const s = io.connect(address, {
|
|
292
|
+
query: 'token=' + makeToken(),
|
|
293
|
+
forceNew: true, // own manager: nothing is shared with the previous client
|
|
294
|
+
reconnection: false, // reconnecting is done here, with a new client and a new token
|
|
295
|
+
timeout: 10000
|
|
296
|
+
});
|
|
297
|
+
socket = s;
|
|
298
|
+
const current = () => gen === generation && !closed;
|
|
299
|
+
|
|
300
|
+
// Deliver every event from the server to the listeners of the returned connection.
|
|
301
|
+
// (Copy the arguments first: socket.io appends its ack callback to packet.data.)
|
|
302
|
+
const onevent = s.onevent;
|
|
303
|
+
s.onevent = function(packet) {
|
|
304
|
+
const args = (packet && packet.data ? packet.data : []).slice();
|
|
305
|
+
onevent.apply(this, arguments);
|
|
306
|
+
if (!current() || !args.length) return;
|
|
307
|
+
if (args[0] === 'error' && bus.listenerCount('error') === 0) return;
|
|
308
|
+
bus.emit.apply(bus, args);
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
s.on('connect', () => {
|
|
312
|
+
if (!current()) return;
|
|
313
|
+
connected = true;
|
|
314
|
+
openTries = 0;
|
|
315
|
+
console.log('Connected to ' + address);
|
|
316
|
+
bus.emit('connect');
|
|
317
|
+
requestOpen(); // attaches to the port if the CNCjs UI already opened it
|
|
318
|
+
});
|
|
319
|
+
|
|
320
|
+
s.on('disconnect', (reason) => {
|
|
321
|
+
if (!current()) return;
|
|
322
|
+
scheduleRebuild(reason || 'disconnected');
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
const failed = (what) => (err) => {
|
|
326
|
+
if (!current()) return;
|
|
327
|
+
console.error('CNCjs connection ' + what + ': ' + errText(err));
|
|
328
|
+
if (!connected) scheduleRebuild(what);
|
|
329
|
+
};
|
|
330
|
+
s.on('connect_error', failed('error'));
|
|
331
|
+
s.on('connect_timeout', failed('timeout'));
|
|
332
|
+
s.on('error', failed('error'));
|
|
333
|
+
|
|
334
|
+
s.on('serialport:open', (data) => {
|
|
335
|
+
if (!current()) return;
|
|
336
|
+
clearTimeout(openTimer);
|
|
337
|
+
openTimer = null;
|
|
338
|
+
openTries = 0;
|
|
339
|
+
backoff = options.reconnectMin;
|
|
340
|
+
setPortOpen(true, data);
|
|
341
|
+
if (!keepaliveTimer && options.keepaliveMs > 0) {
|
|
342
|
+
keepaliveTimer = setInterval(() => {
|
|
343
|
+
if (connected && portOpen && !openTimer) {
|
|
344
|
+
openTries = 0;
|
|
345
|
+
requestOpen();
|
|
346
|
+
}
|
|
347
|
+
}, options.keepaliveMs);
|
|
348
|
+
}
|
|
349
|
+
callback(null, connection);
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
s.on('serialport:error', (data) => {
|
|
353
|
+
if (!current()) return;
|
|
354
|
+
data = data || {};
|
|
355
|
+
setPortOpen(false);
|
|
356
|
+
callback(new Error('Error opening serial port "' + (data.port || options.port) + '"'));
|
|
357
|
+
retryOpenLater();
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
s.on('serialport:close', () => {
|
|
361
|
+
if (!current()) return;
|
|
362
|
+
setPortOpen(false);
|
|
363
|
+
if (options.reopenOnClose) retryOpenLater();
|
|
364
|
+
});
|
|
365
|
+
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const connection = {
|
|
369
|
+
/** @returns {boolean} true while connected to CNCjs */
|
|
370
|
+
get connected() { return connected; },
|
|
371
|
+
/** @returns {boolean} true while CNCjs confirms that the CNC port is open and attached */
|
|
372
|
+
get portOpen() { return portOpen; },
|
|
373
|
+
on(...args) { bus.on(...args); return connection; },
|
|
374
|
+
once(...args) { bus.once(...args); return connection; },
|
|
375
|
+
off(...args) { bus.removeListener(...args); return connection; },
|
|
376
|
+
removeListener(...args) { bus.removeListener(...args); return connection; },
|
|
377
|
+
/**
|
|
378
|
+
* Sends an event to CNCjs. Nothing is queued: while the connection is down the event is
|
|
379
|
+
* dropped and false is returned, so a stale command can never be replayed after a reconnect.
|
|
380
|
+
*
|
|
381
|
+
* @param {...*} args - event name and arguments, as for socket.io
|
|
382
|
+
* @returns {boolean} true if the event was handed to the socket
|
|
383
|
+
*/
|
|
384
|
+
emit(...args) {
|
|
385
|
+
if (!socket || !connected) return false;
|
|
386
|
+
socket.emit(...args);
|
|
387
|
+
return true;
|
|
388
|
+
},
|
|
389
|
+
/**
|
|
390
|
+
* Closes the connection for good and stops all timers.
|
|
391
|
+
*
|
|
392
|
+
* @returns {void}
|
|
393
|
+
*/
|
|
394
|
+
close() {
|
|
395
|
+
closed = true;
|
|
396
|
+
clearTimeout(rebuildTimer);
|
|
397
|
+
markDisconnected('closed');
|
|
398
|
+
teardown();
|
|
399
|
+
}
|
|
400
|
+
};
|
|
153
401
|
|
|
154
402
|
if (options.verbose) {
|
|
155
|
-
|
|
156
|
-
|
|
403
|
+
bus.on('serialport:read', (data) => console.log('<', String(data || '').trim()));
|
|
404
|
+
bus.on('serialport:write', (data) => console.log('>', String(data || '').trim()));
|
|
157
405
|
}
|
|
158
406
|
|
|
159
|
-
|
|
407
|
+
build();
|
|
408
|
+
return connection;
|
|
160
409
|
};
|
|
161
410
|
|
|
162
411
|
/** Exposed so callers can read other sections (e.g. `pendant`) of ~/.cncrc. */
|
|
163
|
-
module.exports.readCncrc = readCncrc;
|
|
412
|
+
module.exports.readCncrc = readCncrc;
|
package/lib/service.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
// "<command> install-service" / "<command> uninstall-service"
|
|
4
|
-
// Sets up (or removes) a systemd unit and, optionally, a udev rule for
|
|
4
|
+
// Sets up (or removes) a systemd unit for the bridge and, optionally, either a udev rule for a USB
|
|
5
|
+
// pendant (--usb-port) or an RFCOMM binding for a Bluetooth pendant (--bt-mac).
|
|
5
6
|
// All names and paths are derived from package.json and the running Node, so a package rename
|
|
6
7
|
// carries through and the unit never depends on PATH (nvm installs work).
|
|
7
8
|
|
|
8
9
|
const fs = require('fs');
|
|
10
|
+
const os = require('os');
|
|
9
11
|
const path = require('path');
|
|
10
12
|
const { execFileSync } = require('child_process');
|
|
11
13
|
const pkg = require('../package.json');
|
|
@@ -16,6 +18,9 @@ const BIN = path.resolve(__dirname, '..', typeof pkg.bin === 'string' ? pkg.bin
|
|
|
16
18
|
const NODE = process.execPath;
|
|
17
19
|
const UNIT_PATH = '/etc/systemd/system/' + NAME + '.service';
|
|
18
20
|
const RULE_PATH = '/etc/udev/rules.d/99-' + NAME + '.rules';
|
|
21
|
+
const RFCOMM_UNIT = NAME + '-rfcomm';
|
|
22
|
+
const RFCOMM_UNIT_PATH = '/etc/systemd/system/' + RFCOMM_UNIT + '.service';
|
|
23
|
+
const RFCOMM_DEV = 0; // the Bluetooth pendant appears as /dev/rfcomm0
|
|
19
24
|
|
|
20
25
|
/**
|
|
21
26
|
* Prints an error message and exits with status 1.
|
|
@@ -47,6 +52,9 @@ function usage() {
|
|
|
47
52
|
' --usb-port PORT USB port the pendant is plugged into: the first KERNELS value of',
|
|
48
53
|
' "udevadm info -a -n /dev/ttyUSBx", e.g. 1-2:1.0. Installs a udev rule that',
|
|
49
54
|
' creates /dev/pendant and sets the port up so opening it does not reset the ESP32.',
|
|
55
|
+
' --bt-mac MAC Bluetooth pendant: its MAC address (e.g. AA:BB:CC:DD:EE:FF). Installs a service that',
|
|
56
|
+
' binds it to /dev/rfcomm' + RFCOMM_DEV + ' at boot. Pair the pendant first (see the README).',
|
|
57
|
+
' --bt-channel N RFCOMM channel of the pendant\'s serial profile (default: 1)',
|
|
50
58
|
' --start start the service now (otherwise edit the config first)',
|
|
51
59
|
' --dry-run print what would be written, change nothing (no root needed)'
|
|
52
60
|
].join('\n'));
|
|
@@ -56,8 +64,9 @@ function usage() {
|
|
|
56
64
|
* Parses the options that follow the subcommand. Exits with an error on an unknown option.
|
|
57
65
|
*
|
|
58
66
|
* @param {string[]} argv - arguments after the subcommand
|
|
59
|
-
* @returns {{user: (string|undefined), usbPort: (string|undefined),
|
|
60
|
-
*
|
|
67
|
+
* @returns {{user: (string|undefined), usbPort: (string|undefined), btMac: (string|undefined),
|
|
68
|
+
* btChannel: (string|undefined), start: (boolean|undefined), dryRun: (boolean|undefined),
|
|
69
|
+
* help: (boolean|undefined)}}
|
|
61
70
|
*/
|
|
62
71
|
function parseArgs(argv) {
|
|
63
72
|
const o = {};
|
|
@@ -65,6 +74,8 @@ function parseArgs(argv) {
|
|
|
65
74
|
const a = argv[i];
|
|
66
75
|
if (a === '--user') o.user = argv[++i];
|
|
67
76
|
else if (a === '--usb-port') o.usbPort = argv[++i];
|
|
77
|
+
else if (a === '--bt-mac') o.btMac = argv[++i];
|
|
78
|
+
else if (a === '--bt-channel') o.btChannel = argv[++i];
|
|
68
79
|
else if (a === '--start') o.start = true;
|
|
69
80
|
else if (a === '--dry-run') o.dryRun = true;
|
|
70
81
|
else if (a === '-h' || a === '--help') o.help = true;
|
|
@@ -111,14 +122,17 @@ function run(cmd, args, tolerate) {
|
|
|
111
122
|
*
|
|
112
123
|
* @param {string} user - user the service runs as
|
|
113
124
|
* @param {?string} group - supplementary group for serial port access, or null
|
|
125
|
+
* @param {boolean} [bluetooth=false] - start after the RFCOMM binding service
|
|
114
126
|
* @returns {string} the unit file content
|
|
115
127
|
*/
|
|
116
|
-
function unitText(user, group) {
|
|
128
|
+
function unitText(user, group, bluetooth) {
|
|
117
129
|
return [
|
|
118
130
|
'[Unit]',
|
|
119
131
|
'Description=' + (pkg.description || NAME),
|
|
120
132
|
'After=network-online.target',
|
|
121
133
|
'Wants=network-online.target',
|
|
134
|
+
bluetooth ? 'After=' + RFCOMM_UNIT + '.service' : null,
|
|
135
|
+
bluetooth ? 'Wants=' + RFCOMM_UNIT + '.service' : null,
|
|
122
136
|
'',
|
|
123
137
|
'[Service]',
|
|
124
138
|
'Type=simple',
|
|
@@ -156,6 +170,72 @@ function ruleText(usbPort) {
|
|
|
156
170
|
].join('\n');
|
|
157
171
|
}
|
|
158
172
|
|
|
173
|
+
/**
|
|
174
|
+
* Finds the absolute path of the `rfcomm` tool (part of the bluez package).
|
|
175
|
+
*
|
|
176
|
+
* @returns {?string} the path, or null if it is not installed
|
|
177
|
+
*/
|
|
178
|
+
function rfcommPath() {
|
|
179
|
+
try {
|
|
180
|
+
return execFileSync('which', ['rfcomm'], { encoding: 'utf8' }).trim() || null;
|
|
181
|
+
} catch (err) {
|
|
182
|
+
return null;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Builds the text of the systemd unit that binds the Bluetooth pendant to /dev/rfcomm0. Binding does
|
|
188
|
+
* not connect: the connection is made when the bridge opens the port, so a pendant that is switched off
|
|
189
|
+
* at boot is not a problem. The unit stays "active" after the bind so that stopping it releases the port.
|
|
190
|
+
*
|
|
191
|
+
* @param {string} rfcomm - absolute path of the rfcomm tool
|
|
192
|
+
* @param {string} mac - Bluetooth address of the pendant
|
|
193
|
+
* @param {number} channel - RFCOMM channel of its serial profile
|
|
194
|
+
* @returns {string} the unit file content
|
|
195
|
+
*/
|
|
196
|
+
function rfcommUnitText(rfcomm, mac, channel) {
|
|
197
|
+
return [
|
|
198
|
+
'[Unit]',
|
|
199
|
+
'Description=RFCOMM binding for the CNC handwheel (' + mac + ')',
|
|
200
|
+
'After=bluetooth.service',
|
|
201
|
+
'Requires=bluetooth.service',
|
|
202
|
+
'',
|
|
203
|
+
'[Service]',
|
|
204
|
+
'Type=oneshot',
|
|
205
|
+
'RemainAfterExit=yes',
|
|
206
|
+
'ExecStart=' + quote(rfcomm) + ' bind ' + RFCOMM_DEV + ' ' + mac + ' ' + channel,
|
|
207
|
+
'ExecStop=' + quote(rfcomm) + ' release ' + RFCOMM_DEV,
|
|
208
|
+
'',
|
|
209
|
+
'[Install]',
|
|
210
|
+
'WantedBy=multi-user.target',
|
|
211
|
+
''
|
|
212
|
+
].join('\n');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Looks for problems that make a Bluetooth pendant fail and returns them as warnings (nothing is
|
|
217
|
+
* changed): a Raspberry Pi kernel from the 6.18 series, whose onboard Bluetooth cannot connect to the
|
|
218
|
+
* handwheel, and a pendant that has not been paired yet.
|
|
219
|
+
*
|
|
220
|
+
* @param {string} mac - Bluetooth address of the pendant
|
|
221
|
+
* @returns {string[]} human readable warnings, empty if nothing was found
|
|
222
|
+
*/
|
|
223
|
+
function bluetoothWarnings(mac) {
|
|
224
|
+
const warnings = [];
|
|
225
|
+
const release = os.release();
|
|
226
|
+
if (/^6\.18\./.test(release) && /rpt/.test(release)) {
|
|
227
|
+
warnings.push('Kernel ' + release + ' (Raspberry Pi 6.18 series): on a Raspberry Pi 4 the onboard Bluetooth cannot ' +
|
|
228
|
+
'pair or connect to the handwheel (Page Timeout). Use kernel 6.12 or a USB Bluetooth adapter. See the README.');
|
|
229
|
+
}
|
|
230
|
+
try {
|
|
231
|
+
const info = execFileSync('bluetoothctl', ['info', mac], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
|
|
232
|
+
if (!/Paired:\s*yes/i.test(info)) warnings.push(mac + ' is known but not paired yet (bluetoothctl pair ' + mac + ').');
|
|
233
|
+
} catch (err) {
|
|
234
|
+
warnings.push(mac + ' is not known to this machine yet. Pair it first with bluetoothctl (see the README).');
|
|
235
|
+
}
|
|
236
|
+
return warnings;
|
|
237
|
+
}
|
|
238
|
+
|
|
159
239
|
/**
|
|
160
240
|
* Installs the systemd unit (and optionally the udev rule), reloads systemd and enables the service.
|
|
161
241
|
* Needs root unless --dry-run is given, in which case the files are only printed.
|
|
@@ -167,6 +247,10 @@ function install(o) {
|
|
|
167
247
|
const user = o.user || process.env.SUDO_USER;
|
|
168
248
|
if (!user || user === 'root') die('Cannot tell which user should run the service. Use --user USER (the user running CNCjs).');
|
|
169
249
|
if (o.usbPort && !/^[0-9]+-[0-9.]+:[0-9.]+$/.test(o.usbPort)) die('--usb-port should look like 1-2:1.0');
|
|
250
|
+
if (o.btMac && !/^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$/.test(o.btMac)) die('--bt-mac should look like AA:BB:CC:DD:EE:FF');
|
|
251
|
+
if (o.btChannel && !/^([1-9]|[12][0-9]|30)$/.test(o.btChannel)) die('--bt-channel should be a number from 1 to 30');
|
|
252
|
+
if (o.btChannel && !o.btMac) die('--bt-channel needs --bt-mac');
|
|
253
|
+
if (o.usbPort && o.btMac) die('Use either --usb-port (USB pendant) or --bt-mac (Bluetooth pendant), not both.');
|
|
170
254
|
if (!o.dryRun) {
|
|
171
255
|
if (typeof process.getuid === 'function' && process.getuid() !== 0) {
|
|
172
256
|
die('Needs root: sudo env "PATH=$PATH" ' + COMMAND + ' install-service ...');
|
|
@@ -174,12 +258,19 @@ function install(o) {
|
|
|
174
258
|
try { execFileSync('id', ['-u', user], { stdio: 'ignore' }); } catch (err) { die('No such user: ' + user); }
|
|
175
259
|
}
|
|
176
260
|
const group = serialGroup();
|
|
177
|
-
const unit = unitText(user, group);
|
|
261
|
+
const unit = unitText(user, group, !!o.btMac);
|
|
178
262
|
const rule = o.usbPort ? ruleText(o.usbPort) : null;
|
|
263
|
+
let rfcommUnit = null;
|
|
264
|
+
if (o.btMac) {
|
|
265
|
+
const rfcomm = rfcommPath();
|
|
266
|
+
if (!rfcomm && !o.dryRun) die('The rfcomm tool was not found. Install it with: sudo apt install bluez');
|
|
267
|
+
rfcommUnit = rfcommUnitText(rfcomm || '/usr/bin/rfcomm', o.btMac.toUpperCase(), Number(o.btChannel || 1));
|
|
268
|
+
}
|
|
179
269
|
|
|
180
270
|
if (o.dryRun) {
|
|
181
271
|
console.log('# ' + UNIT_PATH + '\n' + unit);
|
|
182
272
|
if (rule) console.log('# ' + RULE_PATH + '\n' + rule);
|
|
273
|
+
if (rfcommUnit) console.log('# ' + RFCOMM_UNIT_PATH + '\n' + rfcommUnit);
|
|
183
274
|
return;
|
|
184
275
|
}
|
|
185
276
|
|
|
@@ -190,9 +281,17 @@ function install(o) {
|
|
|
190
281
|
run('udevadm', ['control', '--reload'], true);
|
|
191
282
|
console.log('Wrote ' + RULE_PATH + ' (replug the pendant, then use /dev/pendant as the pendant port)');
|
|
192
283
|
}
|
|
284
|
+
if (rfcommUnit) {
|
|
285
|
+
fs.writeFileSync(RFCOMM_UNIT_PATH, rfcommUnit);
|
|
286
|
+
console.log('Wrote ' + RFCOMM_UNIT_PATH + ' (binds the pendant to /dev/rfcomm' + RFCOMM_DEV +
|
|
287
|
+
'; set the pendant port in the config to /dev/rfcomm' + RFCOMM_DEV + ')');
|
|
288
|
+
bluetoothWarnings(o.btMac).forEach((w) => console.warn('WARNING: ' + w));
|
|
289
|
+
}
|
|
193
290
|
run('systemctl', ['daemon-reload']);
|
|
291
|
+
if (rfcommUnit) run('systemctl', ['enable', RFCOMM_UNIT]);
|
|
194
292
|
run('systemctl', ['enable', NAME]);
|
|
195
293
|
if (o.start) {
|
|
294
|
+
if (rfcommUnit) run('systemctl', ['restart', RFCOMM_UNIT]);
|
|
196
295
|
run('systemctl', ['restart', NAME]);
|
|
197
296
|
console.log('Started.');
|
|
198
297
|
} else {
|
|
@@ -203,7 +302,8 @@ function install(o) {
|
|
|
203
302
|
}
|
|
204
303
|
|
|
205
304
|
/**
|
|
206
|
-
* Stops and disables the service and
|
|
305
|
+
* Stops and disables the service (and the RFCOMM binding service, if present) and removes the units and
|
|
306
|
+
* the udev rule. The config file is kept.
|
|
207
307
|
* Needs root.
|
|
208
308
|
*
|
|
209
309
|
* @returns {void}
|
|
@@ -213,7 +313,8 @@ function uninstall() {
|
|
|
213
313
|
die('Needs root: sudo env "PATH=$PATH" ' + COMMAND + ' uninstall-service');
|
|
214
314
|
}
|
|
215
315
|
run('systemctl', ['disable', '--now', NAME], true);
|
|
216
|
-
|
|
316
|
+
run('systemctl', ['disable', '--now', RFCOMM_UNIT], true);
|
|
317
|
+
[UNIT_PATH, RFCOMM_UNIT_PATH, RULE_PATH].forEach((f) => { try { fs.unlinkSync(f); console.log('Removed ' + f); } catch (err) { /* not there */ } });
|
|
217
318
|
run('systemctl', ['daemon-reload'], true);
|
|
218
319
|
run('udevadm', ['control', '--reload'], true);
|
|
219
320
|
console.log('Done. The config file was left in place.');
|
|
@@ -231,4 +332,4 @@ module.exports = function(cmd, argv) {
|
|
|
231
332
|
if (o.help) return usage();
|
|
232
333
|
if (cmd === 'uninstall-service') return uninstall();
|
|
233
334
|
return install(o);
|
|
234
|
-
};
|
|
335
|
+
};
|