agentslicer 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentslicer/__init__.py +0 -0
- agentslicer/bridge/__init__.py +0 -0
- agentslicer/bridge/ams.py +238 -0
- agentslicer/bridge/bambu.py +385 -0
- agentslicer/bridge/fixtures/orca-project_file-p2s.json +35 -0
- agentslicer/bridge/monitor.py +164 -0
- agentslicer/bridge/orca_printers.py +109 -0
- agentslicer/bridge/sniff.py +61 -0
- agentslicer/render/__init__.py +0 -0
- agentslicer/render/calibrate.py +167 -0
- agentslicer/render/camera.py +59 -0
- agentslicer/render/cameras/p2s.json +72 -0
- agentslicer/render/cameras/p2s_initial.json +3 -0
- agentslicer/render/capture_calib.py +31 -0
- agentslicer/render/gcode.py +149 -0
- agentslicer/render/preview.py +297 -0
- agentslicer/server.py +390 -0
- agentslicer/slicer/__init__.py +0 -0
- agentslicer/slicer/catalog.py +250 -0
- agentslicer/slicer/opc.py +293 -0
- agentslicer/slicer/orca.py +179 -0
- agentslicer/slicer/settings.py +180 -0
- agentslicer/slicer/sync.py +327 -0
- agentslicer-0.1.0.dist-info/METADATA +124 -0
- agentslicer-0.1.0.dist-info/RECORD +28 -0
- agentslicer-0.1.0.dist-info/WHEEL +4 -0
- agentslicer-0.1.0.dist-info/entry_points.txt +3 -0
- agentslicer-0.1.0.dist-info/licenses/LICENSE +661 -0
agentslicer/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""Map a sliced file's filaments to the printer's AMS slots, the way Orca does.
|
|
2
|
+
|
|
3
|
+
Ported from OrcaSlicer v2.5.3:
|
|
4
|
+
- DevMappingUtil::ams_filament_mapping (src/slic3r/GUI/DeviceCore/DevMapping.cpp):
|
|
5
|
+
type must match (and colour alpha), then a greedy global minimum colour distance,
|
|
6
|
+
ties going to the tray with the same filament id; a tray may be reused when no
|
|
7
|
+
unused tray fits; with no AMS at all, the external spool is used.
|
|
8
|
+
- calc_color_distance (GuiColor.cpp) = DeltaE76 over Orca's RGB2Lab
|
|
9
|
+
(Utils/ColorSpaceConvert.cpp). Orca feeds 0-255 channel values into a pivot meant
|
|
10
|
+
for 0-1, so its distances are not standard Delta E; this port keeps that so the
|
|
11
|
+
agent picks the same slots as Orca's Print dialog.
|
|
12
|
+
- Mapping arrays as SelectMachineDialog builds them (SelectMachine.cpp): one entry per
|
|
13
|
+
filament preset in the file; ams_mapping = tray index or -1 (external spool or
|
|
14
|
+
unused); ams_mapping2 = {ams_id, slot_id}, 255/255 when unused.
|
|
15
|
+
- Bambu <-> Orca filament ids from Orca's resources/printers/bambu_filament_ids.json
|
|
16
|
+
(read from the installed Orca).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import json
|
|
22
|
+
import math
|
|
23
|
+
import re
|
|
24
|
+
import zipfile
|
|
25
|
+
from pathlib import Path
|
|
26
|
+
|
|
27
|
+
VIRTUAL_MAIN = 255
|
|
28
|
+
UNSET = 0xFF
|
|
29
|
+
NO_MATCH = 999999.0
|
|
30
|
+
AMS_HT_FIRST_ID = 128 # AMS HT units report ids from 128 and index as ams_id + slot
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _bambu_to_orca() -> dict[str, str]:
|
|
34
|
+
try:
|
|
35
|
+
from agentslicer.slicer import sync
|
|
36
|
+
rows = json.loads(sync.filament_ids_file().read_text(encoding="utf-8"))["filaments"]
|
|
37
|
+
except Exception: # no Orca / offline: match on type and colour only
|
|
38
|
+
return {}
|
|
39
|
+
return {row["bambu_id"]: orca_id for orca_id, row in rows.items()}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ---- Orca's colour distance, verbatim maths ----
|
|
43
|
+
|
|
44
|
+
def _pivot_rgb(n: float) -> float:
|
|
45
|
+
return ((n + 0.055) / 1.055) ** 2.4 * 100.0 if n > 0.04045 else n / 12.92 * 100.0
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _pivot_xyz(n: float) -> float:
|
|
49
|
+
return n ** (1 / 3) if n > 0.008856 else 7.787 * n + 16.0 / 116.0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _lab(r: int, g: int, b: int) -> tuple[float, float, float]:
|
|
53
|
+
r, g, b = _pivot_rgb(r), _pivot_rgb(g), _pivot_rgb(b) # 0-255 in, as Orca does
|
|
54
|
+
x = 0.412453 * r + 0.357580 * g + 0.180423 * b
|
|
55
|
+
y = 0.212671 * r + 0.715160 * g + 0.072169 * b
|
|
56
|
+
z = 0.019334 * r + 0.119193 * g + 0.950227 * b
|
|
57
|
+
fx, fy, fz = _pivot_xyz(x / 95.047), _pivot_xyz(y / 100.0), _pivot_xyz(z / 108.883)
|
|
58
|
+
return 116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def color_distance(c1: tuple, c2: tuple) -> float:
|
|
62
|
+
return math.dist(_lab(*c1[:3]), _lab(*c2[:3]))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_color(s: str) -> tuple[int, int, int, int]:
|
|
66
|
+
"""'#RRGGBB', '#RRGGBBAA' or tray 'RRGGBBAA' -> RGBA (white if unparseable,
|
|
67
|
+
as DevAmsTray::decode_color)."""
|
|
68
|
+
h = (s or "").lstrip("#")
|
|
69
|
+
if len(h) == 6:
|
|
70
|
+
h += "FF"
|
|
71
|
+
if len(h) != 8 or not re.fullmatch(r"[0-9A-Fa-f]{8}", h):
|
|
72
|
+
return (255, 255, 255, 255)
|
|
73
|
+
return tuple(int(h[i:i + 2], 16) for i in (0, 2, 4, 6))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ---- inputs ----
|
|
77
|
+
|
|
78
|
+
def file_filaments(path: Path, plate: int = 1) -> tuple[list[dict], int]:
|
|
79
|
+
"""Filaments the plate uses, and the total number of filament presets in the file."""
|
|
80
|
+
with zipfile.ZipFile(path) as z:
|
|
81
|
+
info = z.read("Metadata/slice_info.config").decode()
|
|
82
|
+
cfg = json.loads(z.read("Metadata/project_settings.config"))
|
|
83
|
+
m = re.search(rf'<plate>\s*<metadata key="index" value="{plate}"/>(.*?)</plate>', info, re.S)
|
|
84
|
+
block = m.group(1) if m else info
|
|
85
|
+
ids = cfg.get("filament_ids") or []
|
|
86
|
+
names = cfg.get("filament_settings_id") or []
|
|
87
|
+
out = []
|
|
88
|
+
for attrs in re.findall(r"<filament ([^>]*)/>", block):
|
|
89
|
+
a = dict(re.findall(r'(\w+)="([^"]*)"', attrs))
|
|
90
|
+
idx = int(a["id"]) - 1
|
|
91
|
+
profile = names[idx] if idx < len(names) else ""
|
|
92
|
+
fid = ids[idx] if idx < len(ids) else ""
|
|
93
|
+
if not fid and profile: # the Orca CLI leaves filament_ids blank; read the profile
|
|
94
|
+
try:
|
|
95
|
+
from agentslicer.slicer.orca import profile_value
|
|
96
|
+
fid = profile_value("filament", profile, "filament_id") or ""
|
|
97
|
+
except Exception:
|
|
98
|
+
fid = ""
|
|
99
|
+
out.append({"index": idx, "type": a.get("type", ""), "color": a.get("color", ""),
|
|
100
|
+
"used_g": float(a.get("used_g", 0) or 0), "filament_id": fid,
|
|
101
|
+
"profile": profile})
|
|
102
|
+
return out, max(len(names), max((f["index"] for f in out), default=-1) + 1)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def printer_trays(report: dict) -> list[dict]:
|
|
106
|
+
"""Loaded AMS trays and the external spool from a full status report."""
|
|
107
|
+
p = report.get("print", report)
|
|
108
|
+
to_orca = _bambu_to_orca()
|
|
109
|
+
trays = []
|
|
110
|
+
for unit in (p.get("ams") or {}).get("ams", []) or []:
|
|
111
|
+
ams_id = int(unit.get("id", 0))
|
|
112
|
+
for t in unit.get("tray", []) or []:
|
|
113
|
+
if not t.get("tray_type"):
|
|
114
|
+
continue # empty slot
|
|
115
|
+
slot = int(t.get("id", 0))
|
|
116
|
+
index = ams_id + slot if ams_id >= AMS_HT_FIRST_ID else ams_id * 4 + slot
|
|
117
|
+
trays.append(_tray(t, index, ams_id, slot, to_orca))
|
|
118
|
+
ext = p.get("vt_tray") or {}
|
|
119
|
+
if ext.get("tray_type"):
|
|
120
|
+
trays.append(_tray(ext, int(ext.get("id", VIRTUAL_MAIN)), VIRTUAL_MAIN, 0, to_orca, external=True))
|
|
121
|
+
return trays
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _tray(t, index, ams_id, slot, to_orca, external=False) -> dict:
|
|
125
|
+
remain = t.get("remain", -1)
|
|
126
|
+
return {"index": index, "ams_id": ams_id, "slot_id": slot, "external": external,
|
|
127
|
+
"type": _fila_type(t.get("tray_type", ""), t.get("tray_info_idx", "")),
|
|
128
|
+
"color": t.get("tray_color", ""),
|
|
129
|
+
"filament_id": to_orca.get(t.get("tray_info_idx", ""), t.get("tray_info_idx", "")),
|
|
130
|
+
"bambu_id": t.get("tray_info_idx", ""), "name": t.get("tray_sub_brands", ""),
|
|
131
|
+
"remain_pct": remain if isinstance(remain, int) and remain >= 0 else None}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _fila_type(tray_type: str, bambu_id: str) -> str:
|
|
135
|
+
"""DevAmsTray::get_filament_type."""
|
|
136
|
+
alias = {"Sup.PLA": "PLA-S", "Sup.PA": "PA-S", "Sup.ABS": "ABS-S", "Support W": "PLA-S",
|
|
137
|
+
"Support G": "PA-S"}
|
|
138
|
+
if tray_type in alias:
|
|
139
|
+
return alias[tray_type]
|
|
140
|
+
if tray_type == "Support":
|
|
141
|
+
return "PA-S" if bambu_id == "GFS01" else "PLA-S"
|
|
142
|
+
return tray_type
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# ---- Orca's mapping algorithm ----
|
|
146
|
+
|
|
147
|
+
def map_filaments(filaments: list[dict], trays: list[dict]) -> list[dict | None]:
|
|
148
|
+
"""Returns, per filament (same order), the chosen tray or None."""
|
|
149
|
+
ams = [t for t in trays if not t["external"]]
|
|
150
|
+
pool = ams if ams else [t for t in trays if t["external"]]
|
|
151
|
+
dist = []
|
|
152
|
+
for f in filaments:
|
|
153
|
+
fc = parse_color(f["color"])
|
|
154
|
+
row = []
|
|
155
|
+
for t in pool:
|
|
156
|
+
tc = parse_color(t["color"])
|
|
157
|
+
d = color_distance(fc, tc)
|
|
158
|
+
match = f["type"] == t["type"]
|
|
159
|
+
if not match or fc[3] != tc[3]:
|
|
160
|
+
d = NO_MATCH
|
|
161
|
+
row.append((d, match))
|
|
162
|
+
dist.append(row)
|
|
163
|
+
|
|
164
|
+
result: list[dict | None] = [None] * len(filaments)
|
|
165
|
+
picked_src, picked_tar = set(), set()
|
|
166
|
+
for _ in range(len(filaments)):
|
|
167
|
+
best = None # (distance, src, tar)
|
|
168
|
+
|
|
169
|
+
def consider(i, j):
|
|
170
|
+
nonlocal best
|
|
171
|
+
d, ok = dist[i][j]
|
|
172
|
+
if not ok:
|
|
173
|
+
return
|
|
174
|
+
if best is None or d < best[0]:
|
|
175
|
+
best = (d, i, j)
|
|
176
|
+
elif d == best[0] and (filaments[best[1]]["filament_id"] != pool[best[2]]["filament_id"]
|
|
177
|
+
and filaments[i]["filament_id"] == pool[j]["filament_id"]):
|
|
178
|
+
best = (d, i, j)
|
|
179
|
+
|
|
180
|
+
for i in range(len(filaments)):
|
|
181
|
+
if i in picked_src:
|
|
182
|
+
continue
|
|
183
|
+
for j in range(len(pool)):
|
|
184
|
+
if j in picked_tar:
|
|
185
|
+
d, ok = dist[i][j]
|
|
186
|
+
if ok and d < 0.0001: # identical colour may share a tray
|
|
187
|
+
best = (d, i, j)
|
|
188
|
+
continue
|
|
189
|
+
consider(i, j)
|
|
190
|
+
if best is None: # Orca: retry allowing used trays only while nothing is picked
|
|
191
|
+
for j in range(len(pool)):
|
|
192
|
+
consider(i, j)
|
|
193
|
+
if best is None:
|
|
194
|
+
break
|
|
195
|
+
_, i, j = best
|
|
196
|
+
result[i] = dict(pool[j], distance=round(best[0], 1))
|
|
197
|
+
picked_src.add(i)
|
|
198
|
+
picked_tar.add(j)
|
|
199
|
+
if len(pool) == 1 and pool[0]["external"]:
|
|
200
|
+
result = [r if r is not None else dict(pool[0], distance=None) for r in result]
|
|
201
|
+
return result
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def plan(path: Path, report: dict, plate: int = 1) -> dict:
|
|
205
|
+
"""Mapping arrays for project_file plus a readable explanation and warnings."""
|
|
206
|
+
filaments, n_presets = file_filaments(path, plate)
|
|
207
|
+
trays = printer_trays(report)
|
|
208
|
+
picks = map_filaments(filaments, trays)
|
|
209
|
+
v0 = [-1] * n_presets
|
|
210
|
+
v1 = [{"ams_id": UNSET, "slot_id": UNSET} for _ in range(n_presets)]
|
|
211
|
+
rows, warnings = [], []
|
|
212
|
+
for f, t in zip(filaments, picks):
|
|
213
|
+
row = {"filament": f["index"] + 1, "wants": f"{f['type']} {f['color']}",
|
|
214
|
+
"profile": f["profile"], "grams": f["used_g"]}
|
|
215
|
+
if t is None:
|
|
216
|
+
row["tray"] = None
|
|
217
|
+
warnings.append(f"filament {f['index'] + 1} ({f['type']}) has no loaded {f['type']} "
|
|
218
|
+
"spool to map to")
|
|
219
|
+
else:
|
|
220
|
+
v0[f["index"]] = -1 if t["external"] else t["index"]
|
|
221
|
+
v1[f["index"]] = {"ams_id": t["ams_id"], "slot_id": t["slot_id"]}
|
|
222
|
+
where = "external spool" if t["external"] else f"AMS {t['ams_id'] + 1} slot {t['slot_id'] + 1}"
|
|
223
|
+
row.update(tray=where, tray_index=t["index"], loaded=f"{t['type']} #{t['color'][:6]}",
|
|
224
|
+
color_distance=t["distance"],
|
|
225
|
+
same_filament=bool(f["filament_id"]) and f["filament_id"] == t["filament_id"])
|
|
226
|
+
if t["distance"] and t["distance"] > 2000:
|
|
227
|
+
warnings.append(f"filament {f['index'] + 1}: closest loaded colour is #{t['color'][:6]}, "
|
|
228
|
+
f"file wants {f['color']}")
|
|
229
|
+
if t["remain_pct"] is not None and t["remain_pct"] < 10:
|
|
230
|
+
warnings.append(f"{where} is at {t['remain_pct']}%")
|
|
231
|
+
rows.append(row)
|
|
232
|
+
used = [t for t in picks if t is not None]
|
|
233
|
+
return {"ok": all(t is not None for t in picks), "mapping": rows, "warnings": warnings,
|
|
234
|
+
"ams_mapping": v0, "ams_mapping2": v1,
|
|
235
|
+
"use_ams": any(not t["external"] for t in used),
|
|
236
|
+
"loaded": [{"tray": "external" if t["external"] else f"AMS {t['ams_id'] + 1} slot {t['slot_id'] + 1}",
|
|
237
|
+
"type": t["type"], "color": t["color"][:6], "name": t["name"],
|
|
238
|
+
"remain_pct": t["remain_pct"]} for t in trays]}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
# /// script
|
|
2
|
+
# requires-python = ">=3.11"
|
|
3
|
+
# dependencies = ["paho-mqtt>=2.1"]
|
|
4
|
+
# ///
|
|
5
|
+
"""Bambu LAN bridge for agents (Developer Mode, MQTT + FTPS + RTSPS).
|
|
6
|
+
|
|
7
|
+
Commands:
|
|
8
|
+
status full status summary as JSON
|
|
9
|
+
frame OUT.jpg grab one camera frame
|
|
10
|
+
light on|off chamber light
|
|
11
|
+
upload FILE.3mf upload a sliced 3MF to the printer's storage
|
|
12
|
+
print FILE.3mf --yes upload a sliced 3MF and start it (needs --yes)
|
|
13
|
+
stop stop the current print
|
|
14
|
+
clear-error dismiss the printer's current print error
|
|
15
|
+
|
|
16
|
+
Printer: any printer connected in OrcaSlicer (--printer NAME, default: the one
|
|
17
|
+
selected in Orca). Output is JSON on stdout.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import ftplib
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import ssl
|
|
25
|
+
import sys
|
|
26
|
+
import threading
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
import paho.mqtt.client as mqtt
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class Printer:
|
|
33
|
+
def __init__(self, ip: str, serial: str, code: str):
|
|
34
|
+
self.ip, self.serial, self.code = ip, serial, code
|
|
35
|
+
|
|
36
|
+
# ---- MQTT ----
|
|
37
|
+
def _client(self) -> mqtt.Client:
|
|
38
|
+
c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
|
|
39
|
+
c.username_pw_set("bblp", self.code)
|
|
40
|
+
c.tls_set(cert_reqs=ssl.CERT_NONE) # self-signed cert; LAN only
|
|
41
|
+
c.tls_insecure_set(True)
|
|
42
|
+
return c
|
|
43
|
+
|
|
44
|
+
def request(self, payload: dict, wait_for=None, timeout=15) -> dict | None:
|
|
45
|
+
"""Publish payload; optionally wait for a report matching wait_for(data)."""
|
|
46
|
+
got, result = threading.Event(), {}
|
|
47
|
+
c = self._client()
|
|
48
|
+
|
|
49
|
+
def on_connect(cl, _u, _f, rc, _p=None):
|
|
50
|
+
if rc != 0:
|
|
51
|
+
result["error"] = f"mqtt connect failed: {rc}"
|
|
52
|
+
got.set()
|
|
53
|
+
return
|
|
54
|
+
cl.subscribe(f"device/{self.serial}/report")
|
|
55
|
+
cl.publish(f"device/{self.serial}/request", json.dumps(payload))
|
|
56
|
+
if wait_for is None:
|
|
57
|
+
got.set()
|
|
58
|
+
|
|
59
|
+
def on_message(_cl, _u, msg):
|
|
60
|
+
data = json.loads(msg.payload)
|
|
61
|
+
if wait_for and wait_for(data):
|
|
62
|
+
result.update(data)
|
|
63
|
+
got.set()
|
|
64
|
+
|
|
65
|
+
c.on_connect, c.on_message = on_connect, on_message
|
|
66
|
+
c.connect(self.ip, 8883, keepalive=30)
|
|
67
|
+
c.loop_start()
|
|
68
|
+
ok = got.wait(timeout)
|
|
69
|
+
c.loop_stop()
|
|
70
|
+
c.disconnect()
|
|
71
|
+
if "error" in result:
|
|
72
|
+
raise RuntimeError(result["error"])
|
|
73
|
+
if wait_for and not ok:
|
|
74
|
+
raise TimeoutError(f"no matching report in {timeout}s")
|
|
75
|
+
return result or None
|
|
76
|
+
|
|
77
|
+
def report(self) -> dict:
|
|
78
|
+
return self.request(
|
|
79
|
+
{"pushing": {"sequence_id": "0", "command": "pushall"}},
|
|
80
|
+
wait_for=lambda d: len(d.get("print", {})) > 20,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
def light(self, on: bool) -> dict:
|
|
84
|
+
mode = "on" if on else "off"
|
|
85
|
+
self.request({"system": {
|
|
86
|
+
"sequence_id": "0", "command": "ledctrl", "led_node": "chamber_light",
|
|
87
|
+
"led_mode": mode, "led_on_time": 500, "led_off_time": 500,
|
|
88
|
+
"loop_times": 0, "interval_time": 0}})
|
|
89
|
+
lights = self.report()["print"].get("lights_report", [])
|
|
90
|
+
return {"chamber_light": next((l["mode"] for l in lights if l.get("node") == "chamber_light"), "unknown")}
|
|
91
|
+
|
|
92
|
+
def start_print(self, name: str, plate: int = 1, use_ams: bool = True,
|
|
93
|
+
ams_mapping: list[int] | None = None, md5: str = "",
|
|
94
|
+
leveling: str = "auto", flow: str = "auto",
|
|
95
|
+
nozzle_offset: str = "auto", layer_inspect: bool = True,
|
|
96
|
+
timelapse: bool = False, bed_type: str = "auto",
|
|
97
|
+
ams_mapping2: list[dict] | None = None) -> dict:
|
|
98
|
+
# Wire format captured from Orca -> P2S (fixtures/orca-project_file-p2s.json);
|
|
99
|
+
# Orca hands these to Bambu's closed network plugin, which builds the JSON.
|
|
100
|
+
# Values from Orca source: PrintOption::getValueInt (off=0, on=1, auto=2)
|
|
101
|
+
# and bed_type_to_gcode_string (plate type names, see BED_TYPES).
|
|
102
|
+
mode = {"off": 0, "on": 1, "auto": 2}
|
|
103
|
+
mapping = ams_mapping or []
|
|
104
|
+
ack = self.request({"print": {
|
|
105
|
+
"sequence_id": "0", "command": "project_file",
|
|
106
|
+
"param": f"Metadata/plate_{plate}.gcode",
|
|
107
|
+
# As Orca sends it. The printer moves the file to /cache after a
|
|
108
|
+
# print, so it must be re-uploaded for every job (see print_file).
|
|
109
|
+
"file": name, "url": f"ftp://{name}",
|
|
110
|
+
"subtask_name": Path(name).name.removesuffix(".3mf").removesuffix(".gcode"),
|
|
111
|
+
"project_id": "0", "profile_id": "0", "task_id": "0", "subtask_id": "0",
|
|
112
|
+
"md5": md5, "cfg": "0", "timelapse": timelapse,
|
|
113
|
+
"bed_type": bed_type, "bed_leveling": False,
|
|
114
|
+
"auto_bed_leveling": mode[leveling],
|
|
115
|
+
"extrude_cali_flag": mode[flow], "flow_cali": False,
|
|
116
|
+
"nozzle_offset_cali": mode[nozzle_offset],
|
|
117
|
+
"vibration_cali": False, "layer_inspect": layer_inspect,
|
|
118
|
+
"use_ams": use_ams, "ams_mapping": mapping,
|
|
119
|
+
"ams_mapping2": ams_mapping2 if ams_mapping2 is not None else
|
|
120
|
+
[{"ams_id": s // 4, "slot_id": s % 4} if s >= 0 else {"ams_id": 255, "slot_id": 255}
|
|
121
|
+
for s in mapping],
|
|
122
|
+
}}, wait_for=lambda d: d.get("print", {}).get("command") == "project_file"
|
|
123
|
+
and "result" in d["print"])
|
|
124
|
+
echo = (ack or {}).get("print", {})
|
|
125
|
+
if echo.get("result") != "SUCCESS":
|
|
126
|
+
raise RuntimeError(f"printer refused start: {echo.get('result')} {echo.get('reason')}")
|
|
127
|
+
return summarize(self.report())
|
|
128
|
+
|
|
129
|
+
def print_file(self, local: Path, **opts) -> dict:
|
|
130
|
+
"""Upload a sliced 3MF as NAME.gcode.3mf (Orca's naming) and start it."""
|
|
131
|
+
base = local.name.removesuffix(".3mf").removesuffix(".gcode")
|
|
132
|
+
name = f"{base}.gcode.3mf"
|
|
133
|
+
self.upload(local, remote_name=name)
|
|
134
|
+
md5 = hashlib.md5(local.read_bytes()).hexdigest().upper()
|
|
135
|
+
return self.start_print(name, md5=md5, bed_type=bed_type_of(local), **opts)
|
|
136
|
+
|
|
137
|
+
def clear_error(self) -> dict:
|
|
138
|
+
# Orca DeviceErrorDialog DBL_CHECK_OK: command_clean_print_error + _uiop
|
|
139
|
+
p = self.report()["print"]
|
|
140
|
+
err = int(p.get("print_error") or 0)
|
|
141
|
+
self.request({"print": {"sequence_id": "0", "command": "clean_print_error",
|
|
142
|
+
"subtask_id": str(p.get("subtask_id", "0")), "print_error": err}})
|
|
143
|
+
self.request({"system": {"sequence_id": "0", "command": "uiop", "name": "print_error",
|
|
144
|
+
"action": "close", "source": 1, "type": "dialog",
|
|
145
|
+
"err": f"{err:08X}"}})
|
|
146
|
+
return {"cleared": f"{err:08X}", **summarize(self.report())}
|
|
147
|
+
|
|
148
|
+
def gcode(self, lines: str) -> None:
|
|
149
|
+
"""Send raw G-code (Orca MachineObject::publish_gcode). Moves the printer."""
|
|
150
|
+
if not lines.endswith("\n"):
|
|
151
|
+
lines += "\n"
|
|
152
|
+
self.request({"print": {"sequence_id": "0", "command": "gcode_line", "param": lines}})
|
|
153
|
+
|
|
154
|
+
def stop(self) -> dict:
|
|
155
|
+
# Same as Orca's MachineObject::command_task_abort
|
|
156
|
+
self.request({"print": {"sequence_id": "0", "command": "stop", "param": ""}})
|
|
157
|
+
return summarize(self.report())
|
|
158
|
+
|
|
159
|
+
# ---- Camera ----
|
|
160
|
+
def frame(self, out: Path, width: int | None = None) -> dict:
|
|
161
|
+
"""One chamber camera frame over RTSPS (port 322), decoded with PyAV's bundled
|
|
162
|
+
FFmpeg. The printer's certificate is self-signed, hence tls_verify 0."""
|
|
163
|
+
import av
|
|
164
|
+
url = f"rtsps://bblp:{self.code}@{self.ip}:322/streaming/live/1"
|
|
165
|
+
try:
|
|
166
|
+
with av.open(url, options={"rtsp_transport": "tcp", "tls_verify": "0"},
|
|
167
|
+
timeout=(10, 10)) as c:
|
|
168
|
+
img = next(c.decode(video=0)).to_image()
|
|
169
|
+
except (av.FFmpegError, StopIteration, OSError) as e:
|
|
170
|
+
raise RuntimeError(f"camera: {str(e).replace(self.code, '***')}") from None
|
|
171
|
+
if width and width < img.width:
|
|
172
|
+
img = img.resize((width, round(img.height * width / img.width)))
|
|
173
|
+
img.save(out, quality=90)
|
|
174
|
+
return {"frame": str(out)}
|
|
175
|
+
|
|
176
|
+
# ---- FTPS (implicit TLS, port 990) ----
|
|
177
|
+
def upload(self, path: Path, remote_name: str | None = None) -> dict:
|
|
178
|
+
ctx = ssl.create_default_context()
|
|
179
|
+
ctx.check_hostname, ctx.verify_mode = False, ssl.CERT_NONE
|
|
180
|
+
ftp = _ImplicitFTPS(context=ctx)
|
|
181
|
+
ftp.connect(self.ip, 990, timeout=30)
|
|
182
|
+
ftp.login("bblp", self.code)
|
|
183
|
+
ftp.prot_p()
|
|
184
|
+
remote = remote_name or path.name
|
|
185
|
+
with path.open("rb") as f:
|
|
186
|
+
ftp.storbinary(f"STOR {remote}", f)
|
|
187
|
+
size = ftp.size(remote)
|
|
188
|
+
ftp.quit()
|
|
189
|
+
if size != path.stat().st_size:
|
|
190
|
+
raise RuntimeError(f"upload size mismatch: {size} != {path.stat().st_size}")
|
|
191
|
+
return {"uploaded": remote, "bytes": size}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class _ImplicitFTPS(ftplib.FTP_TLS):
|
|
195
|
+
"""ftplib only does explicit TLS; Bambu printers use implicit TLS."""
|
|
196
|
+
|
|
197
|
+
def __init__(self, *a, **kw):
|
|
198
|
+
super().__init__(*a, **kw)
|
|
199
|
+
self._sock = None
|
|
200
|
+
|
|
201
|
+
@property
|
|
202
|
+
def sock(self):
|
|
203
|
+
return self._sock
|
|
204
|
+
|
|
205
|
+
@sock.setter
|
|
206
|
+
def sock(self, value):
|
|
207
|
+
if value is not None and not isinstance(value, ssl.SSLSocket):
|
|
208
|
+
value = self.context.wrap_socket(value)
|
|
209
|
+
self._sock = value
|
|
210
|
+
|
|
211
|
+
def ntransfercmd(self, cmd, rest=None):
|
|
212
|
+
# Reuse the control session for data TLS (printer requires it).
|
|
213
|
+
conn, size = ftplib.FTP.ntransfercmd(self, cmd, rest)
|
|
214
|
+
conn = self.context.wrap_socket(conn, session=self.sock.session)
|
|
215
|
+
return conn, size
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
# Print step names, from Orca DeviceManager.cpp get_stage_string (stg_cur)
|
|
219
|
+
STAGES = {
|
|
220
|
+
0: 'Printing',
|
|
221
|
+
1: 'Auto bed leveling',
|
|
222
|
+
2: 'Heatbed preheating',
|
|
223
|
+
3: 'Vibration compensation',
|
|
224
|
+
4: 'Changing filament',
|
|
225
|
+
5: 'M400 pause',
|
|
226
|
+
6: 'Paused (filament ran out)',
|
|
227
|
+
7: 'Heating nozzle',
|
|
228
|
+
8: 'Calibrating dynamic flow',
|
|
229
|
+
9: 'Scanning bed surface',
|
|
230
|
+
10: 'Inspecting first layer',
|
|
231
|
+
11: 'Identifying build plate type',
|
|
232
|
+
12: 'Calibrating Micro Lidar',
|
|
233
|
+
13: 'Homing toolhead',
|
|
234
|
+
14: 'Cleaning nozzle tip',
|
|
235
|
+
15: 'Checking extruder temperature',
|
|
236
|
+
16: 'Paused by the user',
|
|
237
|
+
17: 'Pause (front cover fall off)',
|
|
238
|
+
18: 'Calibrating the micro lidar',
|
|
239
|
+
19: 'Calibrating flow ratio',
|
|
240
|
+
20: 'Pause (nozzle temperature malfunction)',
|
|
241
|
+
21: 'Pause (heatbed temperature malfunction)',
|
|
242
|
+
22: 'Filament unloading',
|
|
243
|
+
23: 'Pause (step loss)',
|
|
244
|
+
24: 'Filament loading',
|
|
245
|
+
25: 'Motor noise cancellation',
|
|
246
|
+
26: 'Pause (AMS offline)',
|
|
247
|
+
27: 'Pause (low speed of the heatbreak fan)',
|
|
248
|
+
28: 'Pause (chamber temperature control problem)',
|
|
249
|
+
29: 'Cooling chamber',
|
|
250
|
+
30: 'Pause (G-code inserted by user)',
|
|
251
|
+
31: 'Motor noise showoff',
|
|
252
|
+
32: 'Pause (nozzle clumping)',
|
|
253
|
+
33: 'Pause (cutter error)',
|
|
254
|
+
34: 'Pause (first layer error)',
|
|
255
|
+
35: 'Pause (nozzle clog)',
|
|
256
|
+
36: 'Measuring motion precision',
|
|
257
|
+
37: 'Enhancing motion precision',
|
|
258
|
+
38: 'Measure motion accuracy',
|
|
259
|
+
39: 'Nozzle offset calibration',
|
|
260
|
+
40: 'High temperature auto bed leveling',
|
|
261
|
+
41: 'Auto Check: Quick Release Lever',
|
|
262
|
+
42: 'Auto Check: Door and Upper Cover',
|
|
263
|
+
43: 'Laser Calibration',
|
|
264
|
+
44: 'Auto Check: Platform',
|
|
265
|
+
45: 'Confirming BirdsEye Camera location',
|
|
266
|
+
46: 'Calibrating BirdsEye Camera',
|
|
267
|
+
47: 'Auto bed leveling -phase 1',
|
|
268
|
+
48: 'Auto bed leveling -phase 2',
|
|
269
|
+
49: 'Heating chamber',
|
|
270
|
+
50: 'Cooling heatbed',
|
|
271
|
+
51: 'Printing calibration lines',
|
|
272
|
+
52: 'Auto Check: Material',
|
|
273
|
+
53: 'Live View Camera Calibration',
|
|
274
|
+
54: 'Waiting for heatbed to reach target temperature',
|
|
275
|
+
55: 'Auto Check: Material Position',
|
|
276
|
+
56: 'Cutting Module Offset Calibration',
|
|
277
|
+
57: 'Measuring Surface',
|
|
278
|
+
58: 'Thermal Preconditioning for first layer optimization',
|
|
279
|
+
65: 'Calibrating the detection position of nozzle clumping',
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
# Slicer curr_bed_type -> wire bed_type (Orca PrintConfig.hpp bed_type_to_gcode_string)
|
|
284
|
+
BED_TYPES = {
|
|
285
|
+
"Supertack Plate": "supertack_plate", "Cool Plate": "cool_plate",
|
|
286
|
+
"Textured Cool Plate": "textured_cool_plate", "Engineering Plate": "eng_plate",
|
|
287
|
+
"High Temp Plate": "hot_plate", "Textured PEI Plate": "textured_plate",
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def bed_type_of(path: Path) -> str:
|
|
292
|
+
"""Read the plate type a 3MF was sliced for."""
|
|
293
|
+
import re
|
|
294
|
+
import zipfile
|
|
295
|
+
with zipfile.ZipFile(path) as z:
|
|
296
|
+
cfg = z.read("Metadata/project_settings.config").decode()
|
|
297
|
+
m = re.search(r'"curr_bed_type":\s*"([^"]*)"', cfg)
|
|
298
|
+
return BED_TYPES.get(m.group(1), "auto") if m else "auto"
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def summarize(report: dict) -> dict:
|
|
302
|
+
p = report.get("print", {})
|
|
303
|
+
dev = p.get("device") or {}
|
|
304
|
+
trays = []
|
|
305
|
+
for unit in (p.get("ams") or {}).get("ams", []) or []:
|
|
306
|
+
for t in unit.get("tray", []) or []:
|
|
307
|
+
if t.get("tray_type"):
|
|
308
|
+
trays.append({
|
|
309
|
+
"ams": unit.get("id"), "slot": t.get("id"),
|
|
310
|
+
"type": t.get("tray_type"), "color": t.get("tray_color"),
|
|
311
|
+
"remain_pct": None if t.get("remain", -1) < 0 else t.get("remain"),
|
|
312
|
+
})
|
|
313
|
+
lights = p.get("lights_report", [])
|
|
314
|
+
return {
|
|
315
|
+
"state": p.get("gcode_state"),
|
|
316
|
+
"step": STAGES.get(p.get("stg_cur"), None if p.get("stg_cur", -1) < 0 else f"unknown ({p.get('stg_cur')})"),
|
|
317
|
+
"progress_pct": p.get("mc_percent"),
|
|
318
|
+
"remaining_min": p.get("mc_remaining_time"),
|
|
319
|
+
"layer": [p.get("layer_num"), p.get("total_layer_num")],
|
|
320
|
+
"file": p.get("subtask_name") or p.get("gcode_file"),
|
|
321
|
+
"nozzle": {"diameter": p.get("nozzle_diameter"), "type": p.get("nozzle_type"),
|
|
322
|
+
"temp": p.get("nozzle_temper"), "target": p.get("nozzle_target_temper")},
|
|
323
|
+
"bed": {"temp": p.get("bed_temper"), "target": p.get("bed_target_temper")},
|
|
324
|
+
# P2S reports chamber temp under device.ctc
|
|
325
|
+
"chamber_temp": p.get("chamber_temper") or (dev.get("ctc") or {}).get("info", {}).get("temp"),
|
|
326
|
+
"chamber_light": next((l["mode"] for l in lights if l.get("node") == "chamber_light"), None),
|
|
327
|
+
"ams_trays": trays,
|
|
328
|
+
"errors": p.get("hms") or [],
|
|
329
|
+
"print_error": f"{p['print_error']:08X}" if p.get("print_error") else None,
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def main() -> int:
|
|
334
|
+
ap = argparse.ArgumentParser()
|
|
335
|
+
ap.add_argument("--printer", help="name or serial of a printer connected in OrcaSlicer "
|
|
336
|
+
"(default: the one selected in Orca)")
|
|
337
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
338
|
+
sub.add_parser("status")
|
|
339
|
+
s = sub.add_parser("frame"); s.add_argument("out", type=Path)
|
|
340
|
+
s = sub.add_parser("light"); s.add_argument("mode", choices=["on", "off"])
|
|
341
|
+
s = sub.add_parser("upload"); s.add_argument("file", type=Path)
|
|
342
|
+
sub.add_parser("stop")
|
|
343
|
+
sub.add_parser("clear-error")
|
|
344
|
+
s = sub.add_parser("print", help="upload a local sliced 3MF and start it")
|
|
345
|
+
s.add_argument("file", type=Path)
|
|
346
|
+
s.add_argument("--plate", type=int, default=1)
|
|
347
|
+
s.add_argument("--ams-mapping", type=lambda v: [int(x) for x in v.split(",")])
|
|
348
|
+
s.add_argument("--no-ams", action="store_true")
|
|
349
|
+
for opt in ("leveling", "flow", "nozzle-offset"):
|
|
350
|
+
s.add_argument(f"--{opt}", choices=["off", "on", "auto"], default="auto")
|
|
351
|
+
s.add_argument("--no-layer-inspect", action="store_true")
|
|
352
|
+
s.add_argument("--yes", action="store_true", help="required: confirms bed is clear")
|
|
353
|
+
a = ap.parse_args()
|
|
354
|
+
from agentslicer.bridge import orca_printers
|
|
355
|
+
pr = Printer(*orca_printers.connection(a.printer))
|
|
356
|
+
|
|
357
|
+
try:
|
|
358
|
+
if a.cmd == "status":
|
|
359
|
+
out = summarize(pr.report())
|
|
360
|
+
elif a.cmd == "frame":
|
|
361
|
+
out = pr.frame(a.out)
|
|
362
|
+
elif a.cmd == "light":
|
|
363
|
+
out = pr.light(a.mode == "on")
|
|
364
|
+
elif a.cmd == "clear-error":
|
|
365
|
+
out = pr.clear_error()
|
|
366
|
+
elif a.cmd == "stop":
|
|
367
|
+
out = pr.stop()
|
|
368
|
+
elif a.cmd == "upload":
|
|
369
|
+
out = pr.upload(a.file)
|
|
370
|
+
elif a.cmd == "print":
|
|
371
|
+
if not a.yes:
|
|
372
|
+
out = {"error": "refusing to start without --yes (confirm the bed is clear)"}
|
|
373
|
+
else:
|
|
374
|
+
out = pr.print_file(a.file, plate=a.plate, use_ams=not a.no_ams,
|
|
375
|
+
ams_mapping=a.ams_mapping, leveling=a.leveling,
|
|
376
|
+
flow=a.flow, nozzle_offset=a.nozzle_offset,
|
|
377
|
+
layer_inspect=not a.no_layer_inspect)
|
|
378
|
+
except Exception as e: # report every failure as JSON for agents
|
|
379
|
+
out = {"error": f"{type(e).__name__}: {e}"}
|
|
380
|
+
print(json.dumps(out, indent=2))
|
|
381
|
+
return 1 if "error" in out else 0
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
if __name__ == "__main__":
|
|
385
|
+
sys.exit(main())
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"print": {
|
|
3
|
+
"ams_mapping": [
|
|
4
|
+
0
|
|
5
|
+
],
|
|
6
|
+
"ams_mapping2": [
|
|
7
|
+
{
|
|
8
|
+
"ams_id": 0,
|
|
9
|
+
"slot_id": 0
|
|
10
|
+
}
|
|
11
|
+
],
|
|
12
|
+
"auto_bed_leveling": 2,
|
|
13
|
+
"bed_leveling": false,
|
|
14
|
+
"bed_type": "hot_plate",
|
|
15
|
+
"cfg": "0",
|
|
16
|
+
"command": "project_file",
|
|
17
|
+
"extrude_cali_flag": 2,
|
|
18
|
+
"file": "Skadis_Pegboard_Tool_Y-Hook_-_Parametric!.gcode.3mf",
|
|
19
|
+
"flow_cali": false,
|
|
20
|
+
"layer_inspect": true,
|
|
21
|
+
"md5": "1F2FE59D68F694F533EDA4C0876FCC09",
|
|
22
|
+
"nozzle_offset_cali": 2,
|
|
23
|
+
"param": "Metadata/plate_1.gcode",
|
|
24
|
+
"profile_id": "0",
|
|
25
|
+
"project_id": "0",
|
|
26
|
+
"sequence_id": "20000",
|
|
27
|
+
"subtask_id": "0",
|
|
28
|
+
"subtask_name": "Skadis_Pegboard_Tool_Y-Hook_-_Parametric!",
|
|
29
|
+
"task_id": "0",
|
|
30
|
+
"timelapse": false,
|
|
31
|
+
"url": "ftp://Skadis_Pegboard_Tool_Y-Hook_-_Parametric!.gcode.3mf",
|
|
32
|
+
"use_ams": true,
|
|
33
|
+
"vibration_cali": false
|
|
34
|
+
}
|
|
35
|
+
}
|