bambu_ftp.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. import asyncio
  2. import ftplib # nosec B402
  3. import logging
  4. import os
  5. import socket
  6. import ssl
  7. import time
  8. from collections.abc import Awaitable, Callable
  9. from ftplib import FTP, FTP_TLS # nosec B402
  10. from io import BytesIO
  11. from pathlib import Path
  12. from typing import TypeVar
  13. logger = logging.getLogger(__name__)
  14. T = TypeVar("T")
  15. class ImplicitFTP_TLS(FTP_TLS):
  16. """FTP_TLS subclass for implicit FTPS (port 990) with model-specific SSL handling.
  17. X1C/P1S printers (vsFTPd) require SSL with session reuse on the data channel.
  18. A1/A1 Mini printers have issues with SSL on the data channel entirely and
  19. timeout waiting for transfer completion. Set skip_session_reuse=True for A1
  20. printers to skip SSL on the data channel (control channel remains encrypted).
  21. """
  22. def __init__(self, *args, skip_session_reuse: bool = False, **kwargs):
  23. super().__init__(*args, **kwargs)
  24. self._sock = None
  25. self.skip_session_reuse = skip_session_reuse
  26. self.ssl_context = ssl.create_default_context()
  27. self.ssl_context.check_hostname = False
  28. self.ssl_context.verify_mode = ssl.CERT_NONE
  29. def connect(self, host="", port=990, timeout=-999, source_address=None):
  30. """Connect to host, wrapping socket in TLS immediately (implicit FTPS)."""
  31. if host:
  32. self.host = host
  33. if port > 0:
  34. self.port = port
  35. if timeout != -999:
  36. self.timeout = timeout
  37. if source_address:
  38. self.source_address = source_address
  39. # Create and wrap socket immediately (implicit TLS)
  40. self.sock = socket.create_connection((self.host, self.port), self.timeout, source_address=self.source_address)
  41. self.sock = self.ssl_context.wrap_socket(self.sock, server_hostname=self.host)
  42. self.af = self.sock.family
  43. self.file = self.sock.makefile("r", encoding=self.encoding)
  44. self.welcome = self.getresp()
  45. return self.welcome
  46. def ntransfercmd(self, cmd, rest=None):
  47. """Override to wrap data connection in SSL for X1C/P1S only.
  48. X1C/P1S printers (vsFTPd) require SSL session reuse on the data channel.
  49. A1/A1 Mini printers have issues with SSL on the data channel entirely -
  50. they timeout waiting for the transfer completion response. For A1, we
  51. skip SSL wrapping on the data channel (control channel remains encrypted).
  52. """
  53. conn, size = FTP.ntransfercmd(self, cmd, rest)
  54. if self._prot_p and not self.skip_session_reuse:
  55. # X1C/P1S: Wrap data channel with SSL session reuse (required by vsFTPd)
  56. conn = self.ssl_context.wrap_socket(
  57. conn,
  58. server_hostname=self.host,
  59. session=self.sock.session,
  60. )
  61. # A1/A1 Mini (skip_session_reuse=True): Don't wrap data channel in SSL
  62. # The control channel remains encrypted via implicit FTPS
  63. return conn, size
  64. class BambuFTPClient:
  65. """FTP client for retrieving files from Bambu Lab printers."""
  66. FTP_PORT = 990
  67. # Default timeout in seconds (increased for A1 printers)
  68. DEFAULT_TIMEOUT = 30
  69. # Models that may need SSL mode fallback (try prot_p first, fall back to prot_c)
  70. # These models have varying FTP SSL behavior depending on firmware version
  71. A1_MODELS = ("A1", "A1 Mini")
  72. # Chunk size for manual upload transfer (64KB)
  73. # Smaller chunks provide smoother progress reporting — at typical printer FTP
  74. # speeds (~50-100KB/s) this gives a progress update roughly every second.
  75. CHUNK_SIZE = 64 * 1024
  76. # Cache for working FTP modes per printer IP
  77. # Maps IP -> "prot_p" or "prot_c"
  78. _mode_cache: dict[str, str] = {}
  79. def __init__(
  80. self,
  81. ip_address: str,
  82. access_code: str,
  83. timeout: float | None = None,
  84. printer_model: str | None = None,
  85. force_prot_c: bool = False,
  86. ):
  87. self.ip_address = ip_address
  88. self.access_code = access_code
  89. self.timeout = timeout if timeout is not None else self.DEFAULT_TIMEOUT
  90. self.printer_model = printer_model
  91. self.force_prot_c = force_prot_c
  92. self._ftp: ImplicitFTP_TLS | None = None
  93. def _is_a1_model(self) -> bool:
  94. """Check if this is an A1 series printer."""
  95. if not self.printer_model:
  96. return False
  97. return self.printer_model in self.A1_MODELS
  98. def _get_cached_mode(self) -> str | None:
  99. """Get cached FTP mode for this printer."""
  100. return self._mode_cache.get(self.ip_address)
  101. @classmethod
  102. def cache_mode(cls, ip_address: str, mode: str):
  103. """Cache the working FTP mode for a printer."""
  104. cls._mode_cache[ip_address] = mode
  105. logger.info("FTP mode cached for %s: %s", ip_address, mode)
  106. def _should_use_prot_c(self) -> bool:
  107. """Determine if we should use prot_c (clear) mode."""
  108. # If explicitly forced, use prot_c
  109. if self.force_prot_c:
  110. return True
  111. # Check cache first
  112. cached = self._get_cached_mode()
  113. if cached:
  114. return cached == "prot_c"
  115. # Default: try prot_p first (will fall back if needed)
  116. return False
  117. def connect(self) -> bool:
  118. """Connect to the printer FTP server (implicit FTPS on port 990)."""
  119. try:
  120. use_prot_c = self._should_use_prot_c()
  121. logger.debug(
  122. f"FTP connecting to {self.ip_address}:{self.FTP_PORT} "
  123. f"(timeout={self.timeout}s, model={self.printer_model}, prot_c={use_prot_c})"
  124. )
  125. self._ftp = ImplicitFTP_TLS(skip_session_reuse=use_prot_c)
  126. self._ftp.connect(self.ip_address, self.FTP_PORT, timeout=self.timeout)
  127. logger.debug("FTP connected, logging in as bblp")
  128. self._ftp.login("bblp", self.access_code)
  129. if use_prot_c:
  130. # Use clear (unencrypted) data channel
  131. logger.debug("FTP logged in, setting prot_c (clear) and passive mode")
  132. self._ftp.prot_c()
  133. else:
  134. # Use protected (encrypted) data channel with session reuse
  135. logger.debug("FTP logged in, setting prot_p (protected) and passive mode")
  136. self._ftp.prot_p()
  137. self._ftp.set_pasv(True)
  138. # Log welcome message for debugging
  139. if hasattr(self._ftp, "welcome") and self._ftp.welcome:
  140. logger.debug("FTP server welcome: %s", self._ftp.welcome)
  141. logger.info(
  142. f"FTP connected successfully to {self.ip_address} (model={self.printer_model}, prot_c={use_prot_c})"
  143. )
  144. return True
  145. except ftplib.error_perm as e:
  146. logger.warning("FTP connection permission error to %s: %s", self.ip_address, e)
  147. self._ftp = None
  148. return False
  149. except TimeoutError as e:
  150. logger.warning("FTP connection timed out to %s: %s", self.ip_address, e)
  151. self._ftp = None
  152. return False
  153. except ssl.SSLError as e:
  154. logger.warning("FTP SSL error connecting to %s: %s", self.ip_address, e)
  155. self._ftp = None
  156. return False
  157. except (OSError, ftplib.Error) as e:
  158. logger.warning("FTP connection failed to %s: %s (type: %s)", self.ip_address, e, type(e).__name__)
  159. self._ftp = None
  160. return False
  161. def disconnect(self):
  162. """Disconnect from the FTP server."""
  163. if self._ftp:
  164. try:
  165. self._ftp.quit()
  166. except (OSError, ftplib.Error, EOFError):
  167. pass # Best-effort FTP cleanup; connection may already be closed
  168. self._ftp = None
  169. def list_files(self, path: str = "/") -> list[dict]:
  170. """List files in a directory."""
  171. if not self._ftp:
  172. return []
  173. files = []
  174. try:
  175. self._ftp.cwd(path)
  176. items = []
  177. self._ftp.retrlines("LIST", items.append)
  178. for item in items:
  179. parts = item.split()
  180. if len(parts) >= 9:
  181. name = " ".join(parts[8:])
  182. is_dir = item.startswith("d")
  183. size = int(parts[4]) if not is_dir else 0
  184. # Parse modification time from FTP listing
  185. # Format: "Nov 30 10:15" or "Nov 30 2024"
  186. mtime = None
  187. try:
  188. from datetime import datetime
  189. month = parts[5]
  190. day = parts[6]
  191. time_or_year = parts[7]
  192. # Determine if it's time (HH:MM) or year
  193. if ":" in time_or_year:
  194. # Recent file: "Nov 30 10:15" - assume current year
  195. year = datetime.now().year
  196. time_str = f"{month} {day} {year} {time_or_year}"
  197. mtime = datetime.strptime(time_str, "%b %d %Y %H:%M")
  198. # If parsed date is in the future, use last year
  199. if mtime > datetime.now():
  200. mtime = mtime.replace(year=year - 1)
  201. else:
  202. # Older file: "Nov 30 2024" - no time, just date
  203. time_str = f"{month} {day} {time_or_year}"
  204. mtime = datetime.strptime(time_str, "%b %d %Y")
  205. except (ValueError, IndexError):
  206. pass # Non-critical: mtime parsing is best-effort; file entry works without it
  207. file_entry = {
  208. "name": name,
  209. "is_directory": is_dir,
  210. "size": size,
  211. "path": f"{path.rstrip('/')}/{name}",
  212. }
  213. if mtime:
  214. file_entry["mtime"] = mtime
  215. files.append(file_entry)
  216. logger.debug("Listed %s files in %s", len(files), path)
  217. except (OSError, ftplib.Error) as e:
  218. logger.info("FTP list_files failed for %s: %s", path, e)
  219. return files
  220. def download_file(self, remote_path: str) -> bytes | None:
  221. """Download a file from the printer."""
  222. if not self._ftp:
  223. return None
  224. try:
  225. buffer = BytesIO()
  226. self._ftp.retrbinary(f"RETR {remote_path}", buffer.write)
  227. return buffer.getvalue()
  228. except (OSError, ftplib.Error):
  229. return None
  230. def download_to_file(self, remote_path: str, local_path: Path) -> bool:
  231. """Download a file from the printer to local filesystem."""
  232. if not self._ftp:
  233. logger.warning("download_to_file called but FTP not connected")
  234. return False
  235. try:
  236. local_path.parent.mkdir(parents=True, exist_ok=True)
  237. with open(local_path, "wb") as f:
  238. self._ftp.retrbinary(f"RETR {remote_path}", f.write)
  239. f.flush()
  240. os.fsync(f.fileno())
  241. file_size = local_path.stat().st_size if local_path.exists() else 0
  242. if file_size == 0:
  243. logger.warning("FTP download returned 0 bytes for %s", remote_path)
  244. if local_path.exists():
  245. local_path.unlink()
  246. return False
  247. logger.info("Successfully downloaded %s to %s (%s bytes)", remote_path, local_path, file_size)
  248. return True
  249. except (OSError, ftplib.Error) as e:
  250. # Log at INFO level so we can see failures in normal logs
  251. logger.info("FTP download failed for %s: %s", remote_path, e)
  252. # Clean up partial file if it exists
  253. if local_path.exists():
  254. try:
  255. local_path.unlink()
  256. except OSError:
  257. pass # Best-effort partial file cleanup; not critical if removal fails
  258. return False
  259. def diagnose_storage(self) -> dict:
  260. """Run storage diagnostics and return results. For debugging upload issues."""
  261. results = {
  262. "connected": self._ftp is not None,
  263. "can_list_root": False,
  264. "root_files": [],
  265. "can_list_cache": False,
  266. "storage_info": None,
  267. "pwd": None,
  268. "errors": [],
  269. }
  270. if not self._ftp:
  271. results["errors"].append("FTP not connected")
  272. return results
  273. # Try to get current directory
  274. try:
  275. results["pwd"] = self._ftp.pwd()
  276. logger.debug("FTP current directory: %s", results["pwd"])
  277. except (OSError, ftplib.Error) as e:
  278. results["errors"].append(f"PWD failed: {e}")
  279. logger.debug("FTP PWD failed: %s", e)
  280. # Try to list root directory
  281. try:
  282. self._ftp.cwd("/")
  283. items = []
  284. self._ftp.retrlines("LIST", items.append)
  285. results["can_list_root"] = True
  286. results["root_files"] = items[:10] # First 10 entries
  287. logger.debug("FTP root listing (%s items): %s", len(items), items[:5])
  288. except (OSError, ftplib.Error) as e:
  289. results["errors"].append(f"LIST / failed: {e}")
  290. logger.debug("FTP LIST / failed: %s", e)
  291. # Try to list /cache (should exist on all printers)
  292. try:
  293. self._ftp.cwd("/cache")
  294. items = []
  295. self._ftp.retrlines("LIST", items.append)
  296. results["can_list_cache"] = True
  297. logger.debug("FTP /cache listing: %s items", len(items))
  298. except (OSError, ftplib.Error) as e:
  299. results["errors"].append(f"LIST /cache failed: {e}")
  300. logger.debug("FTP LIST /cache failed: %s", e)
  301. # Try to get storage info
  302. try:
  303. results["storage_info"] = self.get_storage_info()
  304. logger.debug("FTP storage info: %s", results["storage_info"])
  305. except (OSError, ftplib.Error) as e:
  306. results["errors"].append(f"Storage info failed: {e}")
  307. return results
  308. def upload_file(
  309. self,
  310. local_path: Path,
  311. remote_path: str,
  312. progress_callback: Callable[[int, int], None] | None = None,
  313. ) -> bool:
  314. """Upload a file to the printer with optional progress callback."""
  315. if not self._ftp:
  316. logger.warning("upload_file: FTP not connected")
  317. return False
  318. try:
  319. file_size = local_path.stat().st_size if local_path.exists() else 0
  320. logger.info("FTP uploading %s (%s bytes) to %s", local_path, file_size, remote_path)
  321. uploaded = 0
  322. callback_exception: Exception | None = None
  323. # Use manual transfer instead of storbinary() for A1 compatibility
  324. # A1 printers have issues with storbinary's voidresp() hanging after transfer
  325. with open(local_path, "rb") as f:
  326. logger.debug("FTP STOR command starting for %s", remote_path)
  327. t0 = time.monotonic()
  328. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  329. logger.info(
  330. "FTP data channel ready in %.1fs (PASV + TLS handshake)",
  331. time.monotonic() - t0,
  332. )
  333. # Set explicit socket options for reliable transfer
  334. conn.setblocking(True)
  335. conn.settimeout(self.timeout)
  336. try:
  337. while True:
  338. chunk = f.read(self.CHUNK_SIZE)
  339. if not chunk:
  340. logger.debug("FTP upload: final chunk reached")
  341. break
  342. conn.sendall(chunk)
  343. uploaded += len(chunk)
  344. logger.debug("FTP upload progress: %s/%s bytes", uploaded, file_size)
  345. if progress_callback:
  346. try:
  347. progress_callback(uploaded, file_size)
  348. except Exception as e:
  349. callback_exception = e
  350. logger.info(
  351. "FTP upload callback requested stop for %s at %s/%s bytes: %s",
  352. remote_path,
  353. uploaded,
  354. file_size,
  355. e,
  356. )
  357. break
  358. except OSError as e:
  359. logger.error("FTP connection lost during upload: %s", e)
  360. raise
  361. finally:
  362. try:
  363. conn.close()
  364. except OSError:
  365. pass
  366. # Skip voidresp() for all models — the data transfer is already complete.
  367. # A1 models hang indefinitely on voidresp(). H2D printers (vsFTPd) delay
  368. # the 226 response by 30+ seconds after data is fully sent. Even X1C/P1S
  369. # gain nothing from waiting — the file is on the SD card once sendall() returns.
  370. # Verified via direct curl upload: 226 arrives ~32s after data channel closes.
  371. if callback_exception is not None:
  372. cleanup_ok = False
  373. try:
  374. cleanup_ok = self.delete_file(remote_path)
  375. except Exception as cleanup_error:
  376. logger.warning("FTP cancel cleanup failed for %s: %s", remote_path, cleanup_error)
  377. if cleanup_ok:
  378. logger.info("FTP cancel cleanup succeeded for %s", remote_path)
  379. raise callback_exception
  380. raise RuntimeError(
  381. f"Upload cancelled but failed to remove partial file {remote_path} from printer"
  382. ) from callback_exception
  383. elapsed = time.monotonic() - t0
  384. speed_kbs = (file_size / 1024) / elapsed if elapsed > 0 else 0
  385. logger.info(
  386. "FTP upload complete: %s (%s bytes in %.1fs, %.0f KB/s)",
  387. remote_path,
  388. file_size,
  389. elapsed,
  390. speed_kbs,
  391. )
  392. return True
  393. except ftplib.error_perm as e:
  394. # Permanent FTP error (4xx/5xx response)
  395. error_code = str(e)[:3] if str(e) else "unknown"
  396. logger.error("FTP upload failed for %s: %s (error code: %s)", remote_path, e, error_code)
  397. if error_code == "553":
  398. logger.error(
  399. "FTP 553 error - Could not create file. Possible causes: "
  400. "1) No SD card inserted, 2) SD card full, 3) SD card not formatted correctly (needs FAT32/exFAT), "
  401. "4) Printer busy/not ready, 5) File path issue"
  402. )
  403. elif error_code == "550":
  404. logger.error("FTP 550 error - File/directory not found or permission denied")
  405. elif error_code == "552":
  406. logger.error("FTP 552 error - Storage quota exceeded (SD card full?)")
  407. return False
  408. except (OSError, ftplib.Error) as e:
  409. logger.error("FTP upload failed for %s: %s (type: %s)", remote_path, e, type(e).__name__)
  410. return False
  411. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  412. """Upload bytes to the printer."""
  413. if not self._ftp:
  414. return False
  415. try:
  416. # Use manual transfer instead of storbinary() for A1 compatibility
  417. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  418. conn.setblocking(True)
  419. conn.settimeout(self.timeout)
  420. try:
  421. # Send data in chunks
  422. offset = 0
  423. while offset < len(data):
  424. chunk = data[offset : offset + self.CHUNK_SIZE]
  425. conn.sendall(chunk)
  426. offset += len(chunk)
  427. except OSError as e:
  428. logger.error("FTP connection lost during upload_bytes: %s", e)
  429. raise
  430. finally:
  431. try:
  432. conn.close()
  433. except OSError:
  434. pass
  435. return True
  436. except (OSError, ftplib.Error):
  437. return False
  438. def delete_file(self, remote_path: str) -> bool:
  439. """Delete a file from the printer."""
  440. if not self._ftp:
  441. return False
  442. try:
  443. self._ftp.delete(remote_path)
  444. return True
  445. except (OSError, ftplib.Error) as e:
  446. logger.warning("Failed to delete %s: %s", remote_path, e)
  447. return False
  448. def get_file_size(self, remote_path: str) -> int | None:
  449. """Get the size of a file."""
  450. if not self._ftp:
  451. return None
  452. try:
  453. return self._ftp.size(remote_path)
  454. except (OSError, ftplib.Error):
  455. return None
  456. def get_storage_info(self) -> dict | None:
  457. """Get storage information from the printer."""
  458. if not self._ftp:
  459. return None
  460. result = {}
  461. # Try AVBL command (available space) - some FTP servers support this
  462. try:
  463. response = self._ftp.sendcmd("AVBL")
  464. logger.debug("AVBL response: %s", response)
  465. # Response format: "213 <bytes available>"
  466. if response.startswith("213"):
  467. parts = response.split()
  468. if len(parts) >= 2:
  469. result["free_bytes"] = int(parts[1])
  470. except (OSError, ftplib.Error) as e:
  471. logger.debug("AVBL command not supported: %s", e)
  472. # Try STAT command as fallback
  473. try:
  474. response = self._ftp.sendcmd("STAT")
  475. logger.debug("STAT response: %s", response)
  476. except (OSError, ftplib.Error):
  477. pass # Both AVBL and STAT unsupported; storage info will rely on directory scan
  478. # Calculate used space by listing root directories
  479. try:
  480. total_used = 0
  481. dirs_to_scan = ["/cache", "/timelapse", "/model", "/data", "/data/Metadata", "/"]
  482. for dir_path in dirs_to_scan:
  483. try:
  484. self._ftp.cwd(dir_path)
  485. items = []
  486. self._ftp.retrlines("LIST", items.append)
  487. for item in items:
  488. parts = item.split()
  489. if len(parts) >= 5 and not item.startswith("d"):
  490. try:
  491. total_used += int(parts[4])
  492. except ValueError:
  493. pass # Skip entries with non-numeric size fields
  494. except (OSError, ftplib.Error):
  495. pass # Directory may not exist on this printer model; skip it
  496. result["used_bytes"] = total_used
  497. except (OSError, ftplib.Error):
  498. pass # Storage scan failed; return whatever info was collected above
  499. return result if result else None
  500. async def download_file_async(
  501. ip_address: str,
  502. access_code: str,
  503. remote_path: str,
  504. local_path: Path,
  505. timeout: float = 60.0,
  506. socket_timeout: float | None = None,
  507. printer_model: str | None = None,
  508. ) -> bool:
  509. """Async wrapper for downloading a file with timeout.
  510. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  511. to prot_c if the download fails. The working mode is cached for future operations.
  512. Args:
  513. ip_address: Printer IP address
  514. access_code: Printer access code
  515. remote_path: Remote file path on printer
  516. local_path: Local path to save file
  517. timeout: Overall operation timeout (asyncio)
  518. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  519. printer_model: Printer model for A1-specific workarounds
  520. """
  521. loop = asyncio.get_event_loop()
  522. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  523. def _download(force_prot_c: bool = False) -> bool:
  524. mode_str = "prot_c" if force_prot_c else "prot_p"
  525. client = BambuFTPClient(
  526. ip_address, access_code, timeout=socket_timeout, printer_model=printer_model, force_prot_c=force_prot_c
  527. )
  528. if client.connect():
  529. try:
  530. result = client.download_to_file(remote_path, local_path)
  531. if result:
  532. # Cache the working mode
  533. BambuFTPClient.cache_mode(ip_address, mode_str)
  534. return result
  535. finally:
  536. client.disconnect()
  537. return False
  538. try:
  539. # Check if we have a cached mode for this printer
  540. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  541. if cached_mode:
  542. # Use cached mode
  543. force_prot_c = cached_mode == "prot_c"
  544. return await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(force_prot_c)), timeout=timeout)
  545. # No cached mode - try prot_p first
  546. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(False)), timeout=timeout)
  547. if result:
  548. return True
  549. # Download failed - for A1 models, try prot_c fallback
  550. if is_a1:
  551. logger.info("FTP download failed with prot_p for A1 model, trying prot_c fallback...")
  552. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(True)), timeout=timeout)
  553. return result
  554. return False
  555. except TimeoutError:
  556. logger.warning("FTP download timed out after %ss for %s", timeout, remote_path)
  557. return False
  558. async def download_file_try_paths_async(
  559. ip_address: str,
  560. access_code: str,
  561. remote_paths: list[str],
  562. local_path: Path,
  563. socket_timeout: float | None = None,
  564. printer_model: str | None = None,
  565. ) -> bool:
  566. """Try downloading a file from multiple paths using a single connection.
  567. Args:
  568. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  569. printer_model: Printer model for A1-specific workarounds
  570. """
  571. loop = asyncio.get_event_loop()
  572. def _download():
  573. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  574. if not client.connect():
  575. return False
  576. try:
  577. return any(client.download_to_file(remote_path, local_path) for remote_path in remote_paths)
  578. finally:
  579. client.disconnect()
  580. return await loop.run_in_executor(None, _download)
  581. async def upload_file_async(
  582. ip_address: str,
  583. access_code: str,
  584. local_path: Path,
  585. remote_path: str,
  586. timeout: float = 600.0,
  587. progress_callback: Callable[[int, int], None] | None = None,
  588. socket_timeout: float | None = None,
  589. printer_model: str | None = None,
  590. ) -> bool:
  591. """Async wrapper for uploading a file with timeout and progress callback.
  592. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  593. to prot_c if the upload fails. The working mode is cached for future uploads.
  594. Args:
  595. ip_address: Printer IP address
  596. access_code: Printer access code
  597. local_path: Local file path to upload
  598. remote_path: Remote path on printer
  599. timeout: Overall operation timeout (asyncio)
  600. progress_callback: Optional callback for progress updates
  601. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  602. printer_model: Printer model for A1-specific workarounds
  603. """
  604. loop = asyncio.get_event_loop()
  605. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  606. def _upload(force_prot_c: bool = False) -> bool:
  607. mode_str = "prot_c" if force_prot_c else "prot_p"
  608. logger.info(
  609. f"FTP connecting to {ip_address} for upload (model={printer_model}, "
  610. f"mode={mode_str}, socket_timeout={socket_timeout}s)..."
  611. )
  612. client = BambuFTPClient(
  613. ip_address, access_code, timeout=socket_timeout, printer_model=printer_model, force_prot_c=force_prot_c
  614. )
  615. if client.connect():
  616. logger.info("FTP connected to %s", ip_address)
  617. try:
  618. result = client.upload_file(local_path, remote_path, progress_callback)
  619. if result:
  620. # Cache the working mode
  621. BambuFTPClient.cache_mode(ip_address, mode_str)
  622. return result
  623. finally:
  624. client.disconnect()
  625. logger.warning("FTP connection failed to %s", ip_address)
  626. return False
  627. try:
  628. # Check if we have a cached mode for this printer
  629. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  630. if cached_mode:
  631. # Use cached mode
  632. force_prot_c = cached_mode == "prot_c"
  633. return await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(force_prot_c)), timeout=timeout)
  634. # No cached mode - try prot_p first
  635. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(False)), timeout=timeout)
  636. if result:
  637. return True
  638. # Upload failed - for A1 models, try prot_c fallback
  639. if is_a1:
  640. logger.info("FTP upload failed with prot_p for A1 model, trying prot_c fallback...")
  641. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(True)), timeout=timeout)
  642. return result
  643. return False
  644. except TimeoutError:
  645. logger.warning("FTP upload timed out after %ss for %s", timeout, remote_path)
  646. return False
  647. async def list_files_async(
  648. ip_address: str,
  649. access_code: str,
  650. path: str = "/",
  651. timeout: float = 30.0,
  652. socket_timeout: float | None = None,
  653. printer_model: str | None = None,
  654. ) -> list[dict]:
  655. """Async wrapper for listing files with timeout.
  656. Args:
  657. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  658. printer_model: Printer model for A1-specific workarounds
  659. """
  660. loop = asyncio.get_event_loop()
  661. def _list():
  662. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  663. if client.connect():
  664. try:
  665. return client.list_files(path)
  666. finally:
  667. client.disconnect()
  668. return []
  669. try:
  670. return await asyncio.wait_for(loop.run_in_executor(None, _list), timeout=timeout)
  671. except TimeoutError:
  672. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  673. return []
  674. async def delete_file_async(
  675. ip_address: str,
  676. access_code: str,
  677. remote_path: str,
  678. socket_timeout: float | None = None,
  679. printer_model: str | None = None,
  680. ) -> bool:
  681. """Async wrapper for deleting a file.
  682. Args:
  683. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  684. printer_model: Printer model for A1-specific workarounds
  685. """
  686. loop = asyncio.get_event_loop()
  687. def _delete():
  688. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  689. if client.connect():
  690. try:
  691. return client.delete_file(remote_path)
  692. finally:
  693. client.disconnect()
  694. return False
  695. return await loop.run_in_executor(None, _delete)
  696. async def download_file_bytes_async(
  697. ip_address: str,
  698. access_code: str,
  699. remote_path: str,
  700. socket_timeout: float | None = None,
  701. printer_model: str | None = None,
  702. ) -> bytes | None:
  703. """Async wrapper for downloading file as bytes.
  704. Args:
  705. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  706. printer_model: Printer model for A1-specific workarounds
  707. """
  708. loop = asyncio.get_event_loop()
  709. def _download():
  710. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  711. if client.connect():
  712. try:
  713. return client.download_file(remote_path)
  714. finally:
  715. client.disconnect()
  716. return None
  717. return await loop.run_in_executor(None, _download)
  718. async def get_storage_info_async(
  719. ip_address: str,
  720. access_code: str,
  721. socket_timeout: float | None = None,
  722. printer_model: str | None = None,
  723. ) -> dict | None:
  724. """Async wrapper for getting storage info.
  725. Args:
  726. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  727. printer_model: Printer model for A1-specific workarounds
  728. """
  729. loop = asyncio.get_event_loop()
  730. def _get_storage():
  731. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  732. if client.connect():
  733. try:
  734. return client.get_storage_info()
  735. finally:
  736. client.disconnect()
  737. return None
  738. return await loop.run_in_executor(None, _get_storage)
  739. async def get_ftp_retry_settings() -> tuple[bool, int, float, float]:
  740. """Get FTP retry settings from database.
  741. Returns:
  742. Tuple of (retry_enabled, retry_count, retry_delay, timeout)
  743. """
  744. from backend.app.api.routes.settings import get_setting
  745. from backend.app.core.database import async_session
  746. async with async_session() as db:
  747. enabled = (await get_setting(db, "ftp_retry_enabled") or "true") == "true"
  748. count = int(await get_setting(db, "ftp_retry_count") or "3")
  749. delay = float(await get_setting(db, "ftp_retry_delay") or "2")
  750. timeout = float(await get_setting(db, "ftp_timeout") or "30")
  751. return enabled, count, delay, timeout
  752. async def with_ftp_retry(
  753. operation: Callable[..., Awaitable[T]],
  754. *args,
  755. max_retries: int = 3,
  756. retry_delay: float = 2.0,
  757. operation_name: str = "FTP operation",
  758. non_retry_exceptions: tuple[type[BaseException], ...] = (),
  759. **kwargs,
  760. ) -> T | None:
  761. """Execute FTP operation with retry logic.
  762. Args:
  763. operation: Async function to execute
  764. *args: Positional arguments for the operation
  765. max_retries: Number of retry attempts (default: 3)
  766. retry_delay: Seconds to wait between retries (default: 2.0)
  767. operation_name: Name for logging purposes
  768. non_retry_exceptions: Exception types that should immediately abort retries
  769. **kwargs: Keyword arguments for the operation
  770. Returns:
  771. Result of the operation, or None if all attempts fail
  772. """
  773. last_error = None
  774. for attempt in range(max_retries + 1):
  775. try:
  776. result = await operation(*args, **kwargs)
  777. # Check for "falsy" success indicators
  778. if result not in (False, None, []):
  779. if attempt > 0:
  780. logger.info("%s succeeded on attempt %s/%s", operation_name, attempt + 1, max_retries + 1)
  781. return result
  782. # Operation returned failure indicator
  783. if attempt > 0:
  784. logger.info("%s attempt %s/%s returned failure", operation_name, attempt + 1, max_retries + 1)
  785. except Exception as e:
  786. if non_retry_exceptions and isinstance(e, non_retry_exceptions):
  787. raise
  788. last_error = e
  789. logger.warning("%s attempt %s/%s failed: %s", operation_name, attempt + 1, max_retries + 1, e)
  790. # Don't wait after the last attempt
  791. if attempt < max_retries:
  792. logger.info("%s will retry in %ss...", operation_name, retry_delay)
  793. await asyncio.sleep(retry_delay)
  794. logger.error("%s failed after %s attempts", operation_name, max_retries + 1)
  795. if last_error:
  796. logger.debug("Last error: %s", last_error)
  797. return None