manager.py 103 KB

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