cncjs-handwheel 0.7.3 → 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.
@@ -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.7.3",
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,7 +29,7 @@
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 lib/service.js && node --check lib/guard.js",
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
35
  "dev:widget": "npm run dev --prefix widget",