BlueGit

timfa timdraw

feat: papier en joggrens laten kloppen met de Bachin

Home is niet de papierrand, en GRBL meldt meestal alleen de machinecoördinaat, waardoor de jog te vroeg stopte of voorbij de rand liep. Een virtuele machine in de testsuite legt dat vast.

timfa Tim Falken · pushed by timfa

Authored 2026-09-29 · 7 weeks ago

Hash
4a0b37afa9fbbcb16e1739215220e1c923cd2589
Parent
a8167ec4
8 files changed +626 −69
static/app.js +45 −3
@@ -1,5 +1,8 @@
1 const PAPER_LEFT = -10;
2 const PAPER_TOP = 4;
3 const PAPER_BOTTOM = -307;
1 4 const A4W = 210;
2 const A4H = 297;
5 const A4H = 311;
3 6 const PEN_MM = 0.4;
4 7
5 8 const $ = (id) => document.getElementById(id);
@@ -19,6 +22,7 @@ let filling = false;
19 22 let textTimer = 0;
20 23 let userDisconnected = false;
21 24 let autoTried = "";
25 let pen = null;
22 26 const PORT_KEY = "timdraw-port";
23 27
24 28 const defaults = {
@@ -211,6 +215,13 @@ function drawSheet (view)
211 215 ctx.fillRect(x + 8, y + 10, w, h);
212 216 ctx.fillStyle = "#f6f1e6";
213 217 ctx.fillRect(x, y, w, h);
218 ctx.fillStyle = "rgba(70, 52, 36, 0.16)";
219 const reachLeft = -PAPER_LEFT;
220 const reachTop = A4H - PAPER_TOP;
221 const reachBottom = -PAPER_BOTTOM - 297;
222 fillMmRect(0, 0, reachLeft, A4H);
223 fillMmRect(reachLeft, reachTop, A4W, A4H);
224 fillMmRect(reachLeft, 0, A4W, reachBottom);
214 225 ctx.strokeStyle = "rgba(80,60,40,0.18)";
215 226 ctx.lineWidth = 1;
216 227 ctx.beginPath();
@@ -235,11 +246,19 @@ function drawSheet (view)
235 246 ctx.fillStyle = "#8a7b6c";
236 247 ctx.font = "12px Liberation Sans, sans-serif";
237 248 const originTop = $("origin").value === "top-left";
238 ctx.fillText("0,0", x + 6, originTop ? y + 16 : y + h - 8);
239 ctx.fillText("A4", x + w - 26, originTop ? y + h - 8 : y + 16);
249 const zero = originTop ? mmToPx(reachLeft, reachTop) : mmToPx(0, 0);
250 ctx.fillText("0,0", zero[0] + 6, zero[1] + (originTop ? 16 : -8));
251 ctx.fillText("A4", x + w - 26, y + h - 8);
240 252 ctx.restore();
241 253 }
242 254
255 function fillMmRect (x0, y0, x1, y1)
256 {
257 const a = mmToPx(x0, y0);
258 const b = mmToPx(x1, y1);
259 ctx.fillRect(Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]));
260 }
261
243 262 function tracePoly (points)
244 263 {
245 264 if (!points.length) return;
@@ -337,6 +356,23 @@ function drawHandles (obj)
337 356 ctx.restore();
338 357 }
339 358
359 function pageFromMachine (x, y)
360 {
361 return { x: x - PAPER_LEFT, y: y - PAPER_BOTTOM };
362 }
363
364 function drawPen ()
365 {
366 if (!pen) return;
367 const point = mmToPx(pen.x, pen.y);
368 ctx.save();
369 ctx.fillStyle = "#d7263d";
370 ctx.beginPath();
371 ctx.arc(point[0], point[1], 5, 0, Math.PI * 2);
372 ctx.fill();
373 ctx.restore();
374 }
375
340 376 function draw ()
341 377 {
342 378 const view = layout();
@@ -346,6 +382,7 @@ function draw ()
346 382 if (preview && !interacting) drawPreview();
347 383 else objects.forEach((obj) => drawObject(obj, obj === current));
348 384 if (current) drawHandles(current);
385 drawPen();
349 386 }
350 387
351 388 const SETTINGS_KEY = "timdraw-settings";
@@ -1049,6 +1086,11 @@ function paintStatus (status)
1049 1086 }
1050 1087 const progress = status.jobActive ? (status.progress || 0) : (status.progress === 1 ? 1 : 0);
1051 1088 $("bar").style.width = `${Math.round((progress || 0) * 100)}%`;
1089 const nextPen = status.jobActive && status.wpos ? pageFromMachine(status.wpos[0], status.wpos[1]) : null;
1090 const penSame = (!pen && !nextPen)
1091 || (pen && nextPen && Math.abs(pen.x - nextPen.x) < 0.05 && Math.abs(pen.y - nextPen.y) < 0.05);
1092 pen = nextPen;
1093 if (!penSame && !drag) draw();
1052 1094 if (status.message && status.jobActive) toast(status.message);
1053 1095 }
1054 1096
@@ -1,5 +1,8 @@
1const PAPER_LEFT = -10;
2const PAPER_TOP = 4;
3const PAPER_BOTTOM = -307;
1const A4W = 210;
4const A4W = 210;
2const A4H = 297;
5const A4H = 311;
3const PEN_MM = 0.4;
6const PEN_MM = 0.4;
4
7
5const $ = (id) => document.getElementById(id);
8const $ = (id) => document.getElementById(id);
@@ -19,6 +22,7 @@ let filling = false;
19let textTimer = 0;
22let textTimer = 0;
20let userDisconnected = false;
23let userDisconnected = false;
21let autoTried = "";
24let autoTried = "";
25let pen = null;
22const PORT_KEY = "timdraw-port";
26const PORT_KEY = "timdraw-port";
23
27
24const defaults = {
28const defaults = {
@@ -211,6 +215,13 @@ function drawSheet (view)
211 ctx.fillRect(x + 8, y + 10, w, h);
215 ctx.fillRect(x + 8, y + 10, w, h);
212 ctx.fillStyle = "#f6f1e6";
216 ctx.fillStyle = "#f6f1e6";
213 ctx.fillRect(x, y, w, h);
217 ctx.fillRect(x, y, w, h);
218 ctx.fillStyle = "rgba(70, 52, 36, 0.16)";
219 const reachLeft = -PAPER_LEFT;
220 const reachTop = A4H - PAPER_TOP;
221 const reachBottom = -PAPER_BOTTOM - 297;
222 fillMmRect(0, 0, reachLeft, A4H);
223 fillMmRect(reachLeft, reachTop, A4W, A4H);
224 fillMmRect(reachLeft, 0, A4W, reachBottom);
214 ctx.strokeStyle = "rgba(80,60,40,0.18)";
225 ctx.strokeStyle = "rgba(80,60,40,0.18)";
215 ctx.lineWidth = 1;
226 ctx.lineWidth = 1;
216 ctx.beginPath();
227 ctx.beginPath();
@@ -235,11 +246,19 @@ function drawSheet (view)
235 ctx.fillStyle = "#8a7b6c";
246 ctx.fillStyle = "#8a7b6c";
236 ctx.font = "12px Liberation Sans, sans-serif";
247 ctx.font = "12px Liberation Sans, sans-serif";
237 const originTop = $("origin").value === "top-left";
248 const originTop = $("origin").value === "top-left";
238 ctx.fillText("0,0", x + 6, originTop ? y + 16 : y + h - 8);
249 const zero = originTop ? mmToPx(reachLeft, reachTop) : mmToPx(0, 0);
239 ctx.fillText("A4", x + w - 26, originTop ? y + h - 8 : y + 16);
250 ctx.fillText("0,0", zero[0] + 6, zero[1] + (originTop ? 16 : -8));
251 ctx.fillText("A4", x + w - 26, y + h - 8);
240 ctx.restore();
252 ctx.restore();
241}
253}
242
254
255function fillMmRect (x0, y0, x1, y1)
256{
257 const a = mmToPx(x0, y0);
258 const b = mmToPx(x1, y1);
259 ctx.fillRect(Math.min(a[0], b[0]), Math.min(a[1], b[1]), Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]));
260}
261
243function tracePoly (points)
262function tracePoly (points)
244{
263{
245 if (!points.length) return;
264 if (!points.length) return;
@@ -337,6 +356,23 @@ function drawHandles (obj)
337 ctx.restore();
356 ctx.restore();
338}
357}
339
358
359function pageFromMachine (x, y)
360{
361 return { x: x - PAPER_LEFT, y: y - PAPER_BOTTOM };
362}
363
364function drawPen ()
365{
366 if (!pen) return;
367 const point = mmToPx(pen.x, pen.y);
368 ctx.save();
369 ctx.fillStyle = "#d7263d";
370 ctx.beginPath();
371 ctx.arc(point[0], point[1], 5, 0, Math.PI * 2);
372 ctx.fill();
373 ctx.restore();
374}
375
340function draw ()
376function draw ()
341{
377{
342 const view = layout();
378 const view = layout();
@@ -346,6 +382,7 @@ function draw ()
346 if (preview && !interacting) drawPreview();
382 if (preview && !interacting) drawPreview();
347 else objects.forEach((obj) => drawObject(obj, obj === current));
383 else objects.forEach((obj) => drawObject(obj, obj === current));
348 if (current) drawHandles(current);
384 if (current) drawHandles(current);
385 drawPen();
349}
386}
350
387
351const SETTINGS_KEY = "timdraw-settings";
388const SETTINGS_KEY = "timdraw-settings";
@@ -1049,6 +1086,11 @@ function paintStatus (status)
1049 }
1086 }
1050 const progress = status.jobActive ? (status.progress || 0) : (status.progress === 1 ? 1 : 0);
1087 const progress = status.jobActive ? (status.progress || 0) : (status.progress === 1 ? 1 : 0);
1051 $("bar").style.width = `${Math.round((progress || 0) * 100)}%`;
1088 $("bar").style.width = `${Math.round((progress || 0) * 100)}%`;
1089 const nextPen = status.jobActive && status.wpos ? pageFromMachine(status.wpos[0], status.wpos[1]) : null;
1090 const penSame = (!pen && !nextPen)
1091 || (pen && nextPen && Math.abs(pen.x - nextPen.x) < 0.05 && Math.abs(pen.y - nextPen.y) < 0.05);
1092 pen = nextPen;
1093 if (!penSame && !drag) draw();
1052 if (status.message && status.jobActive) toast(status.message);
1094 if (status.message && status.jobActive) toast(status.message);
1053}
1095}
1054
1096
static/index.html +25 −25
@@ -160,31 +160,6 @@
160 160 <button id="btn-home" type="button">Home</button>
161 161 <button id="btn-release" type="button">Assen los</button>
162 162 </div>
163 <div class="split">
164 <label class="field">Tekensnelheid
165 <input id="draw-speed" type="number" min="50" max="6000" step="50" value="3000">
166 </label>
167 <label class="field">Verplaatsing
168 <input id="travel-speed" type="number" min="50" max="6000" step="50" value="5000">
169 </label>
170 </div>
171 <div class="split">
172 <label class="field">Pen omhoog Z
173 <input id="pen-up" type="number" min="0" max="12" step="0.1" value="0">
174 </label>
175 <label class="field">Pen omlaag Z
176 <input id="pen-down" type="number" min="0" max="12" step="0.1" value="5">
177 </label>
178 </div>
179 <label class="field">Pauze na pen ms
180 <input id="dwell" type="number" min="0" max="2000" step="10" value="120">
181 </label>
182 <label class="field">Nulpunt
183 <select id="origin">
184 <option value="top-left" selected>Linksboven</option>
185 <option value="bottom-left">Linksonder</option>
186 </select>
187 </label>
188 163 <p id="stats" class="hint"></p>
189 164 <div class="progress">
190 165 <div id="bar"></div>
@@ -202,6 +177,31 @@
202 177 </label>
203 178 <button id="btn-connect" type="button" class="primary">Verbinden</button>
204 179 </div>
180 <div class="split">
181 <label class="field">Tekensnelheid
182 <input id="draw-speed" type="number" min="50" max="6000" step="50" value="3000">
183 </label>
184 <label class="field">Verplaatsing
185 <input id="travel-speed" type="number" min="50" max="6000" step="50" value="5000">
186 </label>
187 </div>
188 <div class="split">
189 <label class="field">Pen omhoog Z
190 <input id="pen-up" type="number" min="0" max="12" step="0.1" value="0">
191 </label>
192 <label class="field">Pen omlaag Z
193 <input id="pen-down" type="number" min="0" max="12" step="0.1" value="5">
194 </label>
195 </div>
196 <label class="field">Pauze na pen ms
197 <input id="dwell" type="number" min="0" max="2000" step="10" value="120">
198 </label>
199 <label class="field">Nulpunt
200 <select id="origin">
201 <option value="top-left" selected>Linksboven</option>
202 <option value="bottom-left">Linksonder</option>
203 </select>
204 </label>
205 205 <div class="row">
206 206 <button id="connect-close" type="button">Sluiten</button>
207 207 </div>
@@ -160,31 +160,6 @@
160 <button id="btn-home" type="button">Home</button>
160 <button id="btn-home" type="button">Home</button>
161 <button id="btn-release" type="button">Assen los</button>
161 <button id="btn-release" type="button">Assen los</button>
162 </div>
162 </div>
163 <div class="split">
164 <label class="field">Tekensnelheid
165 <input id="draw-speed" type="number" min="50" max="6000" step="50" value="3000">
166 </label>
167 <label class="field">Verplaatsing
168 <input id="travel-speed" type="number" min="50" max="6000" step="50" value="5000">
169 </label>
170 </div>
171 <div class="split">
172 <label class="field">Pen omhoog Z
173 <input id="pen-up" type="number" min="0" max="12" step="0.1" value="0">
174 </label>
175 <label class="field">Pen omlaag Z
176 <input id="pen-down" type="number" min="0" max="12" step="0.1" value="5">
177 </label>
178 </div>
179 <label class="field">Pauze na pen ms
180 <input id="dwell" type="number" min="0" max="2000" step="10" value="120">
181 </label>
182 <label class="field">Nulpunt
183 <select id="origin">
184 <option value="top-left" selected>Linksboven</option>
185 <option value="bottom-left">Linksonder</option>
186 </select>
187 </label>
188 <p id="stats" class="hint"></p>
163 <p id="stats" class="hint"></p>
189 <div class="progress">
164 <div class="progress">
190 <div id="bar"></div>
165 <div id="bar"></div>
@@ -202,6 +177,31 @@
202 </label>
177 </label>
203 <button id="btn-connect" type="button" class="primary">Verbinden</button>
178 <button id="btn-connect" type="button" class="primary">Verbinden</button>
204 </div>
179 </div>
180 <div class="split">
181 <label class="field">Tekensnelheid
182 <input id="draw-speed" type="number" min="50" max="6000" step="50" value="3000">
183 </label>
184 <label class="field">Verplaatsing
185 <input id="travel-speed" type="number" min="50" max="6000" step="50" value="5000">
186 </label>
187 </div>
188 <div class="split">
189 <label class="field">Pen omhoog Z
190 <input id="pen-up" type="number" min="0" max="12" step="0.1" value="0">
191 </label>
192 <label class="field">Pen omlaag Z
193 <input id="pen-down" type="number" min="0" max="12" step="0.1" value="5">
194 </label>
195 </div>
196 <label class="field">Pauze na pen ms
197 <input id="dwell" type="number" min="0" max="2000" step="10" value="120">
198 </label>
199 <label class="field">Nulpunt
200 <select id="origin">
201 <option value="top-left" selected>Linksboven</option>
202 <option value="bottom-left">Linksonder</option>
203 </select>
204 </label>
205 <div class="row">
205 <div class="row">
206 <button id="connect-close" type="button">Sluiten</button>
206 <button id="connect-close" type="button">Sluiten</button>
207 </div>
207 </div>
static/style.css +3 −1
@@ -131,7 +131,9 @@ header {
131 131 border: 1px solid var(--line);
132 132 border-radius: 12px;
133 133 padding: 1rem 1.1rem 1.15rem;
134 width: min(24rem, calc(100vw - 2rem));
134 width: min(28rem, calc(100vw - 2rem));
135 max-height: calc(100vh - 2rem);
136 overflow: auto;
135 137 }
136 138
137 139 .connect-modal::backdrop {
@@ -131,7 +131,9 @@ header {
131 border: 1px solid var(--line);
131 border: 1px solid var(--line);
132 border-radius: 12px;
132 border-radius: 12px;
133 padding: 1rem 1.1rem 1.15rem;
133 padding: 1rem 1.1rem 1.15rem;
134 width: min(24rem, calc(100vw - 2rem));
134 width: min(28rem, calc(100vw - 2rem));
135 max-height: calc(100vh - 2rem);
136 overflow: auto;
135}
137}
136
138
137.connect-modal::backdrop {
139.connect-modal::backdrop {
timdraw/gcode.py +22 −8
@@ -5,6 +5,9 @@ from __future__ import annotations
5 5 from timdraw.geom import (
6 6 A4_H,
7 7 A4_W,
8 PAPER_BOTTOM,
9 PAPER_LEFT,
10 PAPER_TOP,
8 11 Point,
9 12 Polyline,
10 13 dedupe,
@@ -35,15 +38,15 @@ BED_H = 297.0
35 38
36 39
37 40 def _page_point(x: float, y: float, origin_top: bool) -> Point:
38 # Editor-Y loopt omhoog vanaf de onderkant. Na homing is (0, 0) linksboven.
39 # Machine-Y positief is omhoog, voorbij die hoek. Het blad ligt daarom in
40 # negatieve Y, tot -297 mm.
41 machine_y = (y - A4_H) if origin_top else y
42 if abs(x) < 1e-9:
43 x = 0.0
41 # Paginacoördinaten: oorsprong linksonder op het papier, Y omhoog.
42 # Home (0, 0) ligt 10 mm rechts van de linkerrand en 4 mm onder de bovenrand.
43 machine_x = x + PAPER_LEFT
44 machine_y = (y - A4_H + PAPER_TOP) if origin_top else (y + PAPER_BOTTOM)
45 if abs(machine_x) < 1e-9:
46 machine_x = 0.0
44 47 if abs(machine_y) < 1e-9:
45 48 machine_y = 0.0
46 return x, machine_y
49 return machine_x, machine_y
47 50
48 51
49 52 def _orient(pts: Polyline, pos: Point) -> tuple[Polyline, float]:
@@ -227,7 +230,8 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:
227 230
228 231 # Dubbele waarschuwing maar één keer.
229 232 warnings = list(dict.fromkeys(warnings))
230 start = (0.0, A4_H if origin_top else 0.0)
233 # Start bij home, niet op de papierrand: die ligt buiten het bereik.
234 start = ((-PAPER_LEFT, A4_H - PAPER_TOP) if origin_top else (0.0, 0.0))
231 235 draw: list[Polyline] = []
232 236 pos = start
233 237 if per_object:
@@ -241,6 +245,16 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:
241 245 else:
242 246 flat = [pts for group in groups for pts in group if length_of(pts) >= 0.15]
243 247 draw = _order_paths(flat, start)
248 outside_paper = False
249 for pts in draw:
250 for x, y in pts:
251 if x < -0.2 or y < -0.2 or x > A4_W + 0.2 or y > A4_H + 0.2:
252 outside_paper = True
253 break
254 if outside_paper:
255 break
256 if outside_paper:
257 warnings.append("Een deel valt buiten het papier.")
244 258 travel: list[Polyline] = []
245 259 gcode = ["; Timdraw", "G21", "G90", "G94"]
246 260 pen_down_state = True
@@ -5,6 +5,9 @@ from __future__ import annotations
5from timdraw.geom import (
5from timdraw.geom import (
6 A4_H,
6 A4_H,
7 A4_W,
7 A4_W,
8 PAPER_BOTTOM,
9 PAPER_LEFT,
10 PAPER_TOP,
8 Point,
11 Point,
9 Polyline,
12 Polyline,
10 dedupe,
13 dedupe,
@@ -35,15 +38,15 @@ BED_H = 297.0
35
38
36
39
37def _page_point(x: float, y: float, origin_top: bool) -> Point:
40def _page_point(x: float, y: float, origin_top: bool) -> Point:
38 # Editor-Y loopt omhoog vanaf de onderkant. Na homing is (0, 0) linksboven.
41 # Paginacoördinaten: oorsprong linksonder op het papier, Y omhoog.
39 # Machine-Y positief is omhoog, voorbij die hoek. Het blad ligt daarom in
42 # Home (0, 0) ligt 10 mm rechts van de linkerrand en 4 mm onder de bovenrand.
40 # negatieve Y, tot -297 mm.
43 machine_x = x + PAPER_LEFT
41 machine_y = (y - A4_H) if origin_top else y
44 machine_y = (y - A4_H + PAPER_TOP) if origin_top else (y + PAPER_BOTTOM)
42 if abs(x) < 1e-9:
45 if abs(machine_x) < 1e-9:
43 x = 0.0
46 machine_x = 0.0
44 if abs(machine_y) < 1e-9:
47 if abs(machine_y) < 1e-9:
45 machine_y = 0.0
48 machine_y = 0.0
46 return x, machine_y
49 return machine_x, machine_y
47
50
48
51
49def _orient(pts: Polyline, pos: Point) -> tuple[Polyline, float]:
52def _orient(pts: Polyline, pos: Point) -> tuple[Polyline, float]:
@@ -227,7 +230,8 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:
227
230
228 # Dubbele waarschuwing maar één keer.
231 # Dubbele waarschuwing maar één keer.
229 warnings = list(dict.fromkeys(warnings))
232 warnings = list(dict.fromkeys(warnings))
230 start = (0.0, A4_H if origin_top else 0.0)
233 # Start bij home, niet op de papierrand: die ligt buiten het bereik.
234 start = ((-PAPER_LEFT, A4_H - PAPER_TOP) if origin_top else (0.0, 0.0))
231 draw: list[Polyline] = []
235 draw: list[Polyline] = []
232 pos = start
236 pos = start
233 if per_object:
237 if per_object:
@@ -241,6 +245,16 @@ def plan(objects: list[dict], settings: dict | None = None) -> dict:
241 else:
245 else:
242 flat = [pts for group in groups for pts in group if length_of(pts) >= 0.15]
246 flat = [pts for group in groups for pts in group if length_of(pts) >= 0.15]
243 draw = _order_paths(flat, start)
247 draw = _order_paths(flat, start)
248 outside_paper = False
249 for pts in draw:
250 for x, y in pts:
251 if x < -0.2 or y < -0.2 or x > A4_W + 0.2 or y > A4_H + 0.2:
252 outside_paper = True
253 break
254 if outside_paper:
255 break
256 if outside_paper:
257 warnings.append("Een deel valt buiten het papier.")
244 travel: list[Polyline] = []
258 travel: list[Polyline] = []
245 gcode = ["; Timdraw", "G21", "G90", "G94"]
259 gcode = ["; Timdraw", "G21", "G90", "G94"]
246 pen_down_state = True
260 pen_down_state = True
timdraw/geom.py +42 −3
@@ -7,8 +7,15 @@ import math
7 7 Point = tuple[float, float]
8 8 Polyline = list[Point]
9 9
10 A4_W = 210.0
11 A4_H = 297.0
10 # Fysiek papier t.o.v. machinehome. Y omhoog is positief.
11 # De linkerrand ligt 10 mm links van X=0, de bovenrand 4 mm boven Y=0.
12 # X=200 valt op de rechterrand. Y=-297 valt 10 mm boven de onderrand.
13 PAPER_LEFT = -10.0
14 PAPER_TOP = 4.0
15 PAPER_RIGHT = 200.0
16 PAPER_BOTTOM = -307.0
17 A4_W = PAPER_RIGHT - PAPER_LEFT
18 A4_H = PAPER_TOP - PAPER_BOTTOM
12 19
13 20
14 21 def dist(a: Point, b: Point) -> float:
@@ -196,6 +203,34 @@ def _circle(a: Point, b: Point, c: Point) -> tuple[float, float, float] | None:
196 203 return ux, uy, math.hypot(ax - ux, ay - uy)
197 204
198 205
206 def _mm(value: float) -> float:
207 return float(f"{value:.3f}")
208
209
210 def grbl_arc_ok(start: Point, end: Point, i_off: float, j_off: float) -> bool:
211 """True als GRBL deze boog accepteert, na afronden op 0,001 mm.
212
213 Error 33 volgt als de afstand van het eindpunt tot het middelpunt te ver
214 afwijkt van de beginstraal. GRBL rekent in float32, dus de marge ligt
215 onder de grens van 0,005 mm.
216 """
217 sx, sy = _mm(start[0]), _mm(start[1])
218 ex, ey = _mm(end[0]), _mm(end[1])
219 i_off, j_off = _mm(i_off), _mm(j_off)
220 if (ex, ey) == (sx, sy):
221 return False
222 radius = math.hypot(i_off, j_off)
223 if radius < 0.4:
224 return False
225 target = math.hypot(ex - (sx + i_off), ey - (sy + j_off))
226 delta = abs(target - radius)
227 if delta > 0.003:
228 return False
229 if delta > 0.0008 * radius:
230 return False
231 return True
232
233
199 234 def _try_arc(pts: Polyline, tol: float) -> tuple[str, float, float, float, float] | None:
200 235 """Eén cirkelboog als alle punten erop liggen. G2 is met de klok mee."""
201 236 if len(pts) < 3:
@@ -229,8 +264,12 @@ def _try_arc(pts: Polyline, tol: float) -> tuple[str, float, float, float, float
229 264 sweep += step
230 265 if abs(sweep) < 0.08 or abs(sweep) > 5.5:
231 266 return None
267 sx, sy = _mm(pts[0][0]), _mm(pts[0][1])
268 i_off, j_off = cx - sx, cy - sy
269 if not grbl_arc_ok((sx, sy), pts[-1], i_off, j_off):
270 return None
232 271 code = "G3" if sweep > 0 else "G2"
233 return code, pts[-1][0], pts[-1][1], cx - pts[0][0], cy - pts[0][1]
272 return code, pts[-1][0], pts[-1][1], i_off, j_off
234 273
235 274
236 275 def fit_arcs(pts: Polyline, tol: float = 0.08) -> list[tuple[str, float, float, float, float]]:
@@ -7,8 +7,15 @@ import math
7Point = tuple[float, float]
7Point = tuple[float, float]
8Polyline = list[Point]
8Polyline = list[Point]
9
9
10A4_W = 210.0
10# Fysiek papier t.o.v. machinehome. Y omhoog is positief.
11A4_H = 297.0
11# De linkerrand ligt 10 mm links van X=0, de bovenrand 4 mm boven Y=0.
12# X=200 valt op de rechterrand. Y=-297 valt 10 mm boven de onderrand.
13PAPER_LEFT = -10.0
14PAPER_TOP = 4.0
15PAPER_RIGHT = 200.0
16PAPER_BOTTOM = -307.0
17A4_W = PAPER_RIGHT - PAPER_LEFT
18A4_H = PAPER_TOP - PAPER_BOTTOM
12
19
13
20
14def dist(a: Point, b: Point) -> float:
21def dist(a: Point, b: Point) -> float:
@@ -196,6 +203,34 @@ def _circle(a: Point, b: Point, c: Point) -> tuple[float, float, float] | None:
196 return ux, uy, math.hypot(ax - ux, ay - uy)
203 return ux, uy, math.hypot(ax - ux, ay - uy)
197
204
198
205
206def _mm(value: float) -> float:
207 return float(f"{value:.3f}")
208
209
210def grbl_arc_ok(start: Point, end: Point, i_off: float, j_off: float) -> bool:
211 """True als GRBL deze boog accepteert, na afronden op 0,001 mm.
212
213 Error 33 volgt als de afstand van het eindpunt tot het middelpunt te ver
214 afwijkt van de beginstraal. GRBL rekent in float32, dus de marge ligt
215 onder de grens van 0,005 mm.
216 """
217 sx, sy = _mm(start[0]), _mm(start[1])
218 ex, ey = _mm(end[0]), _mm(end[1])
219 i_off, j_off = _mm(i_off), _mm(j_off)
220 if (ex, ey) == (sx, sy):
221 return False
222 radius = math.hypot(i_off, j_off)
223 if radius < 0.4:
224 return False
225 target = math.hypot(ex - (sx + i_off), ey - (sy + j_off))
226 delta = abs(target - radius)
227 if delta > 0.003:
228 return False
229 if delta > 0.0008 * radius:
230 return False
231 return True
232
233
199def _try_arc(pts: Polyline, tol: float) -> tuple[str, float, float, float, float] | None:
234def _try_arc(pts: Polyline, tol: float) -> tuple[str, float, float, float, float] | None:
200 """Eén cirkelboog als alle punten erop liggen. G2 is met de klok mee."""
235 """Eén cirkelboog als alle punten erop liggen. G2 is met de klok mee."""
201 if len(pts) < 3:
236 if len(pts) < 3:
@@ -229,8 +264,12 @@ def _try_arc(pts: Polyline, tol: float) -> tuple[str, float, float, float, float
229 sweep += step
264 sweep += step
230 if abs(sweep) < 0.08 or abs(sweep) > 5.5:
265 if abs(sweep) < 0.08 or abs(sweep) > 5.5:
231 return None
266 return None
267 sx, sy = _mm(pts[0][0]), _mm(pts[0][1])
268 i_off, j_off = cx - sx, cy - sy
269 if not grbl_arc_ok((sx, sy), pts[-1], i_off, j_off):
270 return None
232 code = "G3" if sweep > 0 else "G2"
271 code = "G3" if sweep > 0 else "G2"
233 return code, pts[-1][0], pts[-1][1], cx - pts[0][0], cy - pts[0][1]
272 return code, pts[-1][0], pts[-1][1], i_off, j_off
234
273
235
274
236def fit_arcs(pts: Polyline, tol: float = 0.08) -> list[tuple[str, float, float, float, float]]:
275def fit_arcs(pts: Polyline, tol: float = 0.08) -> list[tuple[str, float, float, float, float]]:
timdraw/grbl.py +93 −15
@@ -6,6 +6,7 @@ import glob
6 6 import json
7 7 import math
8 8 import os
9 import re
9 10 import threading
10 11 import time
11 12 from pathlib import Path
@@ -24,6 +25,17 @@ except ImportError: # pragma: no cover
24 25 _STATE = Path.home() / ".config" / "timdraw" / "last-device.json"
25 26
26 27
28 def chord_for_arc(line: str) -> str:
29 """Rechte lijn naar hetzelfde eindpunt, als GRBL een boog met error 33 weigert."""
30 words = dict(re.findall(r"([XYF])([+-]?(?:\d+\.\d*|\.\d+|\d+))", line))
31 if "X" not in words or "Y" not in words:
32 raise RuntimeError("error:33")
33 chord = f"G1 X{words['X']} Y{words['Y']}"
34 if "F" in words:
35 chord += f" F{words['F']}"
36 return chord
37
38
27 39 def _mm(value: float) -> str:
28 40 rounded = round(value)
29 41 if abs(value - rounded) < 0.05:
@@ -47,6 +59,22 @@ def limit_step(
47 59 return adx, ady, None
48 60
49 61
62 def resolve_work_position(
63 mpos: list[float] | None,
64 wpos: list[float] | None,
65 wco: list[float] | None,
66 remembered_wco: list[float] | None,
67 ) -> tuple[list[float] | None, list[float] | None]:
68 """Werkpositie uit een statusregel. GRBL stuurt WCO maar af en toe mee."""
69 if wco is not None:
70 remembered_wco = wco
71 if wpos is not None:
72 return wpos, remembered_wco
73 if mpos is not None and remembered_wco is not None:
74 return [mpos[i] - remembered_wco[i] for i in range(3)], remembered_wco
75 return None, remembered_wco
76
77
50 78 def list_ports() -> list[str]:
51 79 by_id = sorted(glob.glob("/dev/serial/by-id/*"))
52 80 if by_id:
@@ -98,6 +126,7 @@ class Machine:
98 126 self._ack_event = threading.Event()
99 127 self._stop = threading.Event()
100 128 self._pause = threading.Event()
129 self._arc_fallbacks = 0
101 130 self.connected = False
102 131 self.connecting = False
103 132 self.auto_enabled = True
@@ -110,6 +139,9 @@ class Machine:
110 139 self.state = "disconnected"
111 140 self.wpos = [0.0, 0.0, 0.0]
112 141 self.mpos = [0.0, 0.0, 0.0]
142 self._wco: list[float] | None = None
143 self._track_xy: tuple[float, float] | None = None
144 self._track_until = 0.0
113 145 self.message = "Niet verbonden"
114 146 self.error = ""
115 147 self.progress = 0.0
@@ -270,6 +302,24 @@ class Machine:
270 302 if reader is not None and reader.is_alive() and threading.current_thread() is not reader:
271 303 reader.join(timeout=1)
272 304
305 def attach(self, port) -> None:
306 """Koppel een al open poort. De testsuite gebruikt dit voor de virtuele machine."""
307 self.disconnect()
308 self._ser = port
309 self.port = "virtual"
310 self.connected = True
311 self.auto_enabled = False
312 self.error = ""
313 self.message = "Verbinden…"
314 self._stop.clear()
315 self._reader = threading.Thread(target=self._read_loop, daemon=True)
316 self._reader.start()
317 self._command("$I", timeout=2)
318 self._command("$$", timeout=2)
319 self._hold_motors()
320 self._query()
321 time.sleep(0.05)
322
273 323 def _write_raw(self, data: bytes) -> None:
274 324 with self._io:
275 325 if self._ser is not None:
@@ -351,11 +401,15 @@ class Machine:
351 401 self.state = state
352 402 if mpos:
353 403 self.mpos = mpos
354 if wpos:
355 self.wpos = wpos
356 elif mpos and wco:
357 self.wpos = [mpos[i] - wco[i] for i in range(3)]
358 if state.lower().startswith("idle") and not self.job_active:
404 resolved, self._wco = resolve_work_position(mpos, wpos, wco, self._wco)
405 if resolved:
406 self.wpos = resolved
407 settled = state.lower().startswith("idle") and not self.job_active
408 if settled and (time.time() >= self._track_until or self._track_xy is None or (
409 abs(resolved[0] - self._track_xy[0]) < 0.4 and abs(resolved[1] - self._track_xy[1]) < 0.4
410 )):
411 self._track_xy = (resolved[0], resolved[1])
412 if state.lower().startswith("idle") and not self.job_active and not self.message.startswith("Klaar"):
359 413 self.message = "Gereed"
360 414
361 415 def _command(self, line: str, timeout: float = 15) -> str:
@@ -381,19 +435,21 @@ class Machine:
381 435 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
382 436 return None
383 437 self._hold_motors()
384 dx, dy, notice = limit_step(self.wpos[0], self.wpos[1], dx, dy, origin_top)
438 x, y = self._track_xy if self._track_xy is not None else (self.wpos[0], self.wpos[1])
439 dx, dy, notice = limit_step(x, y, dx, dy, origin_top)
385 440 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
386 441 return notice
387 parts = ["$J=G91 G21"]
388 if abs(dx) >= 1e-6:
389 parts.append(f"X{dx:.3f}")
390 if abs(dy) >= 1e-6:
391 parts.append(f"Y{dy:.3f}")
442 parts = ["$J=G90 G21"]
443 target_x, target_y = x + dx, y + dy
444 parts.append(f"X{target_x:.3f}")
445 parts.append(f"Y{target_y:.3f}")
392 446 parts.append(f"F{feed:.0f}")
393 447 reply = self._command(" ".join(parts), timeout=8)
394 448 self._query()
395 449 if reply.startswith("error"):
396 450 raise RuntimeError(reply + " — staat de machine in alarm? Ontgrendel of home eerst.")
451 self._track_xy = (target_x, target_y)
452 self._track_until = time.time() + max(0.4, math.hypot(dx, dy) / feed * 60.0 + 0.6)
397 453 return notice
398 454
399 455 def pen(self, down: bool, up_z: float = 0, down_z: float = 5, feed: float = 5000) -> None:
@@ -450,6 +506,15 @@ class Machine:
450 506 return
451 507 self._sync("$H", 120, job)
452 508 self._sync("G92 X0 Y0", 5, job)
509 self.wpos[0] = 0.0
510 self.wpos[1] = 0.0
511 self._track_xy = (0.0, 0.0)
512 self._track_until = 0.0
513 if len(self.mpos) >= 2:
514 if self._wco is None:
515 self._wco = [0.0, 0.0, 0.0]
516 self._wco[0] = self.mpos[0]
517 self._wco[1] = self.mpos[1]
453 518 except Exception:
454 519 try:
455 520 self._sync("G90", 5, job)
@@ -488,6 +553,7 @@ class Machine:
488 553 self.job_paused = False
489 554 self.progress = 0
490 555 self.error = ""
556 self._arc_fallbacks = 0
491 557 self.message = "Tekenen…"
492 558 self._job = threading.Thread(target=self._run_job, args=(lines,), daemon=True)
493 559 self._job.start()
@@ -534,16 +600,17 @@ class Machine:
534 600 time.sleep(0.05)
535 601 if self._stop.is_set():
536 602 break
537 if line.startswith("$"):
603 if line.startswith("$") or line.startswith(("G2 ", "G3 ")):
538 604 while pending and not self._stop.is_set():
539 605 ack = self._wait_ack(60)
540 606 used -= pending.pop(0)
541 607 if ack.startswith("error"):
542 608 raise RuntimeError(ack)
543 self._wait_until_idle(60)
609 if line.startswith("$"):
610 self._wait_until_idle(60)
544 611 if self._stop.is_set():
545 612 break
546 self._job_line(line, 5)
613 self._job_line(line, 30 if line.startswith(("G2 ", "G3 ")) else 5)
547 614 sent += 1
548 615 self.progress = sent / len(lines)
549 616 continue
@@ -571,7 +638,10 @@ class Machine:
571 638 self.message = "Homen…"
572 639 self._prepare_home(True)
573 640 if not self._stop.is_set():
574 self.message = "Klaar"
641 if self._arc_fallbacks:
642 self.message = "Klaar. Een boog klopte niet en is als rechte lijn getekend."
643 else:
644 self.message = "Klaar"
575 645 except Exception as exc:
576 646 self.error = str(exc)
577 647 self.message = str(exc)
@@ -588,6 +658,14 @@ class Machine:
588 658 return
589 659 self._write_raw((line + "\n").encode())
590 660 ack = self._wait_ack(timeout)
661 if ack.startswith("error:33") and line.startswith(("G2 ", "G3 ")):
662 self._arc_fallbacks += 1
663 self._write_raw((chord_for_arc(line) + "\n").encode())
664 ack = self._wait_ack(timeout)
665 if not ack.startswith("error"):
666 with self._state_lock:
667 if self.error.startswith("error:33"):
668 self.error = ""
591 669 if ack.startswith("error"):
592 670 raise RuntimeError(ack)
593 671
@@ -6,6 +6,7 @@ import glob
6import json
6import json
7import math
7import math
8import os
8import os
9import re
9import threading
10import threading
10import time
11import time
11from pathlib import Path
12from pathlib import Path
@@ -24,6 +25,17 @@ except ImportError: # pragma: no cover
24_STATE = Path.home() / ".config" / "timdraw" / "last-device.json"
25_STATE = Path.home() / ".config" / "timdraw" / "last-device.json"
25
26
26
27
28def chord_for_arc(line: str) -> str:
29 """Rechte lijn naar hetzelfde eindpunt, als GRBL een boog met error 33 weigert."""
30 words = dict(re.findall(r"([XYF])([+-]?(?:\d+\.\d*|\.\d+|\d+))", line))
31 if "X" not in words or "Y" not in words:
32 raise RuntimeError("error:33")
33 chord = f"G1 X{words['X']} Y{words['Y']}"
34 if "F" in words:
35 chord += f" F{words['F']}"
36 return chord
37
38
27def _mm(value: float) -> str:
39def _mm(value: float) -> str:
28 rounded = round(value)
40 rounded = round(value)
29 if abs(value - rounded) < 0.05:
41 if abs(value - rounded) < 0.05:
@@ -47,6 +59,22 @@ def limit_step(
47 return adx, ady, None
59 return adx, ady, None
48
60
49
61
62def resolve_work_position(
63 mpos: list[float] | None,
64 wpos: list[float] | None,
65 wco: list[float] | None,
66 remembered_wco: list[float] | None,
67) -> tuple[list[float] | None, list[float] | None]:
68 """Werkpositie uit een statusregel. GRBL stuurt WCO maar af en toe mee."""
69 if wco is not None:
70 remembered_wco = wco
71 if wpos is not None:
72 return wpos, remembered_wco
73 if mpos is not None and remembered_wco is not None:
74 return [mpos[i] - remembered_wco[i] for i in range(3)], remembered_wco
75 return None, remembered_wco
76
77
50def list_ports() -> list[str]:
78def list_ports() -> list[str]:
51 by_id = sorted(glob.glob("/dev/serial/by-id/*"))
79 by_id = sorted(glob.glob("/dev/serial/by-id/*"))
52 if by_id:
80 if by_id:
@@ -98,6 +126,7 @@ class Machine:
98 self._ack_event = threading.Event()
126 self._ack_event = threading.Event()
99 self._stop = threading.Event()
127 self._stop = threading.Event()
100 self._pause = threading.Event()
128 self._pause = threading.Event()
129 self._arc_fallbacks = 0
101 self.connected = False
130 self.connected = False
102 self.connecting = False
131 self.connecting = False
103 self.auto_enabled = True
132 self.auto_enabled = True
@@ -110,6 +139,9 @@ class Machine:
110 self.state = "disconnected"
139 self.state = "disconnected"
111 self.wpos = [0.0, 0.0, 0.0]
140 self.wpos = [0.0, 0.0, 0.0]
112 self.mpos = [0.0, 0.0, 0.0]
141 self.mpos = [0.0, 0.0, 0.0]
142 self._wco: list[float] | None = None
143 self._track_xy: tuple[float, float] | None = None
144 self._track_until = 0.0
113 self.message = "Niet verbonden"
145 self.message = "Niet verbonden"
114 self.error = ""
146 self.error = ""
115 self.progress = 0.0
147 self.progress = 0.0
@@ -270,6 +302,24 @@ class Machine:
270 if reader is not None and reader.is_alive() and threading.current_thread() is not reader:
302 if reader is not None and reader.is_alive() and threading.current_thread() is not reader:
271 reader.join(timeout=1)
303 reader.join(timeout=1)
272
304
305 def attach(self, port) -> None:
306 """Koppel een al open poort. De testsuite gebruikt dit voor de virtuele machine."""
307 self.disconnect()
308 self._ser = port
309 self.port = "virtual"
310 self.connected = True
311 self.auto_enabled = False
312 self.error = ""
313 self.message = "Verbinden…"
314 self._stop.clear()
315 self._reader = threading.Thread(target=self._read_loop, daemon=True)
316 self._reader.start()
317 self._command("$I", timeout=2)
318 self._command("$$", timeout=2)
319 self._hold_motors()
320 self._query()
321 time.sleep(0.05)
322
273 def _write_raw(self, data: bytes) -> None:
323 def _write_raw(self, data: bytes) -> None:
274 with self._io:
324 with self._io:
275 if self._ser is not None:
325 if self._ser is not None:
@@ -351,11 +401,15 @@ class Machine:
351 self.state = state
401 self.state = state
352 if mpos:
402 if mpos:
353 self.mpos = mpos
403 self.mpos = mpos
354 if wpos:
404 resolved, self._wco = resolve_work_position(mpos, wpos, wco, self._wco)
355 self.wpos = wpos
405 if resolved:
356 elif mpos and wco:
406 self.wpos = resolved
357 self.wpos = [mpos[i] - wco[i] for i in range(3)]
407 settled = state.lower().startswith("idle") and not self.job_active
358 if state.lower().startswith("idle") and not self.job_active:
408 if settled and (time.time() >= self._track_until or self._track_xy is None or (
409 abs(resolved[0] - self._track_xy[0]) < 0.4 and abs(resolved[1] - self._track_xy[1]) < 0.4
410 )):
411 self._track_xy = (resolved[0], resolved[1])
412 if state.lower().startswith("idle") and not self.job_active and not self.message.startswith("Klaar"):
359 self.message = "Gereed"
413 self.message = "Gereed"
360
414
361 def _command(self, line: str, timeout: float = 15) -> str:
415 def _command(self, line: str, timeout: float = 15) -> str:
@@ -381,19 +435,21 @@ class Machine:
381 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
435 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
382 return None
436 return None
383 self._hold_motors()
437 self._hold_motors()
384 dx, dy, notice = limit_step(self.wpos[0], self.wpos[1], dx, dy, origin_top)
438 x, y = self._track_xy if self._track_xy is not None else (self.wpos[0], self.wpos[1])
439 dx, dy, notice = limit_step(x, y, dx, dy, origin_top)
385 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
440 if abs(dx) < 1e-6 and abs(dy) < 1e-6:
386 return notice
441 return notice
387 parts = ["$J=G91 G21"]
442 parts = ["$J=G90 G21"]
388 if abs(dx) >= 1e-6:
443 target_x, target_y = x + dx, y + dy
389 parts.append(f"X{dx:.3f}")
444 parts.append(f"X{target_x:.3f}")
390 if abs(dy) >= 1e-6:
445 parts.append(f"Y{target_y:.3f}")
391 parts.append(f"Y{dy:.3f}")
392 parts.append(f"F{feed:.0f}")
446 parts.append(f"F{feed:.0f}")
393 reply = self._command(" ".join(parts), timeout=8)
447 reply = self._command(" ".join(parts), timeout=8)
394 self._query()
448 self._query()
395 if reply.startswith("error"):
449 if reply.startswith("error"):
396 raise RuntimeError(reply + " — staat de machine in alarm? Ontgrendel of home eerst.")
450 raise RuntimeError(reply + " — staat de machine in alarm? Ontgrendel of home eerst.")
451 self._track_xy = (target_x, target_y)
452 self._track_until = time.time() + max(0.4, math.hypot(dx, dy) / feed * 60.0 + 0.6)
397 return notice
453 return notice
398
454
399 def pen(self, down: bool, up_z: float = 0, down_z: float = 5, feed: float = 5000) -> None:
455 def pen(self, down: bool, up_z: float = 0, down_z: float = 5, feed: float = 5000) -> None:
@@ -450,6 +506,15 @@ class Machine:
450 return
506 return
451 self._sync("$H", 120, job)
507 self._sync("$H", 120, job)
452 self._sync("G92 X0 Y0", 5, job)
508 self._sync("G92 X0 Y0", 5, job)
509 self.wpos[0] = 0.0
510 self.wpos[1] = 0.0
511 self._track_xy = (0.0, 0.0)
512 self._track_until = 0.0
513 if len(self.mpos) >= 2:
514 if self._wco is None:
515 self._wco = [0.0, 0.0, 0.0]
516 self._wco[0] = self.mpos[0]
517 self._wco[1] = self.mpos[1]
453 except Exception:
518 except Exception:
454 try:
519 try:
455 self._sync("G90", 5, job)
520 self._sync("G90", 5, job)
@@ -488,6 +553,7 @@ class Machine:
488 self.job_paused = False
553 self.job_paused = False
489 self.progress = 0
554 self.progress = 0
490 self.error = ""
555 self.error = ""
556 self._arc_fallbacks = 0
491 self.message = "Tekenen…"
557 self.message = "Tekenen…"
492 self._job = threading.Thread(target=self._run_job, args=(lines,), daemon=True)
558 self._job = threading.Thread(target=self._run_job, args=(lines,), daemon=True)
493 self._job.start()
559 self._job.start()
@@ -534,16 +600,17 @@ class Machine:
534 time.sleep(0.05)
600 time.sleep(0.05)
535 if self._stop.is_set():
601 if self._stop.is_set():
536 break
602 break
537 if line.startswith("$"):
603 if line.startswith("$") or line.startswith(("G2 ", "G3 ")):
538 while pending and not self._stop.is_set():
604 while pending and not self._stop.is_set():
539 ack = self._wait_ack(60)
605 ack = self._wait_ack(60)
540 used -= pending.pop(0)
606 used -= pending.pop(0)
541 if ack.startswith("error"):
607 if ack.startswith("error"):
542 raise RuntimeError(ack)
608 raise RuntimeError(ack)
543 self._wait_until_idle(60)
609 if line.startswith("$"):
610 self._wait_until_idle(60)
544 if self._stop.is_set():
611 if self._stop.is_set():
545 break
612 break
546 self._job_line(line, 5)
613 self._job_line(line, 30 if line.startswith(("G2 ", "G3 ")) else 5)
547 sent += 1
614 sent += 1
548 self.progress = sent / len(lines)
615 self.progress = sent / len(lines)
549 continue
616 continue
@@ -571,7 +638,10 @@ class Machine:
571 self.message = "Homen…"
638 self.message = "Homen…"
572 self._prepare_home(True)
639 self._prepare_home(True)
573 if not self._stop.is_set():
640 if not self._stop.is_set():
574 self.message = "Klaar"
641 if self._arc_fallbacks:
642 self.message = "Klaar. Een boog klopte niet en is als rechte lijn getekend."
643 else:
644 self.message = "Klaar"
575 except Exception as exc:
645 except Exception as exc:
576 self.error = str(exc)
646 self.error = str(exc)
577 self.message = str(exc)
647 self.message = str(exc)
@@ -588,6 +658,14 @@ class Machine:
588 return
658 return
589 self._write_raw((line + "\n").encode())
659 self._write_raw((line + "\n").encode())
590 ack = self._wait_ack(timeout)
660 ack = self._wait_ack(timeout)
661 if ack.startswith("error:33") and line.startswith(("G2 ", "G3 ")):
662 self._arc_fallbacks += 1
663 self._write_raw((chord_for_arc(line) + "\n").encode())
664 ack = self._wait_ack(timeout)
665 if not ack.startswith("error"):
666 with self._state_lock:
667 if self.error.startswith("error:33"):
668 self.error = ""
591 if ack.startswith("error"):
669 if ack.startswith("error"):
592 raise RuntimeError(ack)
670 raise RuntimeError(ack)
593
671
timdraw/selftest.py +155 −14
@@ -1,13 +1,19 @@
1 """Controle van SVG, tekst, arcering en G-code, zonder de machine te bewegen."""
1 """Controle van SVG, tekst, arcering, G-code en een virtuele machine.
2
3 De virtuele machine vervangt de Bachin: er gaat geen USB open.
4 Draaien: python3 -m timdraw.selftest
5 """
2 6
3 7 from pathlib import Path
4 8 import math
9 import time
5 10
6 11 from timdraw.font import render_text
7 12 from timdraw.gcode import plan
8 from timdraw.grbl import limit_step
9 from timdraw.geom import arc_points, bounds, dist, fit_arcs
13 from timdraw.grbl import chord_for_arc, limit_step, resolve_work_position
14 from timdraw.geom import arc_points, bounds, dist, fit_arcs, grbl_arc_ok
10 15 from timdraw.svgimport import import_svg
16 from timdraw.virtual import HOME_MPOS, connect, settle
11 17
12 18 DEMO = Path("/tools/TO LAPTOP/BachinMaker/demo")
13 19
@@ -74,7 +80,7 @@ def test_text_and_gcode() -> None:
74 80 check("grijswaarden tekenen", gray_job["stats"]["drawMm"] > 100, str(gray_job["stats"]))
75 81 corner = plan([{
76 82 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
77 "strokes": [{"pts": [(0, 297), (20, 277)]}],
83 "strokes": [{"pts": [(10, 307), (30, 287)]}],
78 84 }], {"origin": "top-left"})
79 85 check("homehoek blijft X0 Y0", "X0.000 Y0.000" in corner["gcode"], corner["gcode"])
80 86 check("blad ligt rechts en onder het nulpunt", "X20.000 Y-20.000" in corner["gcode"])
@@ -84,9 +90,9 @@ def test_text_and_gcode() -> None:
84 90 linked = plan([{
85 91 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
86 92 "strokes": [
87 {"pts": [(100, 100), (120, 100)]},
88 {"pts": [(10, 297), (0, 297)]},
89 {"pts": [(10, 287), (10, 297)]},
93 {"pts": [(110, 110), (130, 110)]},
94 {"pts": [(20, 307), (10, 307)]},
95 {"pts": [(20, 297), (20, 307)]},
90 96 ],
91 97 }], {"origin": "top-left", "returnHome": False, "travelSpeed": 4000})
92 98 moves = [line for line in linked["gcode"].splitlines() if line.startswith("G1 X")]
@@ -96,17 +102,17 @@ def test_text_and_gcode() -> None:
96 102 check("geen pen omhoog tussen aansluitende lijnen", len(pen_ups) == 3, str(pen_ups))
97 103 grouped = plan([
98 104 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
99 "strokes": [{"pts": [(100, 100), (120, 100)]}]},
105 "strokes": [{"pts": [(110, 110), (130, 110)]}]},
100 106 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
101 "strokes": [{"pts": [(0, 297), (20, 297)]}]},
107 "strokes": [{"pts": [(10, 307), (30, 307)]}]},
102 108 ], {"origin": "top-left", "perObject": True, "returnHome": False, "travelSpeed": 4000})
103 109 grouped_moves = [line for line in grouped["gcode"].splitlines() if line.startswith("G1 X")]
104 110 check("eerst het eerste object", "X100.000" in grouped_moves[0], " | ".join(grouped_moves[:3]))
105 111 mixed = plan([
106 112 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
107 "strokes": [{"pts": [(100, 100), (120, 100)]}]},
113 "strokes": [{"pts": [(110, 110), (130, 110)]}]},
108 114 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
109 "strokes": [{"pts": [(0, 297), (20, 297)]}]},
115 "strokes": [{"pts": [(10, 307), (30, 307)]}]},
110 116 ], {"origin": "top-left", "returnHome": False, "travelSpeed": 4000})
111 117 mixed_moves = [line for line in mixed["gcode"].splitlines() if line.startswith("G1 X")]
112 118 check("zonder groeperen de dichtstbijzijnde", mixed_moves[0].startswith("G1 X0.000 Y0.000"), " | ".join(mixed_moves[:2]))
@@ -117,14 +123,52 @@ def test_text_and_gcode() -> None:
117 123 check("breedte stopt op 200", abs(step_x - 10) < 0.01 and note == "10 van 50 mm bewogen, daarna limiet bereikt", note or "")
118 124 _, step_y, note = limit_step(10, 0, 0, 20)
119 125 check("niet boven nul", abs(step_y) < 0.01 and note == "0 van 20 mm bewogen, daarna limiet bereikt", note or "")
126 x = y = 0.0
127 for _ in range(6):
128 step_x, step_y, _ = limit_step(x, y, 50, 0)
129 x += step_x
130 y += step_y
131 check("herhaald rechts stopt op 200", abs(x - 200) < 0.01 and abs(y) < 0.01, f"{x},{y}")
132 step_x, _, note = limit_step(200, -10, 50, 0)
133 check("op de rand blijft hij staan", abs(step_x) < 0.01 and note.startswith("0 van 50"), note or "")
134 step_x, _, note = limit_step(0, -20, -30, 0)
135 check("links van nul blijft staan", abs(step_x) < 0.01 and note.startswith("0 van 30"), note or "")
136 worked, remembered = resolve_work_position([12.0, -4.0, 1.0], None, None, [2.0, 1.0, 0.0])
137 check("werkpositie zonder WPos", worked == [10.0, -5.0, 1.0], str(worked))
138 check("WCO blijft bewaard", remembered == [2.0, 1.0, 0.0])
139 off_paper = plan([{
140 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
141 "strokes": [{"pts": [(-5, 100), (20, 100)]}],
142 }], {"origin": "top-left"})
143 check("waarschuwing buiten papier", any("buiten het papier" in item for item in off_paper["warnings"]), str(off_paper["warnings"]))
120 144 quarter = [
121 145 (10 * math.cos(i * math.pi / 32), 10 * math.sin(i * math.pi / 32))
122 146 for i in range(17)
123 147 ]
124 148 arcs = fit_arcs(quarter, 0.08)
125 149 check("kwartcirkel wordt één boog", len(arcs) == 1 and arcs[0][0] == "G3", str(arcs))
126 outer = [(0, 0), (80, 0), (80, 80), (0, 80), (0, 0)]
127 inner = [(30, 30), (50, 30), (50, 50), (30, 50), (30, 30)]
150 pos = (float(f"{quarter[0][0]:.3f}"), float(f"{quarter[0][1]:.3f}"))
151 for code, ex, ey, i_off, j_off in arcs:
152 if code != "G1":
153 check("kwartcirkel haalt error 33 niet", grbl_arc_ok(pos, (ex, ey), i_off, j_off))
154 pos = (float(f"{ex:.3f}"), float(f"{ey:.3f}"))
155 ellipse = [
156 (40 + 18 * math.cos(i / 79 * math.tau * 1.2), 40 + 12 * math.sin(i / 79 * math.tau * 1.2))
157 for i in range(80)
158 ]
159 curved = fit_arcs(ellipse, 0.08)
160 pos = (float(f"{ellipse[0][0]:.3f}"), float(f"{ellipse[0][1]:.3f}"))
161 for code, ex, ey, i_off, j_off in curved:
162 if code != "G1":
163 check("elipsboog haalt error 33 niet", grbl_arc_ok(pos, (ex, ey), i_off, j_off))
164 pos = (float(f"{ex:.3f}"), float(f"{ey:.3f}"))
165 check("scheve boog wordt geweigerd", not grbl_arc_ok((0, 0), (0, 10.02), 0, -10))
166 check(
167 "geweigerde boog wordt een lijn",
168 chord_for_arc("G3 X0.000 Y10.000 I-10.000 J0.000 F3000") == "G1 X0.000 Y10.000 F3000",
169 )
170 outer = [(10, 30), (90, 30), (90, 90), (10, 90), (10, 30)]
171 inner = [(40, 50), (60, 50), (60, 70), (40, 70), (40, 50)]
128 172 traced = plan([{
129 173 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": True,
130 174 "strokes": [
@@ -136,7 +180,103 @@ def test_text_and_gcode() -> None:
136 180 check("voorbeeld volgt de buitenkant", "X80.000" in traced["gcode"])
137 181 arc_lines = [line for line in traced["gcode"].splitlines() if line.startswith(("G2 ", "G3 "))]
138 182 check("voorbeeld houdt hoeken recht", not arc_lines, " | ".join(arc_lines))
139 check("voorbeeld slaat het gat over", "X50.000" not in traced["gcode"] and "X30.000" not in traced["gcode"])
183 check("voorbeeld slaat het gat over", "X30.000" not in traced["gcode"] and "X50.000" not in traced["gcode"])
184
185
186 def _near(points, x: float, y: float) -> bool:
187 return any(abs(px - x) < 0.02 and abs(py - y) < 0.02 for px, py in points)
188
189
190 def test_virtual_machine() -> None:
191 """Jog, papier en error 33 tegen een GRBL die MPos stuurt en jog te vroeg bevestigt."""
192 machine, grbl = connect(40, -20, wco=(5, -3, 0))
193 try:
194 for _ in range(4):
195 machine._query()
196 settle(machine, grbl)
197 check("werkpositie volgt MPos min de onthouden offset", abs(machine.wpos[0] - 40) < 0.05 and abs(machine.wpos[1] + 20) < 0.05, str(machine.wpos))
198 check("machinecoördinaat is niet de werkpositie", abs(machine.mpos[0] - 45) < 0.05, str(machine.mpos))
199 machine.jog(50, 0, 5000)
200 grbl.finish()
201 check("van 40 nog 50 mm naar rechts", abs(grbl.wpos[0] - 90) < 0.02 and len(grbl.jogs) == 1, str(grbl.jogs))
202 finally:
203 machine.disconnect()
204
205 machine, grbl = connect(40, -20, wco=(5, -3, 0))
206 try:
207 notice = machine.jog(-50, 0, 5000)
208 grbl.finish()
209 check("vanaf 40 naar links komt op nul", abs(grbl.wpos[0]) < 0.02 and notice is not None and "limiet" in notice, notice or str(grbl.wpos))
210 finally:
211 machine.disconnect()
212
213 machine, grbl = connect(0, 0, wco=(5, -3, 0))
214 try:
215 left = machine.jog(-10, 0, 5000)
216 up = machine.jog(0, 30, 5000)
217 check("links van nul blijft staan", not grbl.jogs and left is not None and left.startswith("0 van"), left or "")
218 check("boven nul blijft staan", not grbl.jogs and up is not None and up.startswith("0 van"), up or "")
219 for _ in range(6):
220 machine.jog(50, 0, 5000)
221 grbl.finish()
222 check("zes keer naar rechts eindigt op 200", abs(grbl.wpos[0] - 200) < 0.02 and len(grbl.jogs) == 4, str(grbl.jogs))
223 check("geen jog voorbij 200", all(x <= 200.02 for x, _y in grbl.jogs))
224 held = machine.jog(50, 0, 5000)
225 check("ingedrukt houden op x=200 stuurt niets", held is not None and held.startswith("0 van") and len(grbl.jogs) == 4, held or "")
226 finally:
227 machine.disconnect()
228
229 machine, grbl = connect(160, -10, wco=(5, -3, 0))
230 try:
231 notice = machine.jog(50, 0, 5000)
232 machine._ser.inject(grbl.stale_idle())
233 time.sleep(0.08)
234 machine.jog(50, 0, 5000)
235 machine.jog(50, 0, 5000)
236 grbl.finish()
237 check("laatste stap naar rechts noemt de limiet", notice == "40 van 50 mm bewogen, daarna limiet bereikt", notice or "")
238 check("extra druk op de rechterrand blijft op 200", abs(grbl.wpos[0] - 200) < 0.02 and len(grbl.jogs) == 1, str(grbl.jogs))
239 finally:
240 machine.disconnect()
241
242 machine, grbl = connect(20, -250, wco=(5, -3, 0))
243 try:
244 notice = machine.jog(0, -50, 5000)
245 machine._ser.inject(grbl.stale_idle())
246 time.sleep(0.08)
247 machine.jog(0, -50, 5000)
248 grbl.finish()
249 check("omlaag stopt op -297", abs(grbl.wpos[1] + 297) < 0.02 and len(grbl.jogs) == 1, str(grbl.jogs))
250 check("vanaf -250 nog 47 mm", notice == "47 van 50 mm bewogen, daarna limiet bereikt", notice or "")
251 parked = machine.jog(0, -50, 5000)
252 check("ingedrukt houden op y=-297 stuurt niets", parked is not None and parked.startswith("0 van") and len(grbl.jogs) == 1, parked or "")
253 finally:
254 machine.disconnect()
255
256 machine, grbl = connect(0, 0)
257 try:
258 corner = plan([{
259 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
260 "strokes": [{"pts": [(10, 307), (30, 287)]}],
261 }], {"origin": "top-left"})
262 gcode = corner["gcode"] + "\nG3 X30.000 Y-20.000 I0.000 J10.000 F3000\n"
263 machine.start_job(gcode)
264 machine._job.join(20)
265 check("tekening wordt afgerond", not machine.job_active and machine.error == "", machine.message)
266 check("scheve boog wordt als lijn getekend", "rechte lijn" in machine.message, machine.message)
267 check("homehoek komt op de virtuele pen", _near(grbl.drawn, 0, 0))
268 check("20 mm rechts en omlaag komt op de pen", _near(grbl.drawn, 20, -20))
269 check("de geweigerde boog eindigt als lijn", _near(grbl.drawn, 30, -20))
270 check(
271 "de pen blijft binnen het bereik",
272 all(0 <= x <= 200.02 and -297 <= y <= 0.02 for x, y in grbl.drawn),
273 str(grbl.drawn),
274 )
275 settle(machine, grbl)
276 check("na het tekenen staat het nulpunt weer op home", abs(machine.wpos[0]) < 0.05 and abs(machine.wpos[1]) < 0.05, str(machine.wpos))
277 check("home zet de machinecoördinaat, niet de werkpositie", abs(machine.mpos[0] - HOME_MPOS[0]) < 0.05 and abs(machine.mpos[1] - HOME_MPOS[1]) < 0.05, str(machine.mpos))
278 finally:
279 machine.disconnect()
140 280
141 281
142 282 if __name__ == "__main__":
@@ -145,4 +285,5 @@ if __name__ == "__main__":
145 285 test_svg("Dolphin.svg", True)
146 286 test_svg("wiresphere.svg", False)
147 287 test_text_and_gcode()
288 test_virtual_machine()
148 289 print("alle controles geslaagd")
@@ -1,13 +1,19 @@
1"""Controle van SVG, tekst, arcering en G-code, zonder de machine te bewegen."""
1"""Controle van SVG, tekst, arcering, G-code en een virtuele machine.
2
3De virtuele machine vervangt de Bachin: er gaat geen USB open.
4Draaien: python3 -m timdraw.selftest
5"""
2
6
3from pathlib import Path
7from pathlib import Path
4import math
8import math
9import time
5
10
6from timdraw.font import render_text
11from timdraw.font import render_text
7from timdraw.gcode import plan
12from timdraw.gcode import plan
8from timdraw.grbl import limit_step
13from timdraw.grbl import chord_for_arc, limit_step, resolve_work_position
9from timdraw.geom import arc_points, bounds, dist, fit_arcs
14from timdraw.geom import arc_points, bounds, dist, fit_arcs, grbl_arc_ok
10from timdraw.svgimport import import_svg
15from timdraw.svgimport import import_svg
16from timdraw.virtual import HOME_MPOS, connect, settle
11
17
12DEMO = Path("/tools/TO LAPTOP/BachinMaker/demo")
18DEMO = Path("/tools/TO LAPTOP/BachinMaker/demo")
13
19
@@ -74,7 +80,7 @@ def test_text_and_gcode() -> None:
74 check("grijswaarden tekenen", gray_job["stats"]["drawMm"] > 100, str(gray_job["stats"]))
80 check("grijswaarden tekenen", gray_job["stats"]["drawMm"] > 100, str(gray_job["stats"]))
75 corner = plan([{
81 corner = plan([{
76 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
82 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
77 "strokes": [{"pts": [(0, 297), (20, 277)]}],
83 "strokes": [{"pts": [(10, 307), (30, 287)]}],
78 }], {"origin": "top-left"})
84 }], {"origin": "top-left"})
79 check("homehoek blijft X0 Y0", "X0.000 Y0.000" in corner["gcode"], corner["gcode"])
85 check("homehoek blijft X0 Y0", "X0.000 Y0.000" in corner["gcode"], corner["gcode"])
80 check("blad ligt rechts en onder het nulpunt", "X20.000 Y-20.000" in corner["gcode"])
86 check("blad ligt rechts en onder het nulpunt", "X20.000 Y-20.000" in corner["gcode"])
@@ -84,9 +90,9 @@ def test_text_and_gcode() -> None:
84 linked = plan([{
90 linked = plan([{
85 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
91 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
86 "strokes": [
92 "strokes": [
87 {"pts": [(100, 100), (120, 100)]},
93 {"pts": [(110, 110), (130, 110)]},
88 {"pts": [(10, 297), (0, 297)]},
94 {"pts": [(20, 307), (10, 307)]},
89 {"pts": [(10, 287), (10, 297)]},
95 {"pts": [(20, 297), (20, 307)]},
90 ],
96 ],
91 }], {"origin": "top-left", "returnHome": False, "travelSpeed": 4000})
97 }], {"origin": "top-left", "returnHome": False, "travelSpeed": 4000})
92 moves = [line for line in linked["gcode"].splitlines() if line.startswith("G1 X")]
98 moves = [line for line in linked["gcode"].splitlines() if line.startswith("G1 X")]
@@ -96,17 +102,17 @@ def test_text_and_gcode() -> None:
96 check("geen pen omhoog tussen aansluitende lijnen", len(pen_ups) == 3, str(pen_ups))
102 check("geen pen omhoog tussen aansluitende lijnen", len(pen_ups) == 3, str(pen_ups))
97 grouped = plan([
103 grouped = plan([
98 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
104 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
99 "strokes": [{"pts": [(100, 100), (120, 100)]}]},
105 "strokes": [{"pts": [(110, 110), (130, 110)]}]},
100 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
106 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
101 "strokes": [{"pts": [(0, 297), (20, 297)]}]},
107 "strokes": [{"pts": [(10, 307), (30, 307)]}]},
102 ], {"origin": "top-left", "perObject": True, "returnHome": False, "travelSpeed": 4000})
108 ], {"origin": "top-left", "perObject": True, "returnHome": False, "travelSpeed": 4000})
103 grouped_moves = [line for line in grouped["gcode"].splitlines() if line.startswith("G1 X")]
109 grouped_moves = [line for line in grouped["gcode"].splitlines() if line.startswith("G1 X")]
104 check("eerst het eerste object", "X100.000" in grouped_moves[0], " | ".join(grouped_moves[:3]))
110 check("eerst het eerste object", "X100.000" in grouped_moves[0], " | ".join(grouped_moves[:3]))
105 mixed = plan([
111 mixed = plan([
106 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
112 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
107 "strokes": [{"pts": [(100, 100), (120, 100)]}]},
113 "strokes": [{"pts": [(110, 110), (130, 110)]}]},
108 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
114 {"x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
109 "strokes": [{"pts": [(0, 297), (20, 297)]}]},
115 "strokes": [{"pts": [(10, 307), (30, 307)]}]},
110 ], {"origin": "top-left", "returnHome": False, "travelSpeed": 4000})
116 ], {"origin": "top-left", "returnHome": False, "travelSpeed": 4000})
111 mixed_moves = [line for line in mixed["gcode"].splitlines() if line.startswith("G1 X")]
117 mixed_moves = [line for line in mixed["gcode"].splitlines() if line.startswith("G1 X")]
112 check("zonder groeperen de dichtstbijzijnde", mixed_moves[0].startswith("G1 X0.000 Y0.000"), " | ".join(mixed_moves[:2]))
118 check("zonder groeperen de dichtstbijzijnde", mixed_moves[0].startswith("G1 X0.000 Y0.000"), " | ".join(mixed_moves[:2]))
@@ -117,14 +123,52 @@ def test_text_and_gcode() -> None:
117 check("breedte stopt op 200", abs(step_x - 10) < 0.01 and note == "10 van 50 mm bewogen, daarna limiet bereikt", note or "")
123 check("breedte stopt op 200", abs(step_x - 10) < 0.01 and note == "10 van 50 mm bewogen, daarna limiet bereikt", note or "")
118 _, step_y, note = limit_step(10, 0, 0, 20)
124 _, step_y, note = limit_step(10, 0, 0, 20)
119 check("niet boven nul", abs(step_y) < 0.01 and note == "0 van 20 mm bewogen, daarna limiet bereikt", note or "")
125 check("niet boven nul", abs(step_y) < 0.01 and note == "0 van 20 mm bewogen, daarna limiet bereikt", note or "")
126 x = y = 0.0
127 for _ in range(6):
128 step_x, step_y, _ = limit_step(x, y, 50, 0)
129 x += step_x
130 y += step_y
131 check("herhaald rechts stopt op 200", abs(x - 200) < 0.01 and abs(y) < 0.01, f"{x},{y}")
132 step_x, _, note = limit_step(200, -10, 50, 0)
133 check("op de rand blijft hij staan", abs(step_x) < 0.01 and note.startswith("0 van 50"), note or "")
134 step_x, _, note = limit_step(0, -20, -30, 0)
135 check("links van nul blijft staan", abs(step_x) < 0.01 and note.startswith("0 van 30"), note or "")
136 worked, remembered = resolve_work_position([12.0, -4.0, 1.0], None, None, [2.0, 1.0, 0.0])
137 check("werkpositie zonder WPos", worked == [10.0, -5.0, 1.0], str(worked))
138 check("WCO blijft bewaard", remembered == [2.0, 1.0, 0.0])
139 off_paper = plan([{
140 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
141 "strokes": [{"pts": [(-5, 100), (20, 100)]}],
142 }], {"origin": "top-left"})
143 check("waarschuwing buiten papier", any("buiten het papier" in item for item in off_paper["warnings"]), str(off_paper["warnings"]))
120 quarter = [
144 quarter = [
121 (10 * math.cos(i * math.pi / 32), 10 * math.sin(i * math.pi / 32))
145 (10 * math.cos(i * math.pi / 32), 10 * math.sin(i * math.pi / 32))
122 for i in range(17)
146 for i in range(17)
123 ]
147 ]
124 arcs = fit_arcs(quarter, 0.08)
148 arcs = fit_arcs(quarter, 0.08)
125 check("kwartcirkel wordt één boog", len(arcs) == 1 and arcs[0][0] == "G3", str(arcs))
149 check("kwartcirkel wordt één boog", len(arcs) == 1 and arcs[0][0] == "G3", str(arcs))
126 outer = [(0, 0), (80, 0), (80, 80), (0, 80), (0, 0)]
150 pos = (float(f"{quarter[0][0]:.3f}"), float(f"{quarter[0][1]:.3f}"))
127 inner = [(30, 30), (50, 30), (50, 50), (30, 50), (30, 30)]
151 for code, ex, ey, i_off, j_off in arcs:
152 if code != "G1":
153 check("kwartcirkel haalt error 33 niet", grbl_arc_ok(pos, (ex, ey), i_off, j_off))
154 pos = (float(f"{ex:.3f}"), float(f"{ey:.3f}"))
155 ellipse = [
156 (40 + 18 * math.cos(i / 79 * math.tau * 1.2), 40 + 12 * math.sin(i / 79 * math.tau * 1.2))
157 for i in range(80)
158 ]
159 curved = fit_arcs(ellipse, 0.08)
160 pos = (float(f"{ellipse[0][0]:.3f}"), float(f"{ellipse[0][1]:.3f}"))
161 for code, ex, ey, i_off, j_off in curved:
162 if code != "G1":
163 check("elipsboog haalt error 33 niet", grbl_arc_ok(pos, (ex, ey), i_off, j_off))
164 pos = (float(f"{ex:.3f}"), float(f"{ey:.3f}"))
165 check("scheve boog wordt geweigerd", not grbl_arc_ok((0, 0), (0, 10.02), 0, -10))
166 check(
167 "geweigerde boog wordt een lijn",
168 chord_for_arc("G3 X0.000 Y10.000 I-10.000 J0.000 F3000") == "G1 X0.000 Y10.000 F3000",
169 )
170 outer = [(10, 30), (90, 30), (90, 90), (10, 90), (10, 30)]
171 inner = [(40, 50), (60, 50), (60, 70), (40, 70), (40, 50)]
128 traced = plan([{
172 traced = plan([{
129 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": True,
173 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": True,
130 "strokes": [
174 "strokes": [
@@ -136,7 +180,103 @@ def test_text_and_gcode() -> None:
136 check("voorbeeld volgt de buitenkant", "X80.000" in traced["gcode"])
180 check("voorbeeld volgt de buitenkant", "X80.000" in traced["gcode"])
137 arc_lines = [line for line in traced["gcode"].splitlines() if line.startswith(("G2 ", "G3 "))]
181 arc_lines = [line for line in traced["gcode"].splitlines() if line.startswith(("G2 ", "G3 "))]
138 check("voorbeeld houdt hoeken recht", not arc_lines, " | ".join(arc_lines))
182 check("voorbeeld houdt hoeken recht", not arc_lines, " | ".join(arc_lines))
139 check("voorbeeld slaat het gat over", "X50.000" not in traced["gcode"] and "X30.000" not in traced["gcode"])
183 check("voorbeeld slaat het gat over", "X30.000" not in traced["gcode"] and "X50.000" not in traced["gcode"])
184
185
186def _near(points, x: float, y: float) -> bool:
187 return any(abs(px - x) < 0.02 and abs(py - y) < 0.02 for px, py in points)
188
189
190def test_virtual_machine() -> None:
191 """Jog, papier en error 33 tegen een GRBL die MPos stuurt en jog te vroeg bevestigt."""
192 machine, grbl = connect(40, -20, wco=(5, -3, 0))
193 try:
194 for _ in range(4):
195 machine._query()
196 settle(machine, grbl)
197 check("werkpositie volgt MPos min de onthouden offset", abs(machine.wpos[0] - 40) < 0.05 and abs(machine.wpos[1] + 20) < 0.05, str(machine.wpos))
198 check("machinecoördinaat is niet de werkpositie", abs(machine.mpos[0] - 45) < 0.05, str(machine.mpos))
199 machine.jog(50, 0, 5000)
200 grbl.finish()
201 check("van 40 nog 50 mm naar rechts", abs(grbl.wpos[0] - 90) < 0.02 and len(grbl.jogs) == 1, str(grbl.jogs))
202 finally:
203 machine.disconnect()
204
205 machine, grbl = connect(40, -20, wco=(5, -3, 0))
206 try:
207 notice = machine.jog(-50, 0, 5000)
208 grbl.finish()
209 check("vanaf 40 naar links komt op nul", abs(grbl.wpos[0]) < 0.02 and notice is not None and "limiet" in notice, notice or str(grbl.wpos))
210 finally:
211 machine.disconnect()
212
213 machine, grbl = connect(0, 0, wco=(5, -3, 0))
214 try:
215 left = machine.jog(-10, 0, 5000)
216 up = machine.jog(0, 30, 5000)
217 check("links van nul blijft staan", not grbl.jogs and left is not None and left.startswith("0 van"), left or "")
218 check("boven nul blijft staan", not grbl.jogs and up is not None and up.startswith("0 van"), up or "")
219 for _ in range(6):
220 machine.jog(50, 0, 5000)
221 grbl.finish()
222 check("zes keer naar rechts eindigt op 200", abs(grbl.wpos[0] - 200) < 0.02 and len(grbl.jogs) == 4, str(grbl.jogs))
223 check("geen jog voorbij 200", all(x <= 200.02 for x, _y in grbl.jogs))
224 held = machine.jog(50, 0, 5000)
225 check("ingedrukt houden op x=200 stuurt niets", held is not None and held.startswith("0 van") and len(grbl.jogs) == 4, held or "")
226 finally:
227 machine.disconnect()
228
229 machine, grbl = connect(160, -10, wco=(5, -3, 0))
230 try:
231 notice = machine.jog(50, 0, 5000)
232 machine._ser.inject(grbl.stale_idle())
233 time.sleep(0.08)
234 machine.jog(50, 0, 5000)
235 machine.jog(50, 0, 5000)
236 grbl.finish()
237 check("laatste stap naar rechts noemt de limiet", notice == "40 van 50 mm bewogen, daarna limiet bereikt", notice or "")
238 check("extra druk op de rechterrand blijft op 200", abs(grbl.wpos[0] - 200) < 0.02 and len(grbl.jogs) == 1, str(grbl.jogs))
239 finally:
240 machine.disconnect()
241
242 machine, grbl = connect(20, -250, wco=(5, -3, 0))
243 try:
244 notice = machine.jog(0, -50, 5000)
245 machine._ser.inject(grbl.stale_idle())
246 time.sleep(0.08)
247 machine.jog(0, -50, 5000)
248 grbl.finish()
249 check("omlaag stopt op -297", abs(grbl.wpos[1] + 297) < 0.02 and len(grbl.jogs) == 1, str(grbl.jogs))
250 check("vanaf -250 nog 47 mm", notice == "47 van 50 mm bewogen, daarna limiet bereikt", notice or "")
251 parked = machine.jog(0, -50, 5000)
252 check("ingedrukt houden op y=-297 stuurt niets", parked is not None and parked.startswith("0 van") and len(grbl.jogs) == 1, parked or "")
253 finally:
254 machine.disconnect()
255
256 machine, grbl = connect(0, 0)
257 try:
258 corner = plan([{
259 "x": 0, "y": 0, "scale": 1, "rotation": 0, "drawLine": True, "drawFill": False,
260 "strokes": [{"pts": [(10, 307), (30, 287)]}],
261 }], {"origin": "top-left"})
262 gcode = corner["gcode"] + "\nG3 X30.000 Y-20.000 I0.000 J10.000 F3000\n"
263 machine.start_job(gcode)
264 machine._job.join(20)
265 check("tekening wordt afgerond", not machine.job_active and machine.error == "", machine.message)
266 check("scheve boog wordt als lijn getekend", "rechte lijn" in machine.message, machine.message)
267 check("homehoek komt op de virtuele pen", _near(grbl.drawn, 0, 0))
268 check("20 mm rechts en omlaag komt op de pen", _near(grbl.drawn, 20, -20))
269 check("de geweigerde boog eindigt als lijn", _near(grbl.drawn, 30, -20))
270 check(
271 "de pen blijft binnen het bereik",
272 all(0 <= x <= 200.02 and -297 <= y <= 0.02 for x, y in grbl.drawn),
273 str(grbl.drawn),
274 )
275 settle(machine, grbl)
276 check("na het tekenen staat het nulpunt weer op home", abs(machine.wpos[0]) < 0.05 and abs(machine.wpos[1]) < 0.05, str(machine.wpos))
277 check("home zet de machinecoördinaat, niet de werkpositie", abs(machine.mpos[0] - HOME_MPOS[0]) < 0.05 and abs(machine.mpos[1] - HOME_MPOS[1]) < 0.05, str(machine.mpos))
278 finally:
279 machine.disconnect()
140
280
141
281
142if __name__ == "__main__":
282if __name__ == "__main__":
@@ -145,4 +285,5 @@ if __name__ == "__main__":
145 test_svg("Dolphin.svg", True)
285 test_svg("Dolphin.svg", True)
146 test_svg("wiresphere.svg", False)
286 test_svg("wiresphere.svg", False)
147 test_text_and_gcode()
287 test_text_and_gcode()
288 test_virtual_machine()
148 print("alle controles geslaagd")
289 print("alle controles geslaagd")
timdraw/virtual.py added +241 −0
@@ -0,0 +1,241 @@
1 """Virtuele GRBL 1.1, voor de testsuite. Er gaat geen USB open.
2
3 GRBL met $10=1 stuurt meestal alleen MPos. WCO komt af en toe mee.
4 Een jog antwoordt ok zodra de opdracht binnen is, niet pas als de pen daar is.
5 """
6
7 from __future__ import annotations
8
9 import math
10 import queue
11 import re
12 import time
13
14 HOME_MPOS = (5.0, -3.0, 0.0)
15 _WORD = re.compile(r"([A-Za-z])\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+))")
16
17
18 def _words(line: str) -> list[tuple[str, float]]:
19 return [(match.group(1).upper(), float(match.group(2))) for match in _WORD.finditer(line)]
20
21
22 class VirtualGrbl:
23 def __init__(self) -> None:
24 self.mpos = [0.0, 0.0, 0.0]
25 self.wco = [0.0, 0.0, 0.0]
26 self.state = "Idle"
27 self.distance = 90
28 self.force_wco = True
29 self.reports = 0
30 self.jogs: list[tuple[float, float]] = []
31 self.jog_queue: list[tuple[float, float]] = []
32 self.drawn: list[tuple[float, float]] = []
33 self.commands: list[str] = []
34 self._polls = 0
35 self._line = ""
36
37 @property
38 def wpos(self) -> list[float]:
39 return [self.mpos[i] - self.wco[i] for i in range(3)]
40
41 def set_work(self, x: float, y: float, z: float = 0.0) -> None:
42 self.mpos = [self.wco[0] + x, self.wco[1] + y, self.wco[2] + z]
43
44 def finish(self) -> None:
45 """Voer jog die al geaccepteerd is alsnog uit."""
46 for x, y in self.jog_queue:
47 self.mpos[0] = self.wco[0] + x
48 self.mpos[1] = self.wco[1] + y
49 self.jog_queue.clear()
50 self._polls = 0
51 self.state = "Idle"
52
53 def stale_idle(self) -> str:
54 """Idle op de plek van vóór de jog, zonder WCO. Zo'n regel komt te vroeg binnen."""
55 return self._status(False, "Idle")
56
57 def feed(self, data: bytes) -> list[str]:
58 replies: list[str] = []
59 for char in data.decode("latin1"):
60 if char == "?":
61 replies.append(self._status(True, self.state))
62 elif char == "!":
63 self.state = "Hold"
64 elif char == "~":
65 self.state = "Idle" if not self.jog_queue else "Jog"
66 elif char == "\x18":
67 self.state = "Idle"
68 self.jog_queue.clear()
69 self._line = ""
70 replies.append("Grbl 1.1f ['$' for help]")
71 elif char in "\r\n":
72 line = self._line.strip()
73 self._line = ""
74 if line:
75 replies.extend(self._command(line))
76 else:
77 self._line += char
78 return replies
79
80 def _status(self, advance: bool, state: str) -> str:
81 if advance and self.jog_queue:
82 self._polls += 1
83 if self._polls >= 3:
84 x, y = self.jog_queue.pop(0)
85 self.mpos[0] = self.wco[0] + x
86 self.mpos[1] = self.wco[1] + y
87 self._polls = 0
88 self.state = "Jog" if self.jog_queue else "Idle"
89 state = self.state
90 self.reports += 1
91 include_wco = self.force_wco or self.reports % 10 == 0
92 if include_wco:
93 self.force_wco = False
94 mpos = self.mpos
95 body = f"<{state}|MPos:{mpos[0]:.3f},{mpos[1]:.3f},{mpos[2]:.3f}"
96 if include_wco:
97 body += f"|WCO:{self.wco[0]:.3f},{self.wco[1]:.3f},{self.wco[2]:.3f}"
98 return body + ">"
99
100 def _command(self, line: str) -> list[str]:
101 self.commands.append(line)
102 if line.startswith("$J="):
103 return self._jog(line[3:])
104 if line.startswith("$H"):
105 self.finish()
106 self.mpos = list(HOME_MPOS)
107 self.state = "Idle"
108 return [self._status(False, "Idle"), "ok"]
109 if line.startswith("$I"):
110 return ["[VER:1.1f#TA4]", "ok"]
111 if line.startswith("$$"):
112 return ["$110=6000", "$111=6000", "ok"]
113 if line.startswith("$"):
114 return ["ok"]
115 return self._motion(line)
116
117 def _jog(self, rest: str) -> list[str]:
118 mode = 90
119 x = y = None
120 for letter, value in _words(rest):
121 if letter == "G" and int(value) in (90, 91):
122 mode = int(value)
123 elif letter == "X":
124 x = value
125 elif letter == "Y":
126 y = value
127 base = self.jog_queue[-1] if self.jog_queue else (self.wpos[0], self.wpos[1])
128 if mode == 90:
129 target = (base[0] if x is None else x, base[1] if y is None else y)
130 else:
131 target = (base[0] + (x or 0.0), base[1] + (y or 0.0))
132 self.jogs.append(target)
133 self.jog_queue.append(target)
134 self.state = "Jog"
135 self._polls = 0
136 return ["ok"]
137
138 def _motion(self, line: str) -> list[str]:
139 words = _words(line)
140 if not words:
141 return ["ok"]
142 g = None
143 x = y = z = i = j = None
144 for letter, value in words:
145 if letter == "G" and int(value) in (0, 1, 2, 3, 4, 21, 90, 91, 92, 94):
146 g = int(value)
147 elif letter == "X":
148 x = value
149 elif letter == "Y":
150 y = value
151 elif letter == "Z":
152 z = value
153 elif letter == "I":
154 i = value
155 elif letter == "J":
156 j = value
157 if g in (90, 91):
158 self.distance = g
159 if g == 92:
160 if x is not None:
161 self.wco[0] = self.mpos[0] - x
162 if y is not None:
163 self.wco[1] = self.mpos[1] - y
164 if z is not None:
165 self.wco[2] = self.mpos[2] - z
166 self.force_wco = True
167 return ["ok"]
168 if g in (0, 1, 2, 3) or g is None and any(value is not None for value in (x, y, z)):
169 wx, wy, wz = self.wpos
170 if self.distance == 91:
171 tx = wx if x is None else wx + x
172 ty = wy if y is None else wy + y
173 tz = wz if z is None else wz + z
174 else:
175 tx = wx if x is None else x
176 ty = wy if y is None else y
177 tz = wz if z is None else z
178 if g in (2, 3):
179 cx = wx + (i or 0.0)
180 cy = wy + (j or 0.0)
181 if abs(math.hypot(wx - cx, wy - cy) - math.hypot(tx - cx, ty - cy)) > 0.5:
182 return ["error:33"]
183 if x is not None or y is not None:
184 self.drawn.append((tx, ty))
185 self.mpos = [self.wco[0] + tx, self.wco[1] + ty, self.wco[2] + tz]
186 return ["ok"]
187
188
189 class VirtualPort:
190 def __init__(self, grbl: VirtualGrbl) -> None:
191 self.grbl = grbl
192 self.timeout = 0.2
193 self._out: queue.Queue[bytes] = queue.Queue()
194 self._closed = False
195
196 def write(self, data: bytes) -> None:
197 for line in self.grbl.feed(data):
198 self._out.put((line + "\n").encode())
199
200 def inject(self, line: str) -> None:
201 self._out.put((line + "\n").encode())
202
203 def read(self, _size: int = 256) -> bytes:
204 try:
205 chunk = self._out.get(timeout=self.timeout)
206 except queue.Empty:
207 return b""
208 parts = [chunk]
209 while True:
210 try:
211 parts.append(self._out.get_nowait())
212 except queue.Empty:
213 break
214 return b"".join(parts)
215
216 def close(self) -> None:
217 self._closed = True
218 self._out.put(b"")
219
220
221 def settle(machine, grbl: VirtualGrbl) -> None:
222 grbl.finish()
223 machine._query()
224 time.sleep(0.08)
225
226
227 def connect(x: float, y: float, z: float = 0.0, wco: tuple[float, float, float] = (0.0, 0.0, 0.0)):
228 """Machine gekoppeld aan een virtuele GRBL die al op deze werkpositie staat."""
229 from timdraw.grbl import Machine
230
231 grbl = VirtualGrbl()
232 grbl.wco = [wco[0], wco[1], wco[2]]
233 grbl.set_work(x, y, z)
234 machine = Machine()
235 machine.attach(VirtualPort(grbl))
236 deadline = time.time() + 1.0
237 while time.time() < deadline:
238 if abs(machine.wpos[0] - x) < 0.05 and abs(machine.wpos[1] - y) < 0.05:
239 return machine, grbl
240 time.sleep(0.02)
241 return machine, grbl
@@ -0,0 +1,241 @@
1"""Virtuele GRBL 1.1, voor de testsuite. Er gaat geen USB open.
2
3GRBL met $10=1 stuurt meestal alleen MPos. WCO komt af en toe mee.
4Een jog antwoordt ok zodra de opdracht binnen is, niet pas als de pen daar is.
5"""
6
7from __future__ import annotations
8
9import math
10import queue
11import re
12import time
13
14HOME_MPOS = (5.0, -3.0, 0.0)
15_WORD = re.compile(r"([A-Za-z])\s*([+-]?(?:\d+(?:\.\d*)?|\.\d+))")
16
17
18def _words(line: str) -> list[tuple[str, float]]:
19 return [(match.group(1).upper(), float(match.group(2))) for match in _WORD.finditer(line)]
20
21
22class VirtualGrbl:
23 def __init__(self) -> None:
24 self.mpos = [0.0, 0.0, 0.0]
25 self.wco = [0.0, 0.0, 0.0]
26 self.state = "Idle"
27 self.distance = 90
28 self.force_wco = True
29 self.reports = 0
30 self.jogs: list[tuple[float, float]] = []
31 self.jog_queue: list[tuple[float, float]] = []
32 self.drawn: list[tuple[float, float]] = []
33 self.commands: list[str] = []
34 self._polls = 0
35 self._line = ""
36
37 @property
38 def wpos(self) -> list[float]:
39 return [self.mpos[i] - self.wco[i] for i in range(3)]
40
41 def set_work(self, x: float, y: float, z: float = 0.0) -> None:
42 self.mpos = [self.wco[0] + x, self.wco[1] + y, self.wco[2] + z]
43
44 def finish(self) -> None:
45 """Voer jog die al geaccepteerd is alsnog uit."""
46 for x, y in self.jog_queue:
47 self.mpos[0] = self.wco[0] + x
48 self.mpos[1] = self.wco[1] + y
49 self.jog_queue.clear()
50 self._polls = 0
51 self.state = "Idle"
52
53 def stale_idle(self) -> str:
54 """Idle op de plek van vóór de jog, zonder WCO. Zo'n regel komt te vroeg binnen."""
55 return self._status(False, "Idle")
56
57 def feed(self, data: bytes) -> list[str]:
58 replies: list[str] = []
59 for char in data.decode("latin1"):
60 if char == "?":
61 replies.append(self._status(True, self.state))
62 elif char == "!":
63 self.state = "Hold"
64 elif char == "~":
65 self.state = "Idle" if not self.jog_queue else "Jog"
66 elif char == "\x18":
67 self.state = "Idle"
68 self.jog_queue.clear()
69 self._line = ""
70 replies.append("Grbl 1.1f ['$' for help]")
71 elif char in "\r\n":
72 line = self._line.strip()
73 self._line = ""
74 if line:
75 replies.extend(self._command(line))
76 else:
77 self._line += char
78 return replies
79
80 def _status(self, advance: bool, state: str) -> str:
81 if advance and self.jog_queue:
82 self._polls += 1
83 if self._polls >= 3:
84 x, y = self.jog_queue.pop(0)
85 self.mpos[0] = self.wco[0] + x
86 self.mpos[1] = self.wco[1] + y
87 self._polls = 0
88 self.state = "Jog" if self.jog_queue else "Idle"
89 state = self.state
90 self.reports += 1
91 include_wco = self.force_wco or self.reports % 10 == 0
92 if include_wco:
93 self.force_wco = False
94 mpos = self.mpos
95 body = f"<{state}|MPos:{mpos[0]:.3f},{mpos[1]:.3f},{mpos[2]:.3f}"
96 if include_wco:
97 body += f"|WCO:{self.wco[0]:.3f},{self.wco[1]:.3f},{self.wco[2]:.3f}"
98 return body + ">"
99
100 def _command(self, line: str) -> list[str]:
101 self.commands.append(line)
102 if line.startswith("$J="):
103 return self._jog(line[3:])
104 if line.startswith("$H"):
105 self.finish()
106 self.mpos = list(HOME_MPOS)
107 self.state = "Idle"
108 return [self._status(False, "Idle"), "ok"]
109 if line.startswith("$I"):
110 return ["[VER:1.1f#TA4]", "ok"]
111 if line.startswith("$$"):
112 return ["$110=6000", "$111=6000", "ok"]
113 if line.startswith("$"):
114 return ["ok"]
115 return self._motion(line)
116
117 def _jog(self, rest: str) -> list[str]:
118 mode = 90
119 x = y = None
120 for letter, value in _words(rest):
121 if letter == "G" and int(value) in (90, 91):
122 mode = int(value)
123 elif letter == "X":
124 x = value
125 elif letter == "Y":
126 y = value
127 base = self.jog_queue[-1] if self.jog_queue else (self.wpos[0], self.wpos[1])
128 if mode == 90:
129 target = (base[0] if x is None else x, base[1] if y is None else y)
130 else:
131 target = (base[0] + (x or 0.0), base[1] + (y or 0.0))
132 self.jogs.append(target)
133 self.jog_queue.append(target)
134 self.state = "Jog"
135 self._polls = 0
136 return ["ok"]
137
138 def _motion(self, line: str) -> list[str]:
139 words = _words(line)
140 if not words:
141 return ["ok"]
142 g = None
143 x = y = z = i = j = None
144 for letter, value in words:
145 if letter == "G" and int(value) in (0, 1, 2, 3, 4, 21, 90, 91, 92, 94):
146 g = int(value)
147 elif letter == "X":
148 x = value
149 elif letter == "Y":
150 y = value
151 elif letter == "Z":
152 z = value
153 elif letter == "I":
154 i = value
155 elif letter == "J":
156 j = value
157 if g in (90, 91):
158 self.distance = g
159 if g == 92:
160 if x is not None:
161 self.wco[0] = self.mpos[0] - x
162 if y is not None:
163 self.wco[1] = self.mpos[1] - y
164 if z is not None:
165 self.wco[2] = self.mpos[2] - z
166 self.force_wco = True
167 return ["ok"]
168 if g in (0, 1, 2, 3) or g is None and any(value is not None for value in (x, y, z)):
169 wx, wy, wz = self.wpos
170 if self.distance == 91:
171 tx = wx if x is None else wx + x
172 ty = wy if y is None else wy + y
173 tz = wz if z is None else wz + z
174 else:
175 tx = wx if x is None else x
176 ty = wy if y is None else y
177 tz = wz if z is None else z
178 if g in (2, 3):
179 cx = wx + (i or 0.0)
180 cy = wy + (j or 0.0)
181 if abs(math.hypot(wx - cx, wy - cy) - math.hypot(tx - cx, ty - cy)) > 0.5:
182 return ["error:33"]
183 if x is not None or y is not None:
184 self.drawn.append((tx, ty))
185 self.mpos = [self.wco[0] + tx, self.wco[1] + ty, self.wco[2] + tz]
186 return ["ok"]
187
188
189class VirtualPort:
190 def __init__(self, grbl: VirtualGrbl) -> None:
191 self.grbl = grbl
192 self.timeout = 0.2
193 self._out: queue.Queue[bytes] = queue.Queue()
194 self._closed = False
195
196 def write(self, data: bytes) -> None:
197 for line in self.grbl.feed(data):
198 self._out.put((line + "\n").encode())
199
200 def inject(self, line: str) -> None:
201 self._out.put((line + "\n").encode())
202
203 def read(self, _size: int = 256) -> bytes:
204 try:
205 chunk = self._out.get(timeout=self.timeout)
206 except queue.Empty:
207 return b""
208 parts = [chunk]
209 while True:
210 try:
211 parts.append(self._out.get_nowait())
212 except queue.Empty:
213 break
214 return b"".join(parts)
215
216 def close(self) -> None:
217 self._closed = True
218 self._out.put(b"")
219
220
221def settle(machine, grbl: VirtualGrbl) -> None:
222 grbl.finish()
223 machine._query()
224 time.sleep(0.08)
225
226
227def connect(x: float, y: float, z: float = 0.0, wco: tuple[float, float, float] = (0.0, 0.0, 0.0)):
228 """Machine gekoppeld aan een virtuele GRBL die al op deze werkpositie staat."""
229 from timdraw.grbl import Machine
230
231 grbl = VirtualGrbl()
232 grbl.wco = [wco[0], wco[1], wco[2]]
233 grbl.set_work(x, y, z)
234 machine = Machine()
235 machine.attach(VirtualPort(grbl))
236 deadline = time.time() + 1.0
237 while time.time() < deadline:
238 if abs(machine.wpos[0] - x) < 0.05 and abs(machine.wpos[1] - y) < 0.05:
239 return machine, grbl
240 time.sleep(0.02)
241 return machine, grbl