-
Notifications
You must be signed in to change notification settings - Fork 108
/
index.js
3950 lines (3519 loc) · 123 KB
/
index.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
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = '1';
process.on('uncaughtException', function(err) {
//showErrorDialog(err, attempts = 2) // make two attempts to show an uncaughtException in a dialog
if (DEBUG) {
debug_log(err)
} else {
console.log(err);
}
})
function showErrorDialog(err, attempts) {
console.error('Attempting to show an error dialog.')
if (!attempts) return;
try {
let options = {
type: 'error',
buttons: ['OK'],
title: 'Error',
message: `An error occured.`,
detail: `${err.message}\r\r\rIf you feel this shouldn't be happening, please report it at:\r\rhttps://github.com/OpenBuilds/OpenBuilds-CONTROL/issues`,
};
let window = BrowserWindow.getFocusedWindow()
dialog.showMessageBoxSync(window, options)
} catch (e) {
console.error(`An error occurred trying show an error, ho-boy. ${e}. We'll try again ${attempts} more time(s).`)
setTimeout(() => {
showErrorDialog(err, --attempts)
}, millisecondDelay = 2000);
}
}
// To see console.log output run with `DEBUGCONTROL=true electron .` or set environment variable for DEBUGCONTROL=true
// debug_log debug overhead
DEBUG = false;
if (process.env.DEBUGCONTROL) {
DEBUG = true;
console.log("Console Debugging Enabled")
}
function debug_log() {
if (DEBUG) {
console.log.apply(this, arguments);
}
} // end Debug Logger
debug_log("Starting OpenBuilds CONTROL v" + require('./package').version)
var config = {};
config.webPorts = [3000, 3020, 3200, 3220]
config.webPortIdx = 0;
config.nextWebPort = function() {
config.webPort = config.webPorts[config.webPortIdx]
config.webPortIdx++
if (config.webPortIdx == config.webPorts.length) {
throw new Error(`No ports were available to start the http server.\r\rWe tried ports ${config.webPorts.join(",")}.`);
}
return config.webPort;
}
config.webPort = process.env.WEB_PORT || config.nextWebPort();
config.posDecimals = process.env.DRO_DECIMALS || 3;
config.grblWaitTime = 0.5;
var express = require("express");
var app = express();
var http = require("http").Server(app);
var https = require('https');
//var ioServer = require('socket.io');
const {
Server: ioServer
} = require('socket.io');
var io = new ioServer();
var fs = require('fs');
var path = require("path");
const join = require('path').join;
const {
mkdirp
} = require('mkdirp')
//const drivelist = require('drivelist'); // removed in 1.0.350 due to Drivelist stability issues
// FluidNC test
var fluidncConfig = "";
// FluidNC end test
app.use(express.static(path.join(__dirname, "app")));
//app.use(express.limit('200M'));
app.use(function setCommonHeaders(req, res, next) {
res.set("Access-Control-Allow-Private-Network", "true");
next();
});
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Private-Network", "true");
next();
});
// Interface firmware flash
app.post('/uploadCustomFirmware', (req, res) => {
// 'firmwareBin' is the name of our file input field in the HTML form
let upload = multer({
storage: storage
}).single('firmwareBin');
upload(req, res, function(err) {
// req.file contains information of uploaded file
// req.body contains information of text fields, if there were any
if (err instanceof multer.MulterError) {
return res.send(err);
} else if (err) {
return res.send(err);
}
// Display uploaded image for user validation
firmwareImagePath = req.file.path;
res.send(req.file.path);
});
});
// end Interface Firmware flash
//Note when renewing Convert zerossl cert first `openssl.exe rsa -in domain-key.key -out domain-key.key`
// fix error: App threw an error during load
// Error: error:06000066:public key routines:OPENSSL_internal:DECODE_ERROR
var httpsOptions = {
key: fs.readFileSync(path.join(__dirname, 'privkey1.pem')),
cert: fs.readFileSync(path.join(__dirname, 'fullchain1.pem'))
};
const httpsserver = https.createServer(httpsOptions, app).listen(3001, function() {
debug_log('https: listening on:' + ip.address() + ":3001");
});
const httpserver = http.listen(config.webPort, '0.0.0.0', httpServerSuccess).on('error', httpServerError);
function httpServerSuccess() {
debug_log('http: listening on:' + ip.address() + ":" + config.webPort);
if (jogWindow) {
jogWindow.loadURL(`http://localhost:${config.webPort}/`);
}
}
function httpServerError(error) {
// If unable to start (port in use) - try next port in array from config.nextWebPort()
console.error(error.message);
httpserver.listen(config.nextWebPort());
}
io.attach(httpserver);
io.attach(httpsserver);
const grblStrings = require("./grblStrings.js");
// Serial
const {
SerialPort
} = require('serialport')
const {
ReadlineParser
} = require('@serialport/parser-readline')
// telnet
const net = require('net');
var ip = require("ip");
const Evilscan = require('evilscan');
var md5 = require('md5');
var _ = require('lodash');
var formidable = require('formidable')
var lastsentuploadprogress = 0;
// Electron app
const electron = require('electron');
const electronApp = electron.app;
electronApp.setAppUserModelId("openbuilds.control")
const {
dialog
} = require('electron')
electronApp.commandLine.appendSwitch('ignore-gpu-blacklist')
electronApp.commandLine.appendSwitch('enable-gpu-rasterization')
electronApp.commandLine.appendSwitch('enable-zero-copy')
if (isElectron()) {
debug_log("Local User Data: " + electronApp.getPath('userData'))
}
const BrowserWindow = electron.BrowserWindow;
const Tray = electron.Tray;
const nativeImage = require('electron').nativeImage
const Menu = require('electron').Menu
var forceQuit
var appIcon = null,
jogWindow = null,
mainWindow = null
var autoUpdater
var updateIsDownloading = false;
if (isElectron()) {
autoUpdater = require("electron-updater").autoUpdater
var availversion = '0.0.0'
autoUpdater.on('checking-for-update', () => {
var string = 'Starting update... Please wait';
var output = {
'command': 'autoupdate',
'response': string
}
io.sockets.emit('updatedata', output);
})
autoUpdater.on('update-available', (ev, info) => {
updateIsDownloading = true;
var string = "Starting Download: v" + ev.version;
availversion = ev.version
var output = {
'command': 'autoupdate',
'response': string
}
io.sockets.emit('updatedata', output);
debug_log(JSON.stringify(ev))
})
autoUpdater.on('update-not-available', (ev, info) => {
var string = 'Update not available. Installed version: ' + require('./package').version + " / Available version: " + ev.version + ".\n";
if (require('./package').version === ev.version) {
string += "You are already running the latest version!"
}
var output = {
'command': 'autoupdate',
'response': string
}
io.sockets.emit('updatedata', output);
debug_log(JSON.stringify(ev))
})
autoUpdater.on('error', (ev, err) => {
if (err) {
var string = 'Error in auto-updater: \n' + err.split('SyntaxError')[0];
} else {
var string = 'Error in auto-updater';
}
var output = {
'command': 'autoupdate',
'response': string
}
io.sockets.emit('updatedata', output);
})
autoUpdater.on('download-progress', (ev, progressObj) => {
updateIsDownloading = true;
var string = 'Download update ... ' + ev.percent.toFixed(1) + '%';
debug_log(string)
var output = {
'command': 'autoupdate',
'response': string
}
io.sockets.emit('updatedata', output);
io.sockets.emit('updateprogress', ev.percent.toFixed(0));
})
autoUpdater.on('update-downloaded', (info) => {
var string = "New update ready";
var output = {
'command': 'autoupdate',
'response': string
}
io.sockets.emit('updatedata', output);
io.sockets.emit('updateready', availversion);
// repeat every minute
setTimeout(function() {
io.sockets.emit('updateready', availversion);
}, 1000 * 60 * 60 * 8) // 8hrs before alerting again if it was snoozed
updateIsDownloading = false;
});
} else {
debug_log("Running outside Electron: Disabled AutoUpdater")
}
if (isElectron()) {
var uploadsDir = electronApp.getPath('userData') + '/upload/';
} else {
var uploadsDir = process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + 'Library/Preferences' : '/var/local')
}
var jobStartTime = false;
var jobCompletedMsg = ""; // message sent when job is done
var uploadedgcode = ""; // var to store uploaded gcode
var uploadedworkspace = ""; // var to store uploaded OpenBuildsCAM Workspace
mkdirp(uploadsDir).then(made =>
debug_log('Created Uploads Temp Directory'))
// Check USB Selective Suspend Settings
function checkPowerSettings() {
if (process.platform == 'win32') {
debug_log("Checking Power Settings")
var powerplan = "",
usbselectiveAC = false,
usbselectiveDC = false;
const {
exec
} = require('child_process');
const cfg = exec('powercfg /GETACTIVESCHEME', function(error, stdout, stderr) {
if (error) {
debug_log(error.stack);
debug_log('Error code: ' + error.code);
debug_log('Signal received: ' + error.signal);
}
// console.log('Child Process STDOUT: ' + stdout);
// console.log('Child Process STDERR: ' + stderr);
powerplan = stdout.split(":")[1].split("()")[0].trim()
});
cfg.on('exit', function(code) {
debug_log('powercfg /GETACTIVESCHEME exited with exit code ' + code);
if (code == 0) {
const usbsetting = exec('powercfg /q ' + powerplan, function(error, stdout, stderr) {
if (error) {
debug_log(error.stack);
debug_log('Error code: ' + error.code);
debug_log('Signal received: ' + error.signal);
}
// console.log('Child Process STDOUT: ' + stdout);
// console.log('Child Process STDERR: ' + stderr);
usbselective = (stdout.slice(stdout.search("USB selective suspend setting") - 1)).split("\n")
usbselective.length = 7;
if (usbselective[5].indexOf("0x00000000") != -1) {
debug_log("USB Selective Suspend DISABLED on AC power ")
status.driver.powersettings.usbselectiveAC = false;
} else if (usbselective[5].indexOf("0x00000001") != -1) {
debug_log("USB Selective Suspend ENABLED on AC power ")
status.driver.powersettings.usbselectiveAC = true;
}
if (usbselective[6].indexOf("0x00000000") != -1) {
debug_log("USB Selective Suspend DISABLED on DC power ")
status.driver.powersettings.usbselectiveDC = false;
} else if (usbselective[6].indexOf("0x00000001") != -1) {
debug_log("USB Selective Suspend ENABLED on DC power ")
status.driver.powersettings.usbselectiveDC = true;
}
});
usbsetting.on('exit', function(code) {
debug_log('powercfg /q exited with exit code ' + code);
setTimeout(function() {
debug_log(status.driver.powersettings.usbselectiveDC, status.driver.powersettings.usbselectiveAC)
}, 100);
})
}
});
// end USB Selective Suspend
}
}
var oldiplist;
var oldpinslist;
const iconPath = path.join(__dirname, 'app/icon.png');
const iconNoComm = path.join(__dirname, 'app/icon-notconnected.png');
const iconPlay = path.join(__dirname, 'app/icon-play.png');
const iconStop = path.join(__dirname, 'app/icon-stop.png');
const iconPause = path.join(__dirname, 'app/icon-pause.png');
const iconAlarm = path.join(__dirname, 'app/icon-bell.png');
var iosocket;
var lastCommand = false
var gcodeQueue = [];
var queuePointer = 0;
var statusLoop;
var frontEndUpdateLoop
var queueCounter;
var listPortsLoop;
var GRBL_RX_BUFFER_SIZE = 127; // 128 characters
var GRBLHAL_RX_BUFFER_SIZE = 1023; // 128 characters
var sentBuffer = [];
var xPos = 0.00;
var yPos = 0.00;
var zPos = 0.00;
var aPos = 0.00;
var xOffset = 0.00;
var yOffset = 0.00;
var zOffset = 0.00;
var aOffset = 0.00;
var feedOverride = 100,
spindleOverride = 100;
//regex to identify MD5hash on sdupload later
var re = new RegExp("^[a-f0-9]{32}");
var status = {
login: false,
driver: {
version: require('./package').version,
ipaddress: ip.address(),
operatingsystem: false,
powersettings: {
usbselectiveAC: null,
usbselectiveDC: null
},
},
machine: {
name: '',
has4thAxis: false,
inputs: [],
overrides: {
feedOverride: 100, //
spindleOverride: 100, //
realFeed: 0, //
realSpindle: 0 //
},
//
tool: {
nexttool: {
number: 0,
line: ""
}
},
modals: {
//motionmode: "G0", // G0, G1, G2, G3, G38.2, G38.3, G38.4, G38.5, G80
coordinatesys: "G54", // G54, G55, G56, G57, G58, G59
plane: "G17", // G17, G18, G19
distancemode: "G90", // G90, G91
arcdistmode: "G91.1", // G91.1
feedratemode: "G94", // G93, G94
unitsmode: "G21", // G20, G21
radiuscomp: "G40", // G40
tlomode: "G49", // G43.1, G49
// programmode: "M0", // M0, M1, M2, M30
spindlestate: "M5", // M3, M4, M5
coolantstate: "M9", // M7, M8, M9
homedRecently: false
// tool: "0",
// spindle: "0",
// feedrate: "0"
},
probe: {
x: 0.00,
y: 0.00,
z: 0.00,
state: -1
},
position: {
work: {
x: 0,
y: 0,
z: 0,
a: 0,
e: 0
},
offset: {
x: 0,
y: 0,
z: 0,
a: 0,
e: 0
}
},
firmware: {
type: "",
platform: "",
version: "",
date: "",
buffer: [],
features: [],
blockBufferSize: 0,
rxBufferSize: 0,
},
},
comms: {
connectionStatus: 0, //0 = not connected, 1 = opening, 2 = connected, 3 = playing, 4 = paused, 5 = alarm, 6 = firmware upgrade
runStatus: "Pending", // 0 = init, 1 = idle, 2 = alarm, 3 = stop, 4 = run, etc?
queue: 0,
blocked: false,
paused: false,
controllerBuffer: 0, // Seems like you are tracking available buffer? Maybe nice to have in frontend?
interfaces: {
type: "",
ports: "",
networkDevices: [],
activePort: "" // or activeIP in the case of wifi/telnet?
},
alarm: ""
},
interface: {
diskdrive: false,
firmware: {
availVersion: "",
installedVersion: "",
},
connected: false
}
};
async function findPorts() {
const ports = await SerialPort.list()
// console.log(ports)
status.comms.interfaces.ports = ports;
for (i = 0; i < status.comms.interfaces.ports.length; i++) {
var data = friendlyPort(status.comms.interfaces.ports[i])
status.comms.interfaces.ports[i].img = data.img;
status.comms.interfaces.ports[i].note = data.note;
}
}
findPorts()
// async function findDisks() {
// const drives = await drivelist.list();
// status.interface.diskdrives = drives;
// } // removed in 1.0.350 due to Drivelist stability issues
var PortCheckinterval = setInterval(function() {
if (status.comms.connectionStatus == 0) {
findPorts();
}
//findDisks(); // removed in 1.0.350 due to Drivelist stability issues
}, 1000);
// var telnetCheckinterval = setInterval(function() {
// if (status.comms.connectionStatus == 0) {
// scanForTelnetDevices();
// }
// }, 30000);
// scanForTelnetDevices();
checkPowerSettings()
// JSON API
app.get('/api/version', (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
data = {
"application": "OMD",
"version": require('./package').version,
"ipaddress": ip.address() + ":" + config.webPort
}
res.send(JSON.stringify(data), null, 2);
})
app.get('/activate', (req, res) => {
debug_log(req.hostname)
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.send('Host: ' + req.hostname + ' asked to activate OpenBuilds CONTROL v' + require('./package').version);
showJogWindow()
setTimeout(function() {
io.sockets.emit('activate', req.hostname);
}, 500);
})
// Upload
app.get('/upload', (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.sendFile(__dirname + '/app/upload.html');
})
app.get('/gcode', (req, res) => {
if (uploadedgcode.indexOf('$') != 0) { // Ignore grblSettings jobs
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.send(uploadedgcode);
}
})
app.get('/workspace', (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.send(uploadedworkspace);
})
// http-post version of runJob
app.post('/runjob', (req, res) => {
// 'firmwareBin' is the name of our file input field in the HTML form
let upload = multer({
storage: storage
}).single('file');
upload(req, res, function(err) {
// req.file contains information of uploaded file
// req.body contains information of text fields, if there were any
if (err instanceof multer.MulterError) {
return res.send(err);
} else if (err) {
return res.send(err);
}
fs.readFile(req.file.path, 'utf8', function(err, data) {
if (err) {
return console.log(err);
}
var object = {
isJob: true,
//completedMsg: "",
data: data,
}
runJob(object)
});
res.send(`Running ` + req.file.path);
});
});
// File Post
app.post('/upload', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//debug_log(req)
uploadprogress = 0
var form = new formidable.IncomingForm();
form.maxFileSize = 300 * 1024 * 1024;
form.parse(req, function(err, fields, files) {
// debug_log(files);
});
form.on('fileBegin', function(name, file) {
debug_log(JSON.stringify(name));
debug_log(JSON.stringify(file));
debug_log('Uploading ' + file.filepath);
});
form.on('progress', function(bytesReceived, bytesExpected) {
uploadprogress = parseInt(((bytesReceived * 100) / bytesExpected).toFixed(0));
if (uploadprogress != lastsentuploadprogress) {
lastsentuploadprogress = uploadprogress;
}
debug_log('Progress ' + uploadprogress + "% / " + bytesReceived + "b");
});
form.on('file', function(name, file) {
debug_log('Uploaded ' + file.filepath);
showJogWindow()
readFile(file.filepath)
});
form.on('aborted', function() {
// Emitted when the request was aborted by the user. Right now this can be due to a 'timeout' or 'close' event on the socket. After this event is emitted, an error event will follow. In the future there will be a separate 'timeout' event (needs a change in the node core).
});
form.on('end', function() {
//Emitted when the entire request has been received, and all contained files have finished flushing to disk. This is a great place for you to send your response.
res.end();
});
res.sendFile(__dirname + '/app/upload.html');
});
app.on('certificate-error', function(event, webContents, url, error,
certificate, callback) {
event.preventDefault();
callback(true);
});
io.on("connection", function(socket) {
debug_log("New IO Connection ");
iosocket = socket;
if (status.machine.firmware.type == 'grbl') {
debug_log("Is Grbl");
// // handle Grbl RESET external input
// if (status.machine.inputs.length > 0) {
// for (i = 0; i < status.machine.inputs.length; i++) {
// switch (status.machine.inputs[i]) {
// case 'R':
// // debug_log('PIN: SOFTRESET');
// safetosend = true;
// break;
// }
// }
// } else {
// setTimeout(function() {
debug_log("Emit Grbl: 1");
io.sockets.emit('grbl', status.machine.firmware)
// }, 10000);
// }
//
// if (safetosend != undefined && safetosend == true) {
// setTimeout(function() {
// debug_log("Emit Grbl: 2");
// io.sockets.emit('grbl', status.machine.firmware)
// }, 10000);
// }
}
// Global Update loop
clearInterval(frontEndUpdateLoop);
frontEndUpdateLoop = setInterval(function() {
io.sockets.emit("status", status);
}, 100);
socket.on("scannetwork", function(data) {
scanForTelnetDevices(data)
})
socket.on("openFile", function(data) {
dialog.showOpenDialog(jogWindow, {
properties: ['openFile']
}).then(result => {
console.log(result.canceled)
console.log(result.filePaths)
var openFilePath = result.filePaths[0];
if (openFilePath !== "") {
debug_log("path" + openFilePath);
readFile(openFilePath);
}
}).catch(err => {
console.log(err)
})
})
socket.on("openInterfaceDir", function(data) {
dialog.showOpenDialog(jogWindow, {
properties: ['openDirectory'],
title: "Select the USB Flashdrive you want to use with Interface"
}).then(result => {
console.log(result.canceled)
console.log(result.filePaths)
io.sockets.emit("interfaceDrive", result.filePaths[0]);
status.interface.diskdrive = result.filePaths[0]
}).catch(err => {
console.log(err)
})
})
socket.on("openbuilds", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://www.openbuilds.com')
});
socket.on("openbuildspartstore", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://www.openbuildspartstore.com')
});
socket.on("carveco", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://carveco.com/carveco-software-range/?ref=openbuilds')
});
socket.on("fabber", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://www.getfabber.com/openbuilds?ref=OpenBuilds')
});
socket.on("lightburn", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://openbuildspartstore.com/lightburn/')
});
socket.on("vectric", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://openbuildspartstore.com/vectric/')
});
socket.on("opencam", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://cam.openbuilds.com')
});
socket.on("opendocs", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://docs.openbuilds.com/')
});
socket.on("openforum", function(data) {
const {
shell
} = require('electron')
shell.openExternal('https://openbuilds.com/threads/openbuilds-control-software.13121/')
});
socket.on("gpuinfo", function(data) {
// GPU
var gpuInfoWindow = new BrowserWindow({
// 1366 * 768 == minimum to cater for
width: 800,
height: 800,
fullscreen: false,
center: true,
resizable: true,
maximizable: true,
title: "OpenBuilds CONTROL: Chromium's GPU Report",
frame: true,
autoHideMenuBar: true,
//icon: '/app/favicon.png',
icon: nativeImage.createFromPath(
path.join(__dirname, "/app/favicon.png")
),
webgl: true,
experimentalFeatures: true,
experimentalCanvasFeatures: true,
offscreen: true,
backgroundColor: "#fff"
});
gpuInfoWindow.loadURL("chrome://gpu");
gpuInfoWindow.once('ready-to-show', () => {
gpuInfoWindow.show()
gpuInfoWindow.setAlwaysOnTop(true);
gpuInfoWindow.focus();
gpuInfoWindow.setAlwaysOnTop(false);
})
});
socket.on("minimisetotray", function(data) {
jogWindow.hide();
});
socket.on("minimize", function(data) {
jogWindow.minimize();
});
socket.on("maximize", function(data) {
if (jogWindow.isFullScreen()) {
jogWindow.setFullScreen(false);
}
if (jogWindow.isMaximized()) {
jogWindow.unmaximize();
} else {
jogWindow.maximize();
}
});
socket.on("fullscreen", function(data) {
if (jogWindow.isFullScreen()) {
jogWindow.setFullScreen(false);
} else {
jogWindow.setFullScreen(true);
}
});
socket.on("quit", function(data) {
if (appIcon) {
appIcon.destroy();
}
electronApp.exit(0);
});
socket.on("applyUpdate", function(data) {
autoUpdater.quitAndInstall();
})
socket.on("downloadUpdate", function(data) {
if (!updateIsDownloading) {
if (typeof autoUpdater !== 'undefined') {
autoUpdater.checkForUpdates();
} else {
debug_log("autoUpdater not found")
}
}
})
socket.on("flashGrbl", function(data) {
var port = data.port;
var firmwareImagePath = data.file;
var customImg = data.customImg
console.log(__dirname, file, data.file)
if (customImg) {
var firmwarePath = data.file
} else {
var firmwarePath = path.join(__dirname, data.file)
}
console.log("-------------------------------------------")
console.log(firmwarePath)
console.log("-------------------------------------------")
if (status.comms.connectionStatus > 0) {
debug_log('WARN: Closing Port ' + port);
stopPort();
} else {
debug_log('ERROR: Machine connection not open!');
}
function flashGrblCallback(debugString, port) {
debug_log(port, debugString);
var data = {
'port': port,
'string': debugString
}
io.sockets.emit("progStatus", data);
}
// setTimeout(function() {
// var avrgirl = new Avrgirl({
// board: board,
// port: port,
// debug: function(debugString) {
// var port = this.connection.options.port;
// flashGrblCallback(debugString, port)
// }
// });
//
// debug_log(JSON.stringify(avrgirl));
//
// status.comms.connectionStatus = 6;
// avrgirl.flash(firmwarePath, function(error) {
// if (error) {
// console.error(error);
// io.sockets.emit("progStatus", 'Flashing FAILED!');
// status.comms.connectionStatus = 0;
// } else {
// console.info('done.');
// io.sockets.emit("progStatus", 'Programmed Succesfully');
// io.sockets.emit("progStatus", 'Please Reconnect');
// status.comms.connectionStatus = 0;
// }
// status.comms.connectionStatus = 0;
// });
// }, 1000)
})
socket.on("flashGrblHal", function(data) {
if (status.comms.connectionStatus > 0) {
debug_log('WARN: Closing Port ' + port);
stopPort();
} else {
debug_log('ERROR: Machine connection not open!');
}
console.log(JSON.stringify(data), null, 4);
flashGrblHal(data)
})
socket.on("flashInterface", function(data) {
if (status.comms.connectionStatus > 0) {
debug_log('WARN: Closing Port ' + port);
stopPort();
} else {
debug_log('ERROR: Machine connection not open!');
}
flashInterface(data)
})
socket.on("flashBLOX", function(data) {
if (status.comms.connectionStatus > 0) {
debug_log('WARN: Closing Port ' + port);
stopPort();
} else {
debug_log('ERROR: Machine connection not open!');
}
flashBLOX(data)
})
socket.on("writeInterfaceUsbDrive", function(data) {
debug_log(data)
//data.drive = mountpoint dest
//data.controller = type of controller
if (data.controller == "blackbox4x" || data.controller == "genericgrbl") {