-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial_web.py
More file actions
3125 lines (2881 loc) · 139 KB
/
serial_web.py
File metadata and controls
3125 lines (2881 loc) · 139 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
try:
import wiringpi # Raspberry Pi GPIO library
except Exception as _e:
# Fallback dummy for non-RPi environments (disables real GPIO but keeps server running)
class _DummyWiringPi:
class GPIO:
OUTPUT = 1
HIGH = 1
LOW = 0
def wiringPiSetup(self):
return -1
def pinMode(self, *args, **kwargs):
pass
def digitalWrite(self, *args, **kwargs):
pass
def digitalRead(self, *args, **kwargs):
return 0
wiringpi = _DummyWiringPi()
print(f"[WARN] wiringpi not available: {_e}. GPIO features disabled.")
import sys
# Restore user's hard-coded environment site-packages path
sys.path.append("/root/serial_env/lib/python3.12/site-packages")
import os
# Avoid hard-coding site-packages; if running in a virtualenv, do nothing.
# Optionally, allow an extra site-packages path via env (EXTRA_SITE_PACKAGES or PYTHON_SITE_PACKAGES).
try:
if not os.environ.get('VIRTUAL_ENV'):
extra_site = os.environ.get('EXTRA_SITE_PACKAGES') or os.environ.get('PYTHON_SITE_PACKAGES')
if extra_site and os.path.isdir(extra_site) and extra_site not in sys.path:
sys.path.append(extra_site)
except Exception:
pass
import serial
import time
import glob
import threading
import socket
import os # re-import safe; kept for existing import ordering
import json
from flask import Flask, request, jsonify, send_file
from flask_socketio import SocketIO, emit
from werkzeug.utils import secure_filename
# --- Flask & SocketIO Setup ---
app = Flask(__name__)
app.config['SECRET_KEY'] = 'grbl_secret!'
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
# --- Serial Settings ---
BAUDRATE = 115200
SERIAL_CONN = None
TELNET_PORT = 23
# --- Connection state ---
DEVICE = None
DEVICE_CONNECTED = False
# --- G-code job management ---
# Always default to /root paths (as originally), allow overrides via env vars if needed.
GCODE_DIR = os.environ.get('GCODE_DIR', '/root/gcodes')
FONTS_DIR = os.environ.get('FONTS_DIR', '/root/fonts')
CONFIG_FILE = os.environ.get('CONFIG_FILE', '/root/grbl_config.json')
# Max spindle/laser S value (e.g., GRBL $30). Use env LASER_S_MAX to override.
LASER_S_MAX = int(os.environ.get('LASER_S_MAX', '1000'))
current_job = {
'filename': None,
'lines': [],
'current_line': 0,
'total_lines': 0,
'running': False,
'paused': False
}
job_lock = threading.Lock()
# --- M-code command mapping ---
default_mcode_commands = {
'M7': '', # Mist coolant on
'M8': '', # Flood coolant on
'M9': '' # Coolant off
}
mcode_commands = default_mcode_commands.copy()
air_assist_config = {
'on_command': '',
'off_command': '',
'enabled': False,
'pin': 2, # WiringPi pin number
'monitoring_enabled': True # Enable/disable M-code monitoring
}
config_lock = threading.Lock()
# --- WiringPi GPIO Setup ---
AIR_PIN = 2 # Default WiringPi pin
try:
if wiringpi.wiringPiSetup() == -1:
print("[ERROR] WiringPi setup failed!")
AIR_PIN = None
else:
wiringpi.pinMode(AIR_PIN, wiringpi.GPIO.OUTPUT)
wiringpi.digitalWrite(AIR_PIN, wiringpi.GPIO.LOW) # Default OFF
print(f"[INFO] WiringPi initialized, Air Assist on pin {AIR_PIN}")
except Exception as e:
print(f"[ERROR] WiringPi initialization failed: {e}")
AIR_PIN = None
# --- Raw telnet clients (just sockets) ---
raw_telnet_clients = []
telnet_lock = threading.Lock()
# Use absolute path for status file
STATUS_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), 'status.json'))
def save_status(ttyacm_connected, ttyacm_port, telnet_connected):
status = {
'ttyacm_connected': ttyacm_connected,
'ttyacm_port': ttyacm_port,
'telnet_connected': telnet_connected
}
try:
with open(STATUS_FILE, 'w') as f:
json.dump(status, f)
except Exception as e:
print(f"[ERROR] Failed to save status.json at {STATUS_FILE}: {e}")
def load_status():
try:
with open(STATUS_FILE, 'r') as f:
return json.load(f)
except Exception:
return {'ttyacm_connected': False, 'ttyacm_port': None, 'telnet_connected': False}
def find_ttyacm_device():
"""Find first ttyACM device"""
devices = glob.glob("/dev/ttyACM*")
return devices[0] if devices else None
def ensure_gcode_dir():
"""Ensure G-code directory exists"""
if not os.path.exists(GCODE_DIR):
os.makedirs(GCODE_DIR)
def ensure_fonts_dir():
"""Ensure fonts directory exists"""
if not os.path.exists(FONTS_DIR):
os.makedirs(FONTS_DIR)
def allowed_font_file(filename: str) -> bool:
ext = os.path.splitext(filename)[1].lower()
return ext in [".ttf", ".otf", ".woff", ".woff2"]
def list_fonts():
ensure_fonts_dir()
out = []
for filename in os.listdir(FONTS_DIR):
if allowed_font_file(filename):
fp = os.path.join(FONTS_DIR, filename)
try:
out.append({
'name': filename,
'size': os.path.getsize(fp),
'modified': time.strftime('%Y-%m-%d %H:%M', time.localtime(os.path.getmtime(fp)))
})
except Exception:
pass
return sorted(out, key=lambda x: x['modified'], reverse=True)
def node_exe():
"""Return the node executable command name"""
# On most systems simply 'node' is available; allow override via env
return os.environ.get('NODE_BIN', 'node')
def run_font_to_svg(text: str, font_path: str, font_size: float = 72.0, letter_spacing: float = 0.0, line_spacing_factor: float = 0.2, align: str = 'left'):
"""Call the local Node helper to convert text+font to an SVG path using google-font-to-svg-path.
Returns dict with keys: path, width, height. Raises RuntimeError on failure.
"""
import subprocess, json as _json
script_path = os.path.join(os.path.dirname(__file__), 'font_to_svg_path.js')
if not os.path.exists(script_path):
raise RuntimeError('Missing helper: font_to_svg_path.js not found next to server')
if not os.path.exists(font_path):
raise RuntimeError(f'Font not found: {font_path}')
try:
proc = subprocess.run(
[node_exe(), script_path,
'--font', font_path,
'--text', text,
'--fontSize', str(float(font_size)),
'--letterSpacing', str(float(letter_spacing)),
'--lineSpacing', str(float(line_spacing_factor)),
'--align', str(align or 'left')
],
capture_output=True, text=True, timeout=20
)
except FileNotFoundError:
raise RuntimeError('Node.js not found. Please install Node.js and ensure "node" is in PATH.')
except subprocess.TimeoutExpired:
raise RuntimeError('Font to SVG helper timed out')
if proc.returncode != 0:
err = proc.stderr.strip() or proc.stdout.strip() or 'Unknown error'
raise RuntimeError(f'font_to_svg_path failed: {err}')
try:
data = _json.loads(proc.stdout)
if 'path' not in data:
raise RuntimeError('Invalid helper output: missing path')
return data
except Exception as e:
raise RuntimeError(f'Invalid helper output: {e}')
def flatten_svg_path_to_polylines(path_d: str, tolerance: float = 0.5):
"""Very small SVG path parser/flatten for M/L/H/V/C/Q/S/T/Z commands.
Returns list of polylines (each list of (x,y)). tolerance in path units.
"""
import re, math
def tokenize(d):
for token in re.finditer(r"[a-zA-Z]|-?\d*\.?\d+(?:[eE][+-]?\d+)?", d):
t = token.group(0)
yield t
tokens = list(tokenize(path_d))
i = 0
cx = cy = 0.0
sx = sy = 0.0
last_cmd = ''
polylines = []
current = []
pcx = pcy = None # previous control point for smooth curves
def add_point(x, y):
nonlocal current
if not current:
current = [(x, y)]
else:
if current[-1] != (x, y):
current.append((x, y))
def end_subpath(close=False):
nonlocal current
if current and len(current) > 1:
polylines.append(current)
current = []
def read_float():
nonlocal i
v = float(tokens[i]); i += 1
return v
def flatten_q(p0, p1, p2):
# adaptive subdivision by flatness
def rec(a, b, c):
# max distance from control b to line ac
ax, ay = a; bx, by = b; cx_, cy_ = c
dx = cx_ - ax; dy = cy_ - ay
if dx == 0 and dy == 0:
dist = math.hypot(bx-ax, by-ay)
else:
t = ((bx-ax)*dx + (by-ay)*dy) / (dx*dx + dy*dy)
px = ax + t*dx; py = ay + t*dy
dist = math.hypot(bx - px, by - py)
if dist <= tolerance:
add_point(c[0], c[1])
else:
ab = ((a[0]+b[0])/2, (a[1]+b[1])/2)
bc = ((b[0]+c[0])/2, (b[1]+c[1])/2)
abc = ((ab[0]+bc[0])/2, (ab[1]+bc[1])/2)
rec(a, ab, abc)
rec(abc, bc, c)
add_point(p0[0], p0[1])
rec(p0, p1, p2)
def flatten_c(p0, p1, p2, p3):
# Convert cubic to two quadratics recursively or use flatness measure
def rec(a, b, c, d):
# approximate flatness by control polygon
l = (math.hypot(b[0]-a[0], b[1]-a[1]) +
math.hypot(c[0]-b[0], c[1]-b[1]) +
math.hypot(d[0]-c[0], d[1]-c[1]))
chord = math.hypot(d[0]-a[0], d[1]-a[1])
if l - chord <= tolerance:
add_point(d[0], d[1])
else:
# de Casteljau split
ab = ((a[0]+b[0])/2, (a[1]+b[1])/2)
bc = ((b[0]+c[0])/2, (b[1]+c[1])/2)
cd = ((c[0]+d[0])/2, (c[1]+d[1])/2)
abc = ((ab[0]+bc[0])/2, (ab[1]+bc[1])/2)
bcd = ((bc[0]+cd[0])/2, (bc[1]+cd[1])/2)
abcd = ((abc[0]+bcd[0])/2, (abc[1]+bcd[1])/2)
rec(a, ab, abc, abcd)
rec(abcd, bcd, cd, d)
add_point(p0[0], p0[1])
rec(p0, p1, p2, p3)
while i < len(tokens):
t = tokens[i]; i += 1
if t.isalpha():
cmd = t
else:
# implicit command repetition
i -= 1
cmd = last_cmd
absolute = cmd.isupper()
cmdU = cmd.upper()
if cmdU == 'M':
x = read_float(); y = read_float()
if not absolute:
x += cx; y += cy
# end previous
end_subpath()
cx, cy = x, y
sx, sy = x, y
add_point(cx, cy)
# implicit lineTos
last_cmd = cmd
# subsequent pairs are LineTos
while i < len(tokens) and not tokens[i].isalpha():
x = read_float(); y = read_float()
if not absolute:
x += cx; y += cy
add_point(x, y)
cx, cy = x, y
last_cmd = 'L' if absolute else 'l'
elif cmdU == 'L':
while i < len(tokens) and not tokens[i].isalpha():
x = read_float(); y = read_float()
if not absolute:
x += cx; y += cy
add_point(x, y)
cx, cy = x, y
last_cmd = cmd
elif cmdU == 'H':
while i < len(tokens) and not tokens[i].isalpha():
x = read_float()
if not absolute:
x += cx
add_point(x, cy)
cx = x
last_cmd = cmd
elif cmdU == 'V':
while i < len(tokens) and not tokens[i].isalpha():
y = read_float()
if not absolute:
y += cy
add_point(cx, y)
cy = y
last_cmd = cmd
elif cmdU == 'Q':
while i < len(tokens) and not tokens[i].isalpha():
x1 = read_float(); y1 = read_float(); x = read_float(); y = read_float()
if not absolute:
x1 += cx; y1 += cy; x += cx; y += cy
flatten_q((cx, cy), (x1, y1), (x, y))
pcx, pcy = x1, y1
cx, cy = x, y
last_cmd = cmd
elif cmdU == 'T':
while i < len(tokens) and not tokens[i].isalpha():
x = read_float(); y = read_float()
if pcx is None:
rx, ry = cx, cy
else:
rx, ry = 2*cx - pcx, 2*cy - pcy
if not absolute:
x += cx; y += cy
flatten_q((cx, cy), (rx, ry), (x, y))
pcx, pcy = rx, ry
cx, cy = x, y
last_cmd = cmd
elif cmdU == 'C':
while i < len(tokens) and not tokens[i].isalpha():
x1 = read_float(); y1 = read_float(); x2 = read_float(); y2 = read_float(); x = read_float(); y = read_float()
if not absolute:
x1 += cx; y1 += cy; x2 += cx; y2 += cy; x += cx; y += cy
flatten_c((cx, cy), (x1, y1), (x2, y2), (x, y))
pcx, pcy = x2, y2
cx, cy = x, y
last_cmd = cmd
elif cmdU == 'S':
while i < len(tokens) and not tokens[i].isalpha():
x2 = read_float(); y2 = read_float(); x = read_float(); y = read_float()
if pcx is None:
rx, ry = cx, cy
else:
rx, ry = 2*cx - pcx, 2*cy - pcy
if not absolute:
x2 += cx; y2 += cy; x += cx; y += cy
flatten_c((cx, cy), (rx, ry), (x2, y2), (x, y))
pcx, pcy = x2, y2
cx, cy = x, y
last_cmd = cmd
elif cmdU == 'Z':
# Close path
add_point(sx, sy)
cx, cy = sx, sy
end_subpath(close=True)
pcx = pcy = None
last_cmd = cmd
else:
# Unsupported command, break
break
# finalize
end_subpath()
return polylines
def polylines_to_gcode(polylines, scale=1.0, offset=(0.0, 0.0), feed_rate=1000, laser_power=100, dynamic_power=False, include_header=True):
lines = []
if include_header:
lines.append("; Vector text to G-code (custom font)")
lines.append("G90")
lines.append("G21")
lines.append("M5")
lines.append(f"F{int(feed_rate)}")
else:
lines.append(f"F{int(feed_rate)}")
ox, oy = offset
# map 0-100% to 0-LASER_S_MAX
try:
s_val = max(0, min(100, int(round(laser_power))))
except Exception:
s_val = 0
s_cmd = int(round((s_val/100.0) * LASER_S_MAX))
for poly in polylines:
if len(poly) < 2:
continue
x0 = ox + poly[0][0]*scale
y0 = oy + poly[0][1]*scale
lines.append(f"G0 X{round(x0,4)} Y{round(y0,4)}")
lines.append(f"M4 S{s_cmd}")
for x, y in poly[1:]:
X = ox + x*scale
Y = oy + y*scale
lines.append(f"G1 X{round(X,4)} Y{round(Y,4)}")
lines.append("M5")
if include_header:
lines.append("M5")
lines.append("; End of vector text")
return lines
def polylines_to_svg(polylines, width_mm=None, height_mm=None, stroke_width=0.2, stroke_color="#0f0", fit_to_container=True, show_origin=False, origin_color="#f33"):
"""Render polylines (in mm units) into a standalone SVG string.
If width_mm/height_mm are None, compute bbox and use that as viewBox.
"""
if not polylines:
return '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="50"></svg>'
xs = [x for poly in polylines for x, _ in poly]
ys = [y for poly in polylines for _, y in poly]
minx, maxx = min(xs), max(xs)
miny, maxy = min(ys), max(ys)
vb_w = max(1e-6, maxx - minx)
vb_h = max(1e-6, maxy - miny)
# Prepare path data
paths = []
for poly in polylines:
if len(poly) < 2:
continue
d = f"M {poly[0][0] - minx:.4f} {maxy - poly[0][1]:.4f}"
for x, y in poly[1:]:
d += f" L {x - minx:.4f} {maxy - y:.4f}"
paths.append(d)
# Size
out_w = width_mm or vb_w
out_h = height_mm or vb_h
size_attrs = ("width=\"100%\" height=\"100%\"" if fit_to_container else f"width=\"{out_w:.4f}mm\" height=\"{out_h:.4f}mm\"")
svg_parts = [
f"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 {vb_w:.4f} {vb_h:.4f}\" {size_attrs} preserveAspectRatio=\"xMidYMid meet\">",
f"<rect x=\"0\" y=\"0\" width=\"{vb_w:.4f}\" height=\"{vb_h:.4f}\" fill=\"#111\" stroke=\"#333\" stroke-width=\"0.1\" />"
]
if show_origin:
# Origin (0,0) in the original polyline space maps to (ox, oy) in viewBox coords
ox = 0 - minx
oy = maxy - 0
size = max(1.0, min(vb_w, vb_h) * 0.03)
svg_parts.append(f"<g stroke=\"{origin_color}\" stroke-width=\"0.2\">")
svg_parts.append(f"<line x1=\"{ox - size:.4f}\" y1=\"{oy:.4f}\" x2=\"{ox + size:.4f}\" y2=\"{oy:.4f}\" />")
svg_parts.append(f"<line x1=\"{ox:.4f}\" y1=\"{oy - size:.4f}\" x2=\"{ox:.4f}\" y2=\"{oy + size:.4f}\" />")
svg_parts.append("</g>")
for d in paths:
svg_parts.append(f"<path d=\"{d}\" fill=\"none\" stroke=\"{stroke_color}\" stroke-width=\"{stroke_width}\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>")
svg_parts.append("</svg>")
return "".join(svg_parts)
def polylines_bbox(polylines):
if not polylines:
return (0.0, 0.0, 0.0, 0.0)
xs = [x for poly in polylines for x, _ in poly]
ys = [y for poly in polylines for _, y in poly]
return (min(xs), min(ys), max(xs), max(ys))
def add_border_rectangle(polylines, margin_mm=0.0):
"""Add a rectangle polyline around the bbox of given polylines, expanded by margin_mm."""
if margin_mm <= 0:
return polylines
minx, miny, maxx, maxy = polylines_bbox(polylines)
minx -= margin_mm
miny -= margin_mm
maxx += margin_mm
maxy += margin_mm
rect = [(minx, miny), (maxx, miny), (maxx, maxy), (minx, maxy), (minx, miny)]
return polylines + [rect]
def gcode_to_polylines(gcode_lines):
"""Parse basic G-code (G0/G1, G90/G91, M3/M5) into polylines for 'laser on' segments.
Returns list of polylines (x,y in same units as input — assume mm).
"""
import re
absolute = True
x = y = 0.0
laser_on = False
polylines = []
current = []
float_re = r"-?\d*\.?\d+(?:[eE][+-]?\d+)?"
for raw in gcode_lines:
line = raw.strip()
if not line or line.startswith(';') or line.startswith('('):
continue
u = line.upper()
# Mode
if 'G90' in u:
absolute = True
if 'G91' in u:
absolute = False
# Laser
if 'M5' in u:
laser_on = False
if current:
polylines.append(current)
current = []
# M3 with optional S value; treat any M3 as on
if 'M3' in u:
laser_on = True
# don't start a point yet; will add on first move
# Motion: G0/G1
if 'G0' in u or 'G1' in u:
mx = re.search(rf"X({float_re})", u)
my = re.search(rf"Y({float_re})", u)
nx, ny = x, y
if mx:
nx = float(mx.group(1)) + (0 if absolute else x)
if my:
ny = float(my.group(1)) + (0 if absolute else y)
moved = (nx != x) or (ny != y)
if moved:
if laser_on:
if not current:
current = [(x, y)]
current.append((nx, ny))
else:
if current:
polylines.append(current)
current = []
x, y = nx, ny
if current:
polylines.append(current)
return polylines
def load_config():
"""Load M-code and air assist configuration from file"""
global mcode_commands, air_assist_config
try:
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, 'r') as f:
config = json.load(f)
if 'mcode_commands' in config:
with config_lock:
mcode_commands.update(config['mcode_commands'])
print(f"[CONFIG] Loaded M-code commands: {mcode_commands}")
if 'air_assist' in config:
with config_lock:
air_assist_config.update(config['air_assist'])
print(f"[CONFIG] Loaded air assist: {air_assist_config}")
except Exception as e:
print(f"[ERROR] Failed to load config: {e}")
def save_config():
"""Save M-code and air assist configuration to file"""
try:
config = {
'mcode_commands': mcode_commands.copy(),
'air_assist': air_assist_config.copy()
}
with open(CONFIG_FILE, 'w') as f:
json.dump(config, f, indent=2)
print(f"[CONFIG] Saved M-code commands: {mcode_commands}")
print(f"[CONFIG] Saved air assist: {air_assist_config}")
except Exception as e:
print(f"[ERROR] Failed to save config: {e}")
def set_air_assist_gpio(state):
"""Set air assist GPIO pin state"""
if AIR_PIN is not None and air_assist_config.get('monitoring_enabled', True):
try:
wiringpi.digitalWrite(AIR_PIN, wiringpi.GPIO.HIGH if state else wiringpi.GPIO.LOW)
print(f"[GPIO] Air assist pin {AIR_PIN} set to {'HIGH' if state else 'LOW'}")
socketio.emit('air_assist_gpio', {'state': state, 'pin': AIR_PIN})
except Exception as e:
print(f"[ERROR] Failed to set GPIO pin {AIR_PIN}: {e}")
def process_mcode(line):
"""Process M-code commands and return replacement command if any"""
import re
line_upper = line.upper().strip()
# Regex to match M7, M8, M9 as whole words (not part of other words)
mcode_pattern = re.compile(r'\b(M7|M8|M9)\b')
if air_assist_config.get('monitoring_enabled', True):
found = mcode_pattern.findall(line_upper)
# Only act on the last occurrence (GRBL status reports show current state)
if found:
last_mcode = found[-1]
if last_mcode in ['M7', 'M8']:
set_air_assist_gpio(True)
socketio.emit('mcode_detected', {
'original': line.strip(),
'mcode': last_mcode,
'action': 'Air Assist ON'
})
elif last_mcode == 'M9':
set_air_assist_gpio(False)
socketio.emit('mcode_detected', {
'original': line.strip(),
'mcode': 'M9',
'action': 'Air Assist OFF'
})
# Check for custom M-code replacements (still only at start)
for mcode, replacement in mcode_commands.items():
if line_upper.startswith(mcode) and replacement.strip():
# Check if it's exactly the M-code or M-code followed by space/end
if (line_upper == mcode or
(len(line_upper) > len(mcode) and line_upper[len(mcode)] in ' \t\n')):
print(f"[MCODE] Detected {mcode}, replacing with: {replacement}")
socketio.emit('mcode_detected', {
'original': line.strip(),
'mcode': mcode,
'replacement': replacement
})
return replacement
return line
def get_gcode_files():
"""Get list of G-code files"""
ensure_gcode_dir()
files = []
for filename in os.listdir(GCODE_DIR):
if filename.lower().endswith(('.gcode', '.gc', '.nc', '.tap', '.txt')):
filepath = os.path.join(GCODE_DIR, filename)
size = os.path.getsize(filepath)
mtime = os.path.getmtime(filepath)
files.append({
'name': filename,
'size': size,
'modified': time.strftime('%Y-%m-%d %H:%M', time.localtime(mtime))
})
return sorted(files, key=lambda x: x['modified'], reverse=True)
def load_gcode_file(filename):
"""Load G-code file into current job"""
filepath = os.path.join(GCODE_DIR, filename)
if not os.path.exists(filepath):
return False
with job_lock:
try:
with open(filepath, 'r') as f:
lines = []
for line in f:
line = line.strip()
if line and not line.startswith(';') and not line.startswith('('):
lines.append(line)
current_job['filename'] = filename
current_job['lines'] = lines
current_job['current_line'] = 0
current_job['total_lines'] = len(lines)
current_job['running'] = False
current_job['paused'] = False
current_job['lines_sent'] = 0
current_job['lines_acked'] = 0
return True
except Exception as e:
print(f"[ERROR] Failed to load G-code file: {e}")
socketio.emit('job_error', {'error': str(e)})
return False
def broadcast_raw_to_telnet(data):
"""Send raw data to all telnet clients"""
with telnet_lock:
disconnected_clients = []
for client in raw_telnet_clients:
try:
client.send(data)
except:
disconnected_clients.append(client)
# Remove disconnected clients
for client in disconnected_clients:
raw_telnet_clients.remove(client)
try:
client.close()
except:
pass
def update_lightburn_connection_status(connected):
# Only print status for Telnet, no web UI indicator
if connected:
print("[INFO] Telnet connected")
else:
print("[INFO] Telnet disconnected")
def handle_raw_telnet_client(client_socket, addr):
"""Handle raw telnet client - direct bridge to serial"""
print(f"[TELNET] Raw client connected from {addr}")
with telnet_lock:
if len(raw_telnet_clients) == 0:
update_lightburn_connection_status(True) # Telnet connected
socketio.emit('telnet_status', {'connected': True})
raw_telnet_clients.append(client_socket)
update_status_emit() # <-- moved here, after append
try:
buffer = b''
while True:
# Read data from telnet client
data = client_socket.recv(1024)
if not data:
break
buffer += data
# Process complete lines
while b'\n' in buffer:
line, buffer = buffer.split(b'\n', 1)
line = line.rstrip(b'\r')
# Convert to string for processing
try:
line_str = line.decode('utf-8', errors='ignore')
except Exception:
line_str = ''
# Send to GRBL if connected
if SERIAL_CONN and DEVICE_CONNECTED:
try:
SERIAL_CONN.write((line_str + '\n').encode())
SERIAL_CONN.flush()
print(f"[TELNET->GRBL] {line_str}")
except Exception as e:
print(f"[ERROR] Failed to send to GRBL: {e}")
break
else:
client_socket.send(b"error: No GRBL connection\r\n")
# If buffer is too large (no newline), flush it anyway
if len(buffer) > 4096:
buffer = b'' # Clear buffer to prevent memory issues
except Exception as e:
print(f"[ERROR] Raw telnet client error: {e}")
finally:
with telnet_lock:
if client_socket in raw_telnet_clients:
raw_telnet_clients.remove(client_socket)
if len(raw_telnet_clients) == 0:
update_lightburn_connection_status(False) # Telnet disconnected
socketio.emit('telnet_status', {'connected': False})
update_status_emit()
try:
client_socket.close()
except:
pass
print(f"[TELNET] Raw client disconnected from {addr}")
def raw_telnet_server():
"""Raw telnet server for LightBurn compatibility"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('', TELNET_PORT))
server.listen(5)
print(f"[INFO] Telnet server listening on port {TELNET_PORT}")
while True:
try:
client_socket, addr = server.accept()
threading.Thread(target=handle_raw_telnet_client, args=(client_socket, addr), daemon=True).start()
except Exception as e:
print(f"[ERROR] Telnet server error: {e}")
# --- Serial Connection Management ---
def serial_worker():
global SERIAL_CONN, DEVICE, DEVICE_CONNECTED
while True:
# Try to connect if not connected
if SERIAL_CONN is None:
DEVICE = find_ttyacm_device()
if DEVICE:
try:
print(f"[INFO] Connecting to {DEVICE}...")
SERIAL_CONN = serial.Serial(DEVICE, BAUDRATE, timeout=0.1)
time.sleep(2) # GRBL initialization
SERIAL_CONN.flushInput()
# Send wake-up
SERIAL_CONN.write(b'\r\n\r\n')
SERIAL_CONN.flush()
time.sleep(1)
print(f"[INFO] Connected to {DEVICE}")
DEVICE_CONNECTED = True
socketio.emit('status_update', {'device': True, 'port': DEVICE})
update_status_emit()
save_status(True, DEVICE, False)
socketio.emit('status_realtime', load_status())
except Exception as e:
print(f"[ERROR] Connection failed: {e}")
SERIAL_CONN = None
DEVICE_CONNECTED = False
socketio.emit('status_update', {'device': False})
update_status_emit()
save_status(False, None, False)
socketio.emit('status_realtime', load_status())
time.sleep(2)
continue
else:
print("[INFO] No ttyACM device found, retrying...")
DEVICE_CONNECTED = False
socketio.emit('status_update', {'device': False})
update_status_emit()
save_status(False, None, False)
socketio.emit('status_realtime', load_status())
time.sleep(2)
continue
# Read from serial and send raw to both web and telnet
try:
if SERIAL_CONN and SERIAL_CONN.in_waiting:
# Read raw bytes
data = SERIAL_CONN.read(SERIAL_CONN.in_waiting)
if data:
# Send raw data to telnet clients (LightBurn compatibility)
broadcast_raw_to_telnet(data)
# Convert to string for web interface and process M-codes
try:
lines = data.decode('utf-8', errors='ignore').splitlines()
for line in lines:
line = line.strip()
if line:
print(f"[GRBL] {line}")
socketio.emit('serial_output', line)
process_mcode(line)
except Exception:
pass # Ignore decode errors
except Exception as e:
print(f"[ERROR] Serial read error: {e}")
if SERIAL_CONN:
SERIAL_CONN.close()
SERIAL_CONN = None
DEVICE_CONNECTED = False
socketio.emit('status_update', {'device': False})
update_status_emit()
save_status(False, None, False)
socketio.emit('status_realtime', load_status())
time.sleep(0.01) # Faster polling for raw bridge
def job_runner():
while True:
with job_lock:
# Only send next line if job is running, not paused, and not done, and previous line was acked
if (current_job['running'] and not current_job['paused'] and
current_job['lines_sent'] < current_job['total_lines'] and
current_job['lines_sent'] == current_job['lines_acked']):
if SERIAL_CONN and DEVICE_CONNECTED:
line = current_job['lines'][current_job['lines_sent']]
try:
# Process M-codes to toggle GPIO and allow replacements for outgoing job lines
processed = process_mcode(line)
SERIAL_CONN.write(((processed or line) + '\n').encode())
SERIAL_CONN.flush()
print(f"[JOB] Sent line {current_job['lines_sent'] + 1}/{current_job['total_lines']}: {processed or line}")
current_job['lines_sent'] += 1
except Exception as e:
print(f"[ERROR] Job execution error: {e}")
current_job['running'] = False
socketio.emit('job_error', {'error': str(e)})
time.sleep(0.01)
def serial_reader():
global SERIAL_CONN, DEVICE, DEVICE_CONNECTED
while True:
# Try to connect if not connected
if SERIAL_CONN is None:
DEVICE = find_ttyacm_device()
if DEVICE:
try:
print(f"[INFO] Connecting to {DEVICE}...")
SERIAL_CONN = serial.Serial(DEVICE, BAUDRATE, timeout=0.1)
time.sleep(2) # GRBL initialization
SERIAL_CONN.flushInput()
# Send wake-up
SERIAL_CONN.write(b'\r\n\r\n')
SERIAL_CONN.flush()
time.sleep(1)
print(f"[INFO] Connected to {DEVICE}")
DEVICE_CONNECTED = True
socketio.emit('status_update', {'device': True, 'port': DEVICE})
update_status_emit()
save_status(True, DEVICE, False)
socketio.emit('status_realtime', load_status())
except Exception as e:
print(f"[ERROR] Connection failed: {e}")
SERIAL_CONN = None
DEVICE_CONNECTED = False
socketio.emit('status_update', {'device': False})
update_status_emit()
save_status(False, None, False)
socketio.emit('status_realtime', load_status())
time.sleep(2)
continue
else:
print("[INFO] No ttyACM device found, retrying...")
DEVICE_CONNECTED = False
socketio.emit('status_update', {'device': False})
update_status_emit()
save_status(False, None, False)
socketio.emit('status_realtime', load_status())
time.sleep(2)
continue
# Read from serial and send raw to both web and telnet
try:
if SERIAL_CONN and SERIAL_CONN.in_waiting:
# Read raw bytes
data = SERIAL_CONN.read(SERIAL_CONN.in_waiting)
if data:
# Send raw data to telnet clients (LightBurn compatibility)
broadcast_raw_to_telnet(data)
# Convert to string for web interface and process M-codes
try:
lines = data.decode('utf-8', errors='ignore').splitlines()
for line in lines:
line = line.strip()
if line:
print(f"[GRBL] {line}")
socketio.emit('serial_output', line)
process_mcode(line)
# --- Job progress tracking ---
if line == 'ok':
with job_lock:
if current_job['running'] and not current_job['paused'] and current_job['lines_acked'] < current_job['total_lines']:
current_job['lines_acked'] += 1
# Emit progress update
progress = (current_job['lines_acked'] / current_job['total_lines']) * 100 if current_job['total_lines'] > 0 else 0
socketio.emit('job_progress', {
'filename': current_job['filename'],
'current_line': current_job['lines_acked'],
'total_lines': current_job['total_lines'],
'progress': progress,
'running': current_job['running'],
'paused': current_job['paused']
})
# Job completed
if current_job['lines_acked'] >= current_job['total_lines']:
current_job['running'] = False
print(f"[JOB] Completed: {current_job['filename']}")
socketio.emit('job_completed', {'filename': current_job['filename']})
except Exception:
pass # Ignore decode errors
except Exception as e:
print(f"[ERROR] Serial read error: {e}")
if SERIAL_CONN:
SERIAL_CONN.close()
SERIAL_CONN = None
DEVICE_CONNECTED = False
socketio.emit('status_update', {'device': False})
update_status_emit()
save_status(False, None, False)
socketio.emit('status_realtime', load_status())
time.sleep(0.01) # Faster polling for raw bridge
# --- SocketIO Events (for web interface only) ---
@socketio.on('connect')
def handle_connect():
print("[INFO] Web client connected")
emit('status_update', {'device': DEVICE_CONNECTED, 'port': DEVICE})
emit('mcode_config', {'commands': mcode_commands.copy()})
emit('air_assist_config', {'config': air_assist_config.copy()})
@socketio.on('send_command')
def handle_send_command(data):
"""Send command to GRBL from web interface"""
if not SERIAL_CONN or not DEVICE_CONNECTED:
emit('serial_output', '[ERROR] No GRBL connection')
return
command = data.get('command', '').strip()
if not command:
return