manager.py 89 KB

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