-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgcode_generator.py
More file actions
256 lines (192 loc) · 5.91 KB
/
gcode_generator.py
File metadata and controls
256 lines (192 loc) · 5.91 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
# gcode_generator.py
import subprocess
from dataclasses import dataclass
from typing import Optional, List
HF2GCODE_CMD = "../hf2gcode" # To adjust for windows
@dataclass
class Hf2GcodeParams:
font: str = "rowmans"
scale: float = 0.2
feed: int = 200
xoffset: float = 0.0
yoffset: float = 0.0
z_down: float = -3.0
z_up: float = 3.0
align: str = "left"
interline: float = 8.0
precision: int = 3
inch: bool = False
min_gcode: bool = True
no_pre: bool = False
no_post: bool = False
# Limites physiques robot
robot_x_min: float = 0.0
robot_x_max: float = 100.0
robot_y_min: float = -50.0
robot_y_max: float = 100.0
# Zone sûre (avec marges, robot_y_max_effective, etc.)
safe_x_min: float = 0.0
safe_x_max: float = 0.0
safe_y_min: float = 0.0
safe_y_max: float = 0.0
margin: float = 0.0
def build_cmd(params: Hf2GcodeParams) -> List[str]:
cmd = [HF2GCODE_CMD]
if params.font:
cmd += ["--font", params.font]
cmd += ["--scale", str(params.scale)]
cmd += ["--feed", str(params.feed)]
cmd += ["--xoffset", str(params.xoffset)]
cmd += ["--yoffset", str(params.yoffset)]
cmd += ["--z-down", str(params.z_down)]
cmd += ["--z-up", str(params.z_up)]
if params.align == "left":
cmd += ["--align-left"]
elif params.align == "center":
cmd += ["--align-center"]
elif params.align == "right":
cmd += ["--align-right"]
cmd += ["--interline", str(params.interline)]
cmd += ["--precision", str(params.precision)]
if params.min_gcode:
cmd += ["--min-gcode"]
if params.no_pre:
cmd += ["--no-pre"]
if params.no_post:
cmd += ["--no-post"]
if params.inch:
cmd += ["--inch"]
return cmd
def _extract_val(line: str, key: str) -> float | None:
"""
Extrait la valeur numérique associée à une lettre (key) dans une ligne G-code.
Exemple : _extract_val("G1 X12.5 Y10", "X") -> 12.5
"""
if not line:
return None
# Nettoyage des commentaires
clean_line = line.split('(', 1)[0].split(';', 1)[0].strip()
if not clean_line:
return None
# Recherche basique : on découpe par espaces
# Attention : cela suppose un G-code bien formaté type "X12.3" (collé)
parts = clean_line.upper().split()
key = key.upper()
for p in parts:
if p.startswith(key) and len(p) > len(key):
try:
return float(p[len(key):])
except ValueError:
continue
return None
def filter_by_bounds(gcode: str, params: Hf2GcodeParams) -> str:
"""
delete points out of the robot area :
[robot_x_min + margin ; robot_x_max - margin] x
[robot_y_min + margin ; robot_y_max - margin].
"""
x_min = params.robot_x_min + params.margin
x_max = params.robot_x_max - params.margin
y_min = params.robot_y_min + params.margin
y_max = params.robot_y_max - params.margin
lines = gcode.splitlines()
keep: list[str] = []
for line in lines:
s = line.strip()
# Remove empty line
if not s or s.startswith("("):
keep.append(line)
continue
x = _extract_val(line, "X")
y = _extract_val(line, "Y")
# Out of X
if x is not None and (x < x_min or x > x_max):
continue
# Out of Y
if y is not None and (y < y_min or y > y_max):
continue
keep.append(line)
return "\n".join(keep)
def _extract_z(line: str) -> float | None:
return _extract_val(line, "Z")
def _has_xy(line: str) -> bool:
if not line or line.strip().startswith("("):
return False
upper = line.upper()
return "X" in upper or "Y" in upper
def _is_comment_or_empty(line: str) -> bool:
s = line.strip()
if not s:
return True
if s.startswith("(") and s.endswith(")"):
return True
return False
def optimize_pen_lift(gcode: str) -> str:
"""
Optimization :
1. Remove duplicate
2. Remove useless Z move
"""
lines = gcode.splitlines()
deduplicated_lines = []
last_active_command = None
for line in lines:
stripped = line.strip()
if _is_comment_or_empty(line):
deduplicated_lines.append(line)
continue
if stripped == last_active_command:
continue
else:
deduplicated_lines.append(line)
last_active_command = stripped
lines = deduplicated_lines
keep: list[str] = []
i = 0
while i < len(lines):
line = lines[i]
if _is_comment_or_empty(line):
i += 1
continue
j = i + 1
while j < len(lines) and _is_comment_or_empty(lines[j]):
j += 1
if j >= len(lines):
keep.append(line)
i += 1
continue
current = line.strip()
next_line = lines[j].strip()
z1 = _extract_z(current)
z2 = _extract_z(next_line)
has_xy1 = _has_xy(current)
has_xy2 = _has_xy(next_line)
# Detection useless back and forth Z move
if (
z1 is not None
and z2 is not None
and not has_xy1
and not has_xy2
and abs(z2 + z1) < 1e-6
):
# Jump instruction
i = j + 1
continue
keep.append(line)
i += 1
return "\n".join(keep)
def generate_gcode(text: str, params: Hf2GcodeParams) -> str:
cmd = build_cmd(params)
proc = subprocess.run(
cmd,
input=text,
text=True,
capture_output=True,
check=False,
)
if proc.returncode != 0:
raise RuntimeError(proc.stderr or "hf2gcode returned non-zero")
raw_gcode = proc.stdout
# 2. Filtering
filtered_gcode = filter_by_bounds(raw_gcode, params)
return filtered_gcode