manager.py 53 KB

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