manager.py 74 KB

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