-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1067 lines (864 loc) · 31.8 KB
/
index.js
File metadata and controls
1067 lines (864 loc) · 31.8 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
import mqtt from 'mqtt';
import _ from 'lodash';
import moment from 'moment';
import http from 'http';
import { Client as FTPClient } from "basic-ftp";
import { promises as fs } from 'fs';
import { Server as SocketServer } from 'socket.io';
import path from 'path';
import { Worker } from 'worker_threads';
import Config from './config.js';
import { time_to_minutes, is_empty } from './utils.js';
import os from 'os'
import { spawn } from 'child_process'
import BitlairBank from './ssh.js';
import OneWire from './onewire.js';
import NetcatClient from 'netcat/client.js';
// disable self cert
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const CLIENT_ID = 'nodejs-client-' + Math.random().toString(16).substr(2, 8);
const TIME_BETWEEN_COMMANDS_MS = 100;
const BITLAIR_BANK = new BitlairBank();
const IBUTTON_READER = new OneWire();
const USE_DUMMY_DATA = false;
const PROCESSING_TIMEOUT_SECONDS = 300; // 5 min
const LAST_PAID_ITEMS_CACHE_FILE = __dirname + '/printer_paid_cache.json';
console.log("Starting", isWithinDjoTime() ? " DJO tijd" : "bitlair tijd");
const PRINTERS = _.cloneDeep(Config.PRINTERS);
// lets keep track of the amount of workers
let activeWorkers = 0;
const serveStaticFile = (filePath, res) => {
fs.readFile(filePath)
.then((data) => {
const ext = path.extname(filePath);
let contentType = 'text/plain';
if (ext === '.html') contentType = 'text/html';
else if (ext === '.js') contentType = 'application/javascript';
else if (ext === '.css') contentType = 'text/css';
else if (ext === '.jpg' || ext === '.jpeg') contentType = 'image/jpeg';
else if (ext === '.png') contentType = 'image/png';
else if (ext === '.gif') contentType = 'image/gif';
res.setHeader('Content-Type', contentType);
res.end(data);
})
.catch((err) => {
console.error('Error reading file:', err); // Log the error
res.statusCode = 404;
res.end('File not found');
});
};
const http_server = http.createServer(function (req, res) {
// Enable CORS for all origins (or restrict to your frontend URL)
res.setHeader('Access-Control-Allow-Origin', '*'); // or 'http://192.168.2.34:3000'
res.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
// Handle preflight request
if (req.method === 'OPTIONS') {
res.writeHead(204);
res.end();
return;
}
// Normalize the request URL
const requestPath = req.url === '/' ? '/index.html' : req.url;
let filePath;
if (requestPath.endsWith('.3mf')) {
// Serve 3MF files from ../Print-manager/
const fileName = path.basename(requestPath); // extract just the filename
filePath = path.join(__dirname, '..', 'Print-manager', fileName);
} else {
// Serve other files from public folder
filePath = path.join(__dirname, 'public', requestPath);
}
// Serve the requested file (or 404 if it doesn't exist)
serveStaticFile(filePath, res);
});//.listen(8080); //the server object listens on port 8080
const io = new SocketServer(http_server, {
cors: {
origin: '*', // React dev server
methods: ['GET', 'POST']
}
});
/*
last_authenticated_user = {id: 0, username: 'DJO'};
socket.emit('user authenticated', 'DJO');
*/
let socket_selected_printer_serials = {};
let last_authenticated_user = undefined;
let last_ibutton_information = undefined; // persistant version of last_authenticated_user
let last_paid_items = [];
fs.readFile(LAST_PAID_ITEMS_CACHE_FILE).then((content) => {
last_paid_items = JSON.parse(content);
}).catch((error) => {
// bestand bestaat niet
console.log('cache error?', error);
});
io.on('connection', socket => {
console.log('a user connected:', socket.id);
socket_selected_printer_serials[socket.id] = undefined;
IBUTTON_READER.event.on('device-found', (device_id) => {
if(isWithinDjoTime())
{
last_authenticated_user = {id: device_id, username: 'DJO'};
last_ibutton_information = {id: device_id, username: 'DJO'};
socket.emit('user authenticated', 'DJO');
}
else
{
// netcat client for the ibutton to revbank account conversion
const netcat_client = new NetcatClient();
let netcat_response = '';
// reset the last user, we might be getting a new one
last_authenticated_user = undefined;
netcat_client.addr(Config.BITLAIR_SERVICE_URL).port(Config.BITLAIR_SERVICE_PORT).connect().on('data', (data) => {
netcat_response += data.toString();
// usually second package
if (netcat_response.includes('revbank:'))
{
console.log('SERVER RESPONSE:', netcat_response);
const response_parts = netcat_response.split('revbank:');
// when a username is present
if(_.size(response_parts) > 1 && !_.isEmpty(response_parts[1]))
{
const username = response_parts[1].trim();
last_authenticated_user = {id: device_id, username: username};
last_ibutton_information = {id: device_id, username: username};
socket.emit('user authenticated', username);
}
else
{
last_ibutton_information = {id: device_id, username: 'Onbekend'};
socket.emit('user authenticated', '-1');
}
netcat_client.removeAllListeners('data');
netcat_client.end?.();
netcat_client.destroy?.();
}
else if(netcat_response.includes('FAIL'))
{
console.log('authentication failed! ', device_id);
netcat_client.removeAllListeners('data');
netcat_client.end?.();
netcat_client.destroy?.();
last_ibutton_information = {id: device_id, username: 'Onbekend'};
socket.emit('user authenticated', '-1');
}
}).send('id-only ' + device_id + '\n', (event_data) => {
console.log('sending data: ', event_data);
});
}
});
socket.on('message', data => {
console.log('Message received:', data);
// socket.broadcast.emit('message', data);
});
socket.on('select printer', (printer_serial) => {
socket_selected_printer_serials[socket.id] = printer_serial;
});
socket.on('deselect printer', () => {
if(socket_selected_printer_serials[socket.id])
{
socket_selected_printer_serials[socket.id] = undefined;
console.log('socket deselect printer', last_authenticated_user);
// resetten regardless so someone can't abuse it
last_authenticated_user = undefined;
}
});
socket.on('accept print', (auto_payment) => {
console.log('socket: accept print', auto_payment, last_authenticated_user, socket_selected_printer_serials[socket.id]);
// no authenticated user found or selected printer for this socket, why is it even sending this event?
if(is_empty(last_authenticated_user) || is_empty(socket_selected_printer_serials[socket.id]))
return;
const printer = _.find(PRINTERS, printer => printer.serial == socket_selected_printer_serials[socket.id]);
if(printer && printer.last_print)
{
printer.last_accepted_md5 = printer.last_print.md5;
printer.last_accepted_by_user = last_authenticated_user;
printer.auto_payment = auto_payment || false;
// resetten, they performed the action they authenticated for
last_authenticated_user = undefined;
if(isWithinDjoTime)
sendResumeCommand(printer.mqtt_client, printer.serial);
updateClientPrinterData();
}
});
// push latest info to the new client
updateClientPrinterData(socket);
socket.emit('update djo time minutes', Config.DJO_TIME_MINUTES);
socket.on('disconnect', () => {
console.log('user disconnected:', socket.id);
delete socket_selected_printer_serials[socket.id];
});
socket.on('get settings', () => {
socket.emit('settings', {
ip_addresses: getIPAddresses(),
root_active: process.geteuid && process.geteuid() === 0,
djo_time_blocks: Config.DJO_TIME_MINUTES,
last_paid_items: last_paid_items,
last_ibutton_information: last_ibutton_information,
});
});
// only allow the machine itself to restart and shutdown itself
if(socket.handshake.address == '127.0.0.1')
{
socket.on('shutdown', () => {
spawn('shutdown', ['-h', 'now'], {
detached: true,
stdio: 'ignore'
}).unref()
});
socket.on('restart', () => {
spawn('shutdown', ['-r', 'now'], {
detached: true,
stdio: 'ignore'
}).unref()
});
}
socket.on('debug', () => {
last_ibutton_information = {id: '3315FC29050000B2', username: 'DJO'};
})
});
http_server.listen(4000, '0.0.0.0', () => {
console.log('Listening on all interfaces at port 4000');
});
function getIPAddresses() {
const interfaces = os.networkInterfaces()
const addresses = []
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
// Skip internal (127.0.0.1) and non-IPv4 addresses
if (iface.family === 'IPv4' && !iface.internal) {
addresses.push(iface.address)
}
}
}
return addresses
}
let new_printed_object_timeout = undefined;
/*
printed_object = {
printer_index: 0,
weight: 0,
username: "revbank username",
ibutton_id: "331234567890",
filename: "test_file_something.3mf.gcode",
}
*/
function addNewPrintedObject(printed_object)
{
last_paid_items.push(printed_object);
// het scherm kan niet meer tonen dan 10 anyway
if(_.size(last_paid_items) > 10)
last_paid_items = _.takeRight(last_paid_items, 10);
if(new_printed_object_timeout)
clearTimeout(new_printed_object_timeout);
// 5 seconde wachten tot hij echt gaat wegschrijven, voor het geval dat er 2 tegelijk klaar zijn
new_printed_object_timeout = setTimeout(() => {
new_printed_object_timeout = undefined;
fs.writeFile(LAST_PAID_ITEMS_CACHE_FILE, JSON.stringify(last_paid_items)).catch((error) => {
console.log('error saving ' + LAST_PAID_ITEMS_CACHE_FILE, error);
});
}, 5000)
}
function getFtpClient(printer)
{
try {
// ftp_client.ftp.verbose = true;
const ftp_client = new FTPClient();
const access_response = ftp_client.access({
host: printer.ip,
port: 990,
user: printer.username,
password: printer.password,
secure: 'implicit',
}).catch(err =>
console.log('Caught async FTP error:', err.message)
);
return new Promise((resolve, reject) => {
access_response.then(() => {
resolve(ftp_client);
})
});
}
catch(exception)
{
console.log('FTP failed for printer ', printer.title, ' with exception ', exception);
}
}
_.each(PRINTERS, (printer, printer_index) => {
let total_payload = {};
let initialized = false;
let refresh_requested = false;
let processing_new_print_timeout = undefined;
let last_loaded_md5 = undefined;
printer.processing_new_print = false;
printer.last_accepted_md5 = undefined;
// MQTT connection options for Bambu printer
const options = {
clientId: CLIENT_ID,
username: printer.username,
password: printer.password,
protocol: 'mqtts',
rejectUnauthorized: false // Accept self-signed certs (for dev only)
};
const slowedUpdateClientPrinterData = _.throttle(updateClientPrinterData, 2000);
if(USE_DUMMY_DATA)
{
if(!printer.gcode_information)
readPrinterFile('./latest_print_' + printer_index + '.gcode.3mf').then((data) => {
printer.gcode_information = data;
printer.gcode_information.last_file = "test";
printer.last_print = {title: data.filename};
slowedUpdateClientPrinterData();
});
printer.last_print = {title: 'test.png'}
printer.state = 'RUNNING';
}
try {
// Connect to the printer's MQTT broker
printer.mqtt_client = mqtt.connect(`mqtts://${printer.ip}:8883`, options);
printer.mqtt_client.on('connect', () => {
console.log('✅ Connected to printer MQTT!');
printer.state = "IDLE"; // initial state
const topic = `device/${printer.serial}/report`; // This is the standard topic
printer.mqtt_client.subscribe(topic, (err) => {
if (err) {
console.error('❌ Subscription error:', err.message);
} else {
console.log(`📡 Subscribed to topic: ${topic}`);
}
});
sendRefreshCommand(printer.mqtt_client, printer.serial).then(() => {
refresh_requested = true;
});
});
printer.mqtt_client.on('disconnect', () => {
console.log("Printer disconnected: ", printer);
});
printer.mqtt_client.on('message', (topic, message) => {
try {
const payload = JSON.parse(message.toString());
// TODO: just get out what we actually need and don't overcomplicate it.
//payload comes in with only changes every time, not the full payload
total_payload = _.merge(total_payload, payload);
if(isWithinDjoTime())
{
// lets see if we need to pause the print bc someone uploaded it without approval
if (total_payload.print.md5) {
if(printer.last_accepted_md5 != total_payload.print.md5 && total_payload.print.gcode_state == "RUNNING")
{
sendPauseCommand(printer.mqtt_client, printer.serial);
console.log('NOT CONFIRMED PRINT, pausing print: ', total_payload.print.md5);
}
}
// someone tried to modify the speed again... lets deny this
if (total_payload.print.spd_lvl && total_payload.print.spd_lvl > 2)
sendSpeedCommand(printer.mqtt_client, printer.serial, 2);
}
if(printer.auto_payment && printer.gcode_information && printer.gcode_information.weight > 0)
{
if(
total_payload.print.gcode_state == "FINISH" &&
printer.last_accepted_md5 == total_payload.print.md5 &&
printer.last_paid_for_md5 != total_payload.print.md5
)
{
BITLAIR_BANK.pay3DPrint(_.round(printer.gcode_information.weight), printer.last_accepted_by_user.username.toLowerCase());
console.log('Paid for the weight of ' + printer.gcode_information.weight + ' for the user ' + printer.last_accepted_by_user);
printer.last_paid_for_md5 = total_payload.print.md5;
fs.appendFile('printer_paid_log.log', getDateAndTime() + ' Paid for the weight of ' + printer.gcode_information.weight + ' for the user ' + printer.last_accepted_by_user.username + ' (' + printer.last_accepted_by_user.id + ') \n', 'utf8', (err) => {
if (err) {
console.error('Error appending to file:', err);
} else {
console.log('Data has been appended to the file');
}
});
addNewPrintedObject({
printer_index: printer_index,
datetime: getDateAndTime(),
weight: printer.gcode_information.weight,
username: printer.last_accepted_by_user.username,
ibutton_id: printer.last_accepted_by_user.id,
filename: total_payload.print.subtask_name,
});
}
}
// todo check when a new print is executed
if(
(total_payload.print.gcode_state == "FINISH" || total_payload.print.gcode_state == "RUNNING" || !initialized) &&
(
!printer.gcode_information ||
printer.gcode_information.last_file != total_payload.print.subtask_name ||
(printer.last_print && printer.last_print.md5 != last_loaded_md5)
)
) {
// setting the last loaded md5 so it won't trigger a reload of the file
last_loaded_md5 = total_payload.print.md5;
if(total_payload.print.subtask_name)
{
const local_filename = './latest_print_' + printer_index + '.gcode.3mf';
printer.gcode_information = {
last_file: total_payload.print.subtask_name
};
try {
getFtpClient(printer).then((ftp_client) => {
ftp_client.list().then((files) => {
// Find the file that matches the pattern
const matchedFile = files.find(file => {
if(file.name.startsWith('Bench'))
console.log(file.name.toLowerCase(), total_payload.print.subtask_name.toLowerCase(), total_payload.print.subtask_name.replace(/\s+/g, '_').toLowerCase());
return file.name.toLowerCase().includes(total_payload.print.subtask_name.toLowerCase()) || file.name.toLowerCase().includes(total_payload.print.subtask_name.replace(/\s+/g, '_').toLowerCase())
})
if (matchedFile)
{
printer.processing_new_print = true;
slowedUpdateClientPrinterData();
if(processing_new_print_timeout)
clearTimeout(processing_new_print_timeout);
// timeout just in case there is any failure or it just takes ages for very complex prints
processing_new_print_timeout = setTimeout(() => {
printer.processing_new_print = false;
processing_new_print_timeout = undefined;
slowedUpdateClientPrinterData();
console.log('Processing timeout reached for printer ', printer.title);
}, PROCESSING_TIMEOUT_SECONDS * 1000);
try {
ftp_client.downloadTo(local_filename, matchedFile.name).then(() => {
console.log('File downloaded for printer ', printer.title);
readPrinterFile(local_filename).then(data => {
if(data.status)
{
printer.gcode_information = data;
printer.gcode_information.last_file = total_payload.print.subtask_name;
}
if(processing_new_print_timeout)
clearTimeout(processing_new_print_timeout);
printer.processing_new_print = false;
processing_new_print_timeout = undefined;
slowedUpdateClientPrinterData();
console.log('Parsed data from worker:', data);
})
.catch(err => {
console.error('Worker error:', err);
printer.gcode_information = undefined;
last_loaded_md5 = undefined;
slowedUpdateClientPrinterData();
});
ftp_client.close();
}).catch((exception) => {
console.log('FTP downloadTo failed', exception);
printer.gcode_information = undefined;
last_loaded_md5 = undefined;
slowedUpdateClientPrinterData();
ftp_client.close();
});
}
catch (exception)
{
console.log('FTP downlaod to failed', exception);
printer.gcode_information = undefined;
last_loaded_md5 = undefined;
slowedUpdateClientPrinterData();
ftp_client.close();
}
}
});
})
} catch(exception)
{
console.log('FTP list failed', exception);
printer.gcode_information = undefined;
last_loaded_md5 = undefined;
slowedUpdateClientPrinterData();
}
}
}
printer.total_payload = total_payload;
// update printer information
printer.state = total_payload.print.gcode_state || 'IDLE';
printer.remaining_time_min = total_payload.print.mc_remaining_time;
printer.remaining_percentage = total_payload.print.mc_percent;
printer.last_print = {
md5: total_payload.print.md5,
file: total_payload.print.gcode_file,
};
if(total_payload.print.subtask_name);
printer.last_print.title = total_payload.print.subtask_name;
slowedUpdateClientPrinterData();
// set initialized so we know this is the refreshed data
if(!initialized && refresh_requested)
initialized = true;
} catch (err) {
console.log('MQTT message error: ', err);
}
});
printer.mqtt_client.on("printer:statusUpdate", (oldStatus, newStatus) => {
console.log(`The printer's status has changed from ${oldStatus} to ${newStatus}!`)
});
printer.mqtt_client.on("job:update", () => {
console.log("job:update", arguments);
});
printer.mqtt_client.on("job:start", () => {
console.log("job:start", arguments);
});
printer.mqtt_client.on("job:pause", () => {
console.log("job:pause", arguments);
});
printer.mqtt_client.on("job:offlineRecovery", () => {
console.log("job:offlineRecovery", arguments);
});
printer.mqtt_client.on("job:unpause", () => {
console.log("job:unpause", arguments);
});
printer.mqtt_client.on("job:finish", () => {
console.log("job:finish", arguments);
});
printer.mqtt_client.on('error', (err) => {
console.error('❌ MQTT Error:', err.message);
if(!USE_DUMMY_DATA)
printer.state = "OFFLINE"; // initial state
});
} catch(exception) {
console.log('failed to create mqtt client: ', printer);
}
});
function sendGcodeCommand(mqtt_client, serial, gcodeCommand) {
sendCommand(mqtt_client, serial, "gcode_line", gcodeCommand);
}
function sendPauseCommand(mqtt_client, serial) {
sendCommand(mqtt_client, serial, "pause", "");
}
function sendResumeCommand(mqtt_client, serial) {
sendCommand(mqtt_client, serial, "resume", "");
}
function sendSpeedCommand(mqtt_client, serial, speed) {
sendCommand(mqtt_client, serial, "print_speed", "" + speed + "");
}
function sendCommand(mqtt_client, serial, command, params) {
const current_ts = moment().format('x');
// this prevent it from spamming commands every ms
if (mqtt_client.last_command_ts && current_ts < parseInt(mqtt_client.last_command_ts) + TIME_BETWEEN_COMMANDS_MS)
return;
mqtt_client.last_command_ts = current_ts;
const topic = `device/${serial}/request`; // This is typically the topic for G-code commands
// Publish the G-code command to the printer
mqtt_client.publish(topic, JSON.stringify({
"print": {
"sequence_id": "0",
"command": command,
"param": params, // Gcode to execute, can use \n for multiple lines
"user_id": "" // Optional
}
}), (err) => {
if (err) {
console.error('❌ Failed to send command:', err, command, params);
} else {
console.log(`✅ Sent command: ${command} - ${params}`);
}
});
}
/*function sendRefreshCommand(mqtt_client, serial)
{
const topic = `device/${serial}/request`; // This is typically the topic for G-code commands
// Publish the G-code command to the printer
mqtt_client.publish(topic, JSON.stringify({
"pushing": {
"sequence_id": "0",
"command": "pushall",
"version": 1,
"push_target": 1
}
}), (err) => {
if (err) {
console.error('❌ Failed to send REFRESH command:', err);
} else {
console.log(`✅ Sent command: REFRESH`);
}
});
}*/
function sendRefreshCommand(mqtt_client, serial)
{
return new Promise((resolve, reject) => {
const topic = `device/${serial}/request`;
const payload = JSON.stringify({
"pushing": {
"sequence_id": "0",
"command": "pushall",
"version": 1,
"push_target": 1
}
});
mqtt_client.publish(topic, payload, (err) => {
if (err) {
console.error('❌ Failed to send REFRESH command:', err);
reject(err);
} else {
console.log(`✅ Sent command: REFRESH`);
resolve();
}
});
});
}
function getDateAndTime() {
const now = new Date();
return now.toISOString().replace('T', ' ').substring(0, 19);
}
/*
function getGcodeInformationFromContent(content)
{
const lines = content.split('\n');
const response = {weight: 0, estimated_time: 0};
let time_found = false;
let weight_found = false;
_.each(lines, (line) => {
if(line.includes('total estimated time'))
{
const time_in_text = line.split('total estimated time: ')[1];
response.estimated_time = convertToSeconds(time_in_text);
time_found = true;
}
if(line.includes('weight'))
{
const weight_in_text = line.split(':')[1];
response.weight = sumWeightValues(weight_in_text);
weight_found = true;
}
// found both data already, no need to continue to read all lines
if(time_found && weight_found)
return false; // break;
});
if(response.weight <= 1 && response.estimated_time > 0)
response.weight = 1;
return response;
}
function convertToSeconds(timeString) {
const regex = /(\d+)h\s*(\d+)m\s*(\d+)s|(\d+)m\s*(\d+)s|(\d+)s/;
const match = timeString.trim().match(regex);
if (match) {
let totalSeconds = 0;
if (match[1] && match[2] && match[3]) { // "Xh Ym Zs" format
const hours = parseInt(match[1], 10);
const minutes = parseInt(match[2], 10);
const seconds = parseInt(match[3], 10);
totalSeconds = (hours * 3600) + (minutes * 60) + seconds;
} else if (match[4] && match[5]) { // "Ym Zs" format
const minutes = parseInt(match[4], 10);
const seconds = parseInt(match[5], 10);
totalSeconds = (minutes * 60) + seconds;
} else if (match[6]) { // "Xs" format
const seconds = parseInt(match[6], 10);
totalSeconds = seconds;
}
return totalSeconds;
} else {
throw new Error("Invalid time format. Expected 'Xh Ym Zs', 'Ym Zs', or 'Xs'.");
}
}
function sumWeightValues(valueString) {
// Split the string by commas and parse the individual numbers
const values = valueString.split(',').map(value => parseFloat(value.trim()));
// Sum all the parsed values
return values.reduce((sum, value) => sum + value, 0).toFixed(2);
}
*/
// code to go through the whole gcode and calculate weight and time based on it
/*
function getGcodeInformation(filePath) {
return fs.readFile(filePath, 'utf8').then((gcode) => {
const lines = gcode.split('\n');
let totalExtruded = 0;
let isRelativeMode = false;
let lastE = null; // Add this at the top
let lastX = null, lastY = null, lastZ = null, lastF = 1500;
let prevX = null, prevY = null, prevZ = null;
let totalTimeSeconds = 0;
let loadTime = 0;
let unloadTime = 0;
let toolChanges = 0;
let currentTool = null;
for (let line of lines) {
if (line.startsWith(';')) {
// Parse machine config times
const loadMatch = line.match(/machine_load_filament_time\s*=\s*(\d+)/);
const unloadMatch = line.match(/machine_unload_filament_time\s*=\s*(\d+)/);
if (loadMatch)
loadTime = parseInt(loadMatch[1]);
if (unloadMatch)
unloadTime = parseInt(unloadMatch[1]);
continue;
}
if (!line.trim())
continue;
// Detect extrusion mode
if (line.includes('M83'))
isRelativeMode = true;
else if (line.includes('M82'))
isRelativeMode = false;
// Detect tool change
const toolMatch = line.match(/^T(\d+)/);
if (toolMatch) {
const tool = parseInt(toolMatch[1]);
if (tool !== currentTool) {
currentTool = tool;
toolChanges++;
}
}
const isMovement = /^G[0-3]/.test(line);
if (isMovement) {
const x = parseFloat((line.match(/\sX([-\d.]+)/) || [])[1]);
const y = parseFloat((line.match(/\sY([-\d.]+)/) || [])[1]);
const z = parseFloat((line.match(/\sZ([-\d.]+)/) || [])[1]);
const f = parseFloat((line.match(/\sF([-\d.]+)/) || [])[1]);
// Update previous position before overwriting
prevX = lastX;
prevY = lastY;
prevZ = lastZ;
if (!Number.isNaN(x)) lastX = x;
if (!Number.isNaN(y)) lastY = y;
if (!Number.isNaN(z)) lastZ = z;
if (!Number.isNaN(f)) lastF = f;
// Estimate time only when we have at least previous and current coords
if (
prevX !== null && prevY !== null && prevZ !== null &&
lastX !== null && lastY !== null && lastZ !== null &&
lastF !== null
) {
const dx = lastX - prevX;
const dy = lastY - prevY;
const dz = lastZ - prevZ;
const distance = Math.sqrt(dx * dx + dy * dy + dz * dz);
totalTimeSeconds += (distance / lastF) * 60;
}
}
// Match G0/G1/G2/G3 lines with E values
const match = line.match(/^G(?:0|1|2|3)[^;]*\sE([\-]?\d*\.?\d+)/);
if (match) {
const eVal = parseFloat(match[1]);
if (isRelativeMode) {
if (!Number.isNaN(eVal) && lastF)
totalTimeSeconds += (eVal / lastF) * 60;
totalExtruded += eVal;
} else {
if (lastE !== null && !Number.isNaN(eVal)) {
const delta = eVal - lastE;
if (delta > 0)
{
if (lastF)
totalTimeSeconds += (delta / lastF) * 60;
totalExtruded += delta; // Only count forward moves
}
}
lastE = eVal;
}
}
}
const filamentDiameter = 1.75;
const filamentDensity = 1.25;
const radius = filamentDiameter / 2;
const volumeMm3 = Math.PI * Math.pow(radius, 2) * totalExtruded; // in mm3
const volumeCm3 = volumeMm3 / 1000;
const weightGrams = volumeCm3 * filamentDensity;
// Add color change time
totalTimeSeconds += toolChanges * (loadTime + unloadTime);
totalTimeSeconds += 360;// startup time
return {
length: parseFloat(totalExtruded.toFixed(2)),
weight: parseFloat(weightGrams.toFixed(2)),
estimated_time: _.ceil(totalTimeSeconds),
};
});
}
*/
function updateClientPrinterData(socket = undefined)
{
let printers = _.cloneDeep(PRINTERS);
_.each(printers, (printer) => {
// printer = _.omit(printer, ['ip', 'username', 'password']); //strip the ip,username and password from the return values
printer.spool_information = {};
_.each(printer.total_payload?.print?.ams?.ams, (ams) => {
_.each(ams.tray, (spool) => {
if(!spool.tray_sub_brands)
return true;
printer.spool_information[spool.id] = {
index: spool.id,
type: spool.tray_sub_brands,
remaining_percentage: spool.remain,
colors: spool.cols,
};
})
});
delete printer.ip;
delete printer.username;
delete printer.password;
delete printer.total_payload;
delete printer.mqtt_client;
});
if(socket)
socket.emit('update printer data', printers);
else
io.emit('update printer data', printers);
/*
// file needs the state of the files
printers = _.cloneDeep(PRINTERS);
_.each(printers, (printer) => {
// printer = _.omit(printer, ['ip', 'username', 'password']); //strip the ip,username and password from the return values
delete printer.ip;
delete printer.username;
delete printer.password;
delete printer.mqtt_client; // not required
});
fs.appendFile('printer_data_logs.log', JSON.stringify(printers) + '\n\n\n', 'utf8', (err) => {
if (err) {
console.error('Error appending to file:', err);
} else {
console.log('Data has been appended to the file');
}
});
*/
}