manager.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081
  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. from collections.abc import Callable
  8. from datetime import datetime, timezone
  9. from pathlib import Path
  10. from typing import TYPE_CHECKING
  11. from backend.app.core.config import settings as app_settings
  12. from backend.app.services.virtual_printer.bind_server import BindServer
  13. from backend.app.services.virtual_printer.certificate import CertificateService
  14. from backend.app.services.virtual_printer.ftp_server import VirtualPrinterFTPServer
  15. from backend.app.services.virtual_printer.mqtt_bridge import MQTTBridge
  16. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  17. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy, VirtualPrinterSSDPServer
  18. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager, TCPProxy
  19. if TYPE_CHECKING:
  20. from backend.app.services.printer_manager import PrinterManager
  21. logger = logging.getLogger(__name__)
  22. # Mapping of SSDP model codes to display names
  23. # These are the codes that slicers expect during discovery
  24. # Sources:
  25. # - https://gist.github.com/Alex-Schaefer/72a9e2491a42da2ef99fb87601955cc3
  26. # - https://github.com/psychoticbeef/BambuLabOrcaSlicerDiscovery
  27. VIRTUAL_PRINTER_MODELS = {
  28. # X1 Series
  29. "BL-P001": "X1C", # X1 Carbon
  30. "BL-P002": "X1", # X1
  31. "C13": "X1E", # X1E
  32. # X2 Series
  33. "N6": "X2D", # X2D
  34. # P Series
  35. "C11": "P1P", # P1P
  36. "C12": "P1S", # P1S
  37. "N7": "P2S", # P2S
  38. # A1 Series
  39. "N2S": "A1", # A1
  40. "N1": "A1 Mini", # A1 Mini
  41. # H2 Series
  42. "O1D": "H2D", # H2D
  43. "O1C": "H2C", # H2C
  44. "O1C2": "H2C", # H2C (dual nozzle variant)
  45. "O1S": "H2S", # H2S
  46. }
  47. # Serial number prefixes for each model (based on Bambu Lab serial number format)
  48. # Format: MMM??RYMDDUUUUU (15 chars total)
  49. # MMM = Model prefix (3 chars)
  50. # ?? = Unknown/revision code (2 chars)
  51. # R = Revision letter (1 char)
  52. # Y = Year digit (1 char)
  53. # M = Month (1 char, hex: 1-9, A=Oct, B=Nov, C=Dec)
  54. # DD = Day (2 chars)
  55. # UUUUU = Unit number (5 chars)
  56. MODEL_SERIAL_PREFIXES = {
  57. # X1 Series
  58. "BL-P001": "00M00A", # X1C
  59. "BL-P002": "00M00A", # X1
  60. "C13": "03W00A", # X1E
  61. # X2 Series
  62. "N6": "20P90A", # X2D (first 4 chars "20P9" match real serials)
  63. # P Series
  64. "C11": "01S00A", # P1P
  65. "C12": "01P00A", # P1S
  66. "N7": "22E00A", # P2S
  67. # A1 Series
  68. "N2S": "03900A", # A1
  69. "N1": "03000A", # A1 Mini
  70. # H2 Series
  71. "O1D": "09400A", # H2D
  72. "O1C": "09400A", # H2C
  73. "O1C2": "09400A", # H2C (dual nozzle variant)
  74. "O1S": "09400A", # H2S
  75. }
  76. # Reverse mapping: display name → SSDP model code (for auto-inheriting from printer model)
  77. DISPLAY_NAME_TO_MODEL_CODE = {v: k for k, v in VIRTUAL_PRINTER_MODELS.items()}
  78. # Default model
  79. DEFAULT_VIRTUAL_PRINTER_MODEL = "BL-P001" # X1C
  80. def _get_serial_for_model(model: str, serial_suffix: str) -> str:
  81. """Get serial number for the given model and suffix."""
  82. prefix = MODEL_SERIAL_PREFIXES.get(model, "00M09A")
  83. return f"{prefix}{serial_suffix}"
  84. class VirtualPrinterInstance:
  85. """Per-printer state and file handling logic.
  86. Each instance represents one virtual printer with its own config,
  87. upload directory, certificates, and file handling mode.
  88. """
  89. def __init__(
  90. self,
  91. *,
  92. vp_id: int,
  93. name: str,
  94. mode: str,
  95. model: str,
  96. access_code: str,
  97. serial_suffix: str,
  98. target_printer_ip: str = "",
  99. target_printer_serial: str = "",
  100. target_printer_id: int | None = None,
  101. auto_dispatch: bool = True,
  102. queue_force_color_match: bool = False,
  103. bind_ip: str = "",
  104. remote_interface_ip: str = "",
  105. tailscale_disabled: bool = True,
  106. base_dir: Path,
  107. session_factory: Callable | None = None,
  108. printer_manager: "PrinterManager | None" = None,
  109. ):
  110. self.id = vp_id
  111. self.name = name
  112. self.mode = mode
  113. self.model = model
  114. self.access_code = access_code
  115. self.serial_suffix = serial_suffix
  116. self.target_printer_ip = target_printer_ip
  117. self.target_printer_serial = target_printer_serial
  118. self.target_printer_id = target_printer_id
  119. self.auto_dispatch = auto_dispatch
  120. self.queue_force_color_match = queue_force_color_match
  121. self.bind_ip = bind_ip
  122. self.remote_interface_ip = remote_interface_ip
  123. self.tailscale_disabled = tailscale_disabled
  124. self._session_factory = session_factory
  125. self._printer_manager = printer_manager
  126. # Directories
  127. self.upload_dir = base_dir / "uploads" / str(vp_id)
  128. self.cert_dir = base_dir / "certs" / str(vp_id)
  129. shared_ca_dir = base_dir / "certs"
  130. # Ensure directories exist
  131. self.upload_dir.mkdir(parents=True, exist_ok=True)
  132. (self.upload_dir / "cache").mkdir(exist_ok=True)
  133. self.cert_dir.mkdir(parents=True, exist_ok=True)
  134. # Certificate service (shared CA, per-instance printer cert)
  135. self._cert_service = CertificateService(
  136. cert_dir=self.cert_dir,
  137. serial=self.serial,
  138. shared_ca_dir=shared_ca_dir,
  139. )
  140. # Pending files for MQTT correlation
  141. self._pending_files: dict[str, Path] = {}
  142. # Slicer-side print options captured from the MQTT `project_file`
  143. # command, keyed by filename. Used by `_add_to_print_queue` so the
  144. # queue item inherits the user's slicer-chosen timelapse / bed_leveling
  145. # / flow_cali / vibration_cali / layer_inspect / use_ams toggles rather
  146. # than falling back to the global `default_*` settings (#1403). FTP
  147. # completes a few hundred ms before the slicer's MQTT `project_file`
  148. # arrives, so the queue-add path waits briefly on the event below
  149. # before reading the dict. Events are popped along with the options
  150. # so the dict stays bounded.
  151. self._slicer_print_options: dict[str, dict] = {}
  152. self._slicer_print_options_events: dict[str, asyncio.Event] = {}
  153. # Per-instance services
  154. self._proxy: SlicerProxyManager | None = None
  155. self._ftp: VirtualPrinterFTPServer | None = None
  156. self._mqtt: SimpleMQTTServer | None = None
  157. self._mqtt_bridge: MQTTBridge | None = None
  158. self._rtsp_proxy: TCPProxy | None = None
  159. self._bind: BindServer | None = None
  160. self._ssdp: VirtualPrinterSSDPServer | None = None
  161. self._ssdp_proxy: SSDPProxy | None = None
  162. self._tasks: list[asyncio.Task] = []
  163. @property
  164. def serial(self) -> str:
  165. """Full serial number for this virtual printer."""
  166. return _get_serial_for_model(self.model or DEFAULT_VIRTUAL_PRINTER_MODEL, self.serial_suffix)
  167. @property
  168. def cert_path(self) -> Path:
  169. return self._cert_service.cert_path
  170. @property
  171. def key_path(self) -> Path:
  172. return self._cert_service.key_path
  173. @property
  174. def is_proxy(self) -> bool:
  175. return self.mode == "proxy"
  176. @property
  177. def is_running(self) -> bool:
  178. return len(self._tasks) > 0 and all(not t.done() for t in self._tasks)
  179. def generate_certificates(self) -> tuple[Path, Path]:
  180. """Generate certificates for this instance."""
  181. self._cert_service.serial = self.serial if not self.is_proxy else (self.target_printer_serial or self.serial)
  182. additional_ips = [self.remote_interface_ip] if self.remote_interface_ip else None
  183. if self.bind_ip:
  184. additional_ips = additional_ips or []
  185. additional_ips.append(self.bind_ip)
  186. self._cert_service.delete_printer_certificate()
  187. return self._cert_service.generate_certificates(additional_ips=additional_ips)
  188. # -- File handling callbacks --
  189. async def on_file_received(self, file_path: Path, source_ip: str) -> None:
  190. """Handle file upload completion from FTP."""
  191. logger.info("[VP %s] Received file: %s from %s", self.name, file_path.name, source_ip)
  192. self._pending_files[file_path.name] = file_path
  193. if self.mode == "immediate":
  194. await self._archive_file(file_path, source_ip)
  195. elif self.mode == "print_queue":
  196. await self._add_to_print_queue(file_path, source_ip)
  197. else:
  198. await self._queue_file(file_path, source_ip)
  199. # Signal job completion to the slicer. Send-flow slicers don't watch the
  200. # post-upload state and would be happy with anything; the Print flow
  201. # (intended for proxy-mode VPs, but users sometimes click it against
  202. # queue/immediate/review modes too — #1280) watches the gcode_state
  203. # cycle and only releases its in-flight-job lock when it sees FINISH.
  204. # Going PREPARE → IDLE wedges the slicer's UI at "Downloading...(0%)"
  205. # and blocks the next dispatch with "busy with another print job".
  206. # PREPARE → FINISH satisfies both flows. prepare_percent=100 also
  207. # unfreezes the slicer's "Downloading X%" progress bar which it ticks
  208. # against the same field during the upload window.
  209. if self._mqtt and file_path.suffix.lower() == ".3mf":
  210. self._mqtt.set_gcode_state("FINISH", filename=file_path.name, prepare_percent="100")
  211. async def on_print_command(self, filename: str, data: dict) -> None:
  212. """Handle print command from MQTT.
  213. Captures the slicer's project_file options (`timelapse`, `bed_leveling`,
  214. `flow_cali`, `vibration_cali`, `layer_inspect`, `use_ams`) so the
  215. VP-queue path can inherit them when adding the item to the queue,
  216. rather than falling back to the global default settings (#1403).
  217. Only queue mode consumes the capture; immediate / review / proxy
  218. modes ignore the print command, so we skip the stash there to keep
  219. the dict from accumulating one entry per print over the VP's
  220. uptime.
  221. """
  222. logger.info("[VP %s] Print command for: %s", self.name, filename)
  223. if self.mode != "print_queue":
  224. return
  225. self._slicer_print_options[filename] = dict(data)
  226. event = self._slicer_print_options_events.get(filename)
  227. if event:
  228. event.set()
  229. async def _archive_file(self, file_path: Path, source_ip: str) -> None:
  230. """Archive file immediately."""
  231. if not self._session_factory:
  232. logger.error("Cannot archive: no database session factory configured")
  233. return
  234. if file_path.suffix.lower() != ".3mf":
  235. logger.debug("Skipping non-3MF file: %s", file_path.name)
  236. self._pending_files.pop(file_path.name, None)
  237. try:
  238. file_path.unlink()
  239. except OSError:
  240. pass
  241. return
  242. try:
  243. from backend.app.api.routes.settings import get_setting
  244. from backend.app.services.archive import ArchiveService
  245. async with self._session_factory() as db:
  246. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  247. prefer_filename = name_source == "filename"
  248. service = ArchiveService(db)
  249. archive = await service.archive_print(
  250. printer_id=None,
  251. source_file=file_path,
  252. print_data={
  253. "status": "archived",
  254. "source": "virtual_printer",
  255. "source_ip": source_ip,
  256. },
  257. prefer_filename_for_name=prefer_filename,
  258. )
  259. if archive:
  260. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  261. await self._broadcast_archive_created(archive)
  262. try:
  263. file_path.unlink()
  264. except OSError:
  265. pass
  266. self._pending_files.pop(file_path.name, None)
  267. else:
  268. logger.error("Failed to archive file: %s", file_path.name)
  269. except Exception as e:
  270. logger.error("Error archiving file: %s", e)
  271. async def _queue_file(self, file_path: Path, source_ip: str) -> None:
  272. """Queue file for user review."""
  273. if not self._session_factory:
  274. logger.error("Cannot queue: no database session factory configured")
  275. return
  276. if file_path.suffix.lower() != ".3mf":
  277. self._pending_files.pop(file_path.name, None)
  278. try:
  279. file_path.unlink()
  280. except OSError:
  281. pass
  282. return
  283. # Peek at the 3MF for the embedded title BEFORE we hand it off to the
  284. # DB. Storing it now means the /pending-uploads/ list doesn't have to
  285. # reopen every 3MF on every render to keep the review card and the
  286. # eventual archive name in sync (#1152 follow-up). Failure to parse is
  287. # not fatal — the response model falls back to the filename stem.
  288. metadata_print_name: str | None = None
  289. try:
  290. from backend.app.services.archive import ThreeMFParser
  291. parsed = ThreeMFParser(file_path).parse()
  292. raw_name = parsed.get("print_name")
  293. if isinstance(raw_name, str) and raw_name.strip():
  294. metadata_print_name = raw_name.strip()[:255]
  295. except Exception as e:
  296. logger.debug("[VP %s] Metadata title peek failed for %s: %s", self.name, file_path.name, e)
  297. try:
  298. from backend.app.models.pending_upload import PendingUpload
  299. async with self._session_factory() as db:
  300. pending = PendingUpload(
  301. filename=file_path.name,
  302. file_path=str(file_path),
  303. file_size=file_path.stat().st_size,
  304. source_ip=source_ip,
  305. status="pending",
  306. uploaded_at=datetime.now(timezone.utc),
  307. metadata_print_name=metadata_print_name,
  308. )
  309. db.add(pending)
  310. await db.commit()
  311. logger.info("[VP %s] Queued: %s - %s", self.name, pending.id, file_path.name)
  312. self._pending_files.pop(file_path.name, None)
  313. except Exception as e:
  314. logger.error("Error queueing file: %s", e)
  315. async def _add_to_print_queue(self, file_path: Path, source_ip: str) -> None:
  316. """Archive file and add to print queue, assigned to target printer or model."""
  317. if not self._session_factory:
  318. logger.error("Cannot add to print queue: no database session factory configured")
  319. return
  320. if file_path.suffix.lower() != ".3mf":
  321. self._pending_files.pop(file_path.name, None)
  322. try:
  323. file_path.unlink()
  324. except OSError:
  325. pass
  326. return
  327. # Wait briefly for the slicer's MQTT `project_file` command so the
  328. # queue item can inherit the slicer-side print options the user
  329. # picked (timelapse, bed_leveling, etc). Slicers send the FTP upload
  330. # first and the MQTT command immediately after, so the typical lag
  331. # is a few hundred ms; 2 s is conservative without making every
  332. # VP-queue add visibly slow. Falls back to the global default_*
  333. # settings if MQTT doesn't arrive in time (legacy behaviour for
  334. # users on a slicer that doesn't send a print command). #1403.
  335. # The wait is skipped when there's no MQTT server attached — covers
  336. # unit tests that invoke `_add_to_print_queue` directly without
  337. # going through `on_print_command`, so they don't pay the 2 s tax.
  338. slicer_opts = self._slicer_print_options.pop(file_path.name, None)
  339. if slicer_opts is None and self._mqtt is not None:
  340. event = asyncio.Event()
  341. self._slicer_print_options_events[file_path.name] = event
  342. try:
  343. await asyncio.wait_for(event.wait(), timeout=2.0)
  344. slicer_opts = self._slicer_print_options.pop(file_path.name, None)
  345. except asyncio.TimeoutError:
  346. slicer_opts = None
  347. finally:
  348. self._slicer_print_options_events.pop(file_path.name, None)
  349. try:
  350. import json
  351. from backend.app.api.routes.settings import get_setting
  352. from backend.app.models.print_queue import PrintQueueItem
  353. from backend.app.services.archive import ArchiveService
  354. from backend.app.services.filament_requirements import extract_filament_requirements
  355. async with self._session_factory() as db:
  356. name_source = await get_setting(db, "virtual_printer_archive_name_source")
  357. prefer_filename = name_source == "filename"
  358. # Read workflow defaults from settings. Without this the
  359. # PrintQueueItem below would fall back to the column-level
  360. # defaults and ignore the user's workflow preferences (#1235).
  361. # Fallbacks match AppSettings defaults in schemas/settings.py.
  362. # The slicer-side options captured above (if any) take
  363. # precedence per-field over these defaults.
  364. def _bool_setting(value: str | None, default: bool) -> bool:
  365. return value.lower() == "true" if value is not None else default
  366. def _slicer_or(field_mqtt: str, settings_default: bool) -> bool:
  367. """Slicer's MQTT value if present, else the settings default.
  368. Slicer payloads carry both bool and int (0/1) shapes
  369. depending on firmware family — coerce via bool() so
  370. `0`/`False` and `1`/`True` both work.
  371. """
  372. if slicer_opts is not None and field_mqtt in slicer_opts:
  373. return bool(slicer_opts[field_mqtt])
  374. return settings_default
  375. # Note the MQTT field names differ from Bambuddy's column
  376. # names: MQTT uses `bed_leveling` (single L) while the
  377. # column / settings key use `bed_levelling` (double L).
  378. bed_levelling = _slicer_or(
  379. "bed_leveling", _bool_setting(await get_setting(db, "default_bed_levelling"), True)
  380. )
  381. flow_cali = _slicer_or("flow_cali", _bool_setting(await get_setting(db, "default_flow_cali"), False))
  382. vibration_cali = _slicer_or(
  383. "vibration_cali", _bool_setting(await get_setting(db, "default_vibration_cali"), True)
  384. )
  385. layer_inspect = _slicer_or(
  386. "layer_inspect", _bool_setting(await get_setting(db, "default_layer_inspect"), False)
  387. )
  388. timelapse = _slicer_or("timelapse", _bool_setting(await get_setting(db, "default_timelapse"), False))
  389. service = ArchiveService(db)
  390. archive = await service.archive_print(
  391. printer_id=None,
  392. source_file=file_path,
  393. print_data={
  394. "status": "archived",
  395. "source": "virtual_printer",
  396. "source_ip": source_ip,
  397. },
  398. prefer_filename_for_name=prefer_filename,
  399. )
  400. if archive:
  401. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  402. # Assign to specific printer if configured, otherwise use model for "Any X" scheduling
  403. target_model = None
  404. if not self.target_printer_id and self.model:
  405. target_model = VIRTUAL_PRINTER_MODELS.get(self.model)
  406. plate_id = self._extract_plate_id(file_path)
  407. # Parse the 3MF for per-slot filament requirements (#1188).
  408. # The manual /print-queue/ POST flow does this at queue-add
  409. # time; the VP path used to skip it, so the scheduler fell
  410. # through to model-only matching and dispatched onto whatever
  411. # printer happened to be free regardless of loaded colour.
  412. # required_filament_types is populated unconditionally — it's
  413. # cheap, lets the scheduler reject obvious mis-matches even
  414. # without force_color_match. filament_overrides only carries
  415. # force_color_match=True when the per-VP setting is on, so
  416. # upgraders keep the old behaviour by default.
  417. required_filament_types_json: str | None = None
  418. filament_overrides_json: str | None = None
  419. requirements = extract_filament_requirements(file_path, plate_id)
  420. if requirements:
  421. types = sorted({r["type"] for r in requirements if r.get("type")})
  422. if types:
  423. required_filament_types_json = json.dumps(types)
  424. if self.queue_force_color_match:
  425. overrides = [
  426. {
  427. "slot_id": r["slot_id"],
  428. "type": r.get("type", ""),
  429. "color": r.get("color", ""),
  430. "force_color_match": True,
  431. }
  432. for r in requirements
  433. if r.get("type") and r.get("color")
  434. ]
  435. if overrides:
  436. filament_overrides_json = json.dumps(overrides)
  437. queue_item = PrintQueueItem(
  438. printer_id=self.target_printer_id,
  439. target_model=target_model,
  440. archive_id=archive.id,
  441. plate_id=plate_id,
  442. position=1,
  443. status="pending",
  444. manual_start=not self.auto_dispatch,
  445. required_filament_types=required_filament_types_json,
  446. filament_overrides=filament_overrides_json,
  447. bed_levelling=bed_levelling,
  448. flow_cali=flow_cali,
  449. vibration_cali=vibration_cali,
  450. layer_inspect=layer_inspect,
  451. timelapse=timelapse,
  452. )
  453. db.add(queue_item)
  454. await db.commit()
  455. logger.info("[VP %s] Added to queue: %s", self.name, queue_item.id)
  456. await self._broadcast_archive_created(archive)
  457. try:
  458. file_path.unlink()
  459. except OSError:
  460. pass
  461. self._pending_files.pop(file_path.name, None)
  462. else:
  463. logger.error("Failed to archive file: %s", file_path.name)
  464. except Exception as e:
  465. logger.error("Error adding to print queue: %s", e)
  466. async def _broadcast_archive_created(self, archive) -> None:
  467. """Notify connected clients that a new archive exists.
  468. Real-printer prints get this from main.py's MQTT print_start handler;
  469. VP-uploaded prints need their own broadcast or the Archives page stays
  470. stale until the user switches tabs (#1282).
  471. """
  472. try:
  473. from backend.app.core.websocket import ws_manager
  474. await ws_manager.send_archive_created(
  475. {
  476. "id": archive.id,
  477. "printer_id": archive.printer_id,
  478. "filename": archive.filename,
  479. "print_name": archive.print_name,
  480. "status": archive.status,
  481. }
  482. )
  483. except Exception as e:
  484. logger.debug("[VP %s] archive_created broadcast failed: %s", self.name, e)
  485. @staticmethod
  486. def _extract_plate_id(file_path: Path) -> int | None:
  487. """Extract plate index from 3MF slice_info.config."""
  488. try:
  489. import xml.etree.ElementTree as ET
  490. import zipfile
  491. with zipfile.ZipFile(file_path, "r") as zf:
  492. if "Metadata/slice_info.config" in zf.namelist():
  493. content = zf.read("Metadata/slice_info.config").decode()
  494. root = ET.fromstring(content) # noqa: S314 # nosec B314
  495. plate = root.find(".//plate")
  496. if plate is not None:
  497. for meta in plate.findall("metadata"):
  498. if meta.get("key") == "index" and meta.get("value"):
  499. return int(meta.get("value"))
  500. except Exception:
  501. return None
  502. return None
  503. # -- Service lifecycle --
  504. def _resolve_cert_and_advertise(self) -> tuple[Path, Path, str]:
  505. """Return (cert_path, key_path, advertise_address) for TLS services.
  506. Always uses the self-signed cert chain (signed by `bbl_ca`). The user
  507. imports `bbl_ca.crt` once into the slicer; per-VP certs validate from
  508. there. Tailscale exposure is handled by the user picking the Tailscale
  509. IP in the bind_ip dropdown.
  510. """
  511. cert_path, key_path = self.generate_certificates()
  512. advertise = self.remote_interface_ip or self.bind_ip or ""
  513. return cert_path, key_path, advertise
  514. async def start_server(self) -> None:
  515. """Start server-mode services (FTP, MQTT, SSDP, Bind) on this VP's bind_ip."""
  516. logger.info("[VP %s] Starting server-mode services on %s", self.name, self.bind_ip)
  517. cert_path, key_path, advertise_addr = self._resolve_cert_and_advertise()
  518. bind_addr = self.bind_ip or "0.0.0.0" # nosec B104
  519. async def run_with_logging(coro, svc_name):
  520. try:
  521. await coro
  522. except Exception as e:
  523. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  524. self._tasks = []
  525. # FTP server
  526. self._ftp = VirtualPrinterFTPServer(
  527. upload_dir=self.upload_dir,
  528. access_code=self.access_code,
  529. cert_path=cert_path,
  530. key_path=key_path,
  531. on_file_received=self.on_file_received,
  532. bind_address=bind_addr,
  533. vp_name=self.name,
  534. )
  535. self._tasks.append(
  536. asyncio.create_task(
  537. run_with_logging(self._ftp.start(), "FTP"),
  538. name=f"vp_{self.id}_ftp",
  539. )
  540. )
  541. # MQTT server
  542. self._mqtt = SimpleMQTTServer(
  543. serial=self.serial,
  544. access_code=self.access_code,
  545. cert_path=cert_path,
  546. key_path=key_path,
  547. on_print_command=self.on_print_command,
  548. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  549. bind_address=bind_addr,
  550. vp_name=self.name,
  551. )
  552. self._tasks.append(
  553. asyncio.create_task(
  554. run_with_logging(self._mqtt.start(), "MQTT"),
  555. name=f"vp_{self.id}_mqtt",
  556. )
  557. )
  558. # MQTT bridge — fans out the target printer's pushes to slicers connected
  559. # to this VP and forwards their commands back to the printer. Only meaningful
  560. # when a target printer is configured AND printer_manager was injected (it
  561. # always is at runtime; tests may omit it).
  562. if self.target_printer_id is not None and self._printer_manager is not None:
  563. self._mqtt_bridge = MQTTBridge(
  564. vp_id=self.id,
  565. vp_name=self.name,
  566. vp_serial=self.serial,
  567. target_printer_id=self.target_printer_id,
  568. mqtt_server=self._mqtt,
  569. printer_manager=self._printer_manager,
  570. )
  571. self._mqtt.set_bridge(self._mqtt_bridge)
  572. await self._mqtt_bridge.start()
  573. # RTSPS camera passthrough on port 322. BambuStudio's camera button
  574. # connects to the device IP it bound on (the VP), not the IP in
  575. # `ipcam.rtsp_url`. Without a listener on <bind_ip>:322 the slicer
  576. # gets connection refused → "LAN connection failed". Same raw TCP
  577. # pass-through used by SlicerProxyManager in proxy mode.
  578. target_client = self._printer_manager.get_client(self.target_printer_id)
  579. target_ip = getattr(target_client, "ip_address", None) if target_client else None
  580. if target_ip:
  581. self._rtsp_proxy = TCPProxy(
  582. name="RTSP",
  583. listen_port=322,
  584. target_host=target_ip,
  585. target_port=322,
  586. bind_address=bind_addr,
  587. )
  588. self._tasks.append(
  589. asyncio.create_task(
  590. run_with_logging(self._rtsp_proxy.start(), "RTSP"),
  591. name=f"vp_{self.id}_rtsp",
  592. )
  593. )
  594. # Bind server
  595. self._bind = BindServer(
  596. serial=self.serial,
  597. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  598. name=self.name,
  599. bind_address=bind_addr,
  600. cert_path=cert_path,
  601. key_path=key_path,
  602. )
  603. self._tasks.append(
  604. asyncio.create_task(
  605. run_with_logging(self._bind.start(), "Bind"),
  606. name=f"vp_{self.id}_bind",
  607. )
  608. )
  609. # SSDP server — advertise_addr is the Tailscale FQDN when available,
  610. # otherwise the bind/remote IP (existing behaviour)
  611. self._ssdp = VirtualPrinterSSDPServer(
  612. name=self.name,
  613. serial=self.serial,
  614. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  615. advertise_ip=advertise_addr,
  616. bind_ip=bind_addr,
  617. )
  618. self._tasks.append(
  619. asyncio.create_task(
  620. run_with_logging(self._ssdp.start(), "SSDP"),
  621. name=f"vp_{self.id}_ssdp",
  622. )
  623. )
  624. logger.info("[VP %s] Server-mode services started on %s", self.name, bind_addr)
  625. async def stop_server(self) -> None:
  626. """Stop server-mode services."""
  627. if self._mqtt_bridge:
  628. try:
  629. await self._mqtt_bridge.stop()
  630. except Exception:
  631. logger.exception("[VP %s] MQTT bridge stop failed", self.name)
  632. if self._mqtt:
  633. self._mqtt.set_bridge(None)
  634. self._mqtt_bridge = None
  635. if self._rtsp_proxy:
  636. try:
  637. await self._rtsp_proxy.stop()
  638. except Exception:
  639. logger.exception("[VP %s] RTSP proxy stop failed", self.name)
  640. self._rtsp_proxy = None
  641. if self._ftp:
  642. await self._ftp.stop()
  643. self._ftp = None
  644. if self._mqtt:
  645. await self._mqtt.stop()
  646. self._mqtt = None
  647. if self._bind:
  648. await self._bind.stop()
  649. self._bind = None
  650. if self._ssdp:
  651. await self._ssdp.stop()
  652. self._ssdp = None
  653. await self._cancel_tasks()
  654. async def start_proxy(self) -> None:
  655. """Start proxy mode services for this instance."""
  656. logger.info("[VP %s] Starting proxy mode to %s", self.name, self.target_printer_ip)
  657. cert_path, key_path, _ = self._resolve_cert_and_advertise()
  658. self._proxy = SlicerProxyManager(
  659. target_host=self.target_printer_ip,
  660. cert_path=cert_path,
  661. key_path=key_path,
  662. on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m),
  663. bind_address=self.bind_ip or "0.0.0.0", # nosec B104
  664. bind_identity={
  665. "serial": self.target_printer_serial or self.serial,
  666. "model": self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  667. "name": self.name,
  668. "version": "01.00.00.00",
  669. },
  670. )
  671. async def run_with_logging(coro, svc_name):
  672. try:
  673. await coro
  674. except Exception as e:
  675. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  676. self._tasks = []
  677. # SSDP for proxy
  678. proxy_serial = self.target_printer_serial or self.serial
  679. if self.remote_interface_ip:
  680. from backend.app.services.network_utils import find_interface_for_ip
  681. local_iface = find_interface_for_ip(self.target_printer_ip)
  682. if local_iface:
  683. self._ssdp_proxy = SSDPProxy(
  684. local_interface_ip=local_iface["ip"],
  685. remote_interface_ip=self.remote_interface_ip,
  686. target_printer_ip=self.target_printer_ip,
  687. name=self.name,
  688. )
  689. self._tasks.append(
  690. asyncio.create_task(
  691. run_with_logging(self._ssdp_proxy.start(), "SSDP Proxy"),
  692. name=f"vp_{self.id}_ssdp_proxy",
  693. )
  694. )
  695. else:
  696. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  697. else:
  698. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  699. self._tasks.append(
  700. asyncio.create_task(
  701. run_with_logging(self._proxy.start(), "Proxy"),
  702. name=f"vp_{self.id}_proxy",
  703. )
  704. )
  705. def _start_fallback_ssdp(self, proxy_serial: str, run_with_logging) -> None:
  706. """Start single-interface SSDP server as fallback for proxy mode."""
  707. self._ssdp = VirtualPrinterSSDPServer(
  708. name=f"{self.name} (Proxy)",
  709. serial=proxy_serial,
  710. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  711. advertise_ip=self.bind_ip or "",
  712. bind_ip=self.bind_ip or "",
  713. )
  714. self._tasks.append(
  715. asyncio.create_task(
  716. run_with_logging(self._ssdp.start(), "SSDP"),
  717. name=f"vp_{self.id}_ssdp",
  718. )
  719. )
  720. async def stop_proxy(self) -> None:
  721. """Stop proxy mode services for this instance."""
  722. if self._proxy:
  723. await self._proxy.stop()
  724. self._proxy = None
  725. if self._ssdp:
  726. await self._ssdp.stop()
  727. self._ssdp = None
  728. if self._ssdp_proxy:
  729. await self._ssdp_proxy.stop()
  730. self._ssdp_proxy = None
  731. await self._cancel_tasks()
  732. async def _cancel_tasks(self) -> None:
  733. """Cancel all running tasks and wait for cleanup."""
  734. for task in self._tasks:
  735. task.cancel()
  736. if self._tasks:
  737. try:
  738. await asyncio.wait_for(asyncio.gather(*self._tasks, return_exceptions=True), timeout=1.0)
  739. except TimeoutError:
  740. pass
  741. self._tasks = []
  742. def get_status(self) -> dict:
  743. """Get status for this instance."""
  744. status: dict = {
  745. "running": self.is_running,
  746. "pending_files": len(self._pending_files),
  747. }
  748. if self.is_proxy and self._proxy:
  749. status["proxy"] = self._proxy.get_status()
  750. return status
  751. class VirtualPrinterManager:
  752. """Multi-instance virtual printer registry and orchestrator.
  753. Every VP runs its own independent services on a dedicated bind IP.
  754. """
  755. def __init__(self):
  756. self._session_factory: Callable | None = None
  757. self._printer_manager: PrinterManager | None = None
  758. self._instances: dict[int, VirtualPrinterInstance] = {}
  759. # Directories
  760. self._base_dir = app_settings.base_dir / "virtual_printer"
  761. # Ensure base directories exist
  762. self._ensure_base_directories()
  763. def _ensure_base_directories(self) -> None:
  764. """Create base directories at startup."""
  765. for dir_path in [self._base_dir, self._base_dir / "uploads", self._base_dir / "certs"]:
  766. try:
  767. dir_path.mkdir(parents=True, exist_ok=True)
  768. except PermissionError:
  769. logger.error(
  770. f"Cannot create directory {dir_path}: Permission denied. "
  771. f"For Docker: ensure the data volume is writable by the container user. "
  772. f"For bare metal: run 'sudo chown -R $(whoami) {self._base_dir}'"
  773. )
  774. def set_session_factory(self, session_factory: Callable) -> None:
  775. """Set the database session factory."""
  776. self._session_factory = session_factory
  777. def set_printer_manager(self, printer_manager: "PrinterManager") -> None:
  778. """Inject the global printer_manager so non-proxy VPs can mirror their target's MQTT stream."""
  779. self._printer_manager = printer_manager
  780. @property
  781. def is_enabled(self) -> bool:
  782. """Check if any virtual printer is running."""
  783. return len(self._instances) > 0
  784. async def sync_from_db(self) -> None:
  785. """Load all VPs from DB, reconcile running state."""
  786. if not self._session_factory:
  787. logger.warning("Cannot sync virtual printers: no session factory")
  788. return
  789. from sqlalchemy import select
  790. from backend.app.models.printer import Printer
  791. from backend.app.models.virtual_printer import VirtualPrinter
  792. async with self._session_factory() as db:
  793. result = await db.execute(
  794. select(VirtualPrinter).where(VirtualPrinter.enabled == True).order_by(VirtualPrinter.position) # noqa: E712
  795. )
  796. enabled_vps = result.scalars().all()
  797. # Stop instances that are no longer enabled or changed mode
  798. enabled_ids = {vp.id for vp in enabled_vps}
  799. for vp_id in list(self._instances.keys()):
  800. if vp_id not in enabled_ids:
  801. await self.remove_instance(vp_id)
  802. # Look up printer IPs for proxy VPs
  803. proxy_vps = [vp for vp in enabled_vps if vp.mode == "proxy"]
  804. proxy_ips: dict[int, tuple[str, str]] = {}
  805. if proxy_vps:
  806. async with self._session_factory() as db:
  807. for pvp in proxy_vps:
  808. if pvp.target_printer_id:
  809. result = await db.execute(select(Printer).where(Printer.id == pvp.target_printer_id))
  810. printer = result.scalar_one_or_none()
  811. if printer:
  812. proxy_ips[pvp.id] = (printer.ip_address, printer.serial_number)
  813. # Detect config changes on running instances and restart if needed
  814. for vp in enabled_vps:
  815. instance = self._instances.get(vp.id)
  816. if not instance:
  817. continue
  818. changed = (
  819. instance.mode != vp.mode
  820. or instance.model != (vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL)
  821. or instance.access_code != (vp.access_code or "")
  822. or instance.bind_ip != (vp.bind_ip or "")
  823. or instance.remote_interface_ip != (vp.remote_interface_ip or "")
  824. or instance.target_printer_id != vp.target_printer_id
  825. or instance.auto_dispatch != vp.auto_dispatch
  826. )
  827. if changed:
  828. logger.info(
  829. "VP %s config changed (mode: %s→%s), restarting",
  830. instance.name,
  831. instance.mode,
  832. vp.mode,
  833. )
  834. await self.remove_instance(vp.id)
  835. # Start instances for all enabled VPs (skip already running)
  836. for vp in enabled_vps:
  837. if vp.id in self._instances:
  838. continue
  839. if vp.mode == "proxy":
  840. ip_info = proxy_ips.get(vp.id)
  841. if not ip_info:
  842. logger.warning("Proxy VP %s: target printer not found, skipping", vp.name)
  843. continue
  844. target_ip, target_serial = ip_info
  845. instance = VirtualPrinterInstance(
  846. vp_id=vp.id,
  847. name=vp.name,
  848. mode=vp.mode,
  849. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  850. access_code=vp.access_code or "",
  851. serial_suffix=vp.serial_suffix,
  852. target_printer_ip=target_ip,
  853. target_printer_serial=target_serial,
  854. auto_dispatch=vp.auto_dispatch,
  855. bind_ip=vp.bind_ip or "",
  856. remote_interface_ip=vp.remote_interface_ip or "",
  857. tailscale_disabled=vp.tailscale_disabled,
  858. base_dir=self._base_dir,
  859. session_factory=self._session_factory,
  860. )
  861. self._instances[vp.id] = instance
  862. await instance.start_proxy()
  863. logger.info("Started proxy VP: %s → %s (bind=%s)", instance.name, target_ip, instance.bind_ip)
  864. else:
  865. instance = VirtualPrinterInstance(
  866. vp_id=vp.id,
  867. name=vp.name,
  868. mode=vp.mode,
  869. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  870. access_code=vp.access_code or "",
  871. serial_suffix=vp.serial_suffix,
  872. target_printer_id=vp.target_printer_id,
  873. auto_dispatch=vp.auto_dispatch,
  874. queue_force_color_match=vp.queue_force_color_match,
  875. bind_ip=vp.bind_ip or "",
  876. remote_interface_ip=vp.remote_interface_ip or "",
  877. tailscale_disabled=vp.tailscale_disabled,
  878. base_dir=self._base_dir,
  879. session_factory=self._session_factory,
  880. printer_manager=self._printer_manager,
  881. )
  882. self._instances[vp.id] = instance
  883. await instance.start_server()
  884. logger.info("Started server-mode VP: %s on %s", instance.name, vp.bind_ip)
  885. async def remove_instance(self, vp_id: int) -> None:
  886. """Stop and remove a single VP instance."""
  887. instance = self._instances.pop(vp_id, None)
  888. if instance:
  889. if instance.is_proxy:
  890. await instance.stop_proxy()
  891. else:
  892. await instance.stop_server()
  893. logger.info("Removed VP instance: %s", instance.name)
  894. async def stop_all(self) -> None:
  895. """Shutdown all virtual printer services."""
  896. logger.info("Stopping all virtual printer services...")
  897. for vp_id in list(self._instances.keys()):
  898. await self.remove_instance(vp_id)
  899. logger.info("All virtual printer services stopped")
  900. def get_instance(self, vp_id: int) -> VirtualPrinterInstance | None:
  901. """Get a running instance by ID."""
  902. return self._instances.get(vp_id)
  903. def get_all_status(self) -> list[dict]:
  904. """Get status for all running instances."""
  905. return [
  906. {
  907. "id": inst.id,
  908. "name": inst.name,
  909. "mode": inst.mode,
  910. **inst.get_status(),
  911. }
  912. for inst in self._instances.values()
  913. ]
  914. # -- Legacy single-printer compat --
  915. def get_status(self) -> dict:
  916. """Get status for first virtual printer (backward compat)."""
  917. if self._instances:
  918. first = next(iter(self._instances.values()))
  919. return {
  920. "enabled": True,
  921. "running": first.is_running,
  922. "mode": first.mode,
  923. "name": first.name,
  924. "serial": first.serial,
  925. "model": first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  926. "model_name": VIRTUAL_PRINTER_MODELS.get(
  927. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  928. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  929. ),
  930. "pending_files": first.get_status().get("pending_files", 0),
  931. **({"target_printer_ip": first.target_printer_ip} if first.is_proxy else {}),
  932. **({"proxy": first.get_status().get("proxy", {})} if first.is_proxy else {}),
  933. }
  934. return {
  935. "enabled": False,
  936. "running": False,
  937. "mode": "immediate",
  938. "name": "Bambuddy",
  939. "serial": "",
  940. "model": DEFAULT_VIRTUAL_PRINTER_MODEL,
  941. "model_name": VIRTUAL_PRINTER_MODELS[DEFAULT_VIRTUAL_PRINTER_MODEL],
  942. "pending_files": 0,
  943. }
  944. async def configure(
  945. self,
  946. enabled: bool,
  947. access_code: str = "",
  948. mode: str = "immediate",
  949. model: str = "",
  950. target_printer_ip: str = "",
  951. target_printer_serial: str = "",
  952. remote_interface_ip: str = "",
  953. ) -> None:
  954. """Legacy single-printer configure. Delegates to sync_from_db()."""
  955. # This method is kept for backward compat with the settings endpoint.
  956. # The actual work is done by sync_from_db() which reads from the DB.
  957. await self.sync_from_db()
  958. # Global instance
  959. virtual_printer_manager = VirtualPrinterManager()