manager.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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 backend.app.core.config import settings as app_settings
  11. from backend.app.services.virtual_printer.bind_server import BindServer
  12. from backend.app.services.virtual_printer.certificate import CertificateService
  13. from backend.app.services.virtual_printer.ftp_server import VirtualPrinterFTPServer
  14. from backend.app.services.virtual_printer.mqtt_server import SimpleMQTTServer
  15. from backend.app.services.virtual_printer.ssdp_server import SSDPProxy, VirtualPrinterSSDPServer
  16. from backend.app.services.virtual_printer.tcp_proxy import SlicerProxyManager
  17. logger = logging.getLogger(__name__)
  18. # Mapping of SSDP model codes to display names
  19. # These are the codes that slicers expect during discovery
  20. # Sources:
  21. # - https://gist.github.com/Alex-Schaefer/72a9e2491a42da2ef99fb87601955cc3
  22. # - https://github.com/psychoticbeef/BambuLabOrcaSlicerDiscovery
  23. VIRTUAL_PRINTER_MODELS = {
  24. # X1 Series
  25. "3DPrinter-X1-Carbon": "X1C", # X1 Carbon
  26. "3DPrinter-X1": "X1", # X1
  27. "C13": "X1E", # X1E
  28. # P Series
  29. "C11": "P1P", # P1P
  30. "C12": "P1S", # P1S
  31. "N7": "P2S", # P2S
  32. # A1 Series
  33. "N2S": "A1", # A1
  34. "N1": "A1 Mini", # A1 Mini
  35. # H2 Series
  36. "O1D": "H2D", # H2D
  37. "O1C": "H2C", # H2C
  38. "O1S": "H2S", # H2S
  39. }
  40. # Serial number prefixes for each model (based on Bambu Lab serial number format)
  41. # Format: MMM??RYMDDUUUUU (15 chars total)
  42. # MMM = Model prefix (3 chars)
  43. # ?? = Unknown/revision code (2 chars)
  44. # R = Revision letter (1 char)
  45. # Y = Year digit (1 char)
  46. # M = Month (1 char, hex: 1-9, A=Oct, B=Nov, C=Dec)
  47. # DD = Day (2 chars)
  48. # UUUUU = Unit number (5 chars)
  49. MODEL_SERIAL_PREFIXES = {
  50. # X1 Series
  51. "3DPrinter-X1-Carbon": "00M00A", # X1C
  52. "3DPrinter-X1": "00M00A", # X1
  53. "C13": "03W00A", # X1E
  54. # P Series
  55. "C11": "01S00A", # P1P
  56. "C12": "01P00A", # P1S
  57. "N7": "22E00A", # P2S
  58. # A1 Series
  59. "N2S": "03900A", # A1
  60. "N1": "03000A", # A1 Mini
  61. # H2 Series
  62. "O1D": "09400A", # H2D
  63. "O1C": "09400A", # H2C
  64. "O1S": "09400A", # H2S
  65. }
  66. # Default model
  67. DEFAULT_VIRTUAL_PRINTER_MODEL = "3DPrinter-X1-Carbon" # X1C
  68. def _get_serial_for_model(model: str, serial_suffix: str) -> str:
  69. """Get serial number for the given model and suffix."""
  70. prefix = MODEL_SERIAL_PREFIXES.get(model, "00M09A")
  71. return f"{prefix}{serial_suffix}"
  72. class VirtualPrinterInstance:
  73. """Per-printer state and file handling logic.
  74. Each instance represents one virtual printer with its own config,
  75. upload directory, certificates, and file handling mode.
  76. """
  77. def __init__(
  78. self,
  79. *,
  80. vp_id: int,
  81. name: str,
  82. mode: str,
  83. model: str,
  84. access_code: str,
  85. serial_suffix: str,
  86. target_printer_ip: str = "",
  87. target_printer_serial: str = "",
  88. bind_ip: str = "",
  89. remote_interface_ip: str = "",
  90. base_dir: Path,
  91. session_factory: Callable | None = None,
  92. ):
  93. self.id = vp_id
  94. self.name = name
  95. self.mode = mode
  96. self.model = model
  97. self.access_code = access_code
  98. self.serial_suffix = serial_suffix
  99. self.target_printer_ip = target_printer_ip
  100. self.target_printer_serial = target_printer_serial
  101. self.bind_ip = bind_ip
  102. self.remote_interface_ip = remote_interface_ip
  103. self._session_factory = session_factory
  104. # Directories
  105. self.upload_dir = base_dir / "uploads" / str(vp_id)
  106. self.cert_dir = base_dir / "certs" / str(vp_id)
  107. shared_ca_dir = base_dir / "certs"
  108. # Ensure directories exist
  109. self.upload_dir.mkdir(parents=True, exist_ok=True)
  110. (self.upload_dir / "cache").mkdir(exist_ok=True)
  111. self.cert_dir.mkdir(parents=True, exist_ok=True)
  112. # Certificate service (shared CA, per-instance printer cert)
  113. self._cert_service = CertificateService(
  114. cert_dir=self.cert_dir,
  115. serial=self.serial,
  116. shared_ca_dir=shared_ca_dir,
  117. )
  118. # Pending files for MQTT correlation
  119. self._pending_files: dict[str, Path] = {}
  120. # Per-instance services
  121. self._proxy: SlicerProxyManager | None = None
  122. self._ftp: VirtualPrinterFTPServer | None = None
  123. self._mqtt: SimpleMQTTServer | None = None
  124. self._bind: BindServer | None = None
  125. self._ssdp: VirtualPrinterSSDPServer | None = None
  126. self._ssdp_proxy: SSDPProxy | None = None
  127. self._tasks: list[asyncio.Task] = []
  128. @property
  129. def serial(self) -> str:
  130. """Full serial number for this virtual printer."""
  131. return _get_serial_for_model(self.model or DEFAULT_VIRTUAL_PRINTER_MODEL, self.serial_suffix)
  132. @property
  133. def cert_path(self) -> Path:
  134. return self._cert_service.cert_path
  135. @property
  136. def key_path(self) -> Path:
  137. return self._cert_service.key_path
  138. @property
  139. def is_proxy(self) -> bool:
  140. return self.mode == "proxy"
  141. @property
  142. def is_running(self) -> bool:
  143. return len(self._tasks) > 0 and all(not t.done() for t in self._tasks)
  144. def generate_certificates(self) -> tuple[Path, Path]:
  145. """Generate certificates for this instance."""
  146. self._cert_service.serial = self.serial if not self.is_proxy else (self.target_printer_serial or self.serial)
  147. additional_ips = [self.remote_interface_ip] if self.remote_interface_ip else None
  148. if self.bind_ip:
  149. additional_ips = additional_ips or []
  150. additional_ips.append(self.bind_ip)
  151. self._cert_service.delete_printer_certificate()
  152. return self._cert_service.generate_certificates(additional_ips=additional_ips)
  153. # -- File handling callbacks --
  154. async def on_file_received(self, file_path: Path, source_ip: str) -> None:
  155. """Handle file upload completion from FTP."""
  156. logger.info("[VP %s] Received file: %s from %s", self.name, file_path.name, source_ip)
  157. self._pending_files[file_path.name] = file_path
  158. if self.mode == "immediate":
  159. await self._archive_file(file_path, source_ip)
  160. elif self.mode == "print_queue":
  161. await self._add_to_print_queue(file_path, source_ip)
  162. else:
  163. await self._queue_file(file_path, source_ip)
  164. # Reset MQTT status back to IDLE
  165. if self._mqtt and file_path.suffix.lower() == ".3mf":
  166. self._mqtt.set_gcode_state("IDLE")
  167. async def on_print_command(self, filename: str, data: dict) -> None:
  168. """Handle print command from MQTT."""
  169. logger.info("[VP %s] Print command for: %s", self.name, filename)
  170. async def _archive_file(self, file_path: Path, source_ip: str) -> None:
  171. """Archive file immediately."""
  172. if not self._session_factory:
  173. logger.error("Cannot archive: no database session factory configured")
  174. return
  175. if file_path.suffix.lower() != ".3mf":
  176. logger.debug("Skipping non-3MF file: %s", file_path.name)
  177. self._pending_files.pop(file_path.name, None)
  178. try:
  179. file_path.unlink()
  180. except OSError:
  181. pass
  182. return
  183. try:
  184. from backend.app.services.archive import ArchiveService
  185. async with self._session_factory() as db:
  186. service = ArchiveService(db)
  187. archive = await service.archive_print(
  188. printer_id=None,
  189. source_file=file_path,
  190. print_data={
  191. "status": "archived",
  192. "source": "virtual_printer",
  193. "source_ip": source_ip,
  194. },
  195. )
  196. if archive:
  197. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  198. try:
  199. file_path.unlink()
  200. except OSError:
  201. pass
  202. self._pending_files.pop(file_path.name, None)
  203. else:
  204. logger.error("Failed to archive file: %s", file_path.name)
  205. except Exception as e:
  206. logger.error("Error archiving file: %s", e)
  207. async def _queue_file(self, file_path: Path, source_ip: str) -> None:
  208. """Queue file for user review."""
  209. if not self._session_factory:
  210. logger.error("Cannot queue: no database session factory configured")
  211. return
  212. if file_path.suffix.lower() != ".3mf":
  213. self._pending_files.pop(file_path.name, None)
  214. try:
  215. file_path.unlink()
  216. except OSError:
  217. pass
  218. return
  219. try:
  220. from backend.app.models.pending_upload import PendingUpload
  221. async with self._session_factory() as db:
  222. pending = PendingUpload(
  223. filename=file_path.name,
  224. file_path=str(file_path),
  225. file_size=file_path.stat().st_size,
  226. source_ip=source_ip,
  227. status="pending",
  228. uploaded_at=datetime.now(timezone.utc),
  229. )
  230. db.add(pending)
  231. await db.commit()
  232. logger.info("[VP %s] Queued: %s - %s", self.name, pending.id, file_path.name)
  233. self._pending_files.pop(file_path.name, None)
  234. except Exception as e:
  235. logger.error("Error queueing file: %s", e)
  236. async def _add_to_print_queue(self, file_path: Path, source_ip: str) -> None:
  237. """Archive file and add to print queue (unassigned)."""
  238. if not self._session_factory:
  239. logger.error("Cannot add to print queue: no database session factory configured")
  240. return
  241. if file_path.suffix.lower() != ".3mf":
  242. self._pending_files.pop(file_path.name, None)
  243. try:
  244. file_path.unlink()
  245. except OSError:
  246. pass
  247. return
  248. try:
  249. from backend.app.models.print_queue import PrintQueueItem
  250. from backend.app.services.archive import ArchiveService
  251. async with self._session_factory() as db:
  252. service = ArchiveService(db)
  253. archive = await service.archive_print(
  254. printer_id=None,
  255. source_file=file_path,
  256. print_data={
  257. "status": "archived",
  258. "source": "virtual_printer",
  259. "source_ip": source_ip,
  260. },
  261. )
  262. if archive:
  263. logger.info("[VP %s] Archived: %s - %s", self.name, archive.id, archive.print_name)
  264. queue_item = PrintQueueItem(
  265. printer_id=None,
  266. archive_id=archive.id,
  267. position=1,
  268. status="pending",
  269. )
  270. db.add(queue_item)
  271. await db.commit()
  272. logger.info("[VP %s] Added to queue: %s", self.name, queue_item.id)
  273. try:
  274. file_path.unlink()
  275. except OSError:
  276. pass
  277. self._pending_files.pop(file_path.name, None)
  278. else:
  279. logger.error("Failed to archive file: %s", file_path.name)
  280. except Exception as e:
  281. logger.error("Error adding to print queue: %s", e)
  282. # -- Service lifecycle --
  283. async def start_server(self) -> None:
  284. """Start server-mode services (FTP, MQTT, SSDP, Bind) on this VP's bind_ip."""
  285. logger.info("[VP %s] Starting server-mode services on %s", self.name, self.bind_ip)
  286. cert_path, key_path = self.generate_certificates()
  287. bind_addr = self.bind_ip or "0.0.0.0" # nosec B104
  288. async def run_with_logging(coro, svc_name):
  289. try:
  290. await coro
  291. except Exception as e:
  292. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  293. self._tasks = []
  294. # FTP server
  295. self._ftp = VirtualPrinterFTPServer(
  296. upload_dir=self.upload_dir,
  297. access_code=self.access_code,
  298. cert_path=cert_path,
  299. key_path=key_path,
  300. on_file_received=self.on_file_received,
  301. bind_address=bind_addr,
  302. )
  303. self._tasks.append(
  304. asyncio.create_task(
  305. run_with_logging(self._ftp.start(), "FTP"),
  306. name=f"vp_{self.id}_ftp",
  307. )
  308. )
  309. # MQTT server
  310. self._mqtt = SimpleMQTTServer(
  311. serial=self.serial,
  312. access_code=self.access_code,
  313. cert_path=cert_path,
  314. key_path=key_path,
  315. on_print_command=self.on_print_command,
  316. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  317. bind_address=bind_addr,
  318. )
  319. self._tasks.append(
  320. asyncio.create_task(
  321. run_with_logging(self._mqtt.start(), "MQTT"),
  322. name=f"vp_{self.id}_mqtt",
  323. )
  324. )
  325. # Bind server
  326. self._bind = BindServer(
  327. serial=self.serial,
  328. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  329. name=self.name,
  330. bind_address=bind_addr,
  331. )
  332. self._tasks.append(
  333. asyncio.create_task(
  334. run_with_logging(self._bind.start(), "Bind"),
  335. name=f"vp_{self.id}_bind",
  336. )
  337. )
  338. # SSDP server
  339. self._ssdp = VirtualPrinterSSDPServer(
  340. name=self.name,
  341. serial=self.serial,
  342. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  343. advertise_ip=self.remote_interface_ip or self.bind_ip or "",
  344. bind_ip=bind_addr,
  345. )
  346. self._tasks.append(
  347. asyncio.create_task(
  348. run_with_logging(self._ssdp.start(), "SSDP"),
  349. name=f"vp_{self.id}_ssdp",
  350. )
  351. )
  352. logger.info("[VP %s] Server-mode services started on %s", self.name, bind_addr)
  353. async def stop_server(self) -> None:
  354. """Stop server-mode services."""
  355. if self._ftp:
  356. await self._ftp.stop()
  357. self._ftp = None
  358. if self._mqtt:
  359. await self._mqtt.stop()
  360. self._mqtt = None
  361. if self._bind:
  362. await self._bind.stop()
  363. self._bind = None
  364. if self._ssdp:
  365. await self._ssdp.stop()
  366. self._ssdp = None
  367. await self._cancel_tasks()
  368. async def start_proxy(self) -> None:
  369. """Start proxy mode services for this instance."""
  370. logger.info("[VP %s] Starting proxy mode to %s", self.name, self.target_printer_ip)
  371. cert_path, key_path = self.generate_certificates()
  372. self._proxy = SlicerProxyManager(
  373. target_host=self.target_printer_ip,
  374. cert_path=cert_path,
  375. key_path=key_path,
  376. on_activity=lambda n, m: logger.info("[VP %s] Proxy %s: %s", self.name, n, m),
  377. bind_address=self.bind_ip or "0.0.0.0", # nosec B104
  378. )
  379. async def run_with_logging(coro, svc_name):
  380. try:
  381. await coro
  382. except Exception as e:
  383. logger.error("[VP %s] %s failed: %s", self.name, svc_name, e)
  384. self._tasks = []
  385. # SSDP for proxy
  386. proxy_serial = self.target_printer_serial or self.serial
  387. if self.remote_interface_ip:
  388. from backend.app.services.network_utils import find_interface_for_ip
  389. local_iface = find_interface_for_ip(self.target_printer_ip)
  390. if local_iface:
  391. self._ssdp_proxy = SSDPProxy(
  392. local_interface_ip=local_iface["ip"],
  393. remote_interface_ip=self.remote_interface_ip,
  394. target_printer_ip=self.target_printer_ip,
  395. )
  396. self._tasks.append(
  397. asyncio.create_task(
  398. run_with_logging(self._ssdp_proxy.start(), "SSDP Proxy"),
  399. name=f"vp_{self.id}_ssdp_proxy",
  400. )
  401. )
  402. else:
  403. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  404. else:
  405. self._start_fallback_ssdp(proxy_serial, run_with_logging)
  406. self._tasks.append(
  407. asyncio.create_task(
  408. run_with_logging(self._proxy.start(), "Proxy"),
  409. name=f"vp_{self.id}_proxy",
  410. )
  411. )
  412. def _start_fallback_ssdp(self, proxy_serial: str, run_with_logging) -> None:
  413. """Start single-interface SSDP server as fallback for proxy mode."""
  414. self._ssdp = VirtualPrinterSSDPServer(
  415. name=f"{self.name} (Proxy)",
  416. serial=proxy_serial,
  417. model=self.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  418. advertise_ip=self.bind_ip or "",
  419. bind_ip=self.bind_ip or "",
  420. )
  421. self._tasks.append(
  422. asyncio.create_task(
  423. run_with_logging(self._ssdp.start(), "SSDP"),
  424. name=f"vp_{self.id}_ssdp",
  425. )
  426. )
  427. async def stop_proxy(self) -> None:
  428. """Stop proxy mode services for this instance."""
  429. if self._proxy:
  430. await self._proxy.stop()
  431. self._proxy = None
  432. if self._ssdp:
  433. await self._ssdp.stop()
  434. self._ssdp = None
  435. if self._ssdp_proxy:
  436. await self._ssdp_proxy.stop()
  437. self._ssdp_proxy = None
  438. await self._cancel_tasks()
  439. async def _cancel_tasks(self) -> None:
  440. """Cancel all running tasks and wait for cleanup."""
  441. for task in self._tasks:
  442. task.cancel()
  443. if self._tasks:
  444. try:
  445. await asyncio.wait_for(asyncio.gather(*self._tasks, return_exceptions=True), timeout=1.0)
  446. except TimeoutError:
  447. pass
  448. self._tasks = []
  449. def get_status(self) -> dict:
  450. """Get status for this instance."""
  451. status: dict = {
  452. "running": self.is_running,
  453. "pending_files": len(self._pending_files),
  454. }
  455. if self.is_proxy and self._proxy:
  456. status["proxy"] = self._proxy.get_status()
  457. return status
  458. class VirtualPrinterManager:
  459. """Multi-instance virtual printer registry and orchestrator.
  460. Every VP runs its own independent services on a dedicated bind IP.
  461. """
  462. def __init__(self):
  463. self._session_factory: Callable | None = None
  464. self._instances: dict[int, VirtualPrinterInstance] = {}
  465. # Directories
  466. self._base_dir = app_settings.base_dir / "virtual_printer"
  467. # Ensure base directories exist
  468. self._ensure_base_directories()
  469. def _ensure_base_directories(self) -> None:
  470. """Create base directories at startup."""
  471. for dir_path in [self._base_dir, self._base_dir / "uploads", self._base_dir / "certs"]:
  472. try:
  473. dir_path.mkdir(parents=True, exist_ok=True)
  474. except PermissionError:
  475. logger.error(
  476. f"Cannot create directory {dir_path}: Permission denied. "
  477. f"For Docker: ensure the data volume is writable by the container user. "
  478. f"For bare metal: run 'sudo chown -R $(whoami) {self._base_dir}'"
  479. )
  480. def set_session_factory(self, session_factory: Callable) -> None:
  481. """Set the database session factory."""
  482. self._session_factory = session_factory
  483. @property
  484. def is_enabled(self) -> bool:
  485. """Check if any virtual printer is running."""
  486. return len(self._instances) > 0
  487. async def sync_from_db(self) -> None:
  488. """Load all VPs from DB, reconcile running state."""
  489. if not self._session_factory:
  490. logger.warning("Cannot sync virtual printers: no session factory")
  491. return
  492. from sqlalchemy import select
  493. from backend.app.models.printer import Printer
  494. from backend.app.models.virtual_printer import VirtualPrinter
  495. async with self._session_factory() as db:
  496. result = await db.execute(
  497. select(VirtualPrinter).where(VirtualPrinter.enabled == True).order_by(VirtualPrinter.position) # noqa: E712
  498. )
  499. enabled_vps = result.scalars().all()
  500. # Stop instances that are no longer enabled or changed mode
  501. enabled_ids = {vp.id for vp in enabled_vps}
  502. for vp_id in list(self._instances.keys()):
  503. if vp_id not in enabled_ids:
  504. await self.remove_instance(vp_id)
  505. # Look up printer IPs for proxy VPs
  506. proxy_vps = [vp for vp in enabled_vps if vp.mode == "proxy"]
  507. proxy_ips: dict[int, tuple[str, str]] = {}
  508. if proxy_vps:
  509. async with self._session_factory() as db:
  510. for pvp in proxy_vps:
  511. if pvp.target_printer_id:
  512. result = await db.execute(select(Printer).where(Printer.id == pvp.target_printer_id))
  513. printer = result.scalar_one_or_none()
  514. if printer:
  515. proxy_ips[pvp.id] = (printer.ip_address, printer.serial_number)
  516. # Start instances for all enabled VPs (skip already running)
  517. for vp in enabled_vps:
  518. if vp.id in self._instances:
  519. continue
  520. if vp.mode == "proxy":
  521. ip_info = proxy_ips.get(vp.id)
  522. if not ip_info:
  523. logger.warning("Proxy VP %s: target printer not found, skipping", vp.name)
  524. continue
  525. target_ip, target_serial = ip_info
  526. instance = VirtualPrinterInstance(
  527. vp_id=vp.id,
  528. name=vp.name,
  529. mode=vp.mode,
  530. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  531. access_code=vp.access_code or "",
  532. serial_suffix=vp.serial_suffix,
  533. target_printer_ip=target_ip,
  534. target_printer_serial=target_serial,
  535. bind_ip=vp.bind_ip or "",
  536. remote_interface_ip=vp.remote_interface_ip or "",
  537. base_dir=self._base_dir,
  538. session_factory=self._session_factory,
  539. )
  540. self._instances[vp.id] = instance
  541. await instance.start_proxy()
  542. logger.info("Started proxy VP: %s → %s", instance.name, target_ip)
  543. else:
  544. instance = VirtualPrinterInstance(
  545. vp_id=vp.id,
  546. name=vp.name,
  547. mode=vp.mode,
  548. model=vp.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  549. access_code=vp.access_code or "",
  550. serial_suffix=vp.serial_suffix,
  551. bind_ip=vp.bind_ip or "",
  552. remote_interface_ip=vp.remote_interface_ip or "",
  553. base_dir=self._base_dir,
  554. session_factory=self._session_factory,
  555. )
  556. self._instances[vp.id] = instance
  557. await instance.start_server()
  558. logger.info("Started server-mode VP: %s on %s", instance.name, vp.bind_ip)
  559. async def remove_instance(self, vp_id: int) -> None:
  560. """Stop and remove a single VP instance."""
  561. instance = self._instances.pop(vp_id, None)
  562. if instance:
  563. if instance.is_proxy:
  564. await instance.stop_proxy()
  565. else:
  566. await instance.stop_server()
  567. logger.info("Removed VP instance: %s", instance.name)
  568. async def stop_all(self) -> None:
  569. """Shutdown all virtual printer services."""
  570. logger.info("Stopping all virtual printer services...")
  571. for vp_id in list(self._instances.keys()):
  572. await self.remove_instance(vp_id)
  573. logger.info("All virtual printer services stopped")
  574. def get_instance(self, vp_id: int) -> VirtualPrinterInstance | None:
  575. """Get a running instance by ID."""
  576. return self._instances.get(vp_id)
  577. def get_all_status(self) -> list[dict]:
  578. """Get status for all running instances."""
  579. return [
  580. {
  581. "id": inst.id,
  582. "name": inst.name,
  583. "mode": inst.mode,
  584. **inst.get_status(),
  585. }
  586. for inst in self._instances.values()
  587. ]
  588. # -- Legacy single-printer compat --
  589. def get_status(self) -> dict:
  590. """Get status for first virtual printer (backward compat)."""
  591. if self._instances:
  592. first = next(iter(self._instances.values()))
  593. return {
  594. "enabled": True,
  595. "running": first.is_running,
  596. "mode": first.mode,
  597. "name": first.name,
  598. "serial": first.serial,
  599. "model": first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  600. "model_name": VIRTUAL_PRINTER_MODELS.get(
  601. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  602. first.model or DEFAULT_VIRTUAL_PRINTER_MODEL,
  603. ),
  604. "pending_files": first.get_status().get("pending_files", 0),
  605. **({"target_printer_ip": first.target_printer_ip} if first.is_proxy else {}),
  606. **({"proxy": first.get_status().get("proxy", {})} if first.is_proxy else {}),
  607. }
  608. return {
  609. "enabled": False,
  610. "running": False,
  611. "mode": "immediate",
  612. "name": "Bambuddy",
  613. "serial": "",
  614. "model": DEFAULT_VIRTUAL_PRINTER_MODEL,
  615. "model_name": VIRTUAL_PRINTER_MODELS[DEFAULT_VIRTUAL_PRINTER_MODEL],
  616. "pending_files": 0,
  617. }
  618. async def configure(
  619. self,
  620. enabled: bool,
  621. access_code: str = "",
  622. mode: str = "immediate",
  623. model: str = "",
  624. target_printer_ip: str = "",
  625. target_printer_serial: str = "",
  626. remote_interface_ip: str = "",
  627. ) -> None:
  628. """Legacy single-printer configure. Delegates to sync_from_db()."""
  629. # This method is kept for backward compat with the settings endpoint.
  630. # The actual work is done by sync_from_db() which reads from the DB.
  631. await self.sync_from_db()
  632. # Global instance
  633. virtual_printer_manager = VirtualPrinterManager()