manager.py 27 KB

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