manager.py 100 KB

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