manager.py 29 KB

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