manager.py 83 KB

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