manager.py 77 KB

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