manager.py 101 KB

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