forked from FabMo/FabMo-Engine
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmachine.js
730 lines (649 loc) · 18 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
var g2 = require('./g2');
var util = require('util');
var events = require('events');
var PLATFORM = require('process').platform;
var assert = require('assert');
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 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;
function connect(callback) {
switch(PLATFORM) {
case 'linux':
control_path = config.engine.get('control_port_linux');
gcode_path = config.engine.get('data_port_linux');
break;
case 'darwin':
control_path = config.engine.get('control_port_osx');
gcode_path = config.engine.get('data_port_osx');
break;
case 'win32':
case 'win64':
control_path = config.engine.get('control_port_windows');
gcode_path = config.engine.get('data_port_windows');
break;
default:
control_path = null;
gcode_path = null;
break;
}
if(control_path) {
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.fireButtonDebounce = false;
this.APCollapseTimer = null;
// Instantiate driver and connect to G2
this.status = {
state : "not_ready",
posx : 0.0,
posy : 0.0,
posz : 0.0,
in1 : 1,
in2 : 1,
in3 : 1,
in4 : 1,
in5 : 1,
in6 : 1,
in7 : 1,
in8 : 1,
out1 :0,
out2 :0,
out3 :0,
out4 :0,
out5 :0,
out6 :0,
out7 :0,
out8 :0,
job : null,
info : null,
unit : 'mm',
line : null,
nb_lines : null,
auth : false
};
this.info_id = 0;
this.driver = new g2.G2();
this.driver.on("error", function(err) {log.error(err);});
this.driver.connect(control_path, function(err, data) {
// Set the initial state based on whether or not we got a valid connection to G2
if(err){
log.error(JSON.stringify(err));
log.warn("Setting the disconnected state");
this.die("A real bad error has occurred.")
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
]
// Idle
this.setRuntime(null, function() {
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));
config.driver.on('change', function(update) {
['x','y','z','a','b'].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.');
this.status[pos] = 0;
}
}
}.bind(this));
}.bind(this));
this.driver.on('status', function(stat) {
this.handleFireButton(stat);
this.handleAPCollapseButton(stat);
this.handleOkayButton(stat);
this.handleCancelButton(stat);
}.bind(this));
}
util.inherits(Machine, events.EventEmitter);
Machine.prototype.handleAPCollapseButton = function(stat) {
var n = config.machine.get('ap_input');
if(n == 0) { return; }
var ap_input = 'in' + n;
// If the button has been pressed
if(stat[ap_input]) {
var ap_collapse_time = config.machine.get('ap_time');
// For the first time
if(!this.APCollapseTimer) {
// Do an AP collapse in 10 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;
}
}
}
Machine.prototype.handleFireButton = function(stat) {
var auth_input = 'in' + config.machine.get('auth_input');
if(stat[auth_input] && this.status.state === 'armed') {
log.info("Fire button hit!")
this.fire();
}
}
Machine.prototype.handleOkayButton = function(stat){
var auth_input = 'in' + config.machine.get('auth_input');
if(stat[auth_input] && this.status.state === 'paused') {
log.info("Okay hit!")
this.resume();
}
}
Machine.prototype.handleCancelButton = function(stat){
var quit_input = 'in' + config.machine.get('quit_input');
if(stat[quit_input] && this.status.state === 'paused') {
log.info("Cancel hit!")
this.quit();
}
}
/*
* 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);
}
Machine.prototype.restoreDriverState = function(callback) {
callback = callback || function() {};
this.driver.setUnits(config.machine.get('units'), function() {
config.driver.restore(callback);
}.bind(this));
}
Machine.prototype.arm = function(action, timeout) {
switch(this.status.state) {
case 'idle':
break;
case 'paused':
case 'stopped':
if(action.type != 'resume') {
throw new Error('Cannot arm the machine for ' + action.type + ' when ' + this.status.state);
}
break;
default:
throw new Error("Cannot arm the machine from the " + this.status.state + " state.");
break;
}
delete this.status.info
this.action = action;
log.info("Arming the machine" + (action ? (' for ' + action.type) : '(No action)'));
//log.error(new Error())
if(this._armTimer) { clearTimeout(this._armTimer);}
this._armTimer = setTimeout(function() {
log.info('Arm timeout (' + timeout + 's) expired.');
this.disarm();
}.bind(this), timeout*1000);
this.preArmedState = this.status.state;
this.preArmedInfo = this.status.info;
var requireAuth = config.machine.get('auth_required');
if(!requireAuth) {
log.info("Firing automatically since authorization is disabled.");
this.fire(true);
} else {
this.setState(this, 'armed');
this.emit('status', this.status);
}
}
Machine.prototype.disarm = function() {
if(this._armTimer) { clearTimeout(this._armTimer);}
this.action = null;
this.fireButtonDebounce = false;
if(this.status.state === 'armed') {
this.setState(this, this.preArmedState || 'idle', this.preArmedInfo);
}
}
Machine.prototype.fire = function(force) {
if(this.fireButtonDebounce & !force) {
log.debug("Fire button debounce reject.");
return;
}
this.fireButtonDebounce = true;
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;
}
this.deauthorize();
var action = this.action;
this.action = null;
switch(action.type) {
case 'nextJob':
log.debug("Firing a nextJob")
this._runNextJob(force, function() {});
break;
case 'runtimeCode':
log.debug("Firing a runtimeCode")
var name = action.payload.name
var code = action.payload.code
this._executeRuntimeCode(name, code);
break;
case 'runFile':
log.debug("Firing a runFile")
var filename = action.payload.filename
this._runFile(filename);
break;
case 'resume':
log.debug("Firing a resume")
this._resume();
break;
}
}
Machine.prototype.authorize = function(timeout) {
var timeout = timeout || config.machine.get('auth_timeout');
if(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;
//this.setState(this, 'idle');
if(this.status.info && this.status.info.auth) {
delete this.status.info;
}
this.emit('status', this.status);
}
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;
this.emit('status', this.status);
}
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 + "']";
};
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));
};
Machine.prototype.setPreferredUnits = function(units, callback) {
try {
if(config.driver.changeUnits) {
units = u.unitType(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 "' + gc + '"found in machine configuration.');
break;
}
if(uv !== null) {
// Change units on the driver
config.driver.changeUnits(uv, function(err, data) {
log.info("Done setting driver units")
// Change units on each runtime in turn
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), callback);
}.bind(this));
}
} else {
return callback(null);
}
}
catch (e) {
log.warn("Couldn't access driver configuration...");
log.error(e)
try {
this.driver.setUnits(uv);
} catch(e) {
callback(e);
}
}
}
Machine.prototype.getGCodeForFile = function(filename, callback) {
fs.readFile(filename, 'utf8', function (err,data) {
if (err) {
log.error('Error reading file ' + filename);
log.error(err);
return;
} else {
parts = filename.split(path.sep);
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() {});
this.sbp_runtime.simulateString(data, callback);
} else {
fs.readFile(filename, callback);
}
}
}.bind(this));
}
Machine.prototype._runFile = function(filename) {
var parts = filename.split(path.sep);
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;
}
// Set the appropriate runtime
this.setRuntime(runtime, function(err, runtime) {
if(err) {
return log.error(err);
}
runtime.runFile(filename);
});
};
Machine.prototype.setRuntime = function(runtime, callback) {
try {
if(runtime) {
if(this.current_runtime != runtime) {
if(this.current_runtime) {
this.current_runtime.disconnect();
}
runtime.connect(this);
this.current_runtime = runtime;
}
} else {
this.current_runtime = this.idle_runtime;
this.current_runtime.connect(this);
}
} catch(e) {
log.error(e)
setImmediate(callback, e);
}
setImmediate(callback,null, runtime);
};
Machine.prototype.getRuntime = function(name) {
switch(name) {
case 'gcode':
case 'nc':
case 'g':
return this.gcode_runtime;
break;
case 'opensbp':
case 'sbp':
return this.sbp_runtime;
break;
case 'manual':
return this.manual_runtime;
break;
default:
return null;
break;
}
}
Machine.prototype.setState = function(source, newstate, stateinfo) {
this.fireButtonDebounce = false ;
if ((source === this) || (source === this.current_runtime)) {
log.info("Got a machine state change: " + newstate)
if(stateinfo) {
this.status.info = stateinfo
this.info_id += 1;
this.status.info.id = this.info_id;
} else {
delete this.status.info
}
switch(newstate) {
case 'idle':
if(this.status.state != 'idle') {
//this.driver.command({"out4":0});
//if(this.runtime != this.idle_runtime) {
// this.setRuntime(null, function() {});
//}
}
this.status.nb_lines = null;
this.status.line = null;
if(this.action) {
switch(this.action.type) {
case 'nextJob':
break;
default:
this.authorize();
break;
}
}
this.action = null;
// Deliberately fall through
case 'paused':
if(this.status.state != newstate) {
this.driver.get('mpo', function(err, mpo) {
if(config.instance) {
config.instance.update({'position' : mpo});
}
});
}
break;
case 'dead':
log.error('G2 is dead!');
break;
default:
//this.driver.command({"out4":1});
break;
}
this.status.state = newstate;
} else {
log.warn("Got a state change from a runtime that's not the current one. (" + source + ")")
}
this.emit('status',this.status);
};
Machine.prototype.pause = function() {
if(this.status.state === "running") {
if(this.current_runtime) {
this.current_runtime.pause();
}
}
};
Machine.prototype.quit = function() {
this.disarm();
// Quitting from the idle state dismisses the 'info' data
if(this.status.state === "idle") {
delete this.status.info;
this.emit('status', this.status);
}
// Cancel the currently running job, if there is one
if(this.status.job) {
this.status.job.pending_cancel = true;
}
if(this.current_runtime) {
log.info("Quitting the current runtime...")
this.current_runtime.quit();
} else {
log.warn("No current runtime!")
}
};
Machine.prototype.resume = function() {
this.arm({
type : 'resume'
}, config.machine.get('auth_timeout'));
}
Machine.prototype.runFile = function(filename) {
this.arm({
type : 'runFile',
payload : {
filename : filename
}
}, config.machine.get('auth_timeout'));
}
Machine.prototype.runNextJob = function(callback) {
db.Job.getPending(function(err, pendingJobs) {
if(err) {
return callback(err);
}
if(pendingJobs.length > 0) {
this.arm({
type : 'nextJob'
}, config.machine.get('auth_timeout'));
callback();
} else {
callback(new Error('No pending jobs.'));
}
}.bind(this));
}
Machine.prototype.executeRuntimeCode = function(runtimeName, code) {
runtime = this.getRuntime(runtimeName);
var needsAuth = runtime.needsAuth(code);
if (needsAuth){
if(this.status.auth) {
return this._executeRuntimeCode(runtimeName, code);
}
if(runtimeName === 'manual') {
this.arm(null, config.machine.get('auth_timeout'));
return;
} else {
this.arm({
type : 'runtimeCode',
payload : {
name : runtimeName,
code : code
}
}, config.machine.get('auth_timeout'));
}
} else {
this._executeRuntimeCode(runtimeName, code);
}
}
Machine.prototype.sbp = function(string) {
this.executeRuntimeCode('sbp', string);
}
Machine.prototype.gcode = function(string) {
this.executeRuntimeCode('gcode', string);
}
/*
* Functions below require authorization to run
* Don't call them unless the tool is authorized!
*/
Machine.prototype._executeRuntimeCode = function(runtimeName, code, callback) {
runtime = this.getRuntime(runtimeName);
if(runtime) {
this.setRuntime(runtime, function(err, runtime) {
if(err) {
log.error(err);
} else {
runtime.executeCode(code);
}
}.bind(this));
}
}
Machine.prototype._resume = function() {
if(this.current_runtime) {
this.current_runtime.resume();
}
};
Machine.prototype._runNextJob = function(force, callback) {
if(this.isConnected()) {
if(this.status.state === 'armed' || force) {
log.info("Running next job");
db.Job.dequeue(function(err, result) {
log.info(result);
if(err) {
log.error(err);
callback(err, null);
} else {
log.info('Running job ' + JSON.stringify(result));
this.runJob(result);
callback(null, result);
}
}.bind(this));
} else {
callback(new Error("Cannot run next job: Machine not idle"));
}
} else {
callback(new Error("Cannot run next job: Driver is disconnected."));
}
};
exports.connect = connect;