-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathg2.js
More file actions
1865 lines (1686 loc) · 72.2 KB
/
Copy pathg2.js
File metadata and controls
1865 lines (1686 loc) · 72.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* g2.js
*
* This module defines the G2 driver, which is responsible for managing communication
* between the host and a g2 motion conroller. Other objects and functions are
* defined here as well to support this capability.
*/
const { SerialPort } = require("serialport");
var fs = require("fs");
var events = require("events");
var async = require("async");
var util = require("util");
var Queue = require("./util").Queue;
var log = require("./log").logger("g2");
var process = require("process");
var stream = require("stream");
//const { last } = require("underscore");
// Values of the **stat** field that is returned from G2 status reports
var STAT_INIT = 0;
var STAT_READY = 1;
var STAT_ALARM = 2;
var STAT_STOP = 3;
var STAT_END = 4;
var STAT_RUNNING = 5;
var STAT_HOLDING = 6;
var STAT_PROBE = 7;
var STAT_CYCLING = 8;
var STAT_HOMING = 9;
var STAT_INTERLOCK = 11;
var STAT_SHUTDOWN = 12;
var STAT_PANIC = 13;
// Should take no longer than CMD_TIMEOUT to do a get or a set operation
var CMD_TIMEOUT = 100000;
var EXPECT_TIMEOUT = 300000;
// Reconnection constants
var RECONNECT_BASE_DELAY = 1000; // 1s initial retry delay
var RECONNECT_MAX_DELAY = 30000; // 30s max retry delay
var MAX_RECONNECT_TIME = 300000; // 5 minutes total before giving up
var RECONNECT_READY_TIMEOUT = 5000; // 5s to wait for SYSTEM READY on each attempt
// Status poll constants
var STATUS_POLL_INTERVAL = 5000; // 5s between status poll checks
var STATUS_POLL_TIMEOUT = 3000; // 3s to wait for status poll response
var STATUS_POLL_FEEDHOLD_TIMEOUT = 15000; // 15s timeout during feedhold — more tolerant
var _promiseCounter = 1;
var intendedClose = false;
var THRESH = 1;
var PRIMED_THRESHOLD = 10;
//var lastOverride = 1.0;
// var pat = /s*(G(28|38)\.\d|G2(0|1))/g; Not used yet
// Error codes defined by G2
// See https://github.com/synthetos/g2/blob/edge/TinyG2/tinyg2.h for the latest error codes and messages
try {
var G2_ERRORS = JSON.parse(fs.readFileSync("./data/g2_errors.json", "utf8"));
} catch (e) {
G2_ERRORS = {};
}
// A cycle context is created when you run a stream, and is a way to access driver events in the context of the current run
// It is a sort of token that you can recieve events from while the machining cycle is active,
// and that will resolve like a promise when the machining cycle is done.
function CycleContext(driver, st, promise) {
this.done = false;
this._firmed = false;
this._driver = driver;
this._stream = st;
this._paused = false;
this._promise = promise.then(
function () {
this.firm(); // Firm the tool
this.finish();
}.bind(this)
);
this.eventHandlers = {}; // eventname -> [listener]
this.eventQueue = {}; // eventname -> {f : listener, data : data to pass to listener}
}
// A cycle context is "firmed" when it has turned over itself as a promise through the then() call, or when the
// run finishes, whichever comes first.
CycleContext.prototype.firm = function () {
if (this.firmed) {
return;
}
log.debug("Firming the cycle context.");
try {
for (var event in this.eventQueue) {
var handlers = this.eventQueue[event];
for (var i = 0; i < handlers.length; i++) {
handlers[i].f(handlers[i].data);
}
}
this.firmed = true;
} catch (e) {
delete this.eventQueue;
throw e;
}
delete this.eventQueue;
};
// Bind the listener to the provided event name.
// Events bound in this way are queued, so if any have occurred between the beginning of the run and when
// the binding occurs, they will be triggered when the cycle is firmed
CycleContext.prototype.on = function (event, f) {
log.debug("Binding to the " + event + " event in the cycle context: " + f);
if (event in this.eventHandlers) {
this.eventHandlers[event].push(f);
} else {
this.eventHandlers[event] = [f];
}
return this;
};
// Return a promise that resolves when the cycle is complete (Q Promises)
CycleContext.prototype.then = function (f) {
this.firm();
return this._promise.then(function () {
return f();
});
};
// Sort of a do-nothing, for now
CycleContext.prototype.finish = function () {
log.debug("Finishing up the cycle context.");
};
// Emit the provided data to all the listeners to the subscribed event
CycleContext.prototype.emit = function (event, data) {
var handlers = this.eventHandlers[event];
if (handlers) {
for (var i = 0; i < handlers.length; i++) {
handlers[i](data);
}
}
};
// Pause the run by pausing the stream that is piping data into this context
CycleContext.prototype.pause = function () {
this._paused = true;
this._stream.pause();
};
// Resume the run by resuming the stream that is piping data into this context
CycleContext.prototype.resume = function () {
this._paused = false;
this._stream.resume();
};
// The G2 object represents the connection to the driver, which happens as serial over USB
function G2() {
this._currentData = [];
this._currentGCodeData = [];
this.g2_status = { stat: null, posx: 0, posy: 0, posz: 0 };
this.status = { stat: "idle", posx: 0, posy: 0, posz: 0 };
this._seen_ready = false;
this.gcode_queue = new Queue();
this.command_queue = new Queue();
this.pause_flag = false;
this.connected = false;
// OpenSBP Pause
this.pause_hold = false;
// Feedhold/flush
this.quit_pending = false;
this.stat = null;
this.hold = null;
this.manual_hold = false;
this.resumePending = false;
this.holdComplete = false; // Latches true when hold:10 is seen; cleared on resume send
// Readers and callbacks
this.expectations = [];
this.readers = {};
// Members related to streaming
this.qtotal = 0;
this.flooded = false;
this.send_rate = 1;
this.lines_sent = 0;
this.primedThreshold = PRIMED_THRESHOLD;
this.context = null;
// Event emitter inheritance and behavior setup
events.EventEmitter.call(this);
this.setMaxListeners(50);
this.lines_to_send = 4;
this._ignored_responses = 0;
this._primed = false;
this._streamDone = false;
this.lineBuffer = [];
// Reconnection state
this._reconnecting = false;
this._reconnectTimer = null;
// Counts failed attempts within the current reconnect() loop, reset at
// each loop start. Used to drive the "first attempt failed" UX in machine.js.
this._reconnectAttempts = 0;
// Status poll state
this._lastDataReceived = 0;
this._statusPollTimer = null;
this._statusPollTimeout = null;
this._statusPollPending = false;
// Set when the heartbeat probe has been written but its response not yet seen.
// Used to suppress logging of the probe's SR response in onData.
this._silentProbePending = false;
// Set after _handleDisconnect runs so onSerialClose / _write / etc. can
// short-circuit cleanly and only one "disconnect" event is emitted.
this._disconnected = false;
}
util.inherits(G2, events.EventEmitter);
// Reset all internal state that becomes stale after a serial disconnect.
// This prepares the G2 object for a fresh reconnection without creating a new instance.
G2.prototype._resetInternalState = function () {
// Buffers
this._currentData = [];
this.lineBuffer = [];
// Queues (Queue has no clear method, so reinitialize)
this.gcode_queue = new Queue();
this.command_queue = new Queue();
// Pending callbacks — these will never resolve, let them expire naturally
this.expectations = [];
this.readers = {};
// Streaming state
this.lines_to_send = 4;
this._ignored_responses = 0;
this._primed = false;
this._streamDone = false;
this.context = null;
this.flooded = false;
this.qtotal = 0;
this.lines_sent = 0;
// Flags
this.pause_flag = false;
this.quit_pending = false;
this.resumePending = false;
this.holdComplete = false;
this.manual_hold = false;
this.pause_hold = false;
// Connection state — allow "SYSTEM READY" detection again
this.connected = false;
this._seen_ready = false;
};
// Creates a cycle context, which has a pass-through stream into which data can be piped
G2.prototype._createCycleContext = function () {
if (this.context) {
throw new Error("Cannot create a new cycle context. One already exists.");
}
// Create and setup the pass-through stream
var st = new stream.PassThrough();
st.setEncoding("utf8");
this._streamDone = false;
this.lineBuffer = [];
this.flushcallback = null;
// Handle data coming in on the stream
st.on(
"data",
function (chunk) {
// console.log("=== STREAM DATA RECEIVED ===");
// console.log("Chunk raw:", JSON.stringify(chunk.toString()));
// console.log("Chunk length:", chunk.toString().length);
// console.log("Chunk lines:", chunk.toString().split("\n").length);
// Stream data comes in "chunks" which are often multiple lines
chunk = chunk.toString();
var newLines = false;
// Repartition incoming "chunked" data as lines
for (var i = 0; i < chunk.length; i++) {
var ch = chunk[i];
this.lineBuffer.push(ch);
if (ch === "\n") {
newLines = true;
var s = this.lineBuffer.join("").trim();
// Enqueue individual lines in the g-code queue
this.gcode_queue.enqueue(s);
// The G2 sender doesn't actually start sending until it is "primed"
// Priming happens either when the number of lines to send reaches a certain threshold
// or the prime() function is called manually.
if (this.gcode_queue.getLength() >= PRIMED_THRESHOLD) {
this._primed = true;
}
this.lineBuffer = [];
}
}
// If new lines were enqueued as a part of the re-chunkification process, send them.
if (newLines) {
this.sendMore();
}
}.bind(this)
);
////####
// Items that need to be pre-pended for all normal motions cycles.
// So, if we are not in IdleRuntime, then ...
// Set absolute, spindle speed default, units, and turn on output 4 & ...
// M0 sets G2 to 'File Stop' stat:3; thus avoids accidentally starting in stat:4 (needs to be in first 4 commands or vulnerable)
// ... these conditions are exited when in machine as it goes back to idle
////## {spph:true} makes sure that spindle shutoff and pull up is enabled for feedholds; no longer turned off in manual, needed?
////## S1000 is default for spindle speed so that m3 (and SO,1,1) will work correctly w/delay w/o speed
////## TODO: create default variable for S-value for VFD spindle control, just a dummy here now
////## TODO: fix this kludge to get the current_runtime !
if (global.CUR_RUNTIME != "[IdleRuntime]") {
// N1 M5 BEFORE the M0: the toolhead's spindle state only updates when a
// queued engage executes, so a stale "running" state can survive from a
// previous job (M30's spindle_stop is planner-queued and flushable).
// With spph enabled, M0 would pause that stale state and RESUME it —
// physically re-starting the spindle — when the cycle is released. M5
// first clears the state in-order before M0's pause check runs. It's a
// no-op when the spindle is already off (every normal start).
var prependString =
"N1 M5\n" + "N2 M0\n" + "N3 G90\n" + "N4 G61\n" + "{out4:1}\n" + "{spph:true}\n" + "N6 S1000\n";
log.debug("=== PREPEND DEBUG ===");
log.debug("Prepend string:", JSON.stringify(prependString));
log.debug("Lines to send before:", this.lines_to_send);
log.debug("PREPEND to cycle - " + global.CUR_RUNTIME);
st.write(prependString);
// FORCE enough lines_to_send to handle all prepend lines //** IMPORTANT */
this.lines_to_send = Math.max(this.lines_to_send, 7);
log.debug("Lines to send after adjustment:", this.lines_to_send);
}
// Handle a stream finishing or disconnecting.
st.on(
"end",
function () {
log.debug("cycle context end event");
// Send whatever is left in the queue. (There may be stuff unsent even after the stream is over)
this._primed = true;
this._streamDone = true;
this.sendMore();
log.info("***Stream END event.");
}.bind(this)
);
// Handle a stream being piped into this context (currently do nothing)
// chunk is defined but never used
st.on("pipe", function (/* chunk */) {
log.debug("Stream PIPE event");
});
// Create the promise that resolves when the machining cycle ends.
var promise = this._createStatePromise([STAT_END]).then(
function () {
this.context = null;
this._primed = false;
log.debug("Cycle context promise resolved.");
return this;
}.bind(this)
);
// Actually create and return the context built from these configured entities
var ctx = new CycleContext(this, st, promise);
// The G2 instance keeps track of its current (singleton) cycle context.
this.context = ctx;
};
// Actually open the serial port and configure G2 based on stored settings
G2.prototype.connect = function (path, callback) {
// Store paths for safe keeping
this._serialPath = path;
// Open the serial port. This used to be two ports, but now is only the one.
log.info("Opening G2 port: " + this._serialPath);
this._serialPort = new SerialPort({
path: this._serialPath,
baudRate: 115200,
autoOpen: false,
rtscts: true,
});
this._serialToken = "S";
// Handle errors
this._serialPort.on("error", this.onSerialError.bind(this));
this._serialPort.on("close", this.onSerialClose.bind(this));
// The control port is the only one to truly handle incoming data
this._serialPort.on("data", this.onData.bind(this));
// Flush and get status once the "ready" message has been received from the controller.
// G2 reports a "SYSTEM READY" message on connect that indicates that the system is prepared to
// recieve g-codes and JSON commands. We don't want to do anything until we get that.
this.once(
"ready",
function () {
this.connected = true;
////## Have tested both reset and end-file during this start-up to clear "alarm" and bad stop
////## a reset works, but disconnects G2 and requires new manual fabmo start
////## this._write('\x18\n', function() { ////## try reset not a kill
////## this._write('M30\n', function() { ////## try end file
////## Kludging 2 kills seems to allow a restart when g2 stuck
this._write("\x04\n", function () {});
this._write(
"\x04\n",
function () {
this.requestStatusReport(
function () {
callback(null, this);
}.bind(this)
);
}.bind(this)
);
// this._write(
// "\x04\n",
// function () {
// // Clear any leftover alarm state (e.g. soft limit from previous session)
// this.command({ clear: null });
// this.requestStatusReport(
// function () {
// this.startStatusPoll();
// callback(null, this);
// }.bind(this)
// );
// }.bind(this)
// );
}.bind(this)
);
// Actually perform the connect, and wait for the 'ready' event.
// We give 3 seconds for the ready event to materialize, which is plenty of time. Typical
// times to ready the system are on the order of tens or hundreds of milliseconds.
this._serialPort.open(
function (error) {
if (error) {
log.error("ERROR OPENING CONTROL PORT " + error);
return callback(error);
} else {
log.info("G2 Port Opened.");
setTimeout(
function checkConnected() {
if (!this.connected) {
return callback(new Error("Never got the SYSTEM READY from g2."));
}
}.bind(this),
3000
);
}
}.bind(this)
);
};
// Close the serial port - important for shutting down the application and not letting resources "dangle"
G2.prototype.disconnect = function (reason, callback) {
log.info(reason);
if (reason === "firmware") {
intendedClose = true;
}
this.stopStatusPoll();
this._serialPort.close(callback);
};
// Log serial errors. Most of these are exit-able offenses, though.
G2.prototype.onSerialError = function (data) {
// === ENHANCED SERIAL ERROR LOGGING ===
var errorTime = new Date().toISOString();
log.error("╔════════════════════════════════════════════════════════════════");
log.error("║ G2 SERIAL ERROR EVENT");
log.error("╠════════════════════════════════════════════════════════════════");
log.error("║ Timestamp: " + errorTime);
log.error("║ Error Data: " + JSON.stringify(data));
log.error("║ Serial Path: " + (this._serialPath || 'unknown'));
log.error("║ Port Open: " + (this._serialPort && this._serialPort.isOpen ? "YES" : "NO"));
log.error("║ Connected: " + this.connected);
log.error("║ In Cycle Context: " + (this.context ? "YES - FILE RUNNING" : "NO"));
log.error("║ Lines Sent: " + this.lines_sent);
log.error("║ Queue Length: " + this.gcode_queue.getLength());
log.error("╚════════════════════════════════════════════════════════════════");
// Save log immediately on serial errors
require('./log').saveCurrentLog('g2-serial-error', function(err) {
if (err) {
log.error("Failed to save log on serial error: " + err);
}
});
};
// When the serial link to G2 is closed, log diagnostics and notify listeners.
// Recovery is user-initiated — call G2.reconnect() explicitly (e.g. from the
// /reconnect route or the dashboard's persistent disconnect dialog).
G2.prototype.onSerialClose = function () {
this.connected = false;
// === ENHANCED DIAGNOSTIC LOGGING ===
var disconnectTime = new Date().toISOString();
var timeSinceLastData = this._lastDataReceived ? (Date.now() - this._lastDataReceived) : 'N/A';
log.error("╔════════════════════════════════════════════════════════════════");
log.error("║ G2 SERIAL DISCONNECT EVENT");
log.error("╠════════════════════════════════════════════════════════════════");
log.error("║ Timestamp: " + disconnectTime);
log.error("║ Serial Path: " + (this._serialPath || 'unknown'));
log.error("║ Time Since Last Rx: " + timeSinceLastData + " ms");
log.error("║ Lines Sent: " + this.lines_sent);
log.error("║ GCode Queue Length: " + this.gcode_queue.getLength());
log.error("║ Command Queue Len: " + this.command_queue.getLength());
log.error("║ In Cycle Context: " + (this.context ? "YES - FILE RUNNING" : "NO - idle"));
log.error("║ Stream Done: " + this._streamDone);
log.error("║ Primed: " + this._primed);
log.error("║ Connected: " + this.connected);
log.error("║ Reconnecting: " + this._reconnecting);
log.error("║ Pause Flag: " + this.pause_flag);
log.error("║ Quit Pending: " + this.quit_pending);
log.error("║ Last G2 Status: stat=" + (this.status.stat || 'unknown'));
log.error("║ Heartbeat Pending: " + this._heartbeatPending);
// Log current runtime if available
if (typeof global.CUR_RUNTIME !== 'undefined') {
log.error("║ Current Runtime: " + global.CUR_RUNTIME);
}
log.error("╚════════════════════════════════════════════════════════════════");
// Save log for diagnostics
require('./log').saveCurrentLog('g2-disconnect', function (err) {
if (err) {
log.error("Failed to save log on disconnect: " + err);
}
});
// Intentional close (firmware update) — do nothing
if (intendedClose) {
log.info("Serial close was intentional (firmware update) - not handling as disconnect");
return;
}
// Already mid-reconnect — let the retry loop handle the close
if (this._reconnecting) {
log.warn("Serial close during reconnect — handled by retry loop");
return;
}
this._handleDisconnect("serial_close");
};
// Mark the G2 link as down, clean up internal state, and notify listeners
// so the dashboard can prompt the user. Idempotent — repeated calls are no-ops.
// Recovery (G2.reconnect) is NOT triggered automatically; it must be invoked
// explicitly (user action via /reconnect, or engine startup retry).
G2.prototype._handleDisconnect = function (reason) {
if (this._disconnected) {
return;
}
this._disconnected = true;
this.connected = false;
this.stopStatusPoll();
var payload = {
reason: reason,
timestamp: new Date().toISOString(),
timeSinceLastData: this._lastDataReceived
? Date.now() - this._lastDataReceived
: null,
lastStat: (this.status && this.status.stat) || null,
inCycle: !!this.context,
serialPath: this._serialPath || null,
};
// Drop listeners on the (now-stale) port so ghost events don't fire
if (this._serialPort) {
try {
this._serialPort.removeAllListeners();
} catch (e) {
log.warn("Error removing serial listeners on disconnect: " + e);
}
}
// Wipe queues / buffers / flags so a future reconnect starts clean
this._resetInternalState();
log.error(
"G2 link lost (reason=" + reason + ") — awaiting user-initiated reconnect"
);
this.emit("disconnect", payload);
};
// User-initiated reconnect to G2 with exponential backoff.
// Called explicitly — by the /reconnect route, the dashboard's disconnect
// dialog, or from engine startup when the initial connection failed.
// Reuses the existing G2 object in-place so all external references
// (machine.driver, runtimes, config) remain valid.
G2.prototype.reconnect = function () {
if (this._reconnecting) {
log.warn("G2 reconnect already in progress — ignoring duplicate request");
return;
}
var that = this;
this._reconnecting = true;
this._reconnectAttempts = 0;
this.stopStatusPoll();
// Notify listeners (machine.js) so the dashboard can swap the disconnect
// modal for a "Reconnecting…" modal. /reconnect returns 200 immediately;
// without this, the user would see the dialog dismiss and have no signal
// that retries are still in flight.
this.emit("reconnecting", {
timestamp: new Date().toISOString(),
maxTime: MAX_RECONNECT_TIME,
serialPath: this._serialPath || null,
});
// _handleDisconnect normally has already cleaned up, but reconnect may also
// be called from a clean state (engine startup) — make these idempotent.
if (this._serialPort) {
try {
this._serialPort.removeAllListeners();
} catch (e) {
log.warn("Error removing serial listeners during reconnect: " + e);
}
}
this._resetInternalState();
var startTime = Date.now();
var delay = RECONNECT_BASE_DELAY;
function attemptReconnect() {
var elapsed = Date.now() - startTime;
if (elapsed >= MAX_RECONNECT_TIME) {
log.error(
"G2 reconnection failed after " +
Math.round(elapsed / 1000) +
"s — falling back to process exit."
);
require('./log').saveCurrentLog('g2-reconnect-failed', function () {
process.exit(14);
});
return;
}
log.info(
"G2 reconnection attempt (elapsed: " +
Math.round(elapsed / 1000) +
"s, next delay: " +
Math.round(delay / 1000) +
"s)"
);
// Check if the serial device exists before trying to open it
fs.access(that._serialPath, fs.constants.R_OK | fs.constants.W_OK, function (err) {
if (err) {
log.warn("Serial device " + that._serialPath + " not available yet: " + err.code);
scheduleNextRetry();
return;
}
// Create a new serial port object on the same path
var newPort = new SerialPort({
path: that._serialPath,
baudRate: 115200,
autoOpen: false,
rtscts: true,
});
var readyFired = false;
var readyTimeout = null;
// Handler for when G2 sends "SYSTEM READY"
function onReady() {
readyFired = true;
if (readyTimeout) {
clearTimeout(readyTimeout);
readyTimeout = null;
}
that.connected = true;
that._reconnecting = false;
that._disconnected = false;
that._seen_ready = true;
// Wire the global serial close/error handlers to the new port so
// a subsequent disconnect is detected (the retry loop only
// attached local close/error handlers for the open attempt).
that._serialPort.on("close", that.onSerialClose.bind(that));
that._serialPort.on("error", that.onSerialError.bind(that));
// Send kill commands to clear any stale G2 state, then notify success
that._write("\x04\n", function () {});
that._write("\x04\n", function () {
that.requestStatusReport(function () {
log.info("G2 reconnection successful.");
// that.startStatusPoll();
that.emit("reconnected");
});
});
}
// Listen for the "ready" event (emitted when onMessage sees "SYSTEM READY")
that.once("ready", onReady);
// Wire up event handlers on the new port
newPort.on("error", function (err) {
log.error("Serial error during reconnect attempt: " + err);
});
newPort.on("close", function () {
// Port closed during reconnection attempt — handled by retry loop
if (that._reconnecting && !readyFired) {
log.warn("Serial port closed during reconnect attempt");
}
});
newPort.on("data", that.onData.bind(that));
// Replace the internal serial port reference
that._serialPort = newPort;
that._serialToken = "S";
// Attempt to open
newPort.open(function (openErr) {
if (openErr) {
log.warn("Failed to open serial port: " + openErr);
that.removeListener("ready", onReady);
scheduleNextRetry();
return;
}
log.info("G2 port opened during reconnect — waiting for SYSTEM READY...");
// Give G2 time to send "SYSTEM READY"
readyTimeout = setTimeout(function () {
if (!readyFired) {
log.warn("No SYSTEM READY received within " + (RECONNECT_READY_TIMEOUT / 1000) + "s");
that.removeListener("ready", onReady);
// Close this port attempt and retry
try {
newPort.close(function () {
scheduleNextRetry();
});
} catch (e) {
scheduleNextRetry();
}
}
}, RECONNECT_READY_TIMEOUT);
});
});
}
function scheduleNextRetry() {
// Bail out if the user cancelled while an attempt was in flight
if (!that._reconnecting) {
return;
}
that._reconnectAttempts += 1;
that.emit("reconnect-attempt-failed", {
attempt: that._reconnectAttempts,
nextDelayMs: delay,
});
that._reconnectTimer = setTimeout(function () {
that._reconnectTimer = null;
attemptReconnect();
}, delay);
// Exponential backoff with cap
delay = Math.min(delay * 2, RECONNECT_MAX_DELAY);
}
// Start the first attempt after a short delay
that._reconnectTimer = setTimeout(function () {
that._reconnectTimer = null;
attemptReconnect();
}, RECONNECT_BASE_DELAY);
};
// User-initiated cancel of the reconnect retry loop. Clears the pending timer
// and re-emits "disconnect" so the dashboard restores the disconnect modal
// (with the Reconnect button) for the user to try again later.
G2.prototype.cancelReconnect = function () {
if (!this._reconnecting) {
return false;
}
log.warn("User cancelled G2 reconnect retry loop");
if (this._reconnectTimer) {
clearTimeout(this._reconnectTimer);
this._reconnectTimer = null;
}
this._reconnecting = false;
// _disconnected remains true — we are still not connected. Re-emit so the
// dashboard updates its modal (idempotency in _handleDisconnect would
// otherwise swallow this).
this.emit("disconnect", {
reason: "user_cancelled",
timestamp: new Date().toISOString(),
timeSinceLastData: this._lastDataReceived
? Date.now() - this._lastDataReceived
: null,
lastStat: (this.status && this.status.stat) || null,
inCycle: !!this.context,
serialPath: this._serialPath || null,
});
return true;
};
// Start periodic status poll to detect silent G2 failures.
// Sends a status report request if no data has been received recently.
// (Distinct from the blue LED "heartbeat" pulsing on the G2 card itself.)
G2.prototype.startStatusPoll = function () {
this.stopStatusPoll();
this._statusPollTimer = setInterval(
function () {
if (!this.connected || this._reconnecting || this._disconnected) {
return;
}
// Use longer timeout during feedhold — G2 is alive but paused
var inHold = this.pause_flag || this.status.inFeedHold;
var timeout = inHold ? STATUS_POLL_FEEDHOLD_TIMEOUT : STATUS_POLL_TIMEOUT;
// Skip if we received data recently — G2 is alive
if (Date.now() - this._lastDataReceived < STATUS_POLL_INTERVAL) {
return;
}
this._statusPollPending = true;
this._sendSilentProbe();
// Set timeout for response
this._statusPollTimeout = setTimeout(
function () {
if (this._statusPollPending) {
this._onStatusPollTimeout();
}
}.bind(this),
timeout
);
}.bind(this),
STATUS_POLL_INTERVAL
);
};
// Write the heartbeat probe directly to the serial port, bypassing command_queue
// AND the normal g2 log. The probe is identical in shape to a user-requested SR,
// so we tag _silentProbePending so onData can suppress logging of the response.
// _ignored_responses is incremented to balance flow control accounting (the
// returned {"r":{"sr":...}} should not be counted as a completed gcode line).
G2.prototype._sendSilentProbe = function () {
if (!this._serialPort || !this._serialPort.isOpen) {
return;
}
this._silentProbePending = true;
this._ignored_responses += 1;
this._serialPort.write(JSON.stringify({ sr: null }) + "\n", function () {});
};
// Stop the status poll timer and any pending response timeout
G2.prototype.stopStatusPoll = function () {
if (this._statusPollTimer) {
clearInterval(this._statusPollTimer);
this._statusPollTimer = null;
}
if (this._statusPollTimeout) {
clearTimeout(this._statusPollTimeout);
this._statusPollTimeout = null;
}
this._statusPollPending = false;
};
// Called when G2 fails to respond to a status poll within STATUS_POLL_TIMEOUT.
// Logs diagnostics, closes the port (which triggers onSerialClose ->
// _handleDisconnect), and falls back to _handleDisconnect directly if the
// close attempt itself fails. No automatic reconnect — the user is notified
// via the "disconnect" event and must invoke G2.reconnect() explicitly.
G2.prototype._onStatusPollTimeout = function () {
var timeoutTime = new Date().toISOString();
var timeSinceLastData = Date.now() - this._lastDataReceived;
log.error("╔════════════════════════════════════════════════════════════════");
log.error("║ G2 STATUS POLL TIMEOUT");
log.error("╠════════════════════════════════════════════════════════════════");
log.error("║ Timestamp: " + timeoutTime);
log.error("║ Time Since Last Rx: " + timeSinceLastData + " ms");
log.error("║ In Feedhold: " + (this.pause_flag || this.status.inFeedHold));
log.error("║ G2 Status (stat): " + (this.status.stat || 'unknown'));
log.error("║ In Cycle Context: " + (this.context ? "YES" : "NO"));
log.error("║ Status Poll Pending: " + this._statusPollPending);
log.error("╚════════════════════════════════════════════════════════════════");
this.stopStatusPoll();
try {
this._serialPort.close(function (err) {
if (err) {
log.warn("Error closing port after status poll timeout: " + err);
this._handleDisconnect("heartbeat_timeout");
}
}.bind(this));
} catch (e) {
log.warn("Exception closing port after status poll timeout: " + e);
this._handleDisconnect("heartbeat_timeout");
}
};
// Write to the serial port (and log it)
G2.prototype._write = function (s, callback) {
if (!this.connected || !this._serialPort || !this._serialPort.isOpen) {
log.error("Attempted write while disconnected: " + String(s).substring(0, 50));
if (!this._reconnecting && !this._disconnected) {
this._handleDisconnect("write_failed");
}
if (callback) {
setImmediate(callback);
}
return;
}
log.g2(this._serialToken, "out", s);
this._serialPort.write(
s,
function () {
if (callback) {
this._serialPort.drain(callback);
}
}.bind(this)
);
};
// Clear the "alarm" state on the g2 controller. Alarms happen in a few cases:
// - Limit switch triggered (not well handled)
// - Soft limit encountered (also not well handled)
// - Command recieved after a queue flush has been issued (this is handled well by this module)
// - Firmware errors in G2 that put it in the alarm state as a safety feature
G2.prototype.clearAlarm = function () {
this.command({ clear: null });
};
// Units are sort of weird, and our fork of the g2 firmware hijacks the "gun" command
// to set the system units. (Conventionally, you have to use a G-code to do this)
// stat is defined but never used
G2.prototype.setUnits = function (units, callback) {
this.command({ gun: units === 0 || units == "in" ? 0 : 1 });
this.requestStatusReport(function (/* stat */) {
callback();
});
};
// Request a status report from G2
// The callback, if provided, is called with the status report contents.
G2.prototype.requestStatusReport = function (callback) {
// Register the callback to be called when the next status report comes in
typeof callback === "function" && this.once("status", callback);
this.command({ sr: null });
};
// Called for every chunk of data returned from G2
G2.prototype.onData = function (data) {
// Track data reception for status poll
this._lastDataReceived = Date.now();
this._statusPollPending = false;
var t = new Date().getTime(); // Get current time for logging
// raw_data event for listeners that want to snoop on all data.
// Not usually used except for debugging
this.emit("raw_data", data);
// Although data comes in "chunks" from the serial stream, the information is processed as lines
// The following section repartitions the incoming chunk as lines so that it can be interpreted
var s = data.toString("ascii");
var len = s.length;
for (var i = 0; i < len; i++) {
var c = s[i];
if (c === "\n") {
var json_string = this._currentData.join("");
// eslint flags t as unused, used for logging
// eslint-disable-next-line no-unused-vars
t = new Date().getTime();
try {
// Responses from G2 are in JSON format (always) so we parse them out, and handle the messages
var obj = JSON.parse(json_string);
// Suppress logging the SR response that came back from a silent
// heartbeat probe — keeps the g2 log free of idle noise.
var isSilentProbeResponse =
this._silentProbePending &&
obj &&
((obj.r && obj.r.sr) || obj.sr);
if (isSilentProbeResponse) {
this._silentProbePending = false;
} else {
log.g2("S", "in", json_string);
}
this.onMessage(obj);
} catch (e) {
this.handleExceptionReport(e);