manager.py 105 KB

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