-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathmachine.js
1547 lines (1437 loc) · 57.6 KB
/
machine.js
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
/*
* machine.js
*
* Defines the "machine model" which is an abstraction of the physical machine that lives
* sort of one layer up from the G2 driver. It maintains a "machine state" that is similar to, but
* not the same as G2s internal state, and provides functions for high level machine operations.
*
* The machine model includes the important concept of runtimes, which are individual software components
* that get control of the machine for performing certain actions. Runtimes are important for compartmentalizing
* different ways of controlling the machine. Manually driving the machine with a pendant, for example is
* a very different sort of activity from running a g-code file, so those two activities are implemented
* by two separate runtimes that each get a chance to take control of the machine when it is time to perform
* their respective tasks.
*
* This module also sort of "meta manages" the motion systems state. An example
* of this is that G2 has digital inputs defined, and can specify their input mode and basic function, but the
* machine model layers some additional function on top of them, such as their higher-level application
* - perhaps acting as a door interlock, a tool stop button, etc.
*
* The machine model is a singleton. There is only ever one of them, which is instantiated by the connect() method.
*/
/*jshint esversion: 6 */
var g2 = require("./g2");
var util = require("util");
var events = require("events");
var PLATFORM = require("process").platform;
var fs = require("fs");
var path = require("path");
var db = require("./db");
var log = require("./log").logger("machine");
var config = require("./config");
var updater = require("./updater");
var u = require("./util");
var async = require("async");
var canQuit = false;
var canResume = false;
var clickDisabled = false;
var interlockBypass = false;
var runtime = null;
var spindle = require("./spindle1");
////## temp KLUDGES because of difficulty in figuring out a couple of quick comms between modules
global.CUR_RUNTIME;
global.CLIENT_DISCONNECTED = false; // Special purpose kludge to stop any ongoing keypad or keyboard actions if client disconnects
// Load up all the runtimes that are currently defined
// TODO - One day, a folder-scan and auto-registration process might be nice here, this is all sort of hand-rolled.
var GCodeRuntime = require("./runtime/gcode").GCodeRuntime;
var SBPRuntime = require("./runtime/opensbp").SBPRuntime;
var ManualRuntime = require("./runtime/manual").ManualRuntime;
var PassthroughRuntime = require("./runtime/passthrough").PassthroughRuntime;
var IdleRuntime = require("./runtime/idle").IdleRuntime;
// Instantiate a machine, connecting to the serial port specified in the engine configuration.
// TODO: We probably don't need special keys in the config for each platform anymore. Since the engine
// does its first-time config platform-detecting magic (See engine.js) these ports are likely to
// be filled with sensible defaults
function connect(callback) {
var control_path = null;
switch (PLATFORM) {
case "linux":
control_path = config.engine.get("control_port_linux");
break;
case "darwin":
control_path = config.engine.get("control_port_osx");
break;
case "win32":
case "win64":
control_path = config.engine.get("control_port_windows");
break;
default:
control_path = null;
break;
}
if (control_path) {
// TODO - I dunno, this is sort of a weird pattern
exports.machine = new Machine(control_path, callback);
} else {
typeof callback === "function" && callback('No supported serial path for platform "' + PLATFORM + '"');
}
}
function Machine(control_path, callback) {
// Handle Inheritance
events.EventEmitter.call(this);
// this.accessories = {};
// Instantiate driver and connect to G2
this.status = {
state: "not_ready",
posx: 0.0,
posy: 0.0,
posz: 0.0,
posa: 0.0,
posb: 0.0,
posc: 0.0,
in1: 1,
in2: 1,
in3: 1,
in4: 1,
in5: 1,
in6: 1,
in7: 1,
in8: 1,
in9: 1,
in10: 1,
in11: 1,
in12: 1,
spc: 0,
out1: 0,
out2: 0,
out3: 0,
out4: 0,
out5: 0,
out6: 0,
out7: 0,
out8: 0,
out9: 0,
out10: 0,
out11: 0,
out12: 0,
fro: 1.0,
feed: 0.0,
job: null,
info: null,
unit: null,
line: null,
nb_lines: null,
auth: false,
hideKeypad: false,
inFeedHold: false,
resumeFlag: false,
quitFlag: false,
targetHit: false,
lastState: null,
clientDisconnected: false,
};
this.fireButtonDebounce = false;
this.APCollapseTimer = null;
this.quit_pressed = 0;
this.fireButtonPressed = 0;
this.info_id = 0;
this.action = null;
this.interlock_action = null; // Continuing to use this as interlock/lock flag after allowing mult interlock defs
this.overrideLimit = false;
this.pauseTimer = false;
// Instantiate and connect to the G2 driver using the port specified in the constructor
this.driver = new g2.G2();
this.driver.on("error", function (err) {
log.error(err);
});
this.driver.connect(
control_path,
function (err) {
// Most of the setup of the machine happens here, AFTER we've successfully connected to G2
if (err) {
log.error(JSON.stringify(err));
log.warn("Setting the disconnected state");
this.die("An internal error has occurred. You must reboot your tool.");
if (typeof callback === "function") {
return callback(new Error("No connection to G2"));
} else {
return;
}
} else {
this.status.state = "idle";
}
// Create runtimes for different functions/command languages
this.gcode_runtime = new GCodeRuntime();
this.sbp_runtime = new SBPRuntime();
this.manual_runtime = new ManualRuntime();
this.passthrough_runtime = new PassthroughRuntime();
this.idle_runtime = new IdleRuntime();
this.runtimes = [
this.gcode_runtime,
this.sbp_runtime,
this.manual_runtime,
this.passthrough_runtime,
this.idle_runtime,
];
// The machine only has one "active" runtime at a time. When it's not doing anything else
// the active runtime is the IdleRuntime (setRuntime(null) sets the IdleRuntime)
this.setRuntime(
null,
function (err) {
if (err) {
typeof callback === "function" && callback(err);
} else {
this.driver.requestStatusReport(
function (result) {
if ("stat" in result) {
switch (result.stat) {
case g2.STAT_INTERLOCK:
case g2.STAT_SHUTDOWN:
case g2.STAT_PANIC:
this.die("A G2 exception has occurred. You must reboot your tool.");
break;
}
}
typeof callback === "function" && callback(null, this);
}.bind(this)
);
}
}.bind(this)
);
}.bind(this)
);
// If any of the axes in G2s configuration become enabled or disabled, we want to show or hide
// them accordingly. These change events happen even during the initial configuration load, so
// right from the beginning, we will be displaying the correct axes.
// And, Update status for client
config.driver.on(
"change",
function (update) {
["x", "y", "z", "a", "b", "c"].forEach(
function (axis) {
var mode = axis + "am";
var pos = "pos" + axis;
if (mode in update) {
if (update[mode] === 0) {
//log.debug("Disabling display for " + axis + " axis.");
delete this.status[pos];
} else {
//log.debug("Enabling display for " + axis + " axis.");
if (this.status[pos] === undefined) {
// Don't overwrite the position if it's already set
this.status[pos] = null;
}
}
}
}.bind(this)
);
log.debug("G2 Driver change detected -- UPDATING STATUS");
this.emit("status", this.status); // emit a status on any g2 driver change to deal with units, etc
}.bind(this)
);
// This handler deals with inputs that are selected for special functions (authorize, ok, quit, etc)
this.driver.on(
"status",
function (stat) {
var auth_input = "in" + config.machine.get("auth_input");
var quit_input = "in" + config.machine.get("quit_input");
var ap_input = "in" + config.machine.get("ap_input");
// If you press a button to pause, you're not allowed to resume or quit for at least a second
// (To eliminate the chance of a double-tap doing something you didn't intend.)
if (this.status.state === "paused") {
setTimeout(function () {
canQuit = true;
canResume = true;
}, 1000);
} else {
canQuit = false;
canResume = false;
}
// Handle okay and cancel buttons.
// Auth = OK
// Quit = Cancel
// If okay/cancel
if (auth_input === quit_input) {
this.handleOkayCancelDual(stat, auth_input);
} else {
this.handleOkayButton(stat, auth_input);
this.handleCancelButton(stat, quit_input);
}
// Other functions
this.handleFireButton(stat, auth_input);
this.handleAPCollapseButton(stat, ap_input);
this.status.clientDisconnected = global.CLIENT_DISCONNECTED;
}.bind(this)
);
}
util.inherits(Machine, events.EventEmitter);
// Given the status report provided and the specified input, perform the AP Mode Collapse behavior if necessary
// The AP mode collapse is a network failsafe. In the case that a tool gets "lost" on a network, it can be
// provoked back into AP mode by holding down a specific button for some time. Both the input to use for the
// button and the hold-down duration are specified in the machine settings
Machine.prototype.handleAPCollapseButton = function (stat, ap_input) {
// If the button has been pressed
if (stat[ap_input] & 1) {
var ap_collapse_time = config.machine.get("ap_time");
// For the first time
if (!this.APCollapseTimer) {
// Do an AP collapse in ap_collapse_time seconds, if the button is never released
log.debug("Starting a timer for AP mode collapse (AP button was pressed)");
this.APCollapseTimer = setTimeout(
function APCollapse() {
log.info("AP Collapse button held for " + ap_collapse_time + " seconds. Triggering AP collapse.");
this.APCollapseTimer = null;
updater.APModeCollapse();
}.bind(this),
ap_collapse_time * 1000
);
}
}
// Otherwise
else {
// Cancel an AP collapse that is pending, if there is one.
if (this.APCollapseTimer) {
log.debug("Cancelling AP collapse (AP button was released)");
clearTimeout(this.APCollapseTimer);
this.APCollapseTimer = null;
}
}
};
// Given the status report and specified input, process the okay/cancel behavior
// This function is called only when the ok button (authorize) and cancel button (quit)
// are assigned to the same input. The behavior in that case is slightly
// different than if they were separate. (see below)
Machine.prototype.handleOkayCancelDual = function (stat, quit_input) {
//this may be changed to user select wether to continue or to cancel
if (!(stat[quit_input] & 1) && this.status.state === "paused" && canQuit && this.quit_pressed) {
log.info("Cancel hit!");
this.quit(function (err, msg) {
if (err) {
log.error(err);
} else {
log.info(msg);
}
});
} else if (this.status.state === "interlock" && this.quit_pressed) {
log.info("Okay hit, resuming from interlock");
this.resume(function (err, msg) {
if (err) {
log.error(err);
} else {
log.info(msg);
}
});
} else if (this.status.state === "lock" && this.quit_pressed) {
log.info("Okay hit, resuming from lock");
this.resume(function (err, msg) {
if (err) {
log.error(err);
} else {
log.info(msg);
}
});
} else if (this.status.state === "limit" && this.quit_pressed) {
log.info("Okay hit, resuming and over-riding from limit");
this.resume(function (err, msg) {
if (err) {
log.error(err);
} else {
log.info(msg);
}
});
}
this.quit_pressed = stat[quit_input] & 1;
};
// Given the status report and specified input, process the "fire" behavior
// The machine has a state of being "armed" - either with an action, or when preparing to
// go into an authorized state. Pressing "fire" while armed either executes the action, or
// puts the system in an authorized state for the authorization period.
Machine.prototype.handleFireButton = function (stat, auth_input) {
if (this.fireButtonPressed && !(stat[auth_input] & 1) && this.status.state === "armed") {
log.info("FIRE button hit!");
this.fire();
}
this.fireButtonPressed = stat[auth_input];
};
// Given the status report and specified input process the "okay" behavior
// Hitting the "okay" button on the machine essentially causes it to behave as if you had
// hit the okay/resume in the dashboard UI. It is a convenience that prevents you from
// having to return to the dashboard just to confirm an action at the tool.
Machine.prototype.handleOkayButton = function (stat, auth_input) {
if (stat[auth_input] & 1) {
if (clickDisabled) {
log.info("Can't hit okay now");
return;
}
if (this.status.state === "paused" && canResume) {
log.info("Okay hit, resuming from pause");
this.resume(function (err, msg) {
if (err) {
log.error(err);
} else {
log.info(msg);
}
});
clickDisabled = true;
setTimeout(function () {
clickDisabled = false;
}, 2000);
} else if (this.status.state === "interlock") {
log.info("Okay hit, resuming from interlock");
this.resume(function (err, msg) {
if (err) {
log.error(err);
} else {
log.info(msg);
}
});
} else if (this.status.state === "lock") {
log.info("Okay hit, resuming from lock");
this.resume(function (err, msg) {
if (err) {
log.error(err);
} else {
log.info(msg);
}
});
}
}
};
Machine.prototype.handleCancelButton = function (stat, quit_input) {
if (stat[quit_input] & 1 && this.status.state === "paused" && canQuit) {
log.info("Cancel hit!");
this.quit(function (err, msg) {
if (err) {
log.error(err);
} else {
log.info(msg);
}
});
}
};
/*
* State Functions
*/
Machine.prototype.die = function (err_msg) {
this.setState(this, "dead", {
error: err_msg || "A G2 exception has occurred. You must reboot your tool.",
});
this.emit("status", this.status);
};
// This function restores the driver configuration to what is stored in the g2 configuration on disk
// It is typically used after, for instance, a running file has altered the configuration in memory.
// This is used to ensure that when the machine returns to idle the driver is in a "known" configuration
//Machine.prototype.restoreDriverState = async function (callback) {
Machine.prototype.restoreDriverState = function (callback) {
this.driver.setUnits(
config.machine.get("units"),
function () {
this.driver.requestStatusReport(
function (status) {
for (var key in this.status) {
if (key in status) {
this.status[key] = status[key];
}
}
config.driver.restore(function () {
if (callback) {
callback();
}
});
}.bind(this)
);
}.bind(this)
);
};
//This is a decision making function for the arm function. It tells arm the next action to fire.
//If machine object properties are influenced, they are stored in the result_arm_object and
//returned to the arm function along with the next action. if an error should be thrown the error
// is placed in the result_obj and the next action is set to 'throw'.
// Note parameters that are simply read and modified as part of the decision making are suffixed with "_in"
// parameters that are returned with new values to be used by the caller are suffixed with "_io"
function decideNextAction(
require_auth_in,
current_state_in,
driver_status_interlock_in,
interlock_required_io,
interlock_action_io,
driver_status_inFeedHold,
current_action_io,
bypass_in
) {
let result_arm_obj = {
interlock_required: null,
interlock_action: null,
current_action: null,
next_action: null,
error_thrown: null,
};
switch (current_state_in) {
case "idle":
result_arm_obj["interlock_action"] = current_action_io;
break;
case "limit":
if (driver_status_inFeedHold === true) {
// handle lock/interlock after software pause; in FeedHold
result_arm_obj["interlock_action"] = current_action_io;
} else {
result_arm_obj["current_action"] = interlock_action_io || current_action_io;
}
break;
case "lock":
case "interlock":
if (driver_status_inFeedHold === true) {
// handle lock/interlock after software pause; in FeedHold
result_arm_obj["interlock_action"] = current_action_io;
} else {
result_arm_obj["current_action"] = interlock_action_io || current_action_io;
}
break;
case "manual":
if (
current_action_io == null ||
(current_action_io.type == "runtimeCode" && current_action_io.payload.name == "manual")
) {
break;
}
result_arm_obj["error_thrown"] = new Error(
"Cannot arm machine for " + current_action_io.type + " from the manual state"
);
break;
case "paused":
case "stopped":
if (current_action_io.type === "resume" && driver_status_inFeedHold === false) {
require_auth_in = false;
} // Rules out Auth request on Timed Pause; no FeedHold
if (current_action_io.type != "resume") {
result_arm_obj["error_thrown"] = new Error(
"Cannot arm the machine for " + current_action_io.type + " when " + current_state_in
);
}
break;
default:
result_arm_obj["error_thrown"] = new Error(
"Cannot arm the machine from the " + current_state_in + " state."
);
break;
}
if ((current_action_io && current_action_io.payload && current_action_io.payload.name === "manual") || bypass_in) {
result_arm_obj["interlock_required"] = false;
}
// Record correct action to take, start with cases that abort action
if (result_arm_obj["error_thrown"]) {
result_arm_obj["next_action"] = "throw";
return result_arm_obj;
}
if (interlock_required_io && driver_status_interlock_in) {
result_arm_obj["next_action"] = "abort_due_to_interlock";
return result_arm_obj;
}
// Now we decide what the next action should be if we haven't already aborted for some reason
if (current_action_io && current_action_io.payload && current_action_io.payload.name === "manual") {
var cmd = current_action_io.payload.code.cmd;
if (cmd == "set" || cmd == "exit" || cmd == "start" || cmd == "fixed" || cmd == "stop" || cmd == "goto") {
result_arm_obj["next_action"] = "fire";
return result_arm_obj;
}
}
if (result_arm_obj["next_action"] == "abort_due_to_interlock") {
return result_arm_obj;
}
if (require_auth_in) {
result_arm_obj["next_action"] = "set_state_and_emit";
} else {
result_arm_obj["next_action"] = "fire";
}
return result_arm_obj;
}
//This function sets the timeout and records the state we were in before arming.
//That way we can fall back to it if the timer runs out.
function recordPriorStateAndSetTimer(thisMachine, armTimeout, status) {
if (thisMachine._armTimer) {
clearTimeout(thisMachine._armTimer);
}
thisMachine._armTimer = setTimeout(
function () {
log.info("Arm timeout (" + armTimeout + "s) expired.");
thisMachine.disarm();
}.bind(thisMachine),
armTimeout * 1000
);
// The info object contains any dialogs that are displayed in the dash.
delete thisMachine.status.info;
thisMachine.preArmedInfo = null;
// we may need to return to the prior state if the timer pops to disarm.
thisMachine.preArmedState = status;
}
// Before beginning or resuming any runtime action also check for "locking/interlocking" inputs that may be ACTIVE
// Locking/Interlocking Inputs are inputs defined as Stop(stop), FastStop(faststop), Interlock(interlock), or Limit(limit)
// These inputs are fucntionally similar as they produce a feedhold in G2 when effected, BUT they have different user displays and for LIMIT
// a different follow-on action -- so they are distinct for FabMo vs G2 (G2 has some similar functions we do not use because of conflicts)
// Input definitions are stored in machine.json and = "machine: di#ac" in the configuration tree
// ... but these input defs also need to be passed to G2 as current di#ac settings for feedhold (and variations)
// TABLE:
// interlock
// --state-- --action-- --locking?-- --message --G2 di#ac settings (digital input actions)
// - (none) - - 0
// stop - Stop YES Stop ON 1 [feedhold]
// faststop - FastStop YES Stop ON 2 [feedhold w/HiJerk] *not implemented in G2 yet ???
// interlock - Interlock YES Interlock ON 1 [feedhold]
// limit - Limit YES Limit Hit 1 [feedhold]
// hardstop - ImmediateStop NO - 3 [feedhold instant] *not implemented in G2 yet; to be used for OpenSBP "Interrupt"
// We check for interlock state before any action that ARMS tool for action and with any general change in state
function checkForInterlocks(thisMachine, action) {
let getInterlockState = "";
for (let pin = 1; pin < 13; pin++) {
let checkAssignedInput = config.machine.get("di" + pin + "ac");
// Check assignedInput for "none" in letters of any case; then set value to ""
if (checkAssignedInput) {
if (checkAssignedInput.toLowerCase() === "none") {
checkAssignedInput = "";
}
}
// If an "assigned" input pin is active, Set InterlockState to assigned action
// ... if more than one, highest priority will be assigned to InterlockState
// ... currently that is "stop" < "interlock" < "limit" ; This is where an INPUT gets LABELED
// Related: If an input assigned to an interlock function is then selected for Probing [P*] in the opensbp runtime
// - for the case of Limit, the interlock function will be disabled for the duration of the probing and
// ... in G2, feedholds are automatically overridden during probing
// ... in the Dashboard, for this case the Limit messages will not be displayed (managed in fabmoui.js)
// - for the case of Stop, Faststop or Interlock, the opensbp runtime should generate an error with explanation
if (checkAssignedInput) {
if (thisMachine.driver.status["in" + pin]) {
getInterlockState = checkAssignedInput;
}
}
}
// When overrideLimit true and starting in manual, clear interlock state to produce override; one time only
if (thisMachine.overrideLimit === true) {
if (action?.payload?.name) {
// if an action is defined
if (action.payload.name === "manual") {
getInterlockState = "";
if (action.payload.code === "exit") {
thisMachine.overrideLimit = false; // clear overrideLimit on exiting manual
}
}
}
}
return getInterlockState;
}
// "Arm" the machine with the specified action. The armed state is abandoned after the timeout expires.
// The "Interlocked" or "locked" status of an input is checked at start of this process
// action - The action to execute when fire() is called. Can be null.
// If null, the action will be to "authorize" the tool for subsequent actions for the authorization
// period which is specified in the settings.
// timeout - The number of seconds that the system should remain armed
Machine.prototype.arm = function (action, timeout) {
// It's a real finesse job to get authorize to play nice with interlock, etc. ...auth:R.Sturmer
var requireAuth = config.machine.get("auth_required");
var interlockRequired = true; // ... hard coded here; may need to manipulate at some point (no longer in configs)
let isInterlocked = checkForInterlocks(this, action); // check switches before arming
var nextAction = null;
let arm_obj = decideNextAction(
requireAuth,
this.status.state,
isInterlocked,
interlockRequired,
this.interlock_action,
this.status.inFeedHold,
action,
interlockBypass
);
// Implement side-effects that the result obj has returned so state is set correctly:
if (arm_obj["interlock_required"]) {
interlockRequired = arm_obj["interlock_required"];
}
if (arm_obj["interlock_action"]) {
this.interlock_action = arm_obj["interlock_action"];
}
if (arm_obj["current_action"]) {
action = arm_obj["current_action"];
}
if (arm_obj["next_action"]) {
nextAction = arm_obj["next_action"];
}
this.action = action;
log.info("ARMING the machine" + (action ? " for " + action.type : "(No action)"));
switch (nextAction) {
case "throw":
throw arm_obj["error_thrown"];
case "abort_due_to_interlock":
if (isInterlocked === "limit") {
this.setState(this, "limit");
} else if (isInterlocked === "interlock") {
this.setState(this, "interlock");
} else if (isInterlocked === "stop") {
this.setState(this, "lock");
}
return;
case "fire":
log.info("FIRING automatically since authorization is disabled.");
recordPriorStateAndSetTimer(this, timeout, this.status.state);
this.fire(true);
return;
case "set_state_and_emit":
recordPriorStateAndSetTimer(this, timeout, this.status.state);
this.setState(this, "armed");
this.emit("status", this.status);
return;
default:
throw new Error("Unknown case");
}
};
// Collapse out of the armed state. Happens when the user hits cancel in the authorize dialog.
Machine.prototype.disarm = function () {
if (this._armTimer) {
clearTimeout(this._armTimer);
}
this.action = null;
this.fireButtonDebounce = false;
};
// Execute the action in the chamber (the one passed to the arm() method)
Machine.prototype.fire = function (force) {
if (this.fireButtonDebounce & !force) {
log.debug("Fire button debounce reject.");
log.debug("debounce: " + this.fireButtonDebounce + " force: " + force);
return;
}
this.fireButtonDebounce = true;
// Clear the timers related to authorization
// (since we're either going to execute this thing or bounce, those will need to be reset)
if (this._armTimer) {
clearTimeout(this._armTimer);
}
if (this._authTimer) {
clearTimeout(this._authTimer);
}
if (this.status.state != "armed" && !force) {
throw new Error("Cannot fire: Not armed.");
}
// If no action, we're just authorizing for the next auth timeout
if (!this.action) {
this.authorize(config.machine.get("auth_timeout"));
this.setState(this, "idle");
return;
}
// We deauthorize the machine as soon as we're executing an action
// that way, when the action is concluded, the user has to reauthorize again.
// TODO - re-evaluate this decision. The idea here is that once an action is kicked off, once it's
// completed there's a good chance that the user might not be close to the machine anymore.
// many actions take less than the authorization timeout, though, so in those cases, this causes
// incessant authorization prompts.
this.deauthorize();
var action = this.action;
this.action = null;
// Actually execute the action (finally!)
switch (action.type) {
case "nextJob":
this._runNextJob(force, function () {});
break;
case "runtimeCode":
var name = action.payload.name;
var code = action.payload.code;
this._executeRuntimeCode(name, code);
break;
case "runFile":
var filename = action.payload.filename;
this._runFile(filename);
break;
case "resume":
this._resume(action.input);
break;
}
};
// Authorize the machine for the specified period of time (or the default time if unspecified)
Machine.prototype.authorize = function (timeout) {
timeout = timeout || config.machine.get("auth_timeout");
if (config.machine.get("auth_required") && timeout) {
log.info("Machine is authorized for the next " + timeout + " seconds.");
if (this._authTimer) {
clearTimeout(this._authTimer);
}
this._authTimer = setTimeout(
function () {
log.info("Authorization timeout (" + timeout + "s) expired.");
this.deauthorize();
}.bind(this),
timeout * 1000
);
} else {
if (!this.status.auth) {
log.info("Machine is authorized indefinitely.");
}
}
this.status.auth = true;
// Once authorized, clear info (which contains the auth message)
if (this.status.info && this.status.info.auth) {
delete this.status.info;
}
// Report status back to the host (since the auth state has changed)
this.emit("status", this.status);
};
// Clear the authorized state (forbid action without a reauthorize)
Machine.prototype.deauthorize = function () {
if (!config.machine.get("auth_timeout")) {
return;
}
if (this._authTimer) {
clearTimeout(this._authTimer);
}
log.info("Machine is deauthorized.");
this.status.auth = false;
};
Machine.prototype.isConnected = function () {
return this.status.state !== "not_ready" && this.status.state !== "dead";
};
Machine.prototype.disconnect = function (callback) {
this.driver.disconnect(callback);
};
Machine.prototype.toString = function () {
return "[Machine Model on '" + this.driver.path + "']";
};
// Run the provided Job object (see db.js)
Machine.prototype.runJob = function (job) {
db.File.getByID(
job.file_id,
function (err, file) {
if (err) {
// TODO deal with no file found
} else {
log.info("Running file " + file.path);
this.status.job = job;
this._runFile(file.path);
}
}.bind(this)
);
};
// Set the preferred units to the provided value ('in' or 'mm')
// Changing the preferred units is a heavy duty operation. See below.
Machine.prototype.setPreferredUnits = async function (units, lastunits, callback) {
let callbackCalled = false; // Flag to track if callback has been called
const safeCallback = (err) => {
if (!callbackCalled && callback) {
callbackCalled = true;
callback(err);
}
};
try {
// check to see whether the driver has a changeUnits argument that = null or undefined and if so, skip the change
if (lastunits !== units && config.driver.changeUnits) {
units = u.unitType(units); // Normalize units
var uv = null;
switch (units) {
case "in":
log.info("Changing default units to INCH");
uv = 0;
break;
case "mm":
log.info("Changing default units to MM");
uv = 1;
break;
default:
log.warn('Invalid units "' + units + '" found in machine configuration.');
break;
}
if (uv !== null) {
// Wrap asynchronous operations in a Promise to get updated G2 position dispaly at right time
await new Promise((resolve, reject) => {
config.driver.changeUnits(
uv,
function () {
log.info("Done setting driver units");
async.eachSeries(
this.runtimes,
function runtime_set_units(item, callback) {
log.info("Setting preferred units for " + item);
if (item.setPreferredUnits) {
return item.setPreferredUnits(uv, callback);
}
callback();
}.bind(this),
function (err) {
if (err) {
reject(err);
} else {
log.debug("All runtimes have set units.");
resolve();
}
}
);
}.bind(this)
);
});
// After all async operations complete, trigger the update
log.debug("Triggering machine position update after all configurations.");
this.driver.updateMachinePosition();
} else {
safeCallback(null);
}
} else {
safeCallback(null);
}
this.emit("status", this.status); // emit a status change
} catch (e) {
log.warn("Couldn't access driver configuration...");
log.error(e);
try {
this.driver.setUnits(uv);
} catch (e) {
safeCallback(e);
}
}
safeCallback(null);
};
// Retrieve the G-Code output for a specific file ID.
// If the file is a g-code file, just return its contents.
// If the file is a shopbot file, instantiate a SBPRuntime, run it in simulation, and return the result
Machine.prototype.getGCodeForFile = function (filename, callback) {
var ext = null;
fs.readFile(
filename,
"utf8",
function (err, data) {
if (err) {
log.error("Error reading file " + filename);
log.error(err);
return;
} else {
ext = path.extname(filename).toLowerCase();
if (ext == ".sbp") {
/*
if(this.status.state != 'idle') {
return callback(new Error('Cannot generate G-Code from OpenSBP while machine is running.'));
}*/
//this.setRuntime(null, function() {});
// Because preview is not a real runtime, we need to insert and track start points for SBP commands
var tx = this.driver.status.posx;
var ty = this.driver.status.posy;
var tz = this.driver.status.posz;
new SBPRuntime().simulateString(data, tx, ty, tz, callback);
} else {
fs.readFile(filename, callback);
}
}
}.bind(this)
);
};
// Run a file given a filename on disk. Choose the runtime that is appropriate for that file.
Machine.prototype._runFile = function (filename) {
var ext = path.extname(filename).toLowerCase();
// Choose the appropriate runtime based on the file extension
var runtime = this.gcode_runtime;
if (ext === ".sbp") {
runtime = this.sbp_runtime;