manager.py 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016
  1. """Virtual Printer Manager - coordinates SSDP, MQTT, and FTP services.
  2. Each virtual printer runs its own independent services (FTP, MQTT, SSDP, Bind)
  3. bound to its dedicated IP address, regardless of mode.
  4. """
  5. import asyncio
  6. import json
  7. import logging
  8. import time
  9. from collections.abc import Callable
  10. from datetime import datetime, timezone
  11. from pathlib import Path
  12. from typing import TYPE_CHECKING
  13. from backend.app.core.config import settings as app_settings
  14. from backend.app.models.virtual_printer import (
  15. VP_MODE_ARCHIVE,
  16. VP_MODE_PROXY,
  17. VP_MODE_QUEUE,
  18. normalize_vp_mode,
  19. )
  20. from backend.app.services.bambu_mqtt import resolve_external_spools_in_mapping
  21. from backend.app.services.virtual_printer.bind_server import BindServer
  22. from backend.app.services.virtual_printer.certificate import CertificateService
  23. from backend.app.services.virtual_printer.ftp_server import VirtualPrinterFTPServer, compute_passive_port_slice
  24. from backend.app.services.virtual_printer.mqtt_bridge import MQTTBridge
  25. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  26. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy, VirtualPrinterSSDPServer
  27. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager, TCPProxy
  28. from backend.app.utils.printer_models import is_nozzle_rack_model
  29. if TYPE_CHECKING:
  30. from backend.app.services.printer_manager import PrinterManager
  31. logger = logging.getLogger(__name__)
  32. # Mapping of SSDP model codes to display names
  33. # These are the codes that slicers expect during discovery
  34. # Sources:
  35. # - https://gist.github.com/Alex-Schaefer/72a9e2491a42da2ef99fb87601955cc3
  36. # - https://github.com/psychoticbeef/BambuLabOrcaSlicerDiscovery
  37. VIRTUAL_PRINTER_MODELS = {
  38. # X1 Series
  39. "BL-P001": "X1C", # X1 Carbon
  40. "BL-P002": "X1", # X1
  41. "C13": "X1E", # X1E
  42. # X2 Series
  43. "N6": "X2D", # X2D
  44. # A2 Series (single-FDM + integrated cutter/plotter)
  45. "N9": "A2L", # A2L
  46. # P Series
  47. "C11": "P1P", # P1P
  48. "C12": "P1S", # P1S
  49. "N7": "P2S", # P2S
  50. # A1 Series
  51. "N2S": "A1", # A1
  52. "N1": "A1 Mini", # A1 Mini
  53. # H2 Series
  54. "O1D": "H2D", # H2D
  55. "O1E": "H2D Pro", # H2D Pro
  56. "O2D": "H2D Pro", # H2D Pro
  57. "O1C": "H2C", # H2C
  58. "O1C2": "H2C", # H2C (dual nozzle variant)
  59. "O1S": "H2S", # H2S
  60. }
  61. # Serial number prefixes for each model (based on Bambu Lab serial number format)
  62. # Format: MMM??RYMDDUUUUU (15 chars total)
  63. # MMM = Model prefix (3 chars)
  64. # ?? = Unknown/revision code (2 chars)
  65. # R = Revision letter (1 char)
  66. # Y = Year digit (1 char)
  67. # M = Month (1 char, hex: 1-9, A=Oct, B=Nov, C=Dec)
  68. # DD = Day (2 chars)
  69. # UUUUU = Unit number (5 chars)
  70. MODEL_SERIAL_PREFIXES = {
  71. # X1 Series
  72. "BL-P001": "00M00A", # X1C
  73. "BL-P002": "00M00A", # X1
  74. "C13": "03W00A", # X1E
  75. # X2 Series
  76. "N6": "20P90A", # X2D (first 4 chars "20P9" match real serials)
  77. # A2 Series
  78. "N9": "26A19A", # A2L (first 5 chars "26A19" match real serials)
  79. # P Series
  80. "C11": "01S00A", # P1P
  81. "C12": "01P00A", # P1S
  82. "N7": "22E00A", # P2S
  83. # A1 Series
  84. "N2S": "03900A", # A1
  85. "N1": "03000A", # A1 Mini
  86. # H2 Series
  87. "O1D": "09400A", # H2D
  88. "O1E": "09400A", # H2D Pro (same prefix family as H2D)
  89. "O2D": "09400A", # H2D Pro
  90. "O1C": "09400A", # H2C
  91. "O1C2": "09400A", # H2C (dual nozzle variant)
  92. "O1S": "09400A", # H2S
  93. }
  94. # Reverse mapping: display name → SSDP model code (for auto-inheriting from printer model)
  95. DISPLAY_NAME_TO_MODEL_CODE = {v: k for k, v in VIRTUAL_PRINTER_MODELS.items()}
  96. # Default model
  97. DEFAULT_VIRTUAL_PRINTER_MODEL = "BL-P001" # X1C
  98. # Bound on per-instance ``_slicer_print_options`` cache size. The slicer's
  99. # project_file MQTT command stashes one dict per filename; the
  100. # corresponding ``_add_to_print_queue`` pop only fires when the file
  101. # upload completes. Failed / cancelled / non-3MF uploads orphan their
  102. # stash. The bound triggers FIFO eviction in ``on_print_command`` once
  103. # the dict fills, so a long-running VP can't leak unbounded state.
  104. _SLICER_OPTIONS_CACHE_LIMIT = 128
  105. # How long ``_add_to_print_queue`` waits for the slicer's MQTT
  106. # ``project_file`` after the FTP upload completes (#1780 round 3).
  107. # Bambu Studio sends FTP first, then MQTT immediately after — but on
  108. # wireless / loaded setups the MQTT command can land 2+ s after FTP,
  109. # which used to time the wait out and silently drop ``nozzle_mapping``
  110. # + the other slicer-driven flags. The bumped window covers the
  111. # observed worst case in the field; the late-MQTT fallback in
  112. # ``on_print_command`` covers the rest.
  113. _SLICER_OPTIONS_WAIT_TIMEOUT = 5.0
  114. # How long ``on_print_command`` will retroactively stamp slicer fields
  115. # onto a recently-committed queue item when the MQTT print command
  116. # arrives after ``_SLICER_OPTIONS_WAIT_TIMEOUT`` expired. Covers
  117. # extra-late MQTT (slow wireless slicer, NIC drop+retry) and the
  118. # scheduler tick interval before dispatch picks the item up.
  119. _RECENT_QUEUE_ITEM_TTL = 30.0
  120. # BambuStudio's tri-state calibration options (bed_leveling / flow_cali /
  121. # nozzle_offset_cali) travel on the project_file command as an int — off=0,
  122. # on=1, auto=2 (getValueInt parity). Bed levelling and flow calibration add a
  123. # bool that is true only for "on"; nozzle offset calibration is the int alone.
  124. _TRISTATE_INT = {0: "off", 1: "on", 2: "auto"}
  125. def _tristate_from_slicer(data: dict, bool_field: str | None, int_field: str) -> str | None:
  126. """Reconstruct off/on/auto from a captured slicer project_file dict.
  127. Prefer the int companion (auto_bed_leveling / extrude_cali_flag / etc.) which
  128. carries all three states; fall back to the bool field (on/off only); return
  129. None when the slicer sent neither so the caller can use its own default.
  130. """
  131. if int_field in data:
  132. try:
  133. resolved = _TRISTATE_INT.get(int(data[int_field]))
  134. except (TypeError, ValueError):
  135. resolved = None
  136. if resolved is not None:
  137. return resolved
  138. if bool_field is not None and bool_field in data:
  139. return "on" if bool(data[bool_field]) else "off"
  140. return None
  141. def _extract_slicer_ams_mapping_json(data: dict, log_prefix: str, *, is_dual_nozzle: bool = False) -> str | None:
  142. """Pull the slicer's own AMS-slot pick out of a captured project_file payload.
  143. BambuStudio/OrcaSlicer resolves the physical AMS tray for each filament
  144. live, right before sending — either automatically or via the slicer's
  145. manual per-filament AMS-slot assignment dialog — and embeds the result as
  146. ``ams_mapping`` (``list[int]``, position = slot_id-1, value = global tray
  147. ID) directly in the MQTT ``project_file`` command. Confirmed by wire
  148. capture: the field is present and already in the exact shape
  149. ``PrintQueueItem.ams_mapping`` expects.
  150. The VP-queue path previously never read this — every queued print had the
  151. scheduler re-derive a mapping from just the 3MF's static type/color at
  152. dispatch time (`PrintScheduler._compute_ams_mapping_for_printer`), discarding
  153. the slicer's already-correct, live-resolved pick. That re-derivation can
  154. land on the wrong physical spool whenever the file's type+color match
  155. isn't unique (e.g. two spools of the same color) or the file's own
  156. filament-slot color wasn't what the user actually intended for that
  157. particular print. Capturing it here — mirroring the existing
  158. ``nozzle_mapping`` passthrough for H2C rack-swap models (#1780) — lets the
  159. scheduler's "already resolved, don't touch it" branch in
  160. ``_ensure_ams_mapping`` use the slicer's own choice unchanged.
  161. That branch skipping ``_compute_ams_mapping_for_printer`` is also what
  162. makes this a trade rather than a pure win: ``prefer_lowest_filament``, its
  163. AMS-filament-backup gate (#1766), the inventory-remain overrides and the
  164. per-slot force-color overrides all live inside that function. Callers are
  165. responsible for the gating — this parser only says what the slicer sent.
  166. An external spool is ``-1`` in the flat list, the same as a filament with
  167. no tray, and is named only in ``ams_mapping2``. It is resolved from there
  168. to its global tray (254/255), as the usage capture does (#3166); dispatch
  169. turns that back into the external-spool entry. Kept as ``-1`` it dispatched
  170. as unmapped and the printer stopped with 0700-8012 (#3237).
  171. ``is_dual_nozzle`` is the target printer's, since that decides which
  172. global tray an external spool is.
  173. Returns ``None`` when the field is absent, unparsable, or the classic
  174. "all -1" unresolved-race sentinel (#2589) — never worth trusting over a
  175. fresh live computation.
  176. """
  177. raw = data.get("ams_mapping")
  178. if raw is None:
  179. return None
  180. if isinstance(raw, str):
  181. try:
  182. raw = json.loads(raw)
  183. except json.JSONDecodeError:
  184. logger.warning("%s Slicer ams_mapping is unparseable JSON, dropping: %r", log_prefix, raw)
  185. return None
  186. # bool is a subclass of int in Python — isinstance(True, int) is True —
  187. # so it must be excluded explicitly, or [True, False] would pass as a
  188. # valid mapping.
  189. if not isinstance(raw, list) or not raw or not all(isinstance(v, int) and not isinstance(v, bool) for v in raw):
  190. return None
  191. detail = data.get("ams_mapping2")
  192. if isinstance(detail, str):
  193. try:
  194. detail = json.loads(detail)
  195. except json.JSONDecodeError:
  196. detail = None
  197. raw = resolve_external_spools_in_mapping(raw, detail, is_dual_nozzle)
  198. if all(v < 0 for v in raw):
  199. # #2589 sentinel — every slot unresolved. Let the scheduler compute a
  200. # fresh mapping from live AMS state instead of trusting this.
  201. return None
  202. return json.dumps(raw)
  203. def _get_serial_for_model(model: str, serial_suffix: str) -> str:
  204. """Get serial number for the given model and suffix."""
  205. prefix = MODEL_SERIAL_PREFIXES.get(model, "00M09A")
  206. return f"{prefix}{serial_suffix}"
  207. class VirtualPrinterInstance:
  208. """Per-printer state and file handling logic.
  209. Each instance represents one virtual printer with its own config,
  210. upload directory, certificates, and file handling mode.
  211. """
  212. def __init__(
  213. self,
  214. *,
  215. vp_id: int,
  216. name: str,
  217. mode: str,
  218. model: str,
  219. access_code: str,
  220. serial_suffix: str,
  221. target_printer_ip: str = "",
  222. target_printer_serial: str = "",
  223. target_printer_id: int | None = None,
  224. auto_dispatch: bool = True,
  225. queue_force_color_match: bool = False,
  226. save_ams_mapping: bool = False,
  227. gcode_injection: bool = False,
  228. bind_ip: str = "",
  229. remote_interface_ip: str = "",
  230. tailscale_disabled: bool = True,
  231. base_dir: Path,
  232. session_factory: Callable | None = None,
  233. printer_manager: "PrinterManager | None" = None,
  234. ):
  235. self.id = vp_id
  236. self.name = name
  237. # Normalize on construction so the rest of the code only compares
  238. # canonical values, even when a legacy DB row hasn't been migrated
  239. # yet (e.g. fresh-from-disk during the boot window before the
  240. # one-shot migration in `core/database.py` has executed).
  241. self.mode = normalize_vp_mode(mode) or VP_MODE_ARCHIVE
  242. self.model = model
  243. self.access_code = access_code
  244. self.serial_suffix = serial_suffix
  245. self.target_printer_ip = target_printer_ip
  246. self.target_printer_serial = target_printer_serial
  247. self.target_printer_id = target_printer_id
  248. self.auto_dispatch = auto_dispatch
  249. self.queue_force_color_match = queue_force_color_match
  250. self.save_ams_mapping = save_ams_mapping
  251. self.gcode_injection = gcode_injection
  252. self.bind_ip = bind_ip
  253. self.remote_interface_ip = remote_interface_ip
  254. self.tailscale_disabled = tailscale_disabled
  255. self._session_factory = session_factory
  256. self._printer_manager = printer_manager
  257. # Directories
  258. self.upload_dir = base_dir / "uploads" / str(vp_id)
  259. self.cert_dir = base_dir / "certs" / str(vp_id)
  260. shared_ca_dir = base_dir / "certs"
  261. # Ensure directories exist
  262. self.upload_dir.mkdir(parents=True, exist_ok=True)
  263. (self.upload_dir / "cache").mkdir(exist_ok=True)
  264. self.cert_dir.mkdir(parents=True, exist_ok=True)
  265. # Certificate service (shared CA, per-instance printer cert)
  266. self._cert_service = CertificateService(
  267. cert_dir=self.cert_dir,
  268. serial=self.serial,
  269. shared_ca_dir=shared_ca_dir,
  270. )
  271. # Pending files for MQTT correlation
  272. self._pending_files: dict[str, Path] = {}
  273. # Slicer-side print options captured from the MQTT `project_file`
  274. # command, keyed by filename. Used by `_add_to_print_queue` so the
  275. # queue item inherits the user's slicer-chosen timelapse / bed_leveling
  276. # / flow_cali / vibration_cali / layer_inspect / use_ams toggles rather
  277. # than falling back to the global `default_*` settings (#1403). FTP
  278. # completes a few hundred ms before the slicer's MQTT `project_file`
  279. # arrives, so the queue-add path waits briefly on the event below
  280. # before reading the dict. Events are popped along with the options
  281. # so the dict stays bounded.
  282. self._slicer_print_options: dict[str, dict] = {}
  283. self._slicer_print_options_events: dict[str, asyncio.Event] = {}
  284. # Queue items recently committed by `_add_to_print_queue`, keyed by
  285. # FTP filename. Used by `on_print_command` to retroactively stamp the
  286. # slicer's nozzle_mapping (and the other slicer-driven flags) onto a
  287. # queue item when the MQTT `project_file` arrives after the queue-add
  288. # wait timed out — the #1780 round-3 race. Value is
  289. # (queue_item_ids, monotonic_committed_at); entries older than
  290. # `_RECENT_QUEUE_ITEM_TTL` are evicted opportunistically on each
  291. # queue-add.
  292. self._recent_queue_items: dict[str, tuple[list[int], float]] = {}
  293. # Per entry above: the highest slot id each queued plate prints, so a
  294. # late slicer AMS mapping is stamped only onto plates it reaches.
  295. self._recent_queue_item_reach: dict[str, dict[int, int]] = {}
  296. # Per-instance services
  297. self._proxy: SlicerProxyManager | None = None
  298. self._ftp: VirtualPrinterFTPServer | None = None
  299. self._mqtt: SimpleMQTTServer | None = None
  300. self._mqtt_bridge: MQTTBridge | None = None
  301. self._rtsp_proxy: TCPProxy | None = None
  302. self._bind: BindServer | None = None
  303. self._ssdp: VirtualPrinterSSDPServer | None = None
  304. self._ssdp_proxy: SSDPProxy | None = None
  305. self._tasks: list[asyncio.Task] = []
  306. # Pending timer that re-fires gcode_state=FINISH after a project_file
  307. # ack. See ``_schedule_finish_release`` for the #1658 rationale.
  308. self._finish_release_task: asyncio.Task | None = None
  309. @property
  310. def serial(self) -> str:
  311. """Full serial number for this virtual printer."""
  312. return _get_serial_for_model(self.model or DEFAULT_VIRTUAL_PRINTER_MODEL, self.serial_suffix)
  313. @property
  314. def cert_path(self) -> Path:
  315. return self._cert_service.cert_path
  316. @property
  317. def key_path(self) -> Path:
  318. return self._cert_service.key_path
  319. @property
  320. def is_proxy(self) -> bool:
  321. return self.mode == "proxy"
  322. @property
  323. def is_running(self) -> bool:
  324. return len(self._tasks) > 0 and all(not t.done() for t in self._tasks)
  325. def generate_certificates(self) -> tuple[Path, Path]:
  326. """Generate certificates for this instance."""
  327. self._cert_service.serial = self.serial if not self.is_proxy else (self.target_printer_serial or self.serial)
  328. additional_ips = [self.remote_interface_ip] if self.remote_interface_ip else None
  329. if self.bind_ip:
  330. additional_ips = additional_ips or []
  331. additional_ips.append(self.bind_ip)
  332. self._cert_service.delete_printer_certificate()
  333. return self._cert_service.generate_certificates(additional_ips=additional_ips)
  334. # -- File handling callbacks --
  335. async def on_file_received(self, file_path: Path, source_ip: str) -> None:
  336. """Handle file upload completion from FTP."""
  337. logger.info("[VP %s] Received file: %s from %s", self.name, file_path.name, source_ip)
  338. self._pending_files[file_path.name] = file_path
  339. # Accept both canonical (`archive`/`queue`) and legacy
  340. # (`immediate`/`print_queue`) wire values so a stale row that hasn't
  341. # been migrated yet still dispatches correctly. Migration in
  342. # `core/database.py` rewrites existing rows once at boot.
  343. mode = normalize_vp_mode(self.mode)
  344. if mode == VP_MODE_ARCHIVE:
  345. await self._archive_file(file_path, source_ip)
  346. elif mode == VP_MODE_QUEUE:
  347. await self._add_to_print_queue(file_path, source_ip)
  348. else:
  349. await self._queue_file(file_path, source_ip)
  350. # Signal job completion to the slicer. Send-flow slicers don't watch the
  351. # post-upload state and would be happy with anything; the Print flow
  352. # (intended for proxy-mode VPs, but users sometimes click it against
  353. # queue/immediate/review modes too — #1280) watches the gcode_state
  354. # cycle and only releases its in-flight-job lock when it sees FINISH.
  355. # Going PREPARE → IDLE wedges the slicer's UI at "Downloading...(0%)"
  356. # and blocks the next dispatch with "busy with another print job".
  357. # PREPARE → FINISH satisfies both flows. prepare_percent=100 also
  358. # unfreezes the slicer's "Downloading X%" progress bar which it ticks
  359. # against the same field during the upload window.
  360. if self._mqtt and file_path.suffix.lower() == ".3mf":
  361. self._mqtt.set_gcode_state("FINISH", filename=file_path.name, prepare_percent="100")
  362. # FINISH is the terminal state for the upload cycle per #1280
  363. # (commit 0d6171dc). The Print-flow slicer's in-flight-job lock
  364. # releases on FINISH; resetting to IDLE 2 s later would re-confuse
  365. # the slicer that just unwedged. Earlier audit suggesting the
  366. # IDLE reset was wrong — staying at FINISH is the designed
  367. # behaviour. The next upload's PREPARE→FINISH cycle starts fresh.
  368. def _keeps_slicer_nozzle_mapping(self) -> bool:
  369. """Whether the slicer's ``nozzle_mapping`` is stored on the queue item.
  370. On a rack model (H2C) it holds physical rack positions, which name the
  371. rack of the printer the slicer was looking at: kept only when this VP
  372. targets that one printer. A VP for any printer of the model leaves it
  373. empty, and the dispatch resolves the positions against the rack of the
  374. printer it picks. Elsewhere it holds extruder indices, which are the
  375. same on every printer of the model.
  376. """
  377. return self.target_printer_id is not None or not is_nozzle_rack_model(self.model)
  378. def _keeps_slicer_use_ams(self) -> bool:
  379. """Whether the slicer's ``use_ams`` is stored on the queue item.
  380. The slicer was looking at this VP, which advertises no AMS. Only a VP
  381. bound to one printer stands for a machine whose AMS the user chose to
  382. use or not; a VP for any printer of the model leaves it on and the
  383. dispatch reconciles it against the printer it picks (#2595).
  384. """
  385. return self.target_printer_id is not None
  386. def _target_is_dual_nozzle(self) -> bool:
  387. """Whether the target printer has two nozzles, which decides the global
  388. tray of an external spool in the slicer's mapping (#3237).
  389. Same signal dispatch uses: the live client's detection, else its model.
  390. Without a client, the VP's own model is what the slicer sliced for.
  391. """
  392. from backend.app.utils.printer_models import is_dual_nozzle_model
  393. client = (
  394. self._printer_manager.get_client(self.target_printer_id)
  395. if self._printer_manager is not None and self.target_printer_id is not None
  396. else None
  397. )
  398. if client is not None:
  399. return bool(getattr(client, "_is_dual_nozzle", False)) or is_dual_nozzle_model(
  400. getattr(client, "model", None)
  401. )
  402. return is_dual_nozzle_model(self.model)
  403. async def on_print_command(self, filename: str, data: dict) -> None:
  404. """Handle print command from MQTT.
  405. Captures the slicer's project_file options (`timelapse`, `bed_leveling`,
  406. `flow_cali`, `vibration_cali`, `layer_inspect`, `use_ams`, plus the
  407. H2C rack-pick `nozzle_mapping`) so the VP-queue path can inherit them
  408. when adding the item to the queue, rather than falling back to the
  409. global default settings (#1403, #1780).
  410. Only queue mode consumes the capture; archive / review / proxy
  411. modes ignore the print command, so we skip the stash there to keep
  412. the dict from accumulating one entry per print over the VP's
  413. uptime.
  414. Also schedules the #1658 follow-up that re-fires gcode_state=FINISH a
  415. moment after the synthetic project_file ack — for every non-proxy
  416. mode — so the slicer's "Downloading" UI releases on the slicer's
  417. FTP-first-then-MQTT send order.
  418. ``filename`` is the slicer's ``subtask_name`` (bare model name, no
  419. extension) — used verbatim for `_schedule_finish_release` because
  420. push_status echoes it back to the slicer as gcode_file / subtask_name.
  421. The queue-side stash key is derived from ``data["file"]`` (the FTP
  422. filename with extension) so `_add_to_print_queue`'s
  423. ``file_path.name`` lookup matches; falls back to ``filename`` when
  424. ``data["file"]`` is absent (legacy slicers / non-3MF uploads).
  425. Stash/lookup mismatch was the #1780 root cause — every captured field
  426. silently fell back to settings defaults on every Bambu Studio "Send".
  427. """
  428. logger.info("[VP %s] Print command for: %s", self.name, filename)
  429. mode = normalize_vp_mode(self.mode)
  430. if mode != VP_MODE_PROXY and filename and self._mqtt is not None:
  431. self._schedule_finish_release(filename)
  432. if mode != VP_MODE_QUEUE:
  433. return
  434. # Stash key must match `_add_to_print_queue`'s lookup, which uses
  435. # `file_path.name` (FTP filename WITH extension). The slicer's
  436. # `subtask_name` (== this method's `filename` arg) is the bare model
  437. # name, no extension — using it as the stash key was the #1780 root
  438. # cause.
  439. stash_key = data.get("file") or filename
  440. # Drop the oldest stash if the cache is growing — happens when the
  441. # slicer sends project_file for a filename whose FTP upload was
  442. # rejected / cancelled / non-3MF, so _add_to_print_queue's pop
  443. # never fires. With no bound, a long-running VP accumulates one
  444. # dict per such mismatch.
  445. if len(self._slicer_print_options) >= _SLICER_OPTIONS_CACHE_LIMIT:
  446. try:
  447. stale_key = next(iter(self._slicer_print_options))
  448. self._slicer_print_options.pop(stale_key, None)
  449. self._slicer_print_options_events.pop(stale_key, None)
  450. logger.debug("[VP %s] Evicted stale slicer options for %s", self.name, stale_key)
  451. except StopIteration:
  452. pass
  453. self._slicer_print_options[stash_key] = dict(data)
  454. event = self._slicer_print_options_events.get(stash_key)
  455. if event:
  456. event.set()
  457. return
  458. # No consumer waiting: `_add_to_print_queue` either already gave up
  459. # (wait_for timed out) or hasn't started yet (FTP still uploading).
  460. # If a queue item was committed within the last
  461. # `_RECENT_QUEUE_ITEM_TTL`, the wait timed out and the row holds
  462. # settings defaults instead of the slicer's pick — retroactively
  463. # stamp the slicer-driven fields so the dispatcher honours the
  464. # user's choice. Covers the #1780 round-3 race where Bambu Studio's
  465. # MQTT lands just past the bumped wait ceiling.
  466. await self._restamp_recent_queue_item(stash_key, data)
  467. async def _restamp_recent_queue_item(self, stash_key: str, data: dict) -> None:
  468. """Patch slicer-driven fields onto a queue item the MQTT command missed.
  469. ``_add_to_print_queue`` waits up to ``_SLICER_OPTIONS_WAIT_TIMEOUT``
  470. for the slicer's MQTT ``project_file`` before committing the queue
  471. item. If the MQTT command arrives after that window — observed in
  472. the field at ~2.1 s on H2C / wireless setups (#1780 round 3) — the
  473. row was already written with settings defaults. This method runs
  474. on the late MQTT path: it looks up the most recent queue items
  475. committed for this filename and patches in the slicer's
  476. ``nozzle_mapping`` + ``ams_mapping`` + workflow flags, but only
  477. while the items are still ``pending`` (scheduler hasn't dispatched
  478. them yet). The two mappings pass the same gates as in
  479. ``_add_to_print_queue``.
  480. """
  481. if not self._session_factory:
  482. return
  483. entry = self._recent_queue_items.get(stash_key)
  484. plate_reach = self._recent_queue_item_reach.pop(stash_key, {})
  485. if entry is None:
  486. return
  487. queue_item_ids, committed_at = entry
  488. if time.monotonic() - committed_at > _RECENT_QUEUE_ITEM_TTL:
  489. self._recent_queue_items.pop(stash_key, None)
  490. return
  491. import json
  492. # Mirror the field set `_add_to_print_queue` reads off slicer_opts.
  493. # MQTT uses `bed_leveling` (single L); the column is `bed_levelling`.
  494. # `nozzles_info` is intentionally not stamped — column kept for
  495. # legacy rows but never written; see PrintQueueItem.nozzles_info.
  496. patch: dict = {}
  497. # Tri-state options (off/on/auto) — reconstruct from the int companion.
  498. for bool_field, int_field, column in (
  499. ("bed_leveling", "auto_bed_leveling", "bed_levelling"),
  500. ("flow_cali", "extrude_cali_flag", "flow_cali"),
  501. (None, "nozzle_offset_cali", "nozzle_offset_cali"),
  502. ):
  503. resolved = _tristate_from_slicer(data, bool_field, int_field)
  504. if resolved is not None:
  505. patch[column] = resolved
  506. # On/off options.
  507. for mqtt_field, column in (
  508. ("vibration_cali", "vibration_cali"),
  509. ("layer_inspect", "layer_inspect"),
  510. ("timelapse", "timelapse"),
  511. ("use_ams", "use_ams"),
  512. ):
  513. if mqtt_field == "use_ams" and not self._keeps_slicer_use_ams():
  514. continue
  515. if mqtt_field in data:
  516. patch[column] = bool(data[mqtt_field])
  517. # Same gate as in `_add_to_print_queue`.
  518. raw = data.get("nozzle_mapping") if self._keeps_slicer_nozzle_mapping() else None
  519. if raw is not None:
  520. if isinstance(raw, str):
  521. try:
  522. raw = json.loads(raw)
  523. except json.JSONDecodeError:
  524. logger.warning(
  525. "[VP %s] Late MQTT nozzle_mapping is unparseable JSON, dropping: %r",
  526. self.name,
  527. raw,
  528. )
  529. raw = None
  530. if raw is not None:
  531. patch["nozzle_mapping"] = json.dumps(raw)
  532. # Same two gates as the immediate path in `_add_to_print_queue`: a
  533. # model-based VP has no live AMS layout for the slicer to have resolved
  534. # tray IDs against, and taking the slicer's pick at all is the per-VP
  535. # `save_ams_mapping` opt-in (it makes the scheduler skip
  536. # `_compute_ams_mapping_for_printer`, and with it prefer-lowest and the
  537. # #1766 backup gate).
  538. ams_mapping_json = (
  539. _extract_slicer_ams_mapping_json(
  540. data, f"[VP {self.name}] Late MQTT", is_dual_nozzle=self._target_is_dual_nozzle()
  541. )
  542. if self.target_printer_id is not None and self.save_ams_mapping
  543. else None
  544. )
  545. # `Force color match` still wins for this dispatch — see the same
  546. # decision in `_add_to_print_queue`. The archive patch below is
  547. # deliberately not gated on it: persisting the pick for later reprints
  548. # is exactly what the toggle promises.
  549. if ams_mapping_json is not None and not self.queue_force_color_match:
  550. patch["ams_mapping"] = ams_mapping_json
  551. # `ams_mapping_json` alone is enough to keep going even when `patch` is
  552. # empty: with `Force color match` on it never reaches the queue item,
  553. # but it still has to be written onto the archive below.
  554. if not patch and ams_mapping_json is None:
  555. self._recent_queue_items.pop(stash_key, None)
  556. return
  557. from sqlalchemy import select, update
  558. from backend.app.models.archive import PrintArchive
  559. from backend.app.models.print_queue import PrintQueueItem
  560. try:
  561. async with self._session_factory() as db:
  562. # Only stamp items still pending; once the scheduler has
  563. # picked the row up we can't safely race the dispatcher.
  564. result = await db.execute(
  565. select(PrintQueueItem.id, PrintQueueItem.archive_id).where(
  566. PrintQueueItem.id.in_(queue_item_ids),
  567. PrintQueueItem.status == "pending",
  568. )
  569. )
  570. rows = result.all()
  571. eligible_ids = [row[0] for row in rows]
  572. if not eligible_ids:
  573. self._recent_queue_items.pop(stash_key, None)
  574. return
  575. # As in `_add_to_print_queue`: a mapping shorter than a plate's
  576. # highest slot id cannot address that plate's own slots, so that
  577. # plate is left to the scheduler's computed mapping.
  578. short_ids: list[int] = []
  579. if "ams_mapping" in patch:
  580. reach = len(json.loads(patch["ams_mapping"]))
  581. short_ids = [i for i in eligible_ids if plate_reach.get(i, 0) > reach]
  582. if short_ids:
  583. logger.warning(
  584. "[VP %s] Late slicer ams_mapping has %d entries, too few for queue item(s) %s; "
  585. "leaving those to the scheduler's mapping.",
  586. self.name,
  587. reach,
  588. short_ids,
  589. )
  590. reached_ids = [i for i in eligible_ids if i not in short_ids]
  591. if patch and reached_ids:
  592. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id.in_(reached_ids)).values(**patch))
  593. short_patch = {k: v for k, v in patch.items() if k != "ams_mapping"}
  594. if short_ids and short_patch:
  595. await db.execute(
  596. update(PrintQueueItem).where(PrintQueueItem.id.in_(short_ids)).values(**short_patch)
  597. )
  598. # The archive was already created (with no slicer_ams_mapping)
  599. # before this late MQTT arrived — see
  600. # `_extract_slicer_ams_mapping_json`'s docstring. Patch it here
  601. # too so a reprint later still picks up the slicer's pick, and
  602. # the "AMS mapping from slicer" badge reflects reality instead
  603. # of staying stuck on the archive's initial (empty) snapshot.
  604. # Already gated on `save_ams_mapping` above, and deliberately
  605. # NOT on `queue_force_color_match`: that toggle decides how
  606. # *this* print is matched, not whether the pick is worth
  607. # keeping for a later reprint.
  608. if ams_mapping_json is not None:
  609. archive_ids = {row[1] for row in rows if row[1] is not None}
  610. if archive_ids:
  611. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id.in_(archive_ids)))
  612. for archive in archive_result.scalars().all():
  613. extra = dict(archive.extra_data or {})
  614. extra["slicer_ams_mapping"] = {
  615. "mapping": json.loads(ams_mapping_json),
  616. "printer_id": self.target_printer_id,
  617. }
  618. archive.extra_data = extra
  619. await db.commit()
  620. logger.info(
  621. "[VP %s] Late slicer MQTT for %s — retroactively stamped %s onto queue item(s) %s%s",
  622. self.name,
  623. stash_key,
  624. sorted(patch.keys()),
  625. eligible_ids,
  626. " and saved the slicer's AMS pick onto the archive" if ams_mapping_json is not None else "",
  627. )
  628. except Exception as e:
  629. logger.error(
  630. "[VP %s] Failed to retroactively stamp queue item(s) %s for %s: %s",
  631. self.name,
  632. queue_item_ids,
  633. stash_key,
  634. e,
  635. )
  636. finally:
  637. self._recent_queue_items.pop(stash_key, None)
  638. def _schedule_finish_release(self, filename: str, delay: float = 1.5) -> None:
  639. """Re-set gcode_state=FINISH on the VP after the project_file ack.
  640. #1280 set FINISH after the FTP upload completes — that was correct
  641. for the slicer flow at the time (MQTT project_file → FTP → done).
  642. Bambu Studio 2.7.x flipped the order to FTP → FTP → MQTT project_file,
  643. which means ``_send_print_response`` runs *after* the FINISH set in
  644. ``on_file_received`` and overwrites the state back to PREPARE. The
  645. slicer's 1 Hz status stream then carries PREPARE forever and the
  646. send modal sits at "Downloading" until the VP is restarted (#1658).
  647. Re-firing FINISH after a short delay closes the gap: the slicer sees
  648. the synthetic PREPARE in the project_file ack (and likely one PREPARE
  649. push on the 1 Hz cycle), then the next push carries FINISH and the
  650. modal releases. Proxy mode is exempt — there the real printer drives
  651. the state through the bridge and a synthetic FINISH would clobber a
  652. real PREPARE/RUNNING transition coming back from the printer.
  653. Cancels any in-flight timer before scheduling a new one so a slicer
  654. that fires project_file twice in quick succession only ends in one
  655. FINISH.
  656. """
  657. if self._mqtt is None:
  658. return
  659. if self._finish_release_task is not None and not self._finish_release_task.done():
  660. self._finish_release_task.cancel()
  661. self._finish_release_task = asyncio.create_task(
  662. self._delayed_finish_release(filename, delay),
  663. name=f"vp-{self.id}-finish-release",
  664. )
  665. async def _delayed_finish_release(self, filename: str, delay: float) -> None:
  666. """Sleep, then set gcode_state=FINISH. Used by ``_schedule_finish_release``."""
  667. try:
  668. await asyncio.sleep(delay)
  669. except asyncio.CancelledError:
  670. return
  671. if self._mqtt is None:
  672. return
  673. self._mqtt.set_gcode_state("FINISH", filename=filename, prepare_percent="100")
  674. logger.debug("[VP %s] Re-set gcode_state=FINISH after project_file ack (%s)", self.name, filename)
  675. async def _archive_file(self, file_path: Path, source_ip: str) -> None:
  676. """Archive file immediately."""
  677. if not self._session_factory:
  678. logger.error("Cannot archive: no database session factory configured")
  679. return
  680. if file_path.suffix.lower() != ".3mf":
  681. logger.debug("Skipping non-3MF file: %s", file_path.name)
  682. self._pending_files.pop(file_path.name, None)
  683. try:
  684. file_path.unlink()
  685. except OSError:
  686. pass
  687. return
  688. archived = False
  689. try:
  690. from backend.app.api.routes.settings import get_setting
  691. from backend.app.services.archive import ArchiveService
  692. async with self._session_factory() as db:
  693. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  694. prefer_filename = name_source == "filename"
  695. service = ArchiveService(db)
  696. archive = await service.archive_print(
  697. printer_id=None,
  698. source_file=file_path,
  699. print_data={
  700. "status": "archived",
  701. "source": "virtual_printer",
  702. "source_ip": source_ip,
  703. },
  704. prefer_filename_for_name=prefer_filename,
  705. )
  706. if archive:
  707. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  708. await self._broadcast_archive_created(archive)
  709. archived = True
  710. else:
  711. logger.error("Failed to archive file: %s", file_path.name)
  712. except Exception as e:
  713. logger.error("Error archiving file: %s", e)
  714. finally:
  715. # Always release the in-flight marker and delete the temp file —
  716. # previously the failure paths only logged and the next upload of
  717. # the same name was silently rejected with "already uploading",
  718. # the upload_dir filled up indefinitely, and the slicer received
  719. # a clean 226 even though no archive existed (#audit-R2-1).
  720. self._pending_files.pop(file_path.name, None)
  721. if archived:
  722. try:
  723. file_path.unlink()
  724. except OSError:
  725. pass
  726. else:
  727. # Drop the failed temp file so it doesn't accumulate.
  728. try:
  729. file_path.unlink(missing_ok=True)
  730. except OSError:
  731. pass
  732. async def _queue_file(self, file_path: Path, source_ip: str) -> None:
  733. """Queue file for user review."""
  734. if not self._session_factory:
  735. logger.error("Cannot queue: no database session factory configured")
  736. return
  737. if file_path.suffix.lower() != ".3mf":
  738. self._pending_files.pop(file_path.name, None)
  739. try:
  740. file_path.unlink()
  741. except OSError:
  742. pass
  743. return
  744. # Peek at the 3MF for the embedded title BEFORE we hand it off to the
  745. # DB. Storing it now means the /pending-uploads/ list doesn't have to
  746. # reopen every 3MF on every render to keep the review card and the
  747. # eventual archive name in sync (#1152 follow-up). Failure to parse is
  748. # not fatal — the response model falls back to the filename stem.
  749. metadata_print_name: str | None = None
  750. try:
  751. from backend.app.services.archive import ThreeMFParser
  752. parsed = ThreeMFParser(file_path).parse()
  753. raw_name = parsed.get("print_name")
  754. if isinstance(raw_name, str) and raw_name.strip():
  755. metadata_print_name = raw_name.strip()[:255]
  756. except Exception as e:
  757. logger.debug("[VP %s] Metadata title peek failed for %s: %s", self.name, file_path.name, e)
  758. try:
  759. from backend.app.models.pending_upload import PendingUpload
  760. async with self._session_factory() as db:
  761. pending = PendingUpload(
  762. filename=file_path.name,
  763. file_path=str(file_path),
  764. file_size=file_path.stat().st_size,
  765. source_ip=source_ip,
  766. status="pending",
  767. uploaded_at=datetime.now(timezone.utc),
  768. metadata_print_name=metadata_print_name,
  769. )
  770. db.add(pending)
  771. await db.commit()
  772. logger.info("[VP %s] Queued: %s - %s", self.name, pending.id, file_path.name)
  773. except Exception as e:
  774. logger.error("Error queueing file: %s", e)
  775. # Queue insert failed — drop the temp file so it doesn't
  776. # accumulate. The file is unreachable without the DB row.
  777. try:
  778. file_path.unlink(missing_ok=True)
  779. except OSError:
  780. pass
  781. finally:
  782. # Always release the in-flight marker so concurrent uploads
  783. # with the same filename aren't spuriously rejected after
  784. # a queue failure.
  785. self._pending_files.pop(file_path.name, None)
  786. async def _add_to_print_queue(self, file_path: Path, source_ip: str) -> None:
  787. """Archive file and add to print queue, assigned to target printer or model."""
  788. if not self._session_factory:
  789. logger.error("Cannot add to print queue: no database session factory configured")
  790. return
  791. if file_path.suffix.lower() != ".3mf":
  792. self._pending_files.pop(file_path.name, None)
  793. try:
  794. file_path.unlink()
  795. except OSError:
  796. pass
  797. return
  798. # Wait briefly for the slicer's MQTT `project_file` command so the
  799. # queue item can inherit the slicer-side print options the user
  800. # picked (timelapse, bed_leveling, etc). Slicers send the FTP upload
  801. # first and the MQTT command immediately after, so the typical lag
  802. # is a few hundred ms. The window is generous enough to absorb
  803. # wireless / loaded-Pi jitter without making every VP-queue add
  804. # visibly slow — observed worst case in #1780 round 3 was 2.085 s,
  805. # the previous 2.0 s ceiling. Falls back to the global default_*
  806. # settings if MQTT doesn't arrive in time (legacy behaviour for
  807. # users on a slicer that doesn't send a print command). #1403.
  808. # The wait is skipped when there's no MQTT server attached — covers
  809. # unit tests that invoke `_add_to_print_queue` directly without
  810. # going through `on_print_command`, so they don't pay the wait tax.
  811. slicer_opts = self._slicer_print_options.pop(file_path.name, None)
  812. if slicer_opts is None and self._mqtt is not None:
  813. event = asyncio.Event()
  814. self._slicer_print_options_events[file_path.name] = event
  815. try:
  816. await asyncio.wait_for(event.wait(), timeout=_SLICER_OPTIONS_WAIT_TIMEOUT)
  817. slicer_opts = self._slicer_print_options.pop(file_path.name, None)
  818. except TimeoutError:
  819. slicer_opts = None
  820. finally:
  821. self._slicer_print_options_events.pop(file_path.name, None)
  822. # If the cache still misses, queued workflow flags / nozzle pick will
  823. # silently fall back to settings defaults. Surface the missed key so a
  824. # future stash/lookup mismatch (the #1780 root cause) is obvious in
  825. # the log instead of needing a wire capture to diagnose.
  826. if slicer_opts is None:
  827. logger.debug(
  828. "[VP %s] No slicer options cached for %r (cache keys: %s); "
  829. "workflow flags + nozzle pick will fall back to settings defaults.",
  830. self.name,
  831. file_path.name,
  832. sorted(self._slicer_print_options.keys()),
  833. )
  834. try:
  835. import json
  836. from backend.app.api.routes.settings import get_setting
  837. from backend.app.models.print_queue import PrintQueueItem
  838. from backend.app.services.archive import ArchiveService
  839. from backend.app.services.filament_requirements import extract_filament_requirements
  840. from backend.app.services.print_confirmation import confirm_outcome_for_new_queue_item
  841. from backend.app.services.print_defaults import default_print_options
  842. async with self._session_factory() as db:
  843. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  844. prefer_filename = name_source == "filename"
  845. # Workflow defaults from settings. Without this the
  846. # PrintQueueItem below would fall back to the column-level
  847. # defaults and ignore the user's workflow preferences (#1235).
  848. # The slicer-side options captured above (if any) take
  849. # precedence per-field over these defaults.
  850. defaults = await default_print_options(db)
  851. def _slicer_or(field_mqtt: str, settings_default: bool) -> bool:
  852. """Slicer's MQTT value if present, else the settings default.
  853. Slicer payloads carry both bool and int (0/1) shapes
  854. depending on firmware family — coerce via bool() so
  855. `0`/`False` and `1`/`True` both work.
  856. """
  857. if slicer_opts is not None and field_mqtt in slicer_opts:
  858. return bool(slicer_opts[field_mqtt])
  859. return settings_default
  860. def _slicer_tristate(bool_field: str | None, int_field: str, settings_default: str) -> str:
  861. """Slicer's tri-state (off/on/auto) if present, else the default."""
  862. if slicer_opts is not None:
  863. resolved = _tristate_from_slicer(slicer_opts, bool_field, int_field)
  864. if resolved is not None:
  865. return resolved
  866. return settings_default
  867. # Note the MQTT field names differ from Bambuddy's column
  868. # names: MQTT uses `bed_leveling` (single L) while the
  869. # column / settings key use `bed_levelling` (double L).
  870. bed_levelling = _slicer_tristate(
  871. "bed_leveling",
  872. "auto_bed_leveling",
  873. defaults["bed_levelling"],
  874. )
  875. flow_cali = _slicer_tristate(
  876. "flow_cali",
  877. "extrude_cali_flag",
  878. defaults["flow_cali"],
  879. )
  880. nozzle_offset_cali = _slicer_tristate(
  881. None,
  882. "nozzle_offset_cali",
  883. defaults["nozzle_offset_cali"],
  884. )
  885. vibration_cali = _slicer_or("vibration_cali", defaults["vibration_cali"])
  886. layer_inspect = _slicer_or("layer_inspect", defaults["layer_inspect"])
  887. timelapse = _slicer_or("timelapse", defaults["timelapse"])
  888. # No setting for it: the column default (on) when the slicer is
  889. # silent, or when the VP does not stand for one printer.
  890. use_ams = _slicer_or("use_ams", True) if self._keeps_slicer_use_ams() else True
  891. # "Ask for Outcome" is a default print option like the ones
  892. # above. A plate sent here from Bambu Studio is also one of the
  893. # prints `confirm_outcome_external_prints` names — but it
  894. # arrives with a queue item, so on_print_start resumes the
  895. # archive created below instead of treating it as external, and
  896. # without this the setting could never reach it (#1898).
  897. confirm_outcome = await confirm_outcome_for_new_queue_item(db, started_outside_bambuddy=True)
  898. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  899. # BambuStudio's project_file MQTT command for rack-swap models
  900. # (O1C2 today) carries `nozzle_mapping` — a per-filament array
  901. # of physical nozzle position IDs (`list[int]`). Forward it
  902. # verbatim onto the queue item so the dispatcher can replay it
  903. # in its own project_file command. Without this the H2C
  904. # firmware falls back to "last matching nozzle" auto-pick and
  905. # ignores the user's Bambu Studio choice. Every other model
  906. # has it absent from slicer_opts, so the capture is a
  907. # transparent no-op there. (`nozzles_info` was also captured
  908. # in the original fix but BambuStudio never actually sends it
  909. # — verified via wire capture on H2C — so only `nozzle_mapping`
  910. # is forwarded now.)
  911. #
  912. # On a rack model only for a VP that targets one printer: the
  913. # positions name that printer's rack. An "Any <model>" VP leaves
  914. # them to the dispatch, which resolves them against the rack of
  915. # the printer it picks. See `_keeps_slicer_nozzle_mapping`.
  916. nozzle_mapping_json: str | None = None
  917. if slicer_opts is not None and self._keeps_slicer_nozzle_mapping():
  918. raw = slicer_opts.get("nozzle_mapping")
  919. if raw is not None:
  920. # BambuStudio's NetworkAgent embeds this as parsed
  921. # JSON in the project_file body (matching the
  922. # ams_mapping shape Bambuddy already consumes as
  923. # list[int]). Accept a JSON-encoded string defensively
  924. # in case any path arrives stringified.
  925. if isinstance(raw, str):
  926. try:
  927. raw = json.loads(raw)
  928. except json.JSONDecodeError:
  929. logger.warning(
  930. "[VP %s] Slicer nozzle_mapping is unparseable JSON, dropping: %r",
  931. self.name,
  932. raw,
  933. )
  934. raw = None
  935. if raw is not None:
  936. nozzle_mapping_json = json.dumps(raw)
  937. # Slicer's own live-resolved AMS-slot pick (see docstring on
  938. # `_extract_slicer_ams_mapping_json`). Stamped onto every plate
  939. # below, same treatment as nozzle_mapping_json above — when
  940. # present it makes `_ensure_ams_mapping` skip its own
  941. # type/color re-derivation entirely and dispatch use exactly
  942. # the tray the slicer/user picked.
  943. #
  944. # Two gates, both required:
  945. #
  946. # 1. This VP must target one fixed printer. A model-based
  947. # ("Any <model>") VP has no MQTT bridge to a real printer,
  948. # so the slicer has no live AMS layout to resolve tray IDs
  949. # against — whatever it sends here is meaningless (or,
  950. # worse, coincidentally valid for the wrong printer once
  951. # the scheduler later picks one).
  952. # 2. The per-VP `save_ams_mapping` opt-in must be on. Taking
  953. # the slicer's pick means `_ensure_ams_mapping` returns
  954. # early and `_compute_ams_mapping_for_printer` never runs —
  955. # and that function is where `prefer_lowest_filament`, its
  956. # AMS-filament-backup gate (#1766) and the inventory-remain
  957. # overrides live. Honouring the slicer unconditionally would
  958. # silently retire all of that for every existing queue-mode
  959. # VP on upgrade, so it's opt-in like every other queue-mode
  960. # behaviour toggle (#2700 review).
  961. #
  962. # Either gate failing leaves it unset, and the scheduler's
  963. # normal type/color re-derivation runs against whichever
  964. # printer actually gets the job.
  965. ams_mapping_json: str | None = None
  966. if slicer_opts is not None and self.target_printer_id is not None and self.save_ams_mapping:
  967. ams_mapping_json = _extract_slicer_ams_mapping_json(
  968. slicer_opts, f"[VP {self.name}]", is_dual_nozzle=self._target_is_dual_nozzle()
  969. )
  970. # `Force color match` is the user asking Bambuddy to do the
  971. # matching strictly, against the printer's live trays. Its only
  972. # effect on a fixed-printer item is via the per-slot
  973. # `filament_overrides` written below, which are consumed inside
  974. # `_compute_ams_mapping_for_printer` — the exact function a
  975. # stored mapping skips. So when both toggles are on, the
  976. # explicit strictness wins for *this* dispatch and the slicer's
  977. # pick is still persisted onto the archive for later reprints,
  978. # which is what `Save AMS mapping` actually promises (#2700
  979. # review).
  980. queue_ams_mapping_json = ams_mapping_json
  981. if queue_ams_mapping_json is not None and self.queue_force_color_match:
  982. logger.info(
  983. "[VP %s] Saved the slicer's AMS pick to the archive but not onto the queue item(s): "
  984. "'Force color match' is on, so the scheduler matches against live trays for this print.",
  985. self.name,
  986. )
  987. queue_ams_mapping_json = None
  988. # Parsed once for the per-plate length check in the loop below.
  989. queue_ams_mapping = json.loads(queue_ams_mapping_json) if queue_ams_mapping_json else None
  990. service = ArchiveService(db)
  991. archive = await service.archive_print(
  992. printer_id=None,
  993. source_file=file_path,
  994. print_data={
  995. "status": "archived",
  996. "source": "virtual_printer",
  997. "source_ip": source_ip,
  998. },
  999. prefer_filename_for_name=prefer_filename,
  1000. # Slicer's own live AMS-slot pick -- promoted to
  1001. # `extra_data.slicer_ams_mapping` by archive_print() so a
  1002. # later reprint can reuse it. Already gated on the per-VP
  1003. # `save_ams_mapping` opt-in above. Tagged with the printer
  1004. # it was resolved against so a later reprint on a
  1005. # *different* printer knows not to reuse it (#2700 review).
  1006. slicer_ams_mapping=(json.loads(ams_mapping_json) if ams_mapping_json else None),
  1007. slicer_ams_mapping_printer_id=self.target_printer_id,
  1008. )
  1009. if archive:
  1010. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  1011. # Assign to specific printer if configured, otherwise use model for "Any X" scheduling
  1012. target_model = None
  1013. if not self.target_printer_id and self.model:
  1014. target_model = VIRTUAL_PRINTER_MODELS.get(self.model)
  1015. # #1733: multi-plate "Send All" uploads ship every plate in
  1016. # one 3MF — `slice_info.config` lists each `<plate>` with
  1017. # its own index. Enqueue one PrintQueueItem per plate so
  1018. # the scheduler runs each separately. Single-plate "Send"
  1019. # comes through as `[N]` (one plate index) so the loop
  1020. # below runs once and the existing behaviour is preserved.
  1021. plate_ids = self._extract_plate_ids(file_path)
  1022. # Pick a base position the same way the manual /print-queue/
  1023. # POST does, then hand consecutive positions to each plate
  1024. # so a Send All keeps plate-order execution inside the
  1025. # queue (#1733). Previously hardcoded to 1, which created
  1026. # duplicate position=1 rows on every VP upload and made
  1027. # queue execution order non-deterministic for any non-
  1028. # empty queue.
  1029. from sqlalchemy import func, select as _sql_select
  1030. # One sequence across all pending items, not one per
  1031. # printer (#3200): the plates go to the end of the queue.
  1032. queue_scope = _sql_select(func.max(PrintQueueItem.position)).where(
  1033. PrintQueueItem.status == "pending"
  1034. )
  1035. try:
  1036. max_pos_raw = (await db.execute(queue_scope)).scalar()
  1037. max_pos = int(max_pos_raw) if max_pos_raw is not None else 0
  1038. except (TypeError, ValueError):
  1039. max_pos = 0
  1040. # Parse per-plate filament requirements (#1188). Each plate
  1041. # has its own filament set in `slice_info.config`, so the
  1042. # `required_filament_types` / `filament_overrides` columns
  1043. # on each queue item reflect THAT plate, not the file's
  1044. # first plate. Scoping was already plate-aware via #1697 —
  1045. # the `extract_filament_requirements(path, plate_id)` filter
  1046. # returns just the plate's filaments. required_filament_types
  1047. # is populated unconditionally — it's cheap, lets the
  1048. # scheduler reject obvious mis-matches even without
  1049. # force_color_match. filament_overrides only carries
  1050. # force_color_match=True when the per-VP setting is on, so
  1051. # upgraders keep the old behaviour by default.
  1052. queue_item_ids: list[int] = []
  1053. queue_item_reach: dict[int, int] = {}
  1054. for offset, plate_id in enumerate(plate_ids, start=1):
  1055. required_filament_types_json: str | None = None
  1056. filament_overrides_json: str | None = None
  1057. requirements = extract_filament_requirements(file_path, plate_id)
  1058. if requirements:
  1059. types = sorted({r["type"] for r in requirements if r.get("type")})
  1060. if types:
  1061. required_filament_types_json = json.dumps(types)
  1062. if self.queue_force_color_match:
  1063. # Carry tray_info_idx so force_color_match can
  1064. # tell Bambu PLA variants apart (#2650). Bambu
  1065. # reports Basic/Matte/Silk all as tray_type
  1066. # "PLA"; the variant lives only in tray_info_idx
  1067. # (GFA00/GFA01/GFA06/...). A blank idx (custom or
  1068. # third-party spool) means "no variant
  1069. # constraint" and the scheduler falls back to
  1070. # type+colour.
  1071. overrides = [
  1072. {
  1073. "slot_id": r["slot_id"],
  1074. "type": r.get("type", ""),
  1075. "color": r.get("color", ""),
  1076. "tray_info_idx": r.get("tray_info_idx", ""),
  1077. "force_color_match": True,
  1078. }
  1079. for r in requirements
  1080. if r.get("type") and r.get("color")
  1081. ]
  1082. if overrides:
  1083. filament_overrides_json = json.dumps(overrides)
  1084. # The slicer's mapping is indexed by the 3MF's own
  1085. # file-global slot ids (position = slot_id - 1), so one
  1086. # array covers every plate of a multi-plate Send All —
  1087. # each plate just reads the entries for the slots it
  1088. # actually prints. What must be checked is that it
  1089. # reaches that far: a mapping shorter than this plate's
  1090. # highest slot id can't address the plate's own slots,
  1091. # and `_ensure_ams_mapping` would keep it anyway
  1092. # because it only rejects an all-unresolved mapping. Fall
  1093. # back to a computed mapping for that plate instead
  1094. # (#2700 review).
  1095. plate_ams_mapping_json = queue_ams_mapping_json
  1096. plate_max_slot = max((r.get("slot_id") or 0) for r in requirements) if requirements else 0
  1097. if queue_ams_mapping is not None and requirements:
  1098. max_slot_id = max((r.get("slot_id") or 0) for r in requirements)
  1099. if max_slot_id > len(queue_ams_mapping):
  1100. logger.warning(
  1101. "[VP %s] Slicer ams_mapping has %d entries but plate %s needs slot %d; "
  1102. "dropping it for this plate so the scheduler computes one from live AMS state.",
  1103. self.name,
  1104. len(queue_ams_mapping),
  1105. plate_id,
  1106. max_slot_id,
  1107. )
  1108. plate_ams_mapping_json = None
  1109. queue_item = PrintQueueItem(
  1110. printer_id=self.target_printer_id,
  1111. target_model=target_model,
  1112. archive_id=archive.id,
  1113. plate_id=plate_id,
  1114. position=max_pos + offset,
  1115. status="pending",
  1116. manual_start=not self.auto_dispatch,
  1117. required_filament_types=required_filament_types_json,
  1118. filament_overrides=filament_overrides_json,
  1119. bed_levelling=bed_levelling,
  1120. flow_cali=flow_cali,
  1121. nozzle_offset_cali=nozzle_offset_cali,
  1122. vibration_cali=vibration_cali,
  1123. layer_inspect=layer_inspect,
  1124. timelapse=timelapse,
  1125. use_ams=use_ams,
  1126. confirm_outcome=confirm_outcome,
  1127. # Per-VP opt-in for auto-print G-code injection (#1516).
  1128. # Default off; when on, the scheduler still no-ops unless
  1129. # gcode_snippets are configured for the target model, so it's
  1130. # effectively "inject when enabled AND snippets exist".
  1131. gcode_injection=self.gcode_injection,
  1132. # H2C rack-swap slicer pick (#1780). Captured above;
  1133. # stamped on every plate so a multi-plate Send All keeps
  1134. # the same nozzle pick across plates rather than only the
  1135. # first one (mirrors the #1697 / #1188 per-plate loop fix).
  1136. nozzle_mapping=nozzle_mapping_json,
  1137. # Slicer's own live AMS-slot pick, when present —
  1138. # see `_extract_slicer_ams_mapping_json`.
  1139. ams_mapping=plate_ams_mapping_json,
  1140. )
  1141. db.add(queue_item)
  1142. await db.flush() # populate queue_item.id before logging
  1143. queue_item_ids.append(queue_item.id)
  1144. queue_item_reach[queue_item.id] = plate_max_slot
  1145. await db.commit()
  1146. # Track the freshly-committed queue items so
  1147. # `on_print_command` can retroactively stamp slicer-side
  1148. # fields if the MQTT `project_file` lands AFTER the
  1149. # `_SLICER_OPTIONS_WAIT_TIMEOUT` window expired — the
  1150. # #1780 round-3 race. Eviction of stale entries here
  1151. # keeps the dict bounded; the queue path is the only
  1152. # writer, so doing it on commit is enough.
  1153. now = time.monotonic()
  1154. cutoff = now - _RECENT_QUEUE_ITEM_TTL
  1155. self._recent_queue_items = {k: v for k, v in self._recent_queue_items.items() if v[1] > cutoff}
  1156. self._recent_queue_items[file_path.name] = (list(queue_item_ids), now)
  1157. self._recent_queue_item_reach = {
  1158. k: v for k, v in self._recent_queue_item_reach.items() if k in self._recent_queue_items
  1159. }
  1160. self._recent_queue_item_reach[file_path.name] = queue_item_reach
  1161. # Last-chance check: MQTT for this filename could have
  1162. # arrived during ANY await between the initial pop and
  1163. # now — wait_for itself, archive_print, db.flush,
  1164. # db.commit. In all those cases `on_print_command`
  1165. # stashed its data but neither the event-signal path nor
  1166. # the retroactive `_recent_queue_items` path was in
  1167. # place to consume it. Pop any late stash and apply
  1168. # inline so the late MQTT never leaks past the queue-add.
  1169. late_opts = self._slicer_print_options.pop(file_path.name, None)
  1170. if late_opts is not None:
  1171. logger.info(
  1172. "[VP %s] Late slicer MQTT detected for %s during queue-add — "
  1173. "applying inline (race vs commit/archive/flush yield)",
  1174. self.name,
  1175. file_path.name,
  1176. )
  1177. await self._restamp_recent_queue_item(file_path.name, late_opts)
  1178. if len(queue_item_ids) == 1:
  1179. logger.info("[VP %s] Added to queue: %s", self.name, queue_item_ids[0])
  1180. else:
  1181. logger.info(
  1182. "[VP %s] Added %d queue items for multi-plate upload (plates %s): %s",
  1183. self.name,
  1184. len(queue_item_ids),
  1185. plate_ids,
  1186. queue_item_ids,
  1187. )
  1188. await self._broadcast_archive_created(archive)
  1189. from backend.app.services.queue_announcements import announce_queue_jobs_added
  1190. await announce_queue_jobs_added(db, queue_item_ids)
  1191. else:
  1192. logger.error("Failed to archive file: %s", file_path.name)
  1193. except Exception as e:
  1194. logger.error("Error adding to print queue: %s", e)
  1195. finally:
  1196. # Always release the marker and clean the temp file. Without this
  1197. # the same-name STOR guard would block the next upload and the
  1198. # upload_dir would accumulate failed temp files forever
  1199. # (#audit-R2-1).
  1200. self._pending_files.pop(file_path.name, None)
  1201. try:
  1202. file_path.unlink(missing_ok=True)
  1203. except OSError:
  1204. pass
  1205. async def _broadcast_archive_created(self, archive) -> None:
  1206. """Notify connected clients that a new archive exists.
  1207. Real-printer prints get this from main.py's MQTT print_start handler;
  1208. VP-uploaded prints need their own broadcast or the Archives page stays
  1209. stale until the user switches tabs (#1282).
  1210. """
  1211. try:
  1212. from backend.app.core.websocket import ws_manager
  1213. await ws_manager.send_archive_created(
  1214. {
  1215. "id": archive.id,
  1216. "printer_id": archive.printer_id,
  1217. "filename": archive.filename,
  1218. "print_name": archive.print_name,
  1219. "status": archive.status,
  1220. }
  1221. )
  1222. except Exception as e:
  1223. logger.debug("[VP %s] archive_created broadcast failed: %s", self.name, e)
  1224. @staticmethod
  1225. def _extract_plate_ids(file_path: Path) -> list[int]:
  1226. """Extract every plate index from a 3MF's slice_info.config.
  1227. A multi-plate "Send All" from BambuStudio / OrcaSlicer uploads a
  1228. single 3MF containing every plate the user selected. Each plate
  1229. has its own ``<plate>`` block with a ``<metadata key="index"
  1230. value="N"/>`` child and its own ``Metadata/plate_N.gcode`` payload
  1231. inside the same zip. Returning the full ordered list lets the VP
  1232. queue path create one queue item per plate (`_add_to_print_queue`
  1233. loops over the result), so "Send All" of a 3-plate file produces
  1234. 3 queue items sharing the same archive — one per plate to print.
  1235. Single-plate "Send" hits the same code path and returns ``[N]``
  1236. for whichever plate the user selected; the loop runs once and the
  1237. existing single-plate behaviour is preserved.
  1238. Returns ``[1]`` when the 3MF is missing ``slice_info.config``,
  1239. unparseable, or contains no plate-index metadata — the original
  1240. single-plate fallback. Production logs at debug so a non-3MF
  1241. upload doesn't spam, but the trail survives for support bundles.
  1242. """
  1243. try:
  1244. import xml.etree.ElementTree as ET
  1245. import zipfile
  1246. with zipfile.ZipFile(file_path, "r") as zf:
  1247. if "Metadata/slice_info.config" in zf.namelist():
  1248. content = zf.read("Metadata/slice_info.config").decode()
  1249. root = ET.fromstring(content) # noqa: S314 # nosec B314
  1250. plate_ids: list[int] = []
  1251. for plate in root.findall(".//plate"):
  1252. for meta in plate.findall("metadata"):
  1253. if meta.get("key") == "index" and meta.get("value"):
  1254. try:
  1255. plate_ids.append(int(meta.get("value")))
  1256. except ValueError:
  1257. continue
  1258. break
  1259. if plate_ids:
  1260. return plate_ids
  1261. except Exception as e:
  1262. logger.debug("[VP] _extract_plate_ids failed for %s: %s", file_path.name, e)
  1263. return [1]
  1264. # -- Service lifecycle --
  1265. def _resolve_cert_and_advertise(self) -> tuple[Path, Path, str]:
  1266. """Return (cert_path, key_path, advertise_address) for TLS services.
  1267. Always uses the self-signed cert chain (signed by `bbl_ca`). The user
  1268. imports `bbl_ca.crt` once into the slicer; per-VP certs validate from
  1269. there. Tailscale exposure is handled by the user picking the Tailscale
  1270. IP in the bind_ip dropdown.
  1271. """
  1272. cert_path, key_path = self.generate_certificates()
  1273. advertise = self.remote_interface_ip or self.bind_ip or ""
  1274. return cert_path, key_path, advertise
  1275. async def start_server(self) -> None:
  1276. """Start server-mode services (FTP, MQTT, SSDP, Bind) on this VP's bind_ip."""
  1277. logger.info("[VP %s] Starting server-mode services on %s", self.name, self.bind_ip)
  1278. cert_path, key_path, advertise_addr = self._resolve_cert_and_advertise()
  1279. bind_addr = self.bind_ip or "0.0.0.0" # nosec B104
  1280. async def run_with_logging(coro, svc_name):
  1281. try:
  1282. await coro
  1283. except Exception as e:
  1284. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  1285. self._tasks = []
  1286. # FTP server. Each VP gets a non-overlapping passive-mode port slice
  1287. # derived from its DB id so bridge-mode Docker users only have to
  1288. # expose a narrow range (#1646). Default slice is 10 ports per VP;
  1289. # see ftp_server.compute_passive_port_slice for the wrap-around
  1290. # behaviour on installs with very high VP ids.
  1291. passive_port_min, passive_port_max = compute_passive_port_slice(self.id)
  1292. self._ftp = VirtualPrinterFTPServer(
  1293. upload_dir=self.upload_dir,
  1294. access_code=self.access_code,
  1295. cert_path=cert_path,
  1296. key_path=key_path,
  1297. on_file_received=self.on_file_received,
  1298. bind_address=bind_addr,
  1299. vp_name=self.name,
  1300. passive_port_min=passive_port_min,
  1301. passive_port_max=passive_port_max,
  1302. )
  1303. self._tasks.append(
  1304. asyncio.create_task(
  1305. run_with_logging(self._ftp.start(), "FTP"),
  1306. name=f"vp_{self.id}_ftp",
  1307. )
  1308. )
  1309. # MQTT server
  1310. self._mqtt = SimpleMQTTServer(
  1311. serial=self.serial,
  1312. access_code=self.access_code,
  1313. cert_path=cert_path,
  1314. key_path=key_path,
  1315. on_print_command=self.on_print_command,
  1316. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1317. bind_address=bind_addr,
  1318. vp_name=self.name,
  1319. )
  1320. self._tasks.append(
  1321. asyncio.create_task(
  1322. run_with_logging(self._mqtt.start(), "MQTT"),
  1323. name=f"vp_{self.id}_mqtt",
  1324. )
  1325. )
  1326. # MQTT bridge — fans out the target printer's pushes to slicers connected
  1327. # to this VP and forwards their commands back to the printer. Only meaningful
  1328. # when a target printer is configured AND printer_manager was injected (it
  1329. # always is at runtime; tests may omit it).
  1330. if self.target_printer_id is not None and self._printer_manager is not None:
  1331. self._mqtt_bridge = MQTTBridge(
  1332. vp_id=self.id,
  1333. vp_name=self.name,
  1334. vp_serial=self.serial,
  1335. target_printer_id=self.target_printer_id,
  1336. mqtt_server=self._mqtt,
  1337. printer_manager=self._printer_manager,
  1338. )
  1339. self._mqtt.set_bridge(self._mqtt_bridge)
  1340. await self._mqtt_bridge.start()
  1341. # Camera passthrough. BambuStudio / OrcaSlicer connect the "camera"
  1342. # button to the device IP they bound on (the VP), not the IP in the
  1343. # printer's `ipcam.rtsp_url`. Without a listener the slicer gets
  1344. # connection refused → "LAN connection failed" (RTSP models) or
  1345. # OrcaSlicer error `[2:-10061]` (chamber-image models, #1868).
  1346. #
  1347. # The port depends on the TARGET printer's model:
  1348. # RTSPS (X1/X2/H2/P2S) → 322
  1349. # chamber-image (A1/P1P/P1S) → 6000
  1350. #
  1351. # `get_camera_port()` is the same source of truth used by
  1352. # `routes/camera.py`, so slicer and Bambuddy UI agree.
  1353. target_client = self._printer_manager.get_client(self.target_printer_id)
  1354. target_ip = getattr(target_client, "ip_address", None) if target_client else None
  1355. target_model = getattr(target_client, "model", None) if target_client else None
  1356. if target_ip:
  1357. from backend.app.services.camera import get_camera_port
  1358. camera_port = get_camera_port(target_model)
  1359. self._rtsp_proxy = TCPProxy(
  1360. name=f"Camera-{camera_port}",
  1361. listen_port=camera_port,
  1362. target_host=target_ip,
  1363. target_port=camera_port,
  1364. bind_address=bind_addr,
  1365. )
  1366. self._tasks.append(
  1367. asyncio.create_task(
  1368. run_with_logging(self._rtsp_proxy.start(), f"Camera-{camera_port}"),
  1369. name=f"vp_{self.id}_camera",
  1370. )
  1371. )
  1372. # Bind server
  1373. self._bind = BindServer(
  1374. serial=self.serial,
  1375. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1376. name=self.name,
  1377. bind_address=bind_addr,
  1378. cert_path=cert_path,
  1379. key_path=key_path,
  1380. )
  1381. self._tasks.append(
  1382. asyncio.create_task(
  1383. run_with_logging(self._bind.start(), "Bind"),
  1384. name=f"vp_{self.id}_bind",
  1385. )
  1386. )
  1387. # SSDP server — advertise_addr is the remote_interface_ip (Tailscale
  1388. # IP, when chosen from the bind_ip dropdown) or the bind_ip. SSDP
  1389. # Location accepts IPs only; FQDNs go in through bind_ip selection
  1390. # at the printer-IP level and resolve before reaching the SSDP
  1391. # advertisement.
  1392. self._ssdp = VirtualPrinterSSDPServer(
  1393. name=self.name,
  1394. serial=self.serial,
  1395. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1396. advertise_ip=advertise_addr,
  1397. bind_ip=bind_addr,
  1398. )
  1399. self._tasks.append(
  1400. asyncio.create_task(
  1401. run_with_logging(self._ssdp.start(), "SSDP"),
  1402. name=f"vp_{self.id}_ssdp",
  1403. )
  1404. )
  1405. # Wait briefly for every child service to actually finish binding its
  1406. # socket so ``is_running`` doesn't lie. Without this barrier a caller
  1407. # racing the start (e.g. the diagnostic route) would see is_running=True
  1408. # while ports were still in the gap between task creation and the
  1409. # ``asyncio.start_server`` returning. Bounded timeout — if a child
  1410. # hangs we log it and move on; the existing task tracking still
  1411. # catches the failure on the next iteration.
  1412. ready_targets = [
  1413. ("FTP", self._ftp.ready),
  1414. ("MQTT", self._mqtt.ready),
  1415. ("Bind", self._bind.ready),
  1416. ("SSDP", self._ssdp.ready),
  1417. ]
  1418. try:
  1419. await asyncio.wait_for(
  1420. asyncio.gather(*(e.wait() for _, e in ready_targets)),
  1421. timeout=5.0,
  1422. )
  1423. except TimeoutError:
  1424. not_ready = [name for name, e in ready_targets if not e.is_set()]
  1425. logger.warning(
  1426. "[VP %s] Sub-service(s) didn't bind within 5s: %s — continuing anyway",
  1427. self.name,
  1428. ", ".join(not_ready) or "(none)",
  1429. )
  1430. logger.info("[VP %s] Server-mode services started on %s", self.name, bind_addr)
  1431. async def stop_server(self) -> None:
  1432. """Stop server-mode services."""
  1433. if self._finish_release_task is not None and not self._finish_release_task.done():
  1434. self._finish_release_task.cancel()
  1435. self._finish_release_task = None
  1436. if self._mqtt_bridge:
  1437. try:
  1438. await self._mqtt_bridge.stop()
  1439. except Exception:
  1440. logger.exception("[VP %s] MQTT bridge stop failed", self.name)
  1441. if self._mqtt:
  1442. self._mqtt.set_bridge(None)
  1443. self._mqtt_bridge = None
  1444. if self._rtsp_proxy:
  1445. try:
  1446. await self._rtsp_proxy.stop()
  1447. except Exception:
  1448. logger.exception("[VP %s] Camera proxy stop failed", self.name)
  1449. self._rtsp_proxy = None
  1450. if self._ftp:
  1451. await self._ftp.stop()
  1452. self._ftp = None
  1453. if self._mqtt:
  1454. await self._mqtt.stop()
  1455. self._mqtt = None
  1456. if self._bind:
  1457. await self._bind.stop()
  1458. self._bind = None
  1459. if self._ssdp:
  1460. await self._ssdp.stop()
  1461. self._ssdp = None
  1462. await self._cancel_tasks()
  1463. async def start_proxy(self) -> None:
  1464. """Start proxy mode services for this instance."""
  1465. logger.info("[VP %s] Starting proxy mode to %s", self.name, self.target_printer_ip)
  1466. cert_path, key_path, _ = self._resolve_cert_and_advertise()
  1467. self._proxy = SlicerProxyManager(
  1468. target_host=self.target_printer_ip,
  1469. cert_path=cert_path,
  1470. key_path=key_path,
  1471. on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m),
  1472. bind_address=self.bind_ip or "0.0.0.0", # nosec B104
  1473. bind_identity={
  1474. "serial": self.target_printer_serial or self.serial,
  1475. "model": self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1476. "name": self.name,
  1477. "version": "01.00.00.00",
  1478. },
  1479. )
  1480. async def run_with_logging(coro, svc_name):
  1481. try:
  1482. await coro
  1483. except Exception as e:
  1484. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  1485. self._tasks = []
  1486. # SSDP for proxy
  1487. proxy_serial = self.target_printer_serial or self.serial
  1488. if self.remote_interface_ip:
  1489. from backend.app.services.network_utils import find_interface_for_ip
  1490. local_iface = find_interface_for_ip(self.target_printer_ip)
  1491. if local_iface:
  1492. self._ssdp_proxy = SSDPProxy(
  1493. local_interface_ip=local_iface["ip"],
  1494. remote_interface_ip=self.remote_interface_ip,
  1495. target_printer_ip=self.target_printer_ip,
  1496. name=self.name,
  1497. )
  1498. self._tasks.append(
  1499. asyncio.create_task(
  1500. run_with_logging(self._ssdp_proxy.start(), "SSDP Proxy"),
  1501. name=f"vp_{self.id}_ssdp_proxy",
  1502. )
  1503. )
  1504. else:
  1505. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  1506. else:
  1507. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  1508. self._tasks.append(
  1509. asyncio.create_task(
  1510. run_with_logging(self._proxy.start(), "Proxy"),
  1511. name=f"vp_{self.id}_proxy",
  1512. )
  1513. )
  1514. def _start_fallback_ssdp(self, proxy_serial: str, run_with_logging) -> None:
  1515. """Start single-interface SSDP server as fallback for proxy mode."""
  1516. self._ssdp = VirtualPrinterSSDPServer(
  1517. name=f"{self.name} (Proxy)",
  1518. serial=proxy_serial,
  1519. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1520. advertise_ip=self.bind_ip or "",
  1521. bind_ip=self.bind_ip or "",
  1522. )
  1523. self._tasks.append(
  1524. asyncio.create_task(
  1525. run_with_logging(self._ssdp.start(), "SSDP"),
  1526. name=f"vp_{self.id}_ssdp",
  1527. )
  1528. )
  1529. async def stop_proxy(self) -> None:
  1530. """Stop proxy mode services for this instance."""
  1531. if self._proxy:
  1532. await self._proxy.stop()
  1533. self._proxy = None
  1534. if self._ssdp:
  1535. await self._ssdp.stop()
  1536. self._ssdp = None
  1537. if self._ssdp_proxy:
  1538. await self._ssdp_proxy.stop()
  1539. self._ssdp_proxy = None
  1540. await self._cancel_tasks()
  1541. async def _cancel_tasks(self) -> None:
  1542. """Cancel all running tasks and wait for cleanup."""
  1543. for task in self._tasks:
  1544. task.cancel()
  1545. if self._tasks:
  1546. try:
  1547. await asyncio.wait_for(asyncio.gather(*self._tasks, return_exceptions=True), timeout=1.0)
  1548. except TimeoutError:
  1549. pass
  1550. self._tasks = []
  1551. def get_status(self) -> dict:
  1552. """Get status for this instance."""
  1553. status: dict = {
  1554. "running": self.is_running,
  1555. "pending_files": len(self._pending_files),
  1556. }
  1557. if self.is_proxy and self._proxy:
  1558. status["proxy"] = self._proxy.get_status()
  1559. return status
  1560. class VirtualPrinterManager:
  1561. """Multi-instance virtual printer registry and orchestrator.
  1562. Every VP runs its own independent services on a dedicated bind IP.
  1563. """
  1564. def __init__(self):
  1565. self._session_factory: Callable | None = None
  1566. self._printer_manager: PrinterManager | None = None
  1567. self._instances: dict[int, VirtualPrinterInstance] = {}
  1568. # Serialize sync_from_db so concurrent PUT /vp/{id} calls can't
  1569. # race the start/stop sequence and leave duplicate sub-services
  1570. # bound to the same port. The lock is fine-grained enough that
  1571. # a single VP update completes in well under a second; if the
  1572. # user holds the lock with a long-running start they intended
  1573. # to anyway.
  1574. self._sync_lock = asyncio.Lock()
  1575. # Directories
  1576. self._base_dir = app_settings.base_dir / "virtual_printer"
  1577. # Ensure base directories exist
  1578. self._ensure_base_directories()
  1579. def _ensure_base_directories(self) -> None:
  1580. """Create base directories at startup."""
  1581. for dir_path in [self._base_dir, self._base_dir / "uploads", self._base_dir / "certs"]:
  1582. try:
  1583. dir_path.mkdir(parents=True, exist_ok=True)
  1584. except PermissionError:
  1585. logger.error(
  1586. f"Cannot create directory {dir_path}: Permission denied. "
  1587. f"For Docker: ensure the data volume is writable by the container user. "
  1588. f"For bare metal: run 'sudo chown -R $(whoami) {self._base_dir}'"
  1589. )
  1590. def set_session_factory(self, session_factory: Callable) -> None:
  1591. """Set the database session factory."""
  1592. self._session_factory = session_factory
  1593. def set_printer_manager(self, printer_manager: "PrinterManager") -> None:
  1594. """Inject the global printer_manager so non-proxy VPs can mirror their target's MQTT stream."""
  1595. self._printer_manager = printer_manager
  1596. def get_ca_certificate_info(self) -> dict:
  1597. """Return the shared virtual-printer CA certificate for slicer-trust import.
  1598. The CA is shared by every VP (one import covers all of them). It is
  1599. generated on demand here if no VP has triggered cert generation yet,
  1600. so the "copy/download certificate" UI works even before the first VP
  1601. is enabled.
  1602. """
  1603. certs_dir = self._base_dir / "certs"
  1604. cert_service = CertificateService(cert_dir=certs_dir, shared_ca_dir=certs_dir)
  1605. return cert_service.get_ca_certificate_info()
  1606. @property
  1607. def is_enabled(self) -> bool:
  1608. """Check if any virtual printer is running."""
  1609. return len(self._instances) > 0
  1610. async def sync_from_db(self) -> None:
  1611. """Load all VPs from DB, reconcile running state.
  1612. Serialised by ``self._sync_lock`` — concurrent PUT /vp/{id} routes
  1613. all call into this method; without the lock the start / stop
  1614. sequence races and can leave duplicate sub-services bound to the
  1615. same port or orphan still-running tasks.
  1616. """
  1617. if not self._session_factory:
  1618. logger.warning("Cannot sync virtual printers: no session factory")
  1619. return
  1620. async with self._sync_lock:
  1621. await self._sync_from_db_locked()
  1622. async def _sync_from_db_locked(self) -> None:
  1623. """Inner sync body — caller holds ``self._sync_lock``."""
  1624. from sqlalchemy import select
  1625. from backend.app.models.printer import Printer
  1626. from backend.app.models.virtual_printer import VirtualPrinter
  1627. async with self._session_factory() as db:
  1628. result = await db.execute(
  1629. select(VirtualPrinter).where(VirtualPrinter.enabled == True).order_by(VirtualPrinter.position) # noqa: E712
  1630. )
  1631. enabled_vps = result.scalars().all()
  1632. # Stop instances that are no longer enabled or changed mode
  1633. enabled_ids = {vp.id for vp in enabled_vps}
  1634. for vp_id in list(self._instances.keys()):
  1635. if vp_id not in enabled_ids:
  1636. await self.remove_instance(vp_id)
  1637. # Look up printer IPs for proxy VPs
  1638. proxy_vps = [vp for vp in enabled_vps if vp.mode == "proxy"]
  1639. proxy_ips: dict[int, tuple[str, str]] = {}
  1640. if proxy_vps:
  1641. async with self._session_factory() as db:
  1642. for pvp in proxy_vps:
  1643. if pvp.target_printer_id:
  1644. result = await db.execute(select(Printer).where(Printer.id == pvp.target_printer_id))
  1645. printer = result.scalar_one_or_none()
  1646. if printer:
  1647. proxy_ips[pvp.id] = (printer.ip_address, printer.serial_number)
  1648. # Detect config changes on running instances and restart if needed
  1649. for vp in enabled_vps:
  1650. instance = self._instances.get(vp.id)
  1651. if not instance:
  1652. continue
  1653. # Proxy mode: detect target printer IP / serial changes from the
  1654. # DB lookup above. Without this branch a DHCP renewal that gives
  1655. # the target printer a new IP would leave the running proxy
  1656. # forwarding to the stale IP until the user manually toggles the
  1657. # VP. The same shape covers a target-side serial change.
  1658. proxy_target_changed = False
  1659. if vp.mode == "proxy":
  1660. fresh = proxy_ips.get(vp.id)
  1661. if fresh is not None:
  1662. fresh_ip, fresh_serial = fresh
  1663. if (
  1664. getattr(instance, "target_printer_ip", None) != fresh_ip
  1665. or getattr(instance, "target_printer_serial", None) != fresh_serial
  1666. ):
  1667. proxy_target_changed = True
  1668. # Normalize the DB value before comparing — a legacy `immediate`
  1669. # row read before the migration window finishes would otherwise
  1670. # trip the "changed" branch and bounce every VP at boot.
  1671. db_mode = normalize_vp_mode(vp.mode)
  1672. changed = (
  1673. instance.mode != db_mode
  1674. # The name is advertised to the slicer (SSDP, bind) by the
  1675. # running services, so a rename only reaches it on restart.
  1676. or instance.name != vp.name
  1677. or instance.model != (vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL)
  1678. or instance.access_code != (vp.access_code or "")
  1679. or instance.bind_ip != (vp.bind_ip or "")
  1680. or instance.remote_interface_ip != (vp.remote_interface_ip or "")
  1681. or instance.target_printer_id != vp.target_printer_id
  1682. or instance.auto_dispatch != vp.auto_dispatch
  1683. # Queue-mode behaviour toggle — without it the running
  1684. # instance silently keeps the old value until process
  1685. # restart (#1552 follow-up family).
  1686. or instance.queue_force_color_match != vp.queue_force_color_match
  1687. or instance.save_ams_mapping != vp.save_ams_mapping
  1688. or instance.gcode_injection != vp.gcode_injection
  1689. or proxy_target_changed
  1690. )
  1691. if changed:
  1692. logger.info(
  1693. "VP %s config changed (mode: %s→%s), restarting",
  1694. instance.name,
  1695. instance.mode,
  1696. vp.mode,
  1697. )
  1698. await self.remove_instance(vp.id)
  1699. # Start instances for all enabled VPs (skip already running)
  1700. for vp in enabled_vps:
  1701. if vp.id in self._instances:
  1702. continue
  1703. if vp.mode == "proxy":
  1704. ip_info = proxy_ips.get(vp.id)
  1705. if not ip_info:
  1706. logger.warning("Proxy VP %s: target printer not found, skipping", vp.name)
  1707. continue
  1708. target_ip, target_serial = ip_info
  1709. instance = VirtualPrinterInstance(
  1710. vp_id=vp.id,
  1711. name=vp.name,
  1712. mode=vp.mode,
  1713. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1714. access_code=vp.access_code or "",
  1715. serial_suffix=vp.serial_suffix,
  1716. target_printer_ip=target_ip,
  1717. target_printer_serial=target_serial,
  1718. # Carried although the proxy does not use them: the change
  1719. # check above compares them with the row, and a missing
  1720. # value restarted every proxy VP on every sync.
  1721. target_printer_id=vp.target_printer_id,
  1722. auto_dispatch=vp.auto_dispatch,
  1723. queue_force_color_match=vp.queue_force_color_match,
  1724. save_ams_mapping=vp.save_ams_mapping,
  1725. gcode_injection=vp.gcode_injection,
  1726. bind_ip=vp.bind_ip or "",
  1727. remote_interface_ip=vp.remote_interface_ip or "",
  1728. tailscale_disabled=vp.tailscale_disabled,
  1729. base_dir=self._base_dir,
  1730. session_factory=self._session_factory,
  1731. )
  1732. self._instances[vp.id] = instance
  1733. await instance.start_proxy()
  1734. logger.info("Started proxy VP: %s → %s (bind=%s)", instance.name, target_ip, instance.bind_ip)
  1735. else:
  1736. instance = VirtualPrinterInstance(
  1737. vp_id=vp.id,
  1738. name=vp.name,
  1739. mode=vp.mode,
  1740. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1741. access_code=vp.access_code or "",
  1742. serial_suffix=vp.serial_suffix,
  1743. target_printer_id=vp.target_printer_id,
  1744. auto_dispatch=vp.auto_dispatch,
  1745. queue_force_color_match=vp.queue_force_color_match,
  1746. save_ams_mapping=vp.save_ams_mapping,
  1747. gcode_injection=vp.gcode_injection,
  1748. bind_ip=vp.bind_ip or "",
  1749. remote_interface_ip=vp.remote_interface_ip or "",
  1750. tailscale_disabled=vp.tailscale_disabled,
  1751. base_dir=self._base_dir,
  1752. session_factory=self._session_factory,
  1753. printer_manager=self._printer_manager,
  1754. )
  1755. self._instances[vp.id] = instance
  1756. await instance.start_server()
  1757. logger.info("Started server-mode VP: %s on %s", instance.name, vp.bind_ip)
  1758. async def remove_instance(self, vp_id: int) -> None:
  1759. """Stop and remove a single VP instance."""
  1760. instance = self._instances.pop(vp_id, None)
  1761. if instance:
  1762. if instance.is_proxy:
  1763. await instance.stop_proxy()
  1764. else:
  1765. await instance.stop_server()
  1766. logger.info("Removed VP instance: %s", instance.name)
  1767. async def stop_all(self) -> None:
  1768. """Shutdown all virtual printer services."""
  1769. logger.info("Stopping all virtual printer services...")
  1770. for vp_id in list(self._instances.keys()):
  1771. await self.remove_instance(vp_id)
  1772. logger.info("All virtual printer services stopped")
  1773. def get_instance(self, vp_id: int) -> VirtualPrinterInstance | None:
  1774. """Get a running instance by ID."""
  1775. return self._instances.get(vp_id)
  1776. def get_all_status(self) -> list[dict]:
  1777. """Get status for all running instances."""
  1778. return [
  1779. {
  1780. "id": inst.id,
  1781. "name": inst.name,
  1782. "mode": inst.mode,
  1783. **inst.get_status(),
  1784. }
  1785. for inst in self._instances.values()
  1786. ]
  1787. # -- Legacy single-printer compat --
  1788. def get_status(self) -> dict:
  1789. """Get status for first virtual printer (backward compat)."""
  1790. if self._instances:
  1791. first = next(iter(self._instances.values()))
  1792. return {
  1793. "enabled": True,
  1794. "running": first.is_running,
  1795. "mode": first.mode,
  1796. "name": first.name,
  1797. "serial": first.serial,
  1798. "model": first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1799. "model_name": VIRTUAL_PRINTER_MODELS.get(
  1800. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1801. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  1802. ),
  1803. "pending_files": first.get_status().get("pending_files", 0),
  1804. **({"target_printer_ip": first.target_printer_ip} if first.is_proxy else {}),
  1805. **({"proxy": first.get_status().get("proxy", {})} if first.is_proxy else {}),
  1806. }
  1807. return {
  1808. "enabled": False,
  1809. "running": False,
  1810. "mode": VP_MODE_ARCHIVE,
  1811. "name": "Bambuddy",
  1812. "serial": "",
  1813. "model": DEFAULT_VIRTUAL_PRINTER_MODEL,
  1814. "model_name": VIRTUAL_PRINTER_MODELS[DEFAULT_VIRTUAL_PRINTER_MODEL],
  1815. "pending_files": 0,
  1816. }
  1817. async def configure(
  1818. self,
  1819. enabled: bool,
  1820. access_code: str = "",
  1821. mode: str = VP_MODE_ARCHIVE,
  1822. model: str = "",
  1823. target_printer_ip: str = "",
  1824. target_printer_serial: str = "",
  1825. remote_interface_ip: str = "",
  1826. ) -> None:
  1827. """Legacy single-printer configure. Delegates to sync_from_db()."""
  1828. # This method is kept for backward compat with the settings endpoint.
  1829. # The actual work is done by sync_from_db() which reads from the DB.
  1830. await self.sync_from_db()
  1831. # Global instance
  1832. virtual_printer_manager = VirtualPrinterManager()