manager.py 96 KB

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