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/jog.js ADDED
@@ -0,0 +1,202 @@
1
+ 'use strict';
2
+
3
+ // The jog governor.
4
+ // CNCjs hands every gcode line it is given to Grbl without waiting for the previous one to be
5
+ // answered. Grbl only has a 128 byte serial buffer (about 6 jog lines), and stops reading it while its
6
+ // planner is full, so a fast wheel makes it lose characters: jogs vanish or turn into garbage.
7
+ // The bridge therefore counts the lines it has handed to CNCjs minus the ok / error replies it sees,
8
+ // and while jog.maxInFlight is reached it merges further jogs (same axis, feed and relative mode;
9
+ // opposite directions cancel out) into one pending jog that is sent as soon as a reply frees a slot.
10
+
11
+ const { parseJog, fmtDist } = require('./protocol');
12
+
13
+ const CANCEL_SETTLE_DEFAULT_MS = 40;
14
+
15
+ /**
16
+ * Creates the jog governor. Its timer starts at once; call dispose() to stop it.
17
+ *
18
+ * @param {object} ctx - the bridge context
19
+ * @returns {{state: object, sendGcodeLine: function, cancelJog: function, discardHeldJog: function,
20
+ * resetJogs: function, onControllerLine: function, dispose: function}}
21
+ */
22
+ module.exports = function createJog(ctx) {
23
+ const { cfg, health, log } = ctx;
24
+ const jog = { inFlight: 0, lastAck: 0, pending: null };
25
+ let cancelTimer = null;
26
+
27
+ /**
28
+ * Sends a gcode line to CNCjs and counts it as unanswered (when the jog governor is on). Jogs ($J=)
29
+ * carry `{echo: false}` as context when jog.echo is off.
30
+ *
31
+ * @param {string} line - the gcode line
32
+ * @returns {boolean} true if the line was sent
33
+ */
34
+ function writeGcode(line) {
35
+ const sendCommand = ctx.cmd.sendCommand;
36
+ const quiet = !cfg.jog.echo && /^\$J=/.test(line);
37
+ // "$X" as a gcode line would be dropped by CNCjs while the machine is in Alarm (its feeder refuses to send in Alarm
38
+ // mode); the "unlock" command writes it straight to the port, which is what the Unlock button does.
39
+ const sent = /^\$X$/i.test(line) ? sendCommand('unlock')
40
+ : quiet ? sendCommand('gcode', line, { echo: false }) : sendCommand('gcode', line);
41
+ if (!sent) return false;
42
+ if (cfg.jog.maxInFlight > 0) {
43
+ if (jog.inFlight === 0) jog.lastAck = Date.now();
44
+ jog.inFlight++;
45
+ health.jog.inFlight = jog.inFlight;
46
+ }
47
+ health.jog.sent++;
48
+ return true;
49
+ }
50
+
51
+ /**
52
+ * Sends a gcode line from the pendant: jogs go through the governor, everything else goes straight
53
+ * out (after any held back jog, to keep the order).
54
+ *
55
+ * @param {string} line - the gcode line
56
+ * @returns {boolean} true if the line was sent or held back
57
+ */
58
+ function sendGcodeLine(line) {
59
+ const d = ctx.jobGuard.decide(line);
60
+ if (d.action !== 'pass') return ctx.jobGuard.apply(line, d);
61
+ const j = cfg.jog.maxInFlight > 0 ? parseJog(line) : null;
62
+ if (j) return queueJog(j);
63
+ flushJog(true);
64
+ return writeGcode(line);
65
+ }
66
+
67
+ /**
68
+ * Adds a jog to the pending one (same axis, feed and mode: distances add up, opposite jogs cancel;
69
+ * anything else replaces it) and sends it if there is room.
70
+ *
71
+ * @param {object} j - jog from parseJog()
72
+ * @returns {boolean} true
73
+ */
74
+ function queueJog(j) {
75
+ health.jog.lastAt = Date.now(); // the wheel is being turned (the widget shows "Jog" for a moment)
76
+ const p = jog.pending;
77
+ if (p && p.prefix === j.prefix && p.axis === j.axis && p.feed === j.feed) {
78
+ p.dist += j.dist;
79
+ p.raw = null;
80
+ health.jog.merged++;
81
+ if (Math.abs(p.dist) < 1e-9) jog.pending = null;
82
+ } else {
83
+ if (p) health.jog.discarded++;
84
+ jog.pending = j;
85
+ }
86
+ flushJog(false);
87
+ health.jog.held = !!jog.pending;
88
+ return true;
89
+ }
90
+
91
+ /**
92
+ * Sends the pending jog if the limit allows (or when forced).
93
+ *
94
+ * @param {boolean} force - send even if jog.maxInFlight is reached
95
+ * @returns {void}
96
+ */
97
+ function flushJog(force) {
98
+ const p = jog.pending;
99
+ if (!p) return;
100
+ if (ctx.jobGuard.jobGuarded()) { discardHeldJog(); return; }
101
+ if (!force && (cancelTimer || jog.inFlight >= cfg.jog.maxInFlight)) return;
102
+ jog.pending = null;
103
+ health.jog.held = false;
104
+ writeGcode(p.raw || '$J=' + p.prefix + p.axis + fmtDist(p.dist) + 'F' + p.feed);
105
+ }
106
+
107
+ /**
108
+ * Cancels the jog in progress (pendant line 0x85 or JOGCANCEL). Three steps, in this order:
109
+ * 1. the jog held back by the governor is discarded;
110
+ * 2. `feeder:stop` empties the CNCjs feeder queue right away, so no further jog line leaves for Grbl
111
+ * (a Grbl jog cancel only flushes Grbl's planner, jogs still queued in CNCjs would continue);
112
+ * 3. after jog.cancelSettleMs the `jogCancel` command (0x85) is sent. Grbl handles 0x85 the moment it
113
+ * arrives, ahead of lines still unparsed in its serial buffer, so the short wait lets those lines
114
+ * be parsed first; otherwise a long jog sent just before the cancel could start after it.
115
+ * Jogs from the pendant that arrive during the wait are held and released after the cancel.
116
+ * Lines CNCjs had already written to Grbl may still run (at most jog.maxInFlight short jogs).
117
+ *
118
+ * @returns {boolean} true if the cancel was started
119
+ */
120
+ function cancelJog() {
121
+ health.jog.cancels++;
122
+ if (cfg.cncjs.controllerType !== 'Grbl') {
123
+ log('pendant -> jog cancel ignored: only supported for Grbl');
124
+ return false;
125
+ }
126
+ discardHeldJog();
127
+ if (!ctx.cmd.sendCommand('feeder:stop')) return false;
128
+ jog.inFlight = 0; // lines removed from the feeder will never be answered
129
+ health.jog.inFlight = 0;
130
+ clearTimeout(cancelTimer);
131
+ cancelTimer = setTimeout(() => {
132
+ cancelTimer = null;
133
+ ctx.cmd.sendCommand('jogCancel');
134
+ flushJog(false);
135
+ }, Number(cfg.jog.cancelSettleMs !== undefined ? cfg.jog.cancelSettleMs : CANCEL_SETTLE_DEFAULT_MS));
136
+ return true;
137
+ }
138
+
139
+ /**
140
+ * Throws away a jog that is being held back (after a feed hold or reset).
141
+ *
142
+ * @returns {void}
143
+ */
144
+ function discardHeldJog() {
145
+ if (jog.pending) health.jog.discarded++;
146
+ jog.pending = null;
147
+ health.jog.held = false;
148
+ }
149
+
150
+ /**
151
+ * Forgets all jog accounting (CNCjs connection or CNC port changed): nothing stale is replayed.
152
+ *
153
+ * @returns {void}
154
+ */
155
+ function resetJogs() {
156
+ jog.inFlight = 0;
157
+ jog.pending = null;
158
+ health.jog.inFlight = 0;
159
+ health.jog.held = false;
160
+ }
161
+
162
+ /**
163
+ * Handles a line CNCjs read from the controller: every ok / error reply frees a slot and may release
164
+ * the held jog.
165
+ *
166
+ * @param {*} data - the line (string) as emitted by CNCjs
167
+ * @returns {void}
168
+ */
169
+ function onControllerLine(data) {
170
+ const line = String(data === null || data === undefined ? '' : data).trim();
171
+ if (line !== 'ok' && line.slice(0, 6).toLowerCase() !== 'error:') return;
172
+ if (jog.inFlight > 0) jog.inFlight--;
173
+ health.jog.inFlight = jog.inFlight;
174
+ jog.lastAck = Date.now();
175
+ flushJog(false);
176
+ health.jog.held = !!jog.pending;
177
+ }
178
+
179
+ // Lines the controller never answers (lost in transit) would keep the counter up for good.
180
+ const jogTimer = setInterval(() => {
181
+ if (jog.inFlight > 0 && Date.now() - jog.lastAck > cfg.jog.stallMs) {
182
+ health.jog.stalls++;
183
+ console.warn('Controller did not acknowledge ' + jog.inFlight + ' gcode line(s) for ' + cfg.jog.stallMs +
184
+ ' ms: they may have been lost. [' + health.jog.stalls + ' stall(s) so far]');
185
+ jog.inFlight = 0;
186
+ health.jog.inFlight = 0;
187
+ }
188
+ flushJog(false);
189
+ }, 250);
190
+
191
+ /**
192
+ * Stops the timers.
193
+ *
194
+ * @returns {void}
195
+ */
196
+ function dispose() {
197
+ clearInterval(jogTimer);
198
+ clearTimeout(cancelTimer);
199
+ }
200
+
201
+ return { state: jog, sendGcodeLine, cancelJog, discardHeldJog, resetJogs, onControllerLine, dispose };
202
+ };
@@ -0,0 +1,177 @@
1
+ 'use strict';
2
+
3
+ // pendant -> CNCjs
4
+ // Everything from the pendant is LINE based (newline terminated) and must be printable ASCII.
5
+ // Lines that contain anything else are dropped (an ESP32 that is booting or running at the wrong
6
+ // baud rate spews binary garbage, which must never reach the CNC).
7
+ // "!" feed hold "~" cycle start "^X" (0x18) soft reset "?" status request
8
+ // each as a line of its own, e.g. "!\n". Reset is rate limited.
9
+ // ";..." pendant console log entry (any text, ANSI colours stripped): kept in a ring buffer for the
10
+ // widget (GET /log), never sent to CNCjs; with -v it is printed as "pendant log: ..."
11
+ // lines dropped as non-text are reported with -v (escaped, at most one per second)
12
+ // everything after a ";" that is not at the start of the line is a comment and is not sent ("\x18; Reset")
13
+ // "$X" is sent as CNCjs's unlock command (a gcode line would be dropped in Alarm)
14
+ // PING -> PONG, STATUS? -> immediate status line
15
+ // anything that looks like gcode (or a Grbl $ command) -> gcode; any other text is kept out of the machine
16
+ // (device.strictGcode, on by default) and shown in the widget log as "[not gcode, not sent] ..."
17
+ // After the pendant port opens, input is ignored for device.settleMs so the boot output of an
18
+ // ESP32 that was reset by the open is discarded.
19
+
20
+ const guard = require('./guard');
21
+ const { PRINTABLE, REALTIME, ANSI, looksLikeGcode, toJog, parsePendantReport } = require('./protocol');
22
+
23
+ /**
24
+ * Creates the pendant input handler.
25
+ *
26
+ * @param {object} ctx - the bridge context
27
+ * @returns {{onPendantData: function, onPendantLine: function, clearBuffer: function, ignoreFor: function}}
28
+ */
29
+ module.exports = function createPendantInput(ctx) {
30
+ const { cfg, health, log } = ctx;
31
+ let rxBuf = '';
32
+ let skipLine = false;
33
+ let ignoreUntil = 0;
34
+ let lastReset = 0;
35
+ let lastDropLog = 0;
36
+
37
+ /**
38
+ * Handler for raw bytes from the pendant's serial port. Splits the stream into lines, drops overlong
39
+ * lines, and ignores everything during the settle time after the port was opened.
40
+ *
41
+ * @param {Buffer} buf - chunk read from the serial port
42
+ * @returns {void}
43
+ */
44
+ function onPendantData(buf) {
45
+ const now = Date.now();
46
+ if (health.pendant.powered === false) { // switched off: whatever the adapter's RX line picks up is noise
47
+ rxBuf = '';
48
+ skipLine = false;
49
+ return;
50
+ }
51
+ health.pendant.lastRx = now;
52
+ if (now < ignoreUntil) {
53
+ rxBuf = '';
54
+ skipLine = false;
55
+ return;
56
+ }
57
+ const text = buf.toString('binary');
58
+ for (let i = 0; i < text.length; i++) {
59
+ const ch = text[i];
60
+ if (ch === '\n' || ch === '\r') {
61
+ const line = rxBuf.trim();
62
+ const drop = skipLine;
63
+ rxBuf = '';
64
+ skipLine = false;
65
+ if (drop) { health.pendant.garbageLines++; ctx.noteEvent('garbageLines'); }
66
+ else if (line) onPendantLine(line);
67
+ } else if (rxBuf.length < 256) {
68
+ rxBuf += ch;
69
+ } else {
70
+ skipLine = true; // overlong line: drop it up to the next newline
71
+ }
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Forgets a partly received line.
77
+ *
78
+ * @returns {void}
79
+ */
80
+ function clearBuffer() {
81
+ rxBuf = '';
82
+ skipLine = false;
83
+ }
84
+
85
+ /**
86
+ * Ignores the pendant's input for the given time (its boot output after the port was opened or it was switched on).
87
+ *
88
+ * @param {number} ms - how long
89
+ * @returns {void}
90
+ */
91
+ function ignoreFor(ms) {
92
+ ignoreUntil = Date.now() + ms;
93
+ }
94
+
95
+ /**
96
+ * Counts a rejected (non-text) pendant line and, with -v, reports it escaped (at most once a second).
97
+ *
98
+ * @param {string} raw - the rejected line as received (binary string)
99
+ * @returns {void}
100
+ */
101
+ function dropLine(raw) {
102
+ health.pendant.garbageLines++;
103
+ ctx.noteEvent('garbageLines');
104
+ const now = Date.now();
105
+ if (cfg.verbose && now - lastDropLog > 1000) {
106
+ lastDropLog = now;
107
+ console.log('pendant: dropped non-text line', JSON.stringify(raw.slice(0, 60)));
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Handles one complete line from the pendant: realtime commands (! ~ ^X ?), console log entries
113
+ * (; ...), PING / STATUS?, and otherwise gcode (jogs are translated to $J= for Grbl).
114
+ *
115
+ * @param {string} raw - the line without the line terminator (binary string)
116
+ * @returns {void}
117
+ */
118
+ function onPendantLine(raw) {
119
+ health.pendant.rxLines++;
120
+ // As in gcode, everything after a ";" is a comment: the firmware writes e.g. "\x18; Reset the machine". Only the
121
+ // part before it is the command. (A line that starts with ";" is a log entry, handled below.)
122
+ const semi = raw.indexOf(';');
123
+ if (semi > 0) {
124
+ const head = raw.slice(0, semi).trim();
125
+ if (head) {
126
+ log('pendant -> comment ignored:', raw.slice(semi + 1).trim());
127
+ raw = head;
128
+ }
129
+ }
130
+ if (raw === '?') return ctx.status.sendStatus(true);
131
+ // Grbl jog cancel: the raw byte 0x85 (also accepted as UTF-8, C2 85), or the text alias JOGCANCEL
132
+ if (raw === '\x85' || raw === '\xc2\x85' || raw.toUpperCase() === 'JOGCANCEL') return ctx.jog.cancelJog();
133
+ if (REALTIME[raw]) {
134
+ if (raw === '\x18') {
135
+ const now = Date.now();
136
+ if (now - lastReset < 2000) return;
137
+ lastReset = now;
138
+ }
139
+ // stop means stop: jogs still held back must not fire after a feed hold or a reset
140
+ if (raw === '!' || raw === '\x18') ctx.jog.discardHeldJog();
141
+ if (raw === '\x18') ctx.jog.state.inFlight = 0; // a soft reset flushes everything Grbl had not answered yet
142
+ // with a job on, ! and ~ pause and resume the job, so that the CNCjs workflow follows the machine
143
+ return ctx.cmd.sendCommand(guard.realtimeCommand(raw, ctx.jobGuard.workflow()));
144
+ }
145
+ // decode as UTF-8, drop ANSI colour codes, tabs -> spaces
146
+ let line = Buffer.from(raw, 'binary').toString('utf8').replace(ANSI, '').replace(/\t/g, ' ').trim();
147
+ if (!line) return;
148
+ if (line[0] === ';') {
149
+ // console log entry from the pendant: any text is fine, it is never sent to the controller
150
+ ctx.pendantLog.add(line.replace(/^;\s?/, '').replace(/[\x00-\x1f\x7f]/g, ''));
151
+ return;
152
+ }
153
+ if (!PRINTABLE.test(line)) {
154
+ dropLine(raw);
155
+ return;
156
+ }
157
+ const report = parsePendantReport(line, Date.now());
158
+ if (report) { health.pendant.info = report; return; }
159
+ const upper = line.toUpperCase();
160
+ if (upper === 'PING') return ctx.link.send('PONG');
161
+ if (upper === 'STATUS?') return ctx.status.sendStatus(true);
162
+ if (cfg.device.strictGcode !== false && !looksLikeGcode(line)) {
163
+ // Not gcode: most likely a log line that lost its ";" or a piece of one. Never hand it to the controller.
164
+ health.pendant.garbageLines++;
165
+ ctx.noteEvent('garbageLines');
166
+ health.pendant.strayLines = (health.pendant.strayLines || 0) + 1;
167
+ ctx.pendantLog.add('[not gcode, not sent] ' + line.replace(/[\x00-\x1f\x7f]/g, ''));
168
+ return;
169
+ }
170
+ if (cfg.jog.translate && cfg.cncjs.controllerType === 'Grbl') {
171
+ line = toJog(line);
172
+ }
173
+ ctx.jog.sendGcodeLine(line);
174
+ }
175
+
176
+ return { onPendantData, onPendantLine, clearBuffer, ignoreFor };
177
+ };
@@ -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
+ };