manager.py 90 KB

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