Repository navigation
Expand file tree
/
Copy pathgcode_sender.py
More file actions
407 lines (364 loc) · 16.4 KB
/
Copy pathgcode_sender.py
File metadata and controls
407 lines (364 loc) · 16.4 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
"""
Modulo de envio de G-code a GRBL/FluidNC.
v3.0 - Logging persistente + emergency stop robusto + state locks.
Cambios v3.0 (auditoría 2026-05):
- Reemplazado `except: pass` por logging real (logging_config).
- emergency_stop() reintenta M05 hasta 3 veces (crítico para seguridad física).
- pause/resume/stop loguean falla en lugar de silenciarla.
- on_error callback se invoca cuando los comandos de control fallan.
"""
import threading
import time
import re
from logging_config import get_logger, log_exception
logger = get_logger(__name__)
MACHINE_LIMITS = {
"x_min": -1.0, "x_max": 305.0,
"y_min": -1.0, "y_max": 200.0,
"z_min": -10.0, "z_max": 50.0,
}
Z_OVERRIDE_MIN = -0.20
Z_OVERRIDE_MAX = 0.20
SPINDLE_RPM = 8000
SPINDLE_WARMUP = 3
# Cuántas veces reintentar M05 si falla en emergency stop.
# Cada intento usa send_command(...) que tiene su propio timeout interno.
SPINDLE_STOP_RETRIES = 3
SPINDLE_STOP_RETRY_DELAY = 0.4 # segundos entre intentos
class GcodeSender:
def __init__(self, grbl):
self.grbl = grbl
self.lines = []
self.current_line = 0
self.total_lines = 0
self.running = False
self.paused = False
self.stopping = False
self.z_override = 0.0
self.start_time = None
self.file_path = None
self._thread = None
self._lock = threading.Lock()
self.on_progress = None
self.on_complete = None
self.on_error = None
self.on_line_sent = None
self.on_state_change = None
self.on_disconnect = None
def load_file(self, filepath):
with open(filepath, "r", encoding="utf-8", errors="replace") as f:
raw = f.readlines()
self.lines = []
for line in raw:
s = line.strip()
if s and not s.startswith(";") and not s.startswith("("):
self.lines.append(s)
self.total_lines = len(self.lines)
self.current_line = 0
self.file_path = filepath
return self.total_lines
def validate_gcode_bounds(self):
max_x = max_y = max_z = -float("inf")
min_x = min_y = min_z = float("inf")
for line in self.lines:
u = line.upper()
xm = re.search(r"X([-\d.]+)", u)
ym = re.search(r"Y([-\d.]+)", u)
zm = re.search(r"Z([-\d.]+)", u)
if xm: v = float(xm.group(1)); max_x = max(max_x, v); min_x = min(min_x, v)
if ym: v = float(ym.group(1)); max_y = max(max_y, v); min_y = min(min_y, v)
if zm: v = float(zm.group(1)); max_z = max(max_z, v); min_z = min(min_z, v)
warnings = []
if max_x > MACHINE_LIMITS["x_max"]: warnings.append(f"X max {max_x:.1f} > {MACHINE_LIMITS['x_max']}")
if max_y > MACHINE_LIMITS["y_max"]: warnings.append(f"Y max {max_y:.1f} > {MACHINE_LIMITS['y_max']}")
if min_x < MACHINE_LIMITS["x_min"]: warnings.append(f"X min {min_x:.1f} negativo")
if min_y < MACHINE_LIMITS["y_min"]: warnings.append(f"Y min {min_y:.1f} negativo")
if min_z < MACHINE_LIMITS["z_min"]: warnings.append(f"Z min {min_z:.1f} muy profundo")
if warnings: return False, "\n".join(warnings)
return True, f"OK: X({min_x:.1f}-{max_x:.1f}) Y({min_y:.1f}-{max_y:.1f}) Z({min_z:.2f}-{max_z:.1f})"
def start(self, from_line=0):
if self.running or not self.lines: return False
# Un solo _send_loop vivo: si el anterior sigue cerrando (reconexion,
# timeout), arrancar otro intercalaria dos streams sobre el mismo socket.
th = getattr(self, "_thread", None)
if th is not None and th.is_alive():
logger.warning("start() rechazado: el hilo de envío anterior sigue vivo")
return False
if from_line < 0 or from_line >= self.total_lines: from_line = 0
self.current_line = from_line
self.running = True
self.paused = False
self.stopping = False
self.start_time = time.time()
self._notify_state("running")
self._thread = threading.Thread(target=self._send_loop, daemon=True)
self._thread.start()
return True
def pause(self):
with self._lock:
if self.running and not self.paused:
self.paused = True
else:
return
try:
self.grbl.send_realtime("!")
logger.info("Pause: feed-hold enviado")
except Exception as e:
log_exception(logger, "Pause: send_realtime('!') falló", e)
if self.on_error:
self.on_error(f"Pausa pudo no haber tomado efecto: {e}")
self._notify_state("paused")
def resume(self):
with self._lock:
if self.running and self.paused:
self.paused = False
else:
return
try:
self.grbl.send_realtime("~")
logger.info("Resume: cycle-start enviado")
except Exception as e:
log_exception(logger, "Resume: send_realtime('~') falló", e)
if self.on_error:
self.on_error(f"Reanudar pudo no haber tomado efecto: {e}")
self._notify_state("running")
def stop(self):
with self._lock:
self.stopping = True
self.running = False
self.paused = False
try:
self.grbl.send_realtime("\x18")
logger.info("Stop: soft-reset enviado")
except Exception as e:
log_exception(logger, "Stop: soft-reset falló", e)
time.sleep(0.5)
# IMPORTANTE: garantizar que el spindle se apague.
self._force_spindle_off("stop()")
try:
self.grbl.unlock()
logger.info("Stop: unlock OK")
except Exception as e:
log_exception(logger, "Stop: unlock falló (no crítico)", e, level=20) # INFO
self._notify_state("stopped")
def emergency_stop(self):
"""
Apaga la máquina lo más rápido posible. Crítico para seguridad.
Soft-reset (0x18) interrumpe cualquier movimiento. Luego se INSISTE en
M05 hasta SPINDLE_STOP_RETRIES veces; si ninguna funciona, el callback
on_error recibe una notificación crítica.
En condición normal, soft-reset + M05 deja la máquina segura. Pero si
la red WiFi se cayó simultáneamente, M05 puede fallar y el spindle
sigue girando — situación de RIESGO FÍSICO. Este método le da al
usuario evidencia inequívoca de la falla.
"""
logger.warning("EMERGENCY STOP iniciado")
with self._lock:
self.stopping = True
self.running = False
self.paused = False
try:
self.grbl.send_realtime("\x18")
logger.info("Emergency: soft-reset enviado")
except Exception as e:
log_exception(logger, "Emergency: soft-reset falló", e)
time.sleep(0.3)
# CRÍTICO: spindle DEBE apagarse.
spindle_ok = self._force_spindle_off("emergency_stop()")
try:
self.grbl.unlock()
except Exception as e:
log_exception(logger, "Emergency: unlock falló (no crítico)", e, level=20)
self._notify_state("emergency_stop")
if not spindle_ok and self.on_error:
self.on_error(
"⚠️ PELIGRO: M05 no respondió tras emergency stop. "
"VERIFICA FÍSICAMENTE que el spindle se haya detenido."
)
def _force_spindle_off(self, context: str) -> bool:
"""
Intenta enviar M05 con reintentos. Retorna True si alguno tuvo éxito.
En caso de fallo total, queda registrado en el log con nivel CRITICAL.
"""
for attempt in range(1, SPINDLE_STOP_RETRIES + 1):
try:
self.grbl.send_command("M05")
logger.info("%s: M05 OK (intento %d)", context, attempt)
return True
except Exception as e:
logger.warning("%s: M05 intento %d falló: %s", context, attempt, e)
if attempt < SPINDLE_STOP_RETRIES:
time.sleep(SPINDLE_STOP_RETRY_DELAY)
logger.critical("%s: M05 falló %d veces. SPINDLE PUEDE SEGUIR GIRANDO.",
context, SPINDLE_STOP_RETRIES)
return False
def set_z_override(self, offset_mm):
clamped = max(Z_OVERRIDE_MIN, min(Z_OVERRIDE_MAX, offset_mm))
with self._lock: self.z_override = clamped
return clamped
def get_progress(self):
elapsed = time.time() - self.start_time if self.start_time else 0
remaining = 0
if self.current_line > 0 and elapsed > 0:
rate = self.current_line / elapsed
remaining = (self.total_lines - self.current_line) / rate if rate > 0 else 0
return {"current_line": self.current_line, "total_lines": self.total_lines,
"percent": (self.current_line / self.total_lines * 100) if self.total_lines > 0 else 0,
"elapsed": elapsed, "remaining": remaining,
"running": self.running, "paused": self.paused}
def find_line_near_position(self, target_x, target_y):
best_line, best_dist = 0, float("inf")
for i, line in enumerate(self.lines):
xm = re.search(r"X([-\d.]+)", line.upper())
ym = re.search(r"Y([-\d.]+)", line.upper())
if xm and ym:
dist = (float(xm.group(1)) - target_x)**2 + (float(ym.group(1)) - target_y)**2
if dist < best_dist: best_dist = dist; best_line = i
return best_line
def _send_loop(self):
try:
# Encender spindle
self._log("[SPINDLE] Encendiendo a 8000 RPM...")
self.grbl.send_command(f"M03 S{SPINDLE_RPM}")
time.sleep(SPINDLE_WARMUP)
self._log("[SPINDLE] Listo")
# Si start from line > 0, enviar contexto previo
if self.current_line > 0:
for cmd in self._get_context(self.current_line):
if self.stopping: return
self.grbl.send_command(cmd)
# Loop principal
while self.current_line < self.total_lines and not self.stopping:
while self.paused and not self.stopping:
time.sleep(0.1)
if self.stopping: break
line = self.lines[self.current_line]
# Z override (leer con lock para thread safety)
with self._lock:
zo = self.z_override
if zo != 0:
line = self._apply_z_override(line, zo)
# Forzar spindle RPM en M03
upper = line.upper().strip()
if upper.startswith("M03") or upper.startswith("M3 "):
line = f"M03 S{SPINDLE_RPM}"
# Enviar
try:
resp = self.grbl.send_command(line, timeout=30)
# Si no hubo respuesta (timeout WiFi), reintentar una vez
if not resp:
time.sleep(0.5)
resp = self.grbl.send_command(line, timeout=30)
if any(r.startswith("ALARM:") for r in resp):
logger.error("ALARM detectado en línea %d: %s", self.current_line, resp)
self._force_spindle_off("ALARM handler")
if self.on_error: self.on_error(f"ALARM linea {self.current_line}")
self.running = False
self._notify_state("error")
return
# error:N del firmware: la linea NO se ejecuto (feed indefinido,
# G-code no soportado, maquina en Alarm...). Seguir mandando
# saltaria movimientos en silencio: se pausa y se avisa.
errs = [r for r in resp if r.startswith("error:")]
if errs:
logger.error("Firmware rechazó la línea %d (%r): %s",
self.current_line, line, errs)
self._log(f"Línea {self.current_line} rechazada por el firmware: {errs[0]}. Envío en pausa.")
self.paused = True
try:
self.grbl.send_realtime("!")
except Exception as e_h:
log_exception(logger, "Feed-hold tras error: falló", e_h)
self._notify_state("paused")
if self.on_error:
self.on_error(f"{errs[0]} en línea {self.current_line}: {line.strip()}")
continue
except Exception as e:
# Intentar reconectar
self._log(f"Error en linea {self.current_line}: {e}")
if self._try_reconnect():
self.grbl.send_command(f"M03 S{SPINDLE_RPM}")
time.sleep(SPINDLE_WARMUP)
continue
else:
if self.on_error: self.on_error(f"Desconexion linea {self.current_line}")
self.running = False
self._notify_state("error")
return
self.current_line += 1
if self.on_progress and self.current_line % 10 == 0:
pos = self._extract_position(line)
self.on_progress(self.current_line, self.total_lines, *pos)
if not self.stopping:
self._force_spindle_off("job complete")
self.running = False
self._notify_state("complete")
if self.on_complete: self.on_complete()
except Exception as e:
log_exception(logger, "Excepción en _send_loop", e)
self.running = False
self._force_spindle_off("_send_loop exception handler")
if self.on_error: self.on_error(str(e))
self._notify_state("error")
def _get_context(self, line_num):
"""
Contexto modal para arrancar desde la linea N: unidades, absoluto, el
ultimo feed visto y el ultimo modo de movimiento (G00/G01). Sin el F,
el firmware responde error:22 en cada G01 sin feed y esas lineas se
perderian.
"""
last_f = None
last_motion = None
for i in range(min(line_num, len(self.lines))):
up = self.lines[i].upper()
fm = re.search(r"F([\d.]+)", up)
if fm: last_f = float(fm.group(1))
gm = re.search(r"\bG0?([01])\b", up)
if gm: last_motion = gm.group(1)
setup = ["G21", "G90"]
if last_f:
setup.append(f"G01 F{last_f:g}")
if last_motion == "0":
setup.append("G00")
return setup
def _apply_z_override(self, line, override=None):
zm = re.search(r"Z([-\d.]+)", line.upper())
if zm:
z_val = float(zm.group(1))
if z_val < 0:
zo = override if override is not None else self.z_override
new_z = max(z_val + zo, MACHINE_LIMITS["z_min"])
line = re.sub(r"[Zz][-\d.]+", f"Z{new_z:.4f}", line)
return line
def _extract_position(self, line):
x = y = z = 0
xm = re.search(r"X([-\d.]+)", line.upper())
ym = re.search(r"Y([-\d.]+)", line.upper())
zm = re.search(r"Z([-\d.]+)", line.upper())
if xm: x = float(xm.group(1))
if ym: y = float(ym.group(1))
if zm: z = float(zm.group(1))
return x, y, z
def _try_reconnect(self, max_retries=3):
for attempt in range(max_retries):
try:
time.sleep(2)
self.grbl.disconnect()
time.sleep(1)
self.grbl.connect()
self._log(f"Reconectado (intento {attempt+1})")
logger.info("Reconectado en intento %d", attempt + 1)
return True
except Exception as e:
logger.warning("Reconexión intento %d falló: %s", attempt + 1, e)
continue
logger.error("Reconexión falló después de %d intentos", max_retries)
return False
def _log(self, msg):
# Mensaje a la UI (callback) y al logger persistente
logger.info(msg)
if self.on_line_sent:
self.on_line_sent(-1, msg, "ok")
def _notify_state(self, state):
logger.debug("State change: %s", state)
if self.on_state_change: self.on_state_change(state)