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.
package/lib/bridge.js ADDED
@@ -0,0 +1,125 @@
1
+ 'use strict';
2
+
3
+ // CNCjs <-> ESP32 pendant bridge: creates the parts and connects them.
4
+ // pendant -> CNCjs : gcode lines (and a few realtime chars) read from the pendant's serial port
5
+ // CNCjs -> pendant : status lines (state, MPos, WPos, feed/spindle) written to the pendant
6
+ // Health/status of both links is exposed as JSON on http://127.0.0.1:8001/status (configurable).
7
+ // Pendant logs can be accessed on http://127.0.0.1:8001/log (configurable)
8
+ //
9
+ // The parts (commands, job guard, jog governor, status sender, pendant input, pendant link) share one context object,
10
+ // `ctx`, and call each other through it when they run, so none of them needs another one at load time.
11
+
12
+ const createHealth = require('./health');
13
+ const createCommands = require('./commands');
14
+ const createJobGuard = require('./job-guard');
15
+ const createJog = require('./jog');
16
+ const createStatusSender = require('./status-sender');
17
+ const createPendantInput = require('./pendant-input');
18
+ const createPendantLink = require('./pendant-link');
19
+ const { startHttp } = require('./http');
20
+
21
+ /**
22
+ * Starts the bridge: connects to CNCjs, opens the pendant's port and starts the health endpoint.
23
+ * Stops again on SIGINT / SIGTERM.
24
+ *
25
+ * @param {object} opts
26
+ * @param {object} opts.cfg - the configuration (see lib/config.js)
27
+ * @param {object} opts.cli - parsed command line options (the secret comes from here)
28
+ * @param {function} opts.connectToCncjs - connects to the CNCjs socket (index.js)
29
+ * @param {object} opts.pkg - package.json (the version)
30
+ * @returns {object} the context (for tests and tools)
31
+ */
32
+ function start({ cfg, cli, connectToCncjs, pkg }) {
33
+ const ctx = { cfg, cli, pkg, shuttingDown: false, store: { controller: { state: {}, settings: {} }, sender: { status: {} },
34
+ lastWco: null } }; // Grbl 1.1 only reports MPos *or* WPos, plus WCO now and then: WPos = MPos - WCO
35
+
36
+ /**
37
+ * Logs to the console, but only when -v / verbose is on.
38
+ *
39
+ * @param {...*} args - what to print
40
+ * @returns {void}
41
+ */
42
+ ctx.log = (...args) => cfg.verbose && console.log(...args);
43
+
44
+ const h = createHealth(cfg, ctx.log);
45
+ Object.assign(ctx, { health: h.health, noteEvent: h.noteEvent, recentCount: h.recentCount, clearRecent: h.clearRecent,
46
+ windowMs: h.windowMs, maxRecentEvents: h.maxRecentEvents, pendantLog: h.pendantLog });
47
+ const { health, store } = ctx;
48
+
49
+ ctx.cmd = createCommands(ctx);
50
+ ctx.jobGuard = createJobGuard(ctx);
51
+ ctx.jog = createJog(ctx);
52
+ ctx.status = createStatusSender(ctx);
53
+ ctx.input = createPendantInput(ctx);
54
+ ctx.link = createPendantLink(ctx);
55
+
56
+ // ------------------------------------------------------------ CNCjs side
57
+ const cncOpts = Object.assign({}, cfg.cncjs, { secret: cli.secret, verbose: cfg.trace });
58
+ const socket = connectToCncjs(cncOpts, (err) => {
59
+ if (err) {
60
+ health.cncjs.lastError = err.message;
61
+ console.error(err.message);
62
+ }
63
+ });
64
+ ctx.socket = socket;
65
+
66
+ socket.on('connect', () => { health.cncjs.socketConnected = true; });
67
+ socket.on('disconnect', () => {
68
+ health.cncjs.socketConnected = false;
69
+ health.cncjs.portOpen = false;
70
+ ctx.jog.resetJogs();
71
+ ctx.jobGuard.setWorkflow(null);
72
+ });
73
+ socket.on('serialport:read', ctx.jog.onControllerLine);
74
+ socket.on('serialport:open', () => {
75
+ if (!health.cncjs.portOpen) { store.lastWco = null; ctx.jog.resetJogs(); } // a keepalive confirmation must not discard the work offset
76
+ health.cncjs.portOpen = true;
77
+ health.cncjs.lastError = null;
78
+ });
79
+ socket.on('serialport:close', () => { health.cncjs.portOpen = false; ctx.jog.resetJogs(); ctx.jobGuard.setWorkflow(null); });
80
+ socket.on('workflow:state', (state) => ctx.jobGuard.setWorkflow(typeof state === 'string' ? state : null));
81
+
82
+ ['Grbl', 'Smoothie', 'TinyG'].forEach((type) => {
83
+ let dumped = false;
84
+ socket.on(type + ':state', (state) => {
85
+ store.controller.state = state || {};
86
+ ctx.jobGuard.onControllerState();
87
+ const wco = state && state.status && state.status.wco;
88
+ if (wco) store.lastWco = wco;
89
+ ctx.status.sendStatus(false); // forward changes right away (rate limited by status.minGapMs)
90
+ if (cfg.verbose && !dumped) { dumped = true; console.log(type + ':state sample', JSON.stringify(state)); }
91
+ });
92
+ socket.on(type + ':settings', (settings) => { store.controller.settings = settings || {}; });
93
+ });
94
+
95
+ socket.on('sender:status', (data) => { store.sender.status = data || {}; });
96
+
97
+ // ------------------------------------------------------------ health endpoint
98
+ const httpServer = startHttp(ctx);
99
+
100
+ // ------------------------------------------------------------ lifecycle
101
+ /**
102
+ * Stops timers and closes the CNCjs socket, the pendant port and the HTTP server, then exits.
103
+ * Called on SIGINT / SIGTERM.
104
+ *
105
+ * @returns {void}
106
+ */
107
+ function shutdown() {
108
+ if (ctx.shuttingDown) return;
109
+ ctx.shuttingDown = true;
110
+ ctx.status.dispose();
111
+ ctx.jog.dispose();
112
+ ctx.link.dispose();
113
+ socket.close();
114
+ if (httpServer) httpServer.close();
115
+ ctx.link.close();
116
+ setTimeout(() => process.exit(0), 300);
117
+ }
118
+ process.on('SIGINT', shutdown);
119
+ process.on('SIGTERM', shutdown);
120
+
121
+ ctx.link.open();
122
+ return ctx;
123
+ }
124
+
125
+ module.exports = { start };
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ // Commands from the pendant to the CNC controller through CNCjs.
4
+
5
+ /**
6
+ * Creates the command sender.
7
+ *
8
+ * @param {object} ctx - the bridge context (config, health, socket and the other modules, which are looked up when used)
9
+ * @returns {{cncReady: function, noteDropped: function, sendCommand: function, answerCommand: function}}
10
+ */
11
+ module.exports = function createCommands(ctx) {
12
+ const { cfg, health, log } = ctx;
13
+ const fmtArgs = (args) => args.map((a) => (a !== null && typeof a === 'object' ? JSON.stringify(a) : a));
14
+ let lastDropWarn = 0;
15
+ let lastPoll = 0;
16
+
17
+ /**
18
+ * Tells whether commands can currently reach the CNC controller
19
+ * (CNCjs socket connected and the CNC port open).
20
+ *
21
+ * @returns {boolean}
22
+ */
23
+ const cncReady = () => ctx.socket.connected && health.cncjs.portOpen;
24
+
25
+ /**
26
+ * Records and reports a command that could not be sent (at most one console line per second).
27
+ *
28
+ * @param {string} name - the CNCjs command that was dropped
29
+ * @param {Array} args - its arguments
30
+ * @returns {void}
31
+ */
32
+ function noteDropped(name, args) {
33
+ health.cncjs.droppedCommands++;
34
+ ctx.noteEvent('droppedCommands');
35
+ const now = Date.now();
36
+ if (now - lastDropWarn < 1000) return;
37
+ lastDropWarn = now;
38
+ console.warn('Dropped pendant command (' + [name].concat(fmtArgs(args)).join(' ') + '): ' +
39
+ (ctx.socket.connected ? 'the CNC port is not open' : 'not connected to CNCjs') +
40
+ ' [' + health.cncjs.droppedCommands + ' dropped so far]');
41
+ }
42
+
43
+ /**
44
+ * Sends a command to the CNC controller through CNCjs and answers the pendant with a status line.
45
+ * If CNCjs or the CNC port is not ready the command is dropped and the pendant gets
46
+ * `ERR:CNCJS_NOT_READY` plus a status line.
47
+ *
48
+ * @param {string} name - CNCjs command, e.g. 'gcode', 'feedhold', 'cyclestart', 'reset'
49
+ * @param {...*} args - command arguments, e.g. the gcode line
50
+ * @returns {boolean} true if the command was sent
51
+ */
52
+ function sendCommand(name, ...args) {
53
+ if (!cncReady()) {
54
+ noteDropped(name, args);
55
+ ctx.link.send('ERR:CNCJS_NOT_READY');
56
+ ctx.status.queueStatus();
57
+ return false;
58
+ }
59
+ health.lastCommand = { at: Date.now(), name, args };
60
+ log('pendant ->', name, ...fmtArgs(args));
61
+ if (!ctx.socket.emit('command', cfg.cncjs.port, name, ...args)) {
62
+ noteDropped(name, args);
63
+ return false;
64
+ }
65
+ answerCommand();
66
+ return true;
67
+ }
68
+
69
+ // Every command from the pendant is answered with a status line right away. The position in it is
70
+ // what CNCjs knew at that moment; a fresh report is requested so the real position follows within
71
+ // a few tens of ms (forwarded by the :state handler).
72
+ /**
73
+ * Answers a command from the pendant with a status line (within status.minGapMs, so a burst of
74
+ * commands does not flood the pendant), and asks the controller for a fresh status report (at most
75
+ * once per status.minGapMs) so the new position follows shortly after.
76
+ *
77
+ * @returns {void}
78
+ */
79
+ function answerCommand() {
80
+ ctx.status.queueStatus();
81
+ const now = Date.now();
82
+ if (cfg.status.pollAfterCommand && now - lastPoll >= Math.max(50, cfg.status.minGapMs)) {
83
+ lastPoll = now;
84
+ ctx.socket.emit('command', cfg.cncjs.port, 'statusreport');
85
+ }
86
+ }
87
+
88
+ return { cncReady, noteDropped, sendCommand, answerCommand };
89
+ };
package/lib/config.js ADDED
@@ -0,0 +1,160 @@
1
+ 'use strict';
2
+
3
+ // Configuration: the defaults, and how they are combined with ~/.cncrc, the config file and the command line.
4
+
5
+ const fs = require('fs');
6
+ const os = require('os');
7
+ const path = require('path');
8
+
9
+ const DEFAULT_CONFIG_FILE = path.join(os.homedir(), '.cncjs-handwheel.config');
10
+
11
+ const DEFAULTS = {
12
+ cncjs: {
13
+ port: null, // CNC controller port AS KNOWN TO CNCjs (e.g. /dev/ttyUSB0), NOT the pendant
14
+ baudrate: 115200,
15
+ controllerType: 'Grbl', // Grbl | Smoothie (TinyG: state is not mapped yet)
16
+ socketAddress: 'localhost',
17
+ socketPort: 8000,
18
+ accessTokenLifetime: '30d',
19
+ retryInterval: 5000, // ms before a failed or lost port open is retried (0 = never)
20
+ openTimeout: 5000, // ms to wait for CNCjs to answer an open request
21
+ maxOpenTries: 3, // unanswered open requests before the connection to CNCjs is rebuilt
22
+ keepaliveMs: 30000, // repeat the open request this often to verify the attachment (0 = off)
23
+ reopenOnClose: true // reopen the CNC port when it gets closed (e.g. from the CNCjs UI)
24
+ },
25
+ device: {
26
+ path: '/dev/pendant', // the pendant's serial port (e.g. /dev/ttyACM0 or /dev/rfcomm0)
27
+ baudRate: 115200,
28
+ reconnectMs: 3000,
29
+ settleMs: 2000, // ignore pendant input this long after opening the port
30
+ // strictGcode: only forward a pendant line to the machine when it looks like gcode (words such as G21 X+1.5 F2000,
31
+ // Grbl "$" commands, "%" lines for CNCjs) and keep anything else out of it: it is shown in the widget's log
32
+ // as "[not gcode, not sent] ..." and counted as dropped. A log line that lost its leading ";" (or a
33
+ // fragment of one) would otherwise be sent to the controller and answered with error:..
34
+ strictGcode: true,
35
+ send: true, // false: never write anything to the pendant (status, PONG, ERR)
36
+
37
+ // Modem-control lines. The CH340 + auto-reset transistors wire DTR/RTS to EN/IO0, so on Linux
38
+ // the DTR/RTS toggling around open/close can reset the ESP32 or drop it into download mode.
39
+ hupcl: false, // do NOT drop DTR/RTS when the port is closed
40
+ dtr: null, // true/false = force DTR right after open, null = leave alone
41
+ rts: null, // true/false = force RTS right after open, null = leave alone
42
+
43
+ // "Is the handwheel switched on?" for a USB-powered adapter that stays alive when the handwheel is
44
+ // switched off. The handwheel drives one modem INPUT of the USB serial chip (CTS#, DSR# or DCD#),
45
+ // and the bridge reads it. Off by default (line: null). USB only; there is no such line over Bluetooth.
46
+ // line: 'cts' | 'dsr' | 'dcd' which input is wired to the handwheel
47
+ // poweredWhen: 'clear' | 'set' the line state that means "switched on". The inputs are active low:
48
+ // a pin driven HIGH reads as clear, a pin pulled LOW reads as set. 'clear' = high means on
49
+ // pollMs: how often the line is read
50
+ // debounceMs: a change must last this long before it counts (opening the port can reset the ESP32)
51
+ power: { line: null, poweredWhen: 'clear', pollMs: 250, debounceMs: 1000 }
52
+ },
53
+ health: {
54
+ windowMs: 900000 // the counters in the widget header (reconnects, errors, dropped) cover this long; /status also keeps lifetime totals
55
+ },
56
+ status: {
57
+ format: 'grbl', // 'grbl' -> <Idle|MPos:..|WPos:..|FS:..> 'json' -> {"t":"status",...}
58
+ intervalMs: 400, // unsolicited status line at least this often (also the pendant's "host alive" signal)
59
+ minGapMs: 350, // minimum gap between two status lines (about 3 per second at most)
60
+ pollAfterCommand: true, // ask CNCjs/Grbl for a fresh status report after every pendant command
61
+ decimals: 3
62
+ },
63
+ http: { enabled: true, host: '127.0.0.1', port: 8001 },
64
+
65
+ // translate (Grbl 1.1 only): rewrite "G21G91X+10F2000" into "$J=G21G91X+10F2000" so a pendant jog does not
66
+ // leave CNCjs/Grbl stuck in relative mode (and so jogs go through Grbl's jog queue)
67
+ // maxInFlight: at most this many gcode lines handed to CNCjs and not yet answered with ok/error. While the
68
+ // limit is reached, jogs on the same axis and feed are merged into one longer jog (0 = no limit, no merging)
69
+ // stallMs: if nothing is acknowledged for this long, assume lines were lost and start counting afresh
70
+ // echo: tag jog lines sent to CNCjs with {echo: false} in their context. CNCjs passes the context on in its
71
+ // 'serialport:write' event, so a console widget can skip them (see README); it changes nothing else
72
+ jog: { translate: true, maxInFlight: 4, stallMs: 2000, echo: false },
73
+
74
+ // duringJob: while a job is running or paused (CNCjs workflow state not idle) no gcode line from the pendant is sent
75
+ // (jogs, button gcode, macros): CNCjs only holds the job, not its own queue, so a line sent during a pause would
76
+ // run in the middle of the program after the resume. Real-time commands (! ~ ^X ? jog cancel) still go through.
77
+ // M5 and M3 are turned into Grbl's real-time "toggle spindle stop" (0x9E), which works while the machine is in Hold
78
+ guard: { duringJob: true },
79
+
80
+ // pendant console lines ("; ...") are kept here for the widget instead of being sent to Grbl
81
+ log: { max: 500 },
82
+
83
+ verbose: false, // -v: log pendant events and commands
84
+ trace: false // --trace: also log all controller traffic (everything CNCjs reads/writes)
85
+ };
86
+
87
+ /**
88
+ * Tells whether a value is a plain object (not null, not an array).
89
+ *
90
+ * @param {*} v - value to test
91
+ * @returns {boolean}
92
+ */
93
+ const isObj = (v) => v && typeof v === 'object' && !Array.isArray(v);
94
+ /**
95
+ * Recursively merges `extra` into a copy of `base`. Plain objects are merged key by key,
96
+ * everything else (including arrays) is replaced. Neither argument is modified.
97
+ *
98
+ * @param {object} base - lower precedence values
99
+ * @param {object} [extra] - higher precedence values
100
+ * @returns {object} the merged copy
101
+ */
102
+ const deepMerge = (base, extra) => {
103
+ const out = Object.assign({}, base);
104
+ // nested objects are copied too, so changing the result later never changes `base` (the defaults)
105
+ Object.keys(out).forEach((k) => { if (isObj(out[k])) out[k] = deepMerge(out[k], {}); });
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
+ /**
113
+ * Builds the configuration. Precedence (low -> high): defaults, the "pendant" section of ~/.cncrc, the config file,
114
+ * the command line.
115
+ *
116
+ * @param {object} cli - parsed command line options (commander's opts())
117
+ * @param {?object} cncrcPendant - the "pendant" section of ~/.cncrc, if any
118
+ * @param {object} [opts]
119
+ * @param {?string} [opts.defaultFile] - the config file used when --config is not given (default ~/.cncjs-handwheel.config)
120
+ * @returns {{cfg: object, cfgFile: ?string}} the configuration and the config file that was read, if any
121
+ * @throws {Error} with a message for the user when the file cannot be read or a required value is missing or wrong
122
+ */
123
+ function loadConfig(cli, cncrcPendant, opts = {}) {
124
+ let cfg = deepMerge(DEFAULTS, cncrcPendant);
125
+ const defaultFile = opts.defaultFile === undefined ? DEFAULT_CONFIG_FILE : opts.defaultFile;
126
+ const cfgFile = cli.config || (defaultFile && fs.existsSync(defaultFile) ? defaultFile : null);
127
+ if (cfgFile) {
128
+ try {
129
+ cfg = deepMerge(cfg, JSON.parse(fs.readFileSync(cfgFile, 'utf8')));
130
+ } catch (err) {
131
+ throw new Error('Cannot read config file ' + cfgFile + ': ' + err.message);
132
+ }
133
+ }
134
+ if (cli.port) cfg.cncjs.port = cli.port;
135
+ if (cli.baudrate) cfg.cncjs.baudrate = cli.baudrate;
136
+ if (cli.controllerType) cfg.cncjs.controllerType = cli.controllerType;
137
+ if (cli.socketAddress) cfg.cncjs.socketAddress = cli.socketAddress;
138
+ if (cli.socketPort) cfg.cncjs.socketPort = cli.socketPort;
139
+ if (cli.pendantPort) cfg.device.path = cli.pendantPort;
140
+ if (cli.pendantBaudrate) cfg.device.baudRate = cli.pendantBaudrate;
141
+ if (cli.verbose) cfg.verbose = true;
142
+ if (cli.trace) cfg.trace = true;
143
+ if (cli.pendantSend === false) cfg.device.send = false;
144
+ if (cli.jogTranslate === false) cfg.jog.translate = false;
145
+
146
+ if (!cfg.cncjs.port) throw new Error('Missing CNC controller port (cncjs.port / --port)');
147
+ if (!cfg.device.path) throw new Error('Missing pendant port (device.path / --pendant-port). Try --list');
148
+ if (cfg.device.power.line) {
149
+ cfg.device.power.line = String(cfg.device.power.line).toLowerCase();
150
+ if (!['cts', 'dsr', 'dcd'].includes(cfg.device.power.line)) {
151
+ throw new Error('device.power.line must be "cts", "dsr", "dcd" or null, not "' + cfg.device.power.line + '"');
152
+ }
153
+ if (!['clear', 'set'].includes(cfg.device.power.poweredWhen)) {
154
+ throw new Error('device.power.poweredWhen must be "clear" or "set", not "' + cfg.device.power.poweredWhen + '"');
155
+ }
156
+ }
157
+ return { cfg, cfgFile };
158
+ }
159
+
160
+ module.exports = { DEFAULTS, DEFAULT_CONFIG_FILE, deepMerge, loadConfig };
package/lib/health.js ADDED
@@ -0,0 +1,101 @@
1
+ 'use strict';
2
+
3
+ // The bridge's health data: counters for /status, the rolling counters (events inside a window), and the ring buffer of
4
+ // pendant console lines served at /log.
5
+
6
+ /**
7
+ * Creates the health data of one bridge run.
8
+ *
9
+ * @param {object} cfg - the configuration
10
+ * @param {function} log - verbose logger (prints only with -v)
11
+ * @returns {{health: object, noteEvent: function, recentCount: function, clearRecent: function, windowMs: function,
12
+ * pendantLog: {add: function, entries: function, last: function}}}
13
+ */
14
+ function createHealth(cfg, log) {
15
+ const health = {
16
+ startedAt: Date.now(),
17
+ pendant: { path: cfg.device.path, connected: false, lastRx: null, lastTx: null, rxLines: 0, txLines: 0,
18
+ reconnects: 0, errors: 0, lastError: null, logLines: 0, garbageLines: 0, strayLines: 0, link: null, info: null,
19
+ powered: null, powerError: null }, // powered: null = unknown or not configured, true / false = switched on / off
20
+ cncjs: { socketConnected: false, portOpen: false, port: cfg.cncjs.port, controllerType: cfg.cncjs.controllerType,
21
+ lastError: null, droppedCommands: 0, workflow: null },
22
+ guard: { dropped: 0, spindle: 0, lastAt: null },
23
+ jog: { sent: 0, merged: 0, discarded: 0, stalls: 0, cancels: 0, inFlight: 0, held: false, lastAt: null },
24
+ lastCommand: null
25
+ };
26
+
27
+ /** Timestamps of recent events per counter; the lifetime totals live in `health`, these feed the rolling window. */
28
+ const recentEvents = { reconnects: [], errors: [], garbageLines: [], droppedCommands: [] };
29
+ const MAX_RECENT_EVENTS = 1000;
30
+
31
+ /**
32
+ * @returns {number} the length of the rolling window in ms (health.windowMs, at least one minute)
33
+ */
34
+ function windowMs() {
35
+ return Math.max(60000, Number(cfg.health && cfg.health.windowMs) || 900000);
36
+ }
37
+
38
+ /**
39
+ * Remembers that an event happened now, for the rolling counters in the status report. Old entries are dropped,
40
+ * and so are the oldest ones beyond MAX_RECENT_EVENTS (a flood cannot grow the list without bound).
41
+ *
42
+ * @param {string} kind - a key of recentEvents
43
+ * @returns {void}
44
+ */
45
+ function noteEvent(kind) {
46
+ const list = recentEvents[kind];
47
+ const now = Date.now();
48
+ list.push(now);
49
+ const from = now - windowMs();
50
+ while (list.length && (list[0] < from || list.length > MAX_RECENT_EVENTS)) list.shift();
51
+ }
52
+
53
+ /**
54
+ * Counts the events of one kind inside the rolling window.
55
+ *
56
+ * @param {string} kind - a key of recentEvents
57
+ * @returns {number}
58
+ */
59
+ function recentCount(kind) {
60
+ const from = Date.now() - windowMs();
61
+ return recentEvents[kind].filter((t) => t >= from).length;
62
+ }
63
+
64
+ /**
65
+ * Forgets the recent events of the given kinds (the totals in `health` stay).
66
+ *
67
+ * @param {...string} kinds - keys of recentEvents
68
+ * @returns {void}
69
+ */
70
+ function clearRecent(...kinds) {
71
+ kinds.forEach((k) => { recentEvents[k].length = 0; });
72
+ }
73
+
74
+ const logBuf = [];
75
+ let logSeq = 0;
76
+ const pendantLog = {
77
+ /**
78
+ * Appends a pendant console line to the ring buffer served at GET /log (capped at log.max entries).
79
+ *
80
+ * @param {string} text - the log text, without the leading ';'
81
+ * @returns {void}
82
+ */
83
+ add(text) {
84
+ logBuf.push({ id: ++logSeq, t: Date.now(), text });
85
+ if (logBuf.length > cfg.log.max) logBuf.splice(0, logBuf.length - cfg.log.max);
86
+ health.pendant.logLines = logSeq;
87
+ log('pendant -> log:', text);
88
+ },
89
+ /**
90
+ * @param {number} since - id of the last entry the caller has seen
91
+ * @returns {Array} the entries newer than that
92
+ */
93
+ entries(since) { return logBuf.filter((e) => e.id > since); },
94
+ /** @returns {number} id of the newest entry */
95
+ last() { return logSeq; }
96
+ };
97
+
98
+ return { health, noteEvent, recentCount, clearRecent, windowMs, maxRecentEvents: MAX_RECENT_EVENTS, pendantLog };
99
+ }
100
+
101
+ module.exports = createHealth;
package/lib/http.js ADDED
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ // The health endpoint: GET /status (link health, counters, last command, machine status) and GET /log?since=<id>.
4
+
5
+ const http = require('http');
6
+
7
+ /**
8
+ * Builds the JSON served at GET /status: link health of the pendant and CNCjs, the last command
9
+ * sent, and the current machine status.
10
+ *
11
+ * @param {object} ctx - the bridge context
12
+ * @returns {object}
13
+ */
14
+ function healthReport(ctx) {
15
+ const { cfg, health } = ctx;
16
+ const now = Date.now();
17
+ const age = (t) => (t ? now - t : null);
18
+ return {
19
+ ok: health.pendant.connected && health.pendant.powered !== false && ctx.cmd.cncReady(),
20
+ version: ctx.pkg.version,
21
+ uptimeMs: now - health.startedAt,
22
+ pendant: Object.assign({}, health.pendant, { sendEnabled: !!cfg.device.send, powerDetect: !!cfg.device.power.line,
23
+ lastRxAgeMs: age(health.pendant.lastRx),
24
+ lastTxAgeMs: age(health.pendant.lastTx),
25
+ info: health.pendant.info && Object.assign({}, health.pendant.info, { ageMs: age(health.pendant.info.at) }) }),
26
+ cncjs: health.cncjs,
27
+ // The same counters over the last windowMs only (they age out by themselves); the totals above count since the bridge started.
28
+ recent: {
29
+ windowMs: ctx.windowMs(),
30
+ reconnects: ctx.recentCount('reconnects'),
31
+ errors: ctx.recentCount('errors'),
32
+ garbageLines: ctx.recentCount('garbageLines'),
33
+ droppedCommands: ctx.recentCount('droppedCommands'),
34
+ lastError: ctx.recentCount('errors') > 0 ? health.pendant.lastError : null
35
+ },
36
+ jog: Object.assign({}, health.jog, { lastAgeMs: age(health.jog.lastAt) }),
37
+ // gcode from the pendant kept out of the machine during a job; spindle = real-time spindle toggles sent instead of M3 / M5
38
+ guard: Object.assign({}, health.guard, { enabled: cfg.guard.duringJob !== false, lastAgeMs: age(health.guard.lastAt) }),
39
+ // gaps between two status lines written to the pendant (ms); slow = longer than SLOW_STATUS_MS
40
+ statusGap: ctx.status.gapReport(age),
41
+ lastCommand: health.lastCommand,
42
+ status: ctx.status.snapshot()
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Starts the health endpoint if http.enabled is on.
48
+ *
49
+ * @param {object} ctx - the bridge context
50
+ * @returns {?object} the HTTP server, or null when the endpoint is switched off
51
+ */
52
+ function startHttp(ctx) {
53
+ const { cfg } = ctx;
54
+ if (!cfg.http.enabled) return null;
55
+ const httpServer = http.createServer((req, res) => {
56
+ const url = new URL(req.url, 'http://localhost');
57
+ const headers = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' };
58
+ if (url.pathname === '/' || url.pathname === '/status') {
59
+ res.writeHead(200, headers);
60
+ res.end(JSON.stringify(healthReport(ctx)));
61
+ } else if (url.pathname === '/log') {
62
+ // GET /log?since=<id> -> entries with id > since (poll with the last id you saw)
63
+ const since = Number(url.searchParams.get('since')) || 0;
64
+ res.writeHead(200, headers);
65
+ res.end(JSON.stringify({ last: ctx.pendantLog.last(), entries: ctx.pendantLog.entries(since) }));
66
+ } else {
67
+ res.writeHead(404);
68
+ res.end();
69
+ }
70
+ });
71
+ httpServer.on('error', (err) => console.error('Health endpoint error:', err.message));
72
+ httpServer.listen(cfg.http.port, cfg.http.host, () =>
73
+ console.log('Health endpoint on http://' + cfg.http.host + ':' + cfg.http.port + '/status'));
74
+ return httpServer;
75
+ }
76
+
77
+ module.exports = { healthReport, startHttp };
@@ -0,0 +1,116 @@
1
+ 'use strict';
2
+
3
+ // Keeps gcode from the pendant out of a running or paused job (see lib/guard.js for the decisions): the CNCjs workflow
4
+ // state, the Grbl state needed for the spindle stop, and what is done with a line that is not let through.
5
+
6
+ const guard = require('./guard');
7
+
8
+ /**
9
+ * Creates the job guard.
10
+ *
11
+ * @param {object} ctx - the bridge context
12
+ * @returns {{setWorkflow: function, workflow: function, activeState: function, jobGuarded: function,
13
+ * onControllerState: function, decide: function, apply: function}}
14
+ */
15
+ module.exports = function createJobGuard(ctx) {
16
+ const { cfg, health, store, log } = ctx;
17
+ // CNCjs workflow state ('idle', 'running', 'paused'); null until CNCjs has told us.
18
+ let workflowState = null;
19
+ let spindleStopped = false; // the spindle was stopped with 0x9E from here and not switched on again
20
+ let lastGuardNote = 0;
21
+
22
+ /**
23
+ * Records the CNCjs workflow state. When a job starts, a jog that is being held back is thrown away: it must
24
+ * not be released into the job.
25
+ *
26
+ * @param {?string} state - 'idle', 'running', 'paused' or null (not known)
27
+ * @returns {void}
28
+ */
29
+ function setWorkflow(state) {
30
+ if (state === workflowState) return;
31
+ log('workflow state:', workflowState, '->', state);
32
+ workflowState = state;
33
+ health.cncjs.workflow = state;
34
+ if (state !== 'idle') ctx.jog.discardHeldJog();
35
+ if (state === 'idle') spindleStopped = false;
36
+ }
37
+
38
+ /**
39
+ * @returns {?string} the Grbl state from the last status report, e.g. 'Hold', 'Run', 'Idle'
40
+ */
41
+ function activeState() {
42
+ const st = store.controller.state && store.controller.state.status;
43
+ return (st && st.activeState) || null;
44
+ }
45
+
46
+ /**
47
+ * Tells whether the guard keeps gcode from the pendant out of the machine right now.
48
+ *
49
+ * @returns {boolean}
50
+ */
51
+ const jobGuarded = () => cfg.guard.duringJob !== false && workflowState !== 'idle';
52
+
53
+ /**
54
+ * To be called when a controller state report arrives: Grbl switches the spindle back on when the hold ends.
55
+ *
56
+ * @returns {void}
57
+ */
58
+ function onControllerState() {
59
+ if (activeState() !== 'Hold') spindleStopped = false;
60
+ }
61
+
62
+ /**
63
+ * Decides what to do with a gcode line from the pendant.
64
+ *
65
+ * @param {string} line - the gcode line
66
+ * @returns {object} the decision from guard.decide(); `pass` when the controller is not reachable (the normal
67
+ * path then answers with ERR:CNCJS_NOT_READY)
68
+ */
69
+ function decide(line) {
70
+ return !ctx.cmd.cncReady() ? { action: 'pass' } : guard.decide(line, { enabled: cfg.guard.duringJob !== false,
71
+ workflow: workflowState, activeState: activeState(), controllerType: cfg.cncjs.controllerType, spindleStopped });
72
+ }
73
+
74
+ /**
75
+ * Applies the decision of the job guard to a gcode line: drops it (told to the pendant and the widget log, at most
76
+ * once a second) or sends the real-time byte in its place.
77
+ *
78
+ * @param {string} line - the gcode line from the pendant
79
+ * @param {object} d - the decision from guard.decide()
80
+ * @returns {boolean} true if something was sent to the machine
81
+ */
82
+ function apply(line, d) {
83
+ if (d.action === 'realtime') {
84
+ if (!ctx.cmd.cncReady() || !ctx.socket.emit('write', cfg.cncjs.port, d.byte)) {
85
+ ctx.cmd.noteDropped('write', [d.what]);
86
+ ctx.link.send('ERR:CNCJS_NOT_READY');
87
+ ctx.status.queueStatus();
88
+ return false;
89
+ }
90
+ spindleStopped = d.spindleStopped;
91
+ health.guard.spindle++;
92
+ health.lastCommand = { at: Date.now(), name: 'write', args: [d.what] };
93
+ log('pendant ->', d.what, '(real-time 0x9E) instead of', JSON.stringify(line));
94
+ ctx.cmd.answerCommand();
95
+ return true;
96
+ }
97
+ if (!d.quiet) {
98
+ health.guard.dropped++;
99
+ health.guard.lastAt = Date.now();
100
+ }
101
+ const now = Date.now();
102
+ if (!d.quiet && now - lastGuardNote >= 1000) {
103
+ lastGuardNote = now;
104
+ const text = line.replace(/[\x00-\x1f\x7f]/g, '');
105
+ console.warn('Dropped pendant gcode (' + d.reason + '): ' + text + ' [' + health.guard.dropped + ' dropped so far]');
106
+ ctx.pendantLog.add('[' + d.reason + ', not sent] ' + text);
107
+ ctx.link.send('ERR:JOB_ACTIVE');
108
+ ctx.status.queueStatus();
109
+ } else {
110
+ log('pendant -> dropped', JSON.stringify(line), '(' + d.reason + ')');
111
+ }
112
+ return false;
113
+ }
114
+
115
+ return { setWorkflow, workflow: () => workflowState, activeState, jobGuarded, onControllerState, decide, apply };
116
+ };