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
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The pendant's serial port: opening it, reconnecting, writing to it, and watching the modem line that says whether the
|
|
4
|
+
// handwheel is switched on.
|
|
5
|
+
|
|
6
|
+
const { SerialPort } = require('serialport');
|
|
7
|
+
const { detectLink } = require('./protocol');
|
|
8
|
+
|
|
9
|
+
const REAL_OUTAGE_MS = 10000; // a link that was down this long was unplugged or switched off, not a glitch
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Creates the pendant link. Nothing is opened until open() is called.
|
|
13
|
+
*
|
|
14
|
+
* @param {object} ctx - the bridge context
|
|
15
|
+
* @returns {{open: function, send: function, isOpen: function, close: function, dispose: function}}
|
|
16
|
+
*/
|
|
17
|
+
module.exports = function createPendantLink(ctx) {
|
|
18
|
+
const { cfg, health } = ctx;
|
|
19
|
+
let pendantPort = null;
|
|
20
|
+
let reconnectTimer = null;
|
|
21
|
+
let downSince = null; // when the pendant link was lost (null while it is up)
|
|
22
|
+
|
|
23
|
+
let powerTimer = null;
|
|
24
|
+
let powerBusy = false;
|
|
25
|
+
let powerRaw = null; // last reading (true = on), not yet debounced
|
|
26
|
+
let powerSince = 0; // when powerRaw last changed
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Records a pendant serial error in the health data and prints it.
|
|
30
|
+
*
|
|
31
|
+
* @param {Error} err
|
|
32
|
+
* @returns {void}
|
|
33
|
+
*/
|
|
34
|
+
function noteError(err) {
|
|
35
|
+
health.pendant.errors++;
|
|
36
|
+
ctx.noteEvent('errors');
|
|
37
|
+
health.pendant.lastError = err.message;
|
|
38
|
+
console.error('Pendant error:', err.message);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Writes one line to the pendant's serial port.
|
|
43
|
+
*
|
|
44
|
+
* @param {string} text - the line, without terminator (a newline is added)
|
|
45
|
+
* @param {boolean} [should_log=false] - print the line when -v is on
|
|
46
|
+
* @returns {boolean} false if the pendant port is not open (or nothing may be written to the pendant)
|
|
47
|
+
*/
|
|
48
|
+
function send(text, should_log = false) {
|
|
49
|
+
if (!cfg.device.send) return false;
|
|
50
|
+
const port = pendantPort;
|
|
51
|
+
if (!port || !port.isOpen || health.pendant.powered === false) return false;
|
|
52
|
+
if (should_log) ctx.log('cncjs -> ', 'pendant', text);
|
|
53
|
+
port.write(text + '\n', (err) => {
|
|
54
|
+
if (err) noteError(err);
|
|
55
|
+
});
|
|
56
|
+
health.pendant.lastTx = Date.now();
|
|
57
|
+
health.pendant.txLines++;
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Schedules a reopen of the pendant serial port after device.reconnectMs (at most one pending).
|
|
63
|
+
*
|
|
64
|
+
* @returns {void}
|
|
65
|
+
*/
|
|
66
|
+
function scheduleReconnect() {
|
|
67
|
+
if (ctx.shuttingDown || reconnectTimer) return;
|
|
68
|
+
if (downSince === null) downSince = Date.now();
|
|
69
|
+
reconnectTimer = setTimeout(() => {
|
|
70
|
+
reconnectTimer = null;
|
|
71
|
+
health.pendant.reconnects++;
|
|
72
|
+
ctx.noteEvent('reconnects');
|
|
73
|
+
open();
|
|
74
|
+
}, cfg.device.reconnectMs);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Stops reading the power line and forgets what it said (the state is unknown while the port is closed).
|
|
79
|
+
*
|
|
80
|
+
* @returns {void}
|
|
81
|
+
*/
|
|
82
|
+
function stopPowerWatch() {
|
|
83
|
+
clearInterval(powerTimer);
|
|
84
|
+
powerTimer = null;
|
|
85
|
+
powerBusy = false;
|
|
86
|
+
powerRaw = null;
|
|
87
|
+
health.pendant.powered = null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Records a debounced change of the handwheel's power state.
|
|
92
|
+
*
|
|
93
|
+
* @param {boolean} on - true if the handwheel is switched on
|
|
94
|
+
* @returns {void}
|
|
95
|
+
*/
|
|
96
|
+
function setPowered(on) {
|
|
97
|
+
health.pendant.powered = on;
|
|
98
|
+
ctx.input.clearBuffer();
|
|
99
|
+
if (on) {
|
|
100
|
+
// the ESP32 is booting: ignore its output like after opening the port
|
|
101
|
+
ctx.input.ignoreFor(Number(cfg.device.settleMs || 0));
|
|
102
|
+
} else {
|
|
103
|
+
health.pendant.info = null; // a stale battery level is worse than none
|
|
104
|
+
ctx.jog.discardHeldJog(); // switching the handwheel off must not let a held jog fire afterwards
|
|
105
|
+
}
|
|
106
|
+
console.log('Handwheel switched ' + (on ? 'on' : 'off'));
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Reads the modem line once and applies the debounce.
|
|
111
|
+
*
|
|
112
|
+
* @param {SerialPort} port - the open pendant port
|
|
113
|
+
* @returns {void}
|
|
114
|
+
*/
|
|
115
|
+
function pollPower(port) {
|
|
116
|
+
if (powerBusy || !port.isOpen) return;
|
|
117
|
+
powerBusy = true;
|
|
118
|
+
port.get((err, signals) => {
|
|
119
|
+
powerBusy = false;
|
|
120
|
+
if (port !== pendantPort || !port.isOpen) return;
|
|
121
|
+
if (err) {
|
|
122
|
+
// e.g. Bluetooth (rfcomm) has no modem lines: say so once and stop asking
|
|
123
|
+
health.pendant.powerError = err.message;
|
|
124
|
+
console.error('Pendant power line cannot be read, power detection is off:', err.message);
|
|
125
|
+
stopPowerWatch();
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
const set = !!(signals && signals[cfg.device.power.line]);
|
|
129
|
+
const on = cfg.device.power.poweredWhen === 'set' ? set : !set;
|
|
130
|
+
const now = Date.now();
|
|
131
|
+
if (on !== powerRaw) {
|
|
132
|
+
powerRaw = on;
|
|
133
|
+
powerSince = now;
|
|
134
|
+
}
|
|
135
|
+
if (health.pendant.powered !== on && now - powerSince >= Number(cfg.device.power.debounceMs || 0)) setPowered(on);
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Starts polling the configured modem line of the pendant's port (nothing happens if device.power.line is null).
|
|
141
|
+
*
|
|
142
|
+
* @param {SerialPort} port - the open pendant port
|
|
143
|
+
* @returns {void}
|
|
144
|
+
*/
|
|
145
|
+
function startPowerWatch(port) {
|
|
146
|
+
stopPowerWatch();
|
|
147
|
+
health.pendant.powerError = null;
|
|
148
|
+
if (!cfg.device.power.line) return;
|
|
149
|
+
powerTimer = setInterval(() => pollPower(port), Math.max(50, Number(cfg.device.power.pollMs) || 250));
|
|
150
|
+
pollPower(port);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Opens the pendant's serial port and wires up its events. Failures and closes schedule a reconnect.
|
|
155
|
+
* After a successful open, pendant input is ignored for device.settleMs and a status line is sent.
|
|
156
|
+
*
|
|
157
|
+
* @returns {void}
|
|
158
|
+
*/
|
|
159
|
+
function open() {
|
|
160
|
+
const port = new SerialPort({
|
|
161
|
+
path: cfg.device.path,
|
|
162
|
+
baudRate: Number(cfg.device.baudRate),
|
|
163
|
+
autoOpen: false,
|
|
164
|
+
dataBits: 8,
|
|
165
|
+
stopBits: 1,
|
|
166
|
+
parity: 'none',
|
|
167
|
+
rtscts: false,
|
|
168
|
+
xon: false,
|
|
169
|
+
xoff: false,
|
|
170
|
+
xany: false,
|
|
171
|
+
hupcl: !!cfg.device.hupcl
|
|
172
|
+
});
|
|
173
|
+
pendantPort = port;
|
|
174
|
+
port.on('data', ctx.input.onPendantData);
|
|
175
|
+
port.on('error', noteError);
|
|
176
|
+
port.on('close', () => {
|
|
177
|
+
health.pendant.connected = false;
|
|
178
|
+
health.pendant.info = null; // a stale battery level is worse than none
|
|
179
|
+
ctx.jog.discardHeldJog(); // a jog held back for a handwheel that is gone must not fire later
|
|
180
|
+
stopPowerWatch();
|
|
181
|
+
if (!ctx.shuttingDown) console.log('Pendant port closed');
|
|
182
|
+
scheduleReconnect();
|
|
183
|
+
});
|
|
184
|
+
port.open((err) => {
|
|
185
|
+
if (err) {
|
|
186
|
+
noteError(err);
|
|
187
|
+
scheduleReconnect();
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
ctx.input.clearBuffer();
|
|
191
|
+
ctx.input.ignoreFor(Number(cfg.device.settleMs || 0));
|
|
192
|
+
const lines = {};
|
|
193
|
+
if (cfg.device.dtr !== null && cfg.device.dtr !== undefined) lines.dtr = !!cfg.device.dtr;
|
|
194
|
+
if (cfg.device.rts !== null && cfg.device.rts !== undefined) lines.rts = !!cfg.device.rts;
|
|
195
|
+
if (Object.keys(lines).length) {
|
|
196
|
+
port.set(lines, (setErr) => { if (setErr) noteError(setErr); });
|
|
197
|
+
}
|
|
198
|
+
health.pendant.connected = true;
|
|
199
|
+
// Every retry while the wheel was away counted as a reconnect and an error (hundreds after a night unplugged).
|
|
200
|
+
// After a real outage they say nothing about the link, so the rolling counters start over; short drops stay counted
|
|
201
|
+
// so a flapping link still shows. The totals since start are not touched.
|
|
202
|
+
if (downSince !== null && Date.now() - downSince >= REAL_OUTAGE_MS) {
|
|
203
|
+
ctx.clearRecent('reconnects', 'errors');
|
|
204
|
+
}
|
|
205
|
+
downSince = null;
|
|
206
|
+
health.pendant.link = detectLink(cfg.device.path);
|
|
207
|
+
health.pendant.lastError = null;
|
|
208
|
+
console.log('Pendant connected on ' + cfg.device.path);
|
|
209
|
+
startPowerWatch(port);
|
|
210
|
+
ctx.status.sendStatus(true);
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Closes the port if it is open (at shutdown).
|
|
216
|
+
*
|
|
217
|
+
* @returns {void}
|
|
218
|
+
*/
|
|
219
|
+
function close() {
|
|
220
|
+
if (pendantPort && pendantPort.isOpen) pendantPort.close();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Stops the timers.
|
|
225
|
+
*
|
|
226
|
+
* @returns {void}
|
|
227
|
+
*/
|
|
228
|
+
function dispose() {
|
|
229
|
+
clearInterval(powerTimer);
|
|
230
|
+
clearTimeout(reconnectTimer);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return { open, send, isOpen: () => !!(pendantPort && pendantPort.isOpen), close, dispose };
|
|
234
|
+
};
|
package/lib/protocol.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// What a line from the pendant means, without any state: which lines are gcode, how a jog is turned into a Grbl jog and
|
|
4
|
+
// split into its parts, the pendant's own status report, and whether its port is USB or Bluetooth.
|
|
5
|
+
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
|
|
8
|
+
const PRINTABLE = /^[\x20-\x7e]+$/;
|
|
9
|
+
const REALTIME = { '!': 'feedhold', '~': 'cyclestart', '\x18': 'reset' };
|
|
10
|
+
const ANSI = /\x1b\[[0-9;]*[A-Za-z]/g;
|
|
11
|
+
|
|
12
|
+
// A gcode line: words (a letter and a number, a #parameter or a [expression]) with optional (comments) and spaces
|
|
13
|
+
// between them, a Grbl "$" command (`$J=...`, `$H`, `$X`, `$$`, `$100=250`), or a "%" line for CNCjs (`%wait`).
|
|
14
|
+
const GCODE_WORDS = /^(?:N\d+)?(?:[A-Z](?:[-+]?(?:\d+\.?\d*|\.\d+)|#\d+|\[[^\]]*\]))+$/;
|
|
15
|
+
const GRBL_SYSTEM = /^\$[\w#$=.+\-]*$/;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Says whether a text line from the pendant can be sent to the machine as gcode.
|
|
19
|
+
*
|
|
20
|
+
* @param {string} line - trimmed, printable line
|
|
21
|
+
* @returns {boolean}
|
|
22
|
+
*/
|
|
23
|
+
function looksLikeGcode(line) {
|
|
24
|
+
if (line[0] === '%') return true; // CNCjs's own statements (%wait, %x = ...)
|
|
25
|
+
const compact = line.replace(/\([^)]*\)/g, '').replace(/\s+/g, '').toUpperCase(); // comments and blanks do not count
|
|
26
|
+
if (!compact) return true; // only a comment: harmless
|
|
27
|
+
return GRBL_SYSTEM.test(compact) || GCODE_WORDS.test(compact);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Only modal words (G20/G21/G90/G91), axis words and a feed, no G0/G1/G2/G3 -> this is a jog.
|
|
31
|
+
const JOG_RE = /^(?:G(?:20|21|90|91))+(?:[XYZABC][-+]?\d*\.?\d+|F\d*\.?\d+)+$/;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Turns a pendant jog such as `G21G91X+10F2000` into a Grbl jog command (`$J=G21G91X+10F2000`).
|
|
35
|
+
* Lines that are not pure jogs (no axis word, or containing G0/G1/G2/G3 etc.) are returned unchanged.
|
|
36
|
+
*
|
|
37
|
+
* @param {string} line - gcode line from the pendant
|
|
38
|
+
* @returns {string} the jog command, or the original line
|
|
39
|
+
*/
|
|
40
|
+
function toJog(line) {
|
|
41
|
+
const compact = line.replace(/\s+/g, '').toUpperCase();
|
|
42
|
+
return JOG_RE.test(compact) && /[XYZABC]/.test(compact) ? '$J=' + compact : line;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const JOG_PARTS = /^\$J=((?:G(?:20|21|90|91))+)([XYZABC])([-+]?\d*\.?\d+)F(\d*\.?\d+)$/;
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Splits a single-axis relative Grbl jog (`$J=G21G91Y-0.1F2000`) into its parts.
|
|
49
|
+
*
|
|
50
|
+
* @param {string} line - gcode line, already translated by toJog()
|
|
51
|
+
* @returns {?{raw: string, prefix: string, axis: string, dist: number, feed: string}} null if the line
|
|
52
|
+
* is not a jog that can be merged with others
|
|
53
|
+
*/
|
|
54
|
+
function parseJog(line) {
|
|
55
|
+
const m = JOG_PARTS.exec(line);
|
|
56
|
+
if (!m) return null;
|
|
57
|
+
const words = m[1].match(/G\d+/g);
|
|
58
|
+
if (!words.includes('G91') || words.includes('G90')) return null;
|
|
59
|
+
return { raw: line, prefix: m[1], axis: m[2], dist: Number(m[3]), feed: m[4] };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Formats a signed jog distance without floating point noise, e.g. -0.1, +0.3, +10.
|
|
64
|
+
*
|
|
65
|
+
* @param {number} d - distance
|
|
66
|
+
* @returns {string}
|
|
67
|
+
*/
|
|
68
|
+
function fmtDist(d) {
|
|
69
|
+
const s = Math.abs(d).toFixed(4).replace(/\.?0+$/, '');
|
|
70
|
+
return (d < 0 ? '-' : '+') + (s || '0');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Parses the pendant's own status report. Two spellings are accepted:
|
|
75
|
+
* `[HW:bat=74,chg=0,eta=13200,st=ok]` and the same wrapped in a gcode message comment,
|
|
76
|
+
* `(MSG, [HW:bat=74,...])`, which a controller reached directly ignores (and may echo as a message).
|
|
77
|
+
* Keys (integers only): bat 0-100 (%), chg 1 while charging, eta seconds to full (charging) or empty,
|
|
78
|
+
* st ok|warn|err, heap free heap memory in bytes, stk number of tasks close to using up their stack.
|
|
79
|
+
* All are optional and unknown keys are ignored, so the firmware can grow.
|
|
80
|
+
*
|
|
81
|
+
* @param {string} line - trimmed line from the pendant
|
|
82
|
+
* @param {number} now - Date.now(), stored as `at`
|
|
83
|
+
* @returns {?object} the report (each one replaces the last: a key that is left out is unknown, not unchanged),
|
|
84
|
+
* or null if the line is not a pendant status report
|
|
85
|
+
*/
|
|
86
|
+
function parsePendantReport(line, now) {
|
|
87
|
+
const m = /^\[HW:([^\]]*)\]$/.exec(line) || /^\(\s*MSG\s*,\s*\[HW:([^\]]*)\]\s*\)$/i.exec(line);
|
|
88
|
+
if (!m) return null;
|
|
89
|
+
const info = {};
|
|
90
|
+
m[1].split(',').forEach((pair) => {
|
|
91
|
+
const [k, v] = pair.split('=').map((x) => x.trim());
|
|
92
|
+
const num = /^\d+$/.test(v) ? Number(v) : null;
|
|
93
|
+
if (k === 'bat' && num !== null && num <= 100) info.bat = num;
|
|
94
|
+
else if (k === 'chg' && (v === '0' || v === '1')) info.chg = v === '1';
|
|
95
|
+
else if (k === 'eta' && num !== null) info.eta = num;
|
|
96
|
+
else if (k === 'st' && /^(ok|warn|err)$/.test(v)) info.st = v;
|
|
97
|
+
else if (k === 'heap' && num !== null) info.heap = num;
|
|
98
|
+
else if (k === 'stk' && num !== null) info.stk = num;
|
|
99
|
+
});
|
|
100
|
+
info.at = now;
|
|
101
|
+
return info;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Works out whether the pendant port is USB or Bluetooth (rfcomm), looking through the udev symlink
|
|
106
|
+
* (/dev/pendant) at the real device node.
|
|
107
|
+
*
|
|
108
|
+
* @param {string} devPath - configured pendant port
|
|
109
|
+
* @returns {?string} 'bluetooth', 'usb' or null if it cannot be told
|
|
110
|
+
*/
|
|
111
|
+
function detectLink(devPath) {
|
|
112
|
+
let real = devPath;
|
|
113
|
+
try { real = fs.realpathSync(devPath); } catch (err) { /* keep the configured path */ }
|
|
114
|
+
if (/rfcomm/i.test(real)) return 'bluetooth';
|
|
115
|
+
if (/tty(USB|ACM)/i.test(real) || /usb/i.test(real)) return 'usb';
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
module.exports = { PRINTABLE, REALTIME, ANSI, looksLikeGcode, toJog, parseJog, fmtDist, parsePendantReport, detectLink };
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// CNCjs -> pendant: when a status line goes to the pendant, and how evenly it does.
|
|
4
|
+
|
|
5
|
+
const { snapshot, formatStatus } = require('./status');
|
|
6
|
+
|
|
7
|
+
// How evenly the status lines reach the pendant. The pendant treats a status older than about 1.5 s as lost, so a gap
|
|
8
|
+
// that long is worth knowing about, and whether it comes from here (timer late, write refused) or from further down.
|
|
9
|
+
const SLOW_STATUS_MS = 1000; // a gap between two status lines longer than this is counted as slow
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Creates the status sender. Its timer starts at once; call dispose() to stop it.
|
|
13
|
+
*
|
|
14
|
+
* @param {object} ctx - the bridge context
|
|
15
|
+
* @returns {{snapshot: function, sendStatus: function, queueStatus: function, gapReport: function, dispose: function}}
|
|
16
|
+
*/
|
|
17
|
+
module.exports = function createStatusSender(ctx) {
|
|
18
|
+
const { cfg, health, store } = ctx;
|
|
19
|
+
let lastLine = '';
|
|
20
|
+
let lastStatusAt = 0;
|
|
21
|
+
let statusQueued = false;
|
|
22
|
+
const statusGap = { lastSentAt: null, lastMs: null, maxMs: 0, slow: 0, lastSlowAt: null, warnedAt: 0 };
|
|
23
|
+
const slowStatusEvents = [];
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Builds the current machine status from the latest CNCjs controller and sender state.
|
|
27
|
+
*
|
|
28
|
+
* @returns {object} see status.snapshot()
|
|
29
|
+
*/
|
|
30
|
+
function currentSnapshot() {
|
|
31
|
+
return snapshot({
|
|
32
|
+
connected: ctx.cmd.cncReady(),
|
|
33
|
+
controllerState: store.controller.state,
|
|
34
|
+
senderStatus: store.sender.status,
|
|
35
|
+
lastWco: store.lastWco
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Records the time since the previous status line that went to the pendant. A gap only counts between two lines that
|
|
41
|
+
* were both written: a refused write (port closed, wheel off) starts the measurement over.
|
|
42
|
+
*
|
|
43
|
+
* @param {boolean} sent - whether the status line was written now
|
|
44
|
+
* @param {number} now - Date.now()
|
|
45
|
+
* @returns {void}
|
|
46
|
+
*/
|
|
47
|
+
function noteStatusSent(sent, now) {
|
|
48
|
+
if (!sent) { statusGap.lastSentAt = null; return; }
|
|
49
|
+
if (statusGap.lastSentAt !== null) {
|
|
50
|
+
const gap = now - statusGap.lastSentAt;
|
|
51
|
+
statusGap.lastMs = gap;
|
|
52
|
+
if (gap > statusGap.maxMs) statusGap.maxMs = gap;
|
|
53
|
+
if (gap > SLOW_STATUS_MS) {
|
|
54
|
+
statusGap.slow++;
|
|
55
|
+
statusGap.lastSlowAt = now;
|
|
56
|
+
slowStatusEvents.push(now);
|
|
57
|
+
if (slowStatusEvents.length > ctx.maxRecentEvents) slowStatusEvents.shift();
|
|
58
|
+
if (now - statusGap.warnedAt >= 5000) { // at most one line per 5 s
|
|
59
|
+
statusGap.warnedAt = now;
|
|
60
|
+
const text = 'status to the pendant went out ' + gap + ' ms after the previous one';
|
|
61
|
+
console.warn('Handwheel: ' + text);
|
|
62
|
+
ctx.pendantLog.add('[bridge] ' + text);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
statusGap.lastSentAt = now;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Sends the current status to the pendant if one is due: forced, at least every status.intervalMs,
|
|
71
|
+
* when the values changed and status.minGapMs has passed, or when one was queued with queueStatus().
|
|
72
|
+
*
|
|
73
|
+
* @param {boolean} [force=false] - send regardless of timing
|
|
74
|
+
* @returns {void}
|
|
75
|
+
*/
|
|
76
|
+
function sendStatus(force) {
|
|
77
|
+
if (!cfg.device.send) return;
|
|
78
|
+
const line = formatStatus(currentSnapshot(), cfg.status);
|
|
79
|
+
const now = Date.now();
|
|
80
|
+
const gapOk = now - lastStatusAt >= cfg.status.minGapMs;
|
|
81
|
+
const due = now - lastStatusAt >= cfg.status.intervalMs;
|
|
82
|
+
const changed = line !== lastLine && gapOk;
|
|
83
|
+
if (force || due || changed || (statusQueued && gapOk)) {
|
|
84
|
+
const sent = ctx.link.send(line, changed);
|
|
85
|
+
noteStatusSent(sent, now);
|
|
86
|
+
if (sent) {
|
|
87
|
+
lastLine = line;
|
|
88
|
+
lastStatusAt = now;
|
|
89
|
+
statusQueued = false;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Asks for a status line to go to the pendant soon: now if status.minGapMs has passed since the last
|
|
96
|
+
* one, otherwise as soon as it has (the periodic timer sends it). Many requests in a row cost one line.
|
|
97
|
+
*
|
|
98
|
+
* @returns {void}
|
|
99
|
+
*/
|
|
100
|
+
function queueStatus() {
|
|
101
|
+
statusQueued = true;
|
|
102
|
+
sendStatus(false);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Gaps between two status lines written to the pendant (ms), for /status; slow = longer than SLOW_STATUS_MS.
|
|
107
|
+
*
|
|
108
|
+
* @param {function} age - maps a timestamp to its age in ms (null stays null)
|
|
109
|
+
* @returns {object}
|
|
110
|
+
*/
|
|
111
|
+
function gapReport(age) {
|
|
112
|
+
return {
|
|
113
|
+
lastMs: statusGap.lastMs,
|
|
114
|
+
maxMs: statusGap.maxMs,
|
|
115
|
+
slow: statusGap.slow,
|
|
116
|
+
recentSlow: slowStatusEvents.filter((t) => t >= Date.now() - ctx.windowMs()).length,
|
|
117
|
+
lastSlowAgeMs: age(statusGap.lastSlowAt)
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const statusTimer = setInterval(() => sendStatus(false), Math.max(10, Math.min(100, cfg.status.minGapMs, cfg.status.intervalMs)));
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Stops the timer.
|
|
125
|
+
*
|
|
126
|
+
* @returns {void}
|
|
127
|
+
*/
|
|
128
|
+
function dispose() {
|
|
129
|
+
clearInterval(statusTimer);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
return { snapshot: currentSnapshot, sendStatus, queueStatus, gapReport, dispose };
|
|
133
|
+
};
|
package/lib/status.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The machine status as the pendant gets it: positions (machine and work), the snapshot of the CNCjs state, and the
|
|
4
|
+
// status line. No state of its own.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Converts a value to a number, treating anything non-numeric as 0.
|
|
8
|
+
*
|
|
9
|
+
* @param {*} v
|
|
10
|
+
* @returns {number}
|
|
11
|
+
*/
|
|
12
|
+
const num = (v) => Number(v) || 0;
|
|
13
|
+
/**
|
|
14
|
+
* Subtracts two {x, y, z} positions (a - b).
|
|
15
|
+
*
|
|
16
|
+
* @param {{x: (number|string), y: (number|string), z: (number|string)}} a
|
|
17
|
+
* @param {{x: (number|string), y: (number|string), z: (number|string)}} b
|
|
18
|
+
* @returns {{x: number, y: number, z: number}}
|
|
19
|
+
*/
|
|
20
|
+
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) });
|
|
21
|
+
/**
|
|
22
|
+
* Adds two {x, y, z} positions (a + b).
|
|
23
|
+
*
|
|
24
|
+
* @param {{x: (number|string), y: (number|string), z: (number|string)}} a
|
|
25
|
+
* @param {{x: (number|string), y: (number|string), z: (number|string)}} b
|
|
26
|
+
* @returns {{x: number, y: number, z: number}}
|
|
27
|
+
*/
|
|
28
|
+
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) });
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Returns machine and work position. Grbl 1.1 reports only one of them plus the work coordinate
|
|
32
|
+
* offset (WCO) now and then, so the missing one is derived: WPos = MPos - WCO.
|
|
33
|
+
*
|
|
34
|
+
* @param {object} st - the `status` object of the CNCjs controller state
|
|
35
|
+
* @param {?object} lastWco - the last work coordinate offset seen, used when `st` has none
|
|
36
|
+
* @returns {{mpos: ?object, wpos: ?object}} positions, null where they cannot be determined yet
|
|
37
|
+
*/
|
|
38
|
+
function positions(st, lastWco) {
|
|
39
|
+
const wco = st.wco || lastWco;
|
|
40
|
+
let mpos = st.mpos || null;
|
|
41
|
+
let wpos = st.wpos || null;
|
|
42
|
+
if (!wpos && mpos && wco) wpos = sub(mpos, wco);
|
|
43
|
+
if (!mpos && wpos && wco) mpos = add(wpos, wco);
|
|
44
|
+
return { mpos, wpos };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Builds the current machine status from the latest CNCjs controller and sender state.
|
|
49
|
+
*
|
|
50
|
+
* @param {object} src
|
|
51
|
+
* @param {boolean} src.connected - whether commands can reach the controller
|
|
52
|
+
* @param {object} [src.controllerState] - the last `<Type>:state` payload of CNCjs
|
|
53
|
+
* @param {object} [src.senderStatus] - the last `sender:status` payload of CNCjs
|
|
54
|
+
* @param {?object} [src.lastWco] - the last work coordinate offset seen
|
|
55
|
+
* @returns {{connected: boolean, state: string, mpos: ?object, wpos: ?object, feed: ?number,
|
|
56
|
+
* spindle: ?number, sender: object}}
|
|
57
|
+
*/
|
|
58
|
+
function snapshot({ connected, controllerState, senderStatus, lastWco }) {
|
|
59
|
+
const st = (controllerState && controllerState.status) || {};
|
|
60
|
+
const pos = positions(st, lastWco);
|
|
61
|
+
const snd = senderStatus || {};
|
|
62
|
+
return {
|
|
63
|
+
connected,
|
|
64
|
+
state: connected ? (st.activeState || 'Unknown') : 'Disconnected',
|
|
65
|
+
mpos: pos.mpos,
|
|
66
|
+
wpos: pos.wpos,
|
|
67
|
+
feed: st.feedrate !== undefined ? st.feedrate : null,
|
|
68
|
+
spindle: st.spindle !== undefined ? st.spindle : null,
|
|
69
|
+
sender: { name: snd.name || null, total: snd.total || 0, sent: snd.sent || 0,
|
|
70
|
+
received: snd.received || 0, hold: !!snd.hold }
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Formats a status snapshot as the line sent to the pendant, either Grbl style
|
|
76
|
+
* (`<Idle|MPos:x,y,z|WPos:x,y,z|FS:feed,spindle>`) or JSON, depending on status.format.
|
|
77
|
+
*
|
|
78
|
+
* @param {object} s - snapshot from snapshot()
|
|
79
|
+
* @param {{format: string, decimals: number}} statusCfg - the `status` section of the config
|
|
80
|
+
* @returns {string} the status line without terminator
|
|
81
|
+
*/
|
|
82
|
+
function formatStatus(s, statusCfg) {
|
|
83
|
+
if (statusCfg.format === 'json') {
|
|
84
|
+
return JSON.stringify(Object.assign({ t: 'status' }, s));
|
|
85
|
+
}
|
|
86
|
+
const d = statusCfg.decimals;
|
|
87
|
+
const pos = (p) => [p.x, p.y, p.z].map((n) => (Number(n) || 0).toFixed(d)).join(',');
|
|
88
|
+
const parts = [s.state];
|
|
89
|
+
if (s.connected) {
|
|
90
|
+
if (s.mpos) parts.push('MPos:' + pos(s.mpos));
|
|
91
|
+
if (s.wpos) parts.push('WPos:' + pos(s.wpos));
|
|
92
|
+
if (s.feed !== null) parts.push('FS:' + (Number(s.feed) || 0) + ',' + (Number(s.spindle) || 0));
|
|
93
|
+
}
|
|
94
|
+
return '<' + parts.join('|') + '>';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
module.exports = { positions, snapshot, formatStatus };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cncjs-handwheel",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "CNCjs pendant bridge for a serial (USB/Bluetooth) ESP32 CNC handwheel",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cncjs",
|
|
@@ -29,10 +29,11 @@
|
|
|
29
29
|
],
|
|
30
30
|
"scripts": {
|
|
31
31
|
"start": "node bin/cncjs-handwheel",
|
|
32
|
-
"check": "node --check index.js && node --check bin/cncjs-handwheel && node --check
|
|
32
|
+
"check": "node --check index.js && node --check bin/cncjs-handwheel && for f in lib/*.js; do node --check $f || exit 1; done",
|
|
33
33
|
"prepublishOnly": "npm run check && npm run build:widget",
|
|
34
34
|
"build:widget": "npm install --prefix widget && npm run build --prefix widget",
|
|
35
|
-
"dev:widget": "npm run dev --prefix widget"
|
|
35
|
+
"dev:widget": "npm run dev --prefix widget",
|
|
36
|
+
"test": "node --test test/*.test.js"
|
|
36
37
|
},
|
|
37
38
|
"engines": {
|
|
38
39
|
"node": ">=20"
|