manager.py 29 KB

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