manager.py 95 KB

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