bambu_ftp.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. import asyncio
  2. import ftplib # nosec B402
  3. import logging
  4. import os
  5. import socket
  6. import ssl
  7. from collections.abc import Awaitable, Callable
  8. from ftplib import FTP, FTP_TLS # nosec B402
  9. from io import BytesIO
  10. from pathlib import Path
  11. from typing import TypeVar
  12. logger = logging.getLogger(__name__)
  13. T = TypeVar("T")
  14. class ImplicitFTP_TLS(FTP_TLS):
  15. """FTP_TLS subclass for implicit FTPS (port 990) with model-specific SSL handling.
  16. X1C/P1S printers (vsFTPd) require SSL with session reuse on the data channel.
  17. A1/A1 Mini printers have issues with SSL on the data channel entirely and
  18. timeout waiting for transfer completion. Set skip_session_reuse=True for A1
  19. printers to skip SSL on the data channel (control channel remains encrypted).
  20. """
  21. def __init__(self, *args, skip_session_reuse: bool = False, **kwargs):
  22. super().__init__(*args, **kwargs)
  23. self._sock = None
  24. self.skip_session_reuse = skip_session_reuse
  25. self.ssl_context = ssl.create_default_context()
  26. self.ssl_context.check_hostname = False
  27. self.ssl_context.verify_mode = ssl.CERT_NONE
  28. def connect(self, host="", port=990, timeout=-999, source_address=None):
  29. """Connect to host, wrapping socket in TLS immediately (implicit FTPS)."""
  30. if host:
  31. self.host = host
  32. if port > 0:
  33. self.port = port
  34. if timeout != -999:
  35. self.timeout = timeout
  36. if source_address:
  37. self.source_address = source_address
  38. # Create and wrap socket immediately (implicit TLS)
  39. self.sock = socket.create_connection((self.host, self.port), self.timeout, source_address=self.source_address)
  40. self.sock = self.ssl_context.wrap_socket(self.sock, server_hostname=self.host)
  41. self.af = self.sock.family
  42. self.file = self.sock.makefile("r", encoding=self.encoding)
  43. self.welcome = self.getresp()
  44. return self.welcome
  45. def ntransfercmd(self, cmd, rest=None):
  46. """Override to wrap data connection in SSL for X1C/P1S only.
  47. X1C/P1S printers (vsFTPd) require SSL session reuse on the data channel.
  48. A1/A1 Mini printers have issues with SSL on the data channel entirely -
  49. they timeout waiting for the transfer completion response. For A1, we
  50. skip SSL wrapping on the data channel (control channel remains encrypted).
  51. """
  52. conn, size = FTP.ntransfercmd(self, cmd, rest)
  53. if self._prot_p and not self.skip_session_reuse:
  54. # X1C/P1S: Wrap data channel with SSL session reuse (required by vsFTPd)
  55. conn = self.ssl_context.wrap_socket(
  56. conn,
  57. server_hostname=self.host,
  58. session=self.sock.session,
  59. )
  60. # A1/A1 Mini (skip_session_reuse=True): Don't wrap data channel in SSL
  61. # The control channel remains encrypted via implicit FTPS
  62. return conn, size
  63. class BambuFTPClient:
  64. """FTP client for retrieving files from Bambu Lab printers."""
  65. FTP_PORT = 990
  66. # Default timeout in seconds (increased for A1 printers)
  67. DEFAULT_TIMEOUT = 30
  68. # Models that may need SSL mode fallback (try prot_p first, fall back to prot_c)
  69. # These models have varying FTP SSL behavior depending on firmware version
  70. A1_MODELS = ("A1", "A1 Mini")
  71. # Chunk size for manual upload transfer (1MB)
  72. # Larger chunks reduce overhead and work better with A1 printers
  73. CHUNK_SIZE = 1024 * 1024
  74. # Per-chunk data socket timeout during upload.
  75. UPLOAD_CHUNK_TIMEOUT = 120
  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. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  328. # Set explicit socket options for reliable transfer
  329. conn.setblocking(True)
  330. conn.settimeout(self.UPLOAD_CHUNK_TIMEOUT)
  331. try:
  332. while True:
  333. chunk = f.read(self.CHUNK_SIZE)
  334. if not chunk:
  335. logger.debug("FTP upload: final chunk reached")
  336. break
  337. conn.sendall(chunk)
  338. uploaded += len(chunk)
  339. logger.debug("FTP upload progress: %s/%s bytes", uploaded, file_size)
  340. if progress_callback:
  341. try:
  342. progress_callback(uploaded, file_size)
  343. except Exception as e:
  344. callback_exception = e
  345. logger.info(
  346. "FTP upload callback requested stop for %s at %s/%s bytes: %s",
  347. remote_path,
  348. uploaded,
  349. file_size,
  350. e,
  351. )
  352. break
  353. except OSError as e:
  354. logger.error("FTP connection lost during upload: %s", e)
  355. raise
  356. finally:
  357. try:
  358. conn.close()
  359. except OSError:
  360. pass
  361. # Skip voidresp() for A1 models — they hang after transfercmd uploads
  362. if self.printer_model not in self.A1_MODELS:
  363. try:
  364. self._ftp.voidresp()
  365. except (OSError, ftplib.Error) as e:
  366. # Data transfer already completed — voidresp() failure is just a noisy
  367. # 226 acknowledgment issue, not an actual upload failure. Log and continue.
  368. logger.warning("FTP upload response for %s was not clean (data already sent): %s", remote_path, e)
  369. if callback_exception is not None:
  370. cleanup_ok = False
  371. try:
  372. cleanup_ok = self.delete_file(remote_path)
  373. except Exception as cleanup_error:
  374. logger.warning("FTP cancel cleanup failed for %s: %s", remote_path, cleanup_error)
  375. if cleanup_ok:
  376. logger.info("FTP cancel cleanup succeeded for %s", remote_path)
  377. raise callback_exception
  378. raise RuntimeError(
  379. f"Upload cancelled but failed to remove partial file {remote_path} from printer"
  380. ) from callback_exception
  381. logger.info("FTP upload complete: %s", remote_path)
  382. return True
  383. except ftplib.error_perm as e:
  384. # Permanent FTP error (4xx/5xx response)
  385. error_code = str(e)[:3] if str(e) else "unknown"
  386. logger.error("FTP upload failed for %s: %s (error code: %s)", remote_path, e, error_code)
  387. if error_code == "553":
  388. logger.error(
  389. "FTP 553 error - Could not create file. Possible causes: "
  390. "1) No SD card inserted, 2) SD card full, 3) SD card not formatted correctly (needs FAT32/exFAT), "
  391. "4) Printer busy/not ready, 5) File path issue"
  392. )
  393. elif error_code == "550":
  394. logger.error("FTP 550 error - File/directory not found or permission denied")
  395. elif error_code == "552":
  396. logger.error("FTP 552 error - Storage quota exceeded (SD card full?)")
  397. return False
  398. except (OSError, ftplib.Error) as e:
  399. logger.error("FTP upload failed for %s: %s (type: %s)", remote_path, e, type(e).__name__)
  400. return False
  401. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  402. """Upload bytes to the printer."""
  403. if not self._ftp:
  404. return False
  405. try:
  406. # Use manual transfer instead of storbinary() for A1 compatibility
  407. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  408. conn.setblocking(True)
  409. conn.settimeout(self.UPLOAD_CHUNK_TIMEOUT)
  410. try:
  411. # Send data in chunks
  412. offset = 0
  413. while offset < len(data):
  414. chunk = data[offset : offset + self.CHUNK_SIZE]
  415. conn.sendall(chunk)
  416. offset += len(chunk)
  417. except OSError as e:
  418. logger.error("FTP connection lost during upload_bytes: %s", e)
  419. raise
  420. finally:
  421. try:
  422. conn.close()
  423. except OSError:
  424. pass
  425. return True
  426. except (OSError, ftplib.Error):
  427. return False
  428. def delete_file(self, remote_path: str) -> bool:
  429. """Delete a file from the printer."""
  430. if not self._ftp:
  431. return False
  432. try:
  433. self._ftp.delete(remote_path)
  434. return True
  435. except (OSError, ftplib.Error) as e:
  436. logger.warning("Failed to delete %s: %s", remote_path, e)
  437. return False
  438. def get_file_size(self, remote_path: str) -> int | None:
  439. """Get the size of a file."""
  440. if not self._ftp:
  441. return None
  442. try:
  443. return self._ftp.size(remote_path)
  444. except (OSError, ftplib.Error):
  445. return None
  446. def get_storage_info(self) -> dict | None:
  447. """Get storage information from the printer."""
  448. if not self._ftp:
  449. return None
  450. result = {}
  451. # Try AVBL command (available space) - some FTP servers support this
  452. try:
  453. response = self._ftp.sendcmd("AVBL")
  454. logger.debug("AVBL response: %s", response)
  455. # Response format: "213 <bytes available>"
  456. if response.startswith("213"):
  457. parts = response.split()
  458. if len(parts) >= 2:
  459. result["free_bytes"] = int(parts[1])
  460. except (OSError, ftplib.Error) as e:
  461. logger.debug("AVBL command not supported: %s", e)
  462. # Try STAT command as fallback
  463. try:
  464. response = self._ftp.sendcmd("STAT")
  465. logger.debug("STAT response: %s", response)
  466. except (OSError, ftplib.Error):
  467. pass # Both AVBL and STAT unsupported; storage info will rely on directory scan
  468. # Calculate used space by listing root directories
  469. try:
  470. total_used = 0
  471. dirs_to_scan = ["/cache", "/timelapse", "/model", "/data", "/data/Metadata", "/"]
  472. for dir_path in dirs_to_scan:
  473. try:
  474. self._ftp.cwd(dir_path)
  475. items = []
  476. self._ftp.retrlines("LIST", items.append)
  477. for item in items:
  478. parts = item.split()
  479. if len(parts) >= 5 and not item.startswith("d"):
  480. try:
  481. total_used += int(parts[4])
  482. except ValueError:
  483. pass # Skip entries with non-numeric size fields
  484. except (OSError, ftplib.Error):
  485. pass # Directory may not exist on this printer model; skip it
  486. result["used_bytes"] = total_used
  487. except (OSError, ftplib.Error):
  488. pass # Storage scan failed; return whatever info was collected above
  489. return result if result else None
  490. async def download_file_async(
  491. ip_address: str,
  492. access_code: str,
  493. remote_path: str,
  494. local_path: Path,
  495. timeout: float = 60.0,
  496. socket_timeout: float | None = None,
  497. printer_model: str | None = None,
  498. ) -> bool:
  499. """Async wrapper for downloading a file with timeout.
  500. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  501. to prot_c if the download fails. The working mode is cached for future operations.
  502. Args:
  503. ip_address: Printer IP address
  504. access_code: Printer access code
  505. remote_path: Remote file path on printer
  506. local_path: Local path to save file
  507. timeout: Overall operation timeout (asyncio)
  508. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  509. printer_model: Printer model for A1-specific workarounds
  510. """
  511. loop = asyncio.get_event_loop()
  512. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  513. def _download(force_prot_c: bool = False) -> bool:
  514. mode_str = "prot_c" if force_prot_c else "prot_p"
  515. client = BambuFTPClient(
  516. ip_address, access_code, timeout=socket_timeout, printer_model=printer_model, force_prot_c=force_prot_c
  517. )
  518. if client.connect():
  519. try:
  520. result = client.download_to_file(remote_path, local_path)
  521. if result:
  522. # Cache the working mode
  523. BambuFTPClient.cache_mode(ip_address, mode_str)
  524. return result
  525. finally:
  526. client.disconnect()
  527. return False
  528. try:
  529. # Check if we have a cached mode for this printer
  530. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  531. if cached_mode:
  532. # Use cached mode
  533. force_prot_c = cached_mode == "prot_c"
  534. return await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(force_prot_c)), timeout=timeout)
  535. # No cached mode - try prot_p first
  536. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(False)), timeout=timeout)
  537. if result:
  538. return True
  539. # Download failed - for A1 models, try prot_c fallback
  540. if is_a1:
  541. logger.info("FTP download failed with prot_p for A1 model, trying prot_c fallback...")
  542. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(True)), timeout=timeout)
  543. return result
  544. return False
  545. except TimeoutError:
  546. logger.warning("FTP download timed out after %ss for %s", timeout, remote_path)
  547. return False
  548. async def download_file_try_paths_async(
  549. ip_address: str,
  550. access_code: str,
  551. remote_paths: list[str],
  552. local_path: Path,
  553. socket_timeout: float | None = None,
  554. printer_model: str | None = None,
  555. ) -> bool:
  556. """Try downloading a file from multiple paths using a single connection.
  557. Args:
  558. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  559. printer_model: Printer model for A1-specific workarounds
  560. """
  561. loop = asyncio.get_event_loop()
  562. def _download():
  563. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  564. if not client.connect():
  565. return False
  566. try:
  567. return any(client.download_to_file(remote_path, local_path) for remote_path in remote_paths)
  568. finally:
  569. client.disconnect()
  570. return await loop.run_in_executor(None, _download)
  571. async def upload_file_async(
  572. ip_address: str,
  573. access_code: str,
  574. local_path: Path,
  575. remote_path: str,
  576. timeout: float = 600.0,
  577. progress_callback: Callable[[int, int], None] | None = None,
  578. socket_timeout: float | None = None,
  579. printer_model: str | None = None,
  580. ) -> bool:
  581. """Async wrapper for uploading a file with timeout and progress callback.
  582. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  583. to prot_c if the upload fails. The working mode is cached for future uploads.
  584. Args:
  585. ip_address: Printer IP address
  586. access_code: Printer access code
  587. local_path: Local file path to upload
  588. remote_path: Remote path on printer
  589. timeout: Overall operation timeout (asyncio)
  590. progress_callback: Optional callback for progress updates
  591. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  592. printer_model: Printer model for A1-specific workarounds
  593. """
  594. loop = asyncio.get_event_loop()
  595. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  596. def _upload(force_prot_c: bool = False) -> bool:
  597. mode_str = "prot_c" if force_prot_c else "prot_p"
  598. logger.info(
  599. f"FTP connecting to {ip_address} for upload (model={printer_model}, "
  600. f"mode={mode_str}, socket_timeout={socket_timeout}s)..."
  601. )
  602. client = BambuFTPClient(
  603. ip_address, access_code, timeout=socket_timeout, printer_model=printer_model, force_prot_c=force_prot_c
  604. )
  605. if client.connect():
  606. logger.info("FTP connected to %s", ip_address)
  607. try:
  608. result = client.upload_file(local_path, remote_path, progress_callback)
  609. if result:
  610. # Cache the working mode
  611. BambuFTPClient.cache_mode(ip_address, mode_str)
  612. return result
  613. finally:
  614. client.disconnect()
  615. logger.warning("FTP connection failed to %s", ip_address)
  616. return False
  617. try:
  618. # Check if we have a cached mode for this printer
  619. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  620. if cached_mode:
  621. # Use cached mode
  622. force_prot_c = cached_mode == "prot_c"
  623. return await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(force_prot_c)), timeout=timeout)
  624. # No cached mode - try prot_p first
  625. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(False)), timeout=timeout)
  626. if result:
  627. return True
  628. # Upload failed - for A1 models, try prot_c fallback
  629. if is_a1:
  630. logger.info("FTP upload failed with prot_p for A1 model, trying prot_c fallback...")
  631. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(True)), timeout=timeout)
  632. return result
  633. return False
  634. except TimeoutError:
  635. logger.warning("FTP upload timed out after %ss for %s", timeout, remote_path)
  636. return False
  637. async def list_files_async(
  638. ip_address: str,
  639. access_code: str,
  640. path: str = "/",
  641. timeout: float = 30.0,
  642. socket_timeout: float | None = None,
  643. printer_model: str | None = None,
  644. ) -> list[dict]:
  645. """Async wrapper for listing files with timeout.
  646. Args:
  647. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  648. printer_model: Printer model for A1-specific workarounds
  649. """
  650. loop = asyncio.get_event_loop()
  651. def _list():
  652. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  653. if client.connect():
  654. try:
  655. return client.list_files(path)
  656. finally:
  657. client.disconnect()
  658. return []
  659. try:
  660. return await asyncio.wait_for(loop.run_in_executor(None, _list), timeout=timeout)
  661. except TimeoutError:
  662. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  663. return []
  664. async def delete_file_async(
  665. ip_address: str,
  666. access_code: str,
  667. remote_path: str,
  668. socket_timeout: float | None = None,
  669. printer_model: str | None = None,
  670. ) -> bool:
  671. """Async wrapper for deleting a file.
  672. Args:
  673. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  674. printer_model: Printer model for A1-specific workarounds
  675. """
  676. loop = asyncio.get_event_loop()
  677. def _delete():
  678. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  679. if client.connect():
  680. try:
  681. return client.delete_file(remote_path)
  682. finally:
  683. client.disconnect()
  684. return False
  685. return await loop.run_in_executor(None, _delete)
  686. async def download_file_bytes_async(
  687. ip_address: str,
  688. access_code: str,
  689. remote_path: str,
  690. socket_timeout: float | None = None,
  691. printer_model: str | None = None,
  692. ) -> bytes | None:
  693. """Async wrapper for downloading file as bytes.
  694. Args:
  695. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  696. printer_model: Printer model for A1-specific workarounds
  697. """
  698. loop = asyncio.get_event_loop()
  699. def _download():
  700. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  701. if client.connect():
  702. try:
  703. return client.download_file(remote_path)
  704. finally:
  705. client.disconnect()
  706. return None
  707. return await loop.run_in_executor(None, _download)
  708. async def get_storage_info_async(
  709. ip_address: str,
  710. access_code: str,
  711. socket_timeout: float | None = None,
  712. printer_model: str | None = None,
  713. ) -> dict | None:
  714. """Async wrapper for getting storage info.
  715. Args:
  716. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  717. printer_model: Printer model for A1-specific workarounds
  718. """
  719. loop = asyncio.get_event_loop()
  720. def _get_storage():
  721. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  722. if client.connect():
  723. try:
  724. return client.get_storage_info()
  725. finally:
  726. client.disconnect()
  727. return None
  728. return await loop.run_in_executor(None, _get_storage)
  729. async def get_ftp_retry_settings() -> tuple[bool, int, float, float]:
  730. """Get FTP retry settings from database.
  731. Returns:
  732. Tuple of (retry_enabled, retry_count, retry_delay, timeout)
  733. """
  734. from backend.app.api.routes.settings import get_setting
  735. from backend.app.core.database import async_session
  736. async with async_session() as db:
  737. enabled = (await get_setting(db, "ftp_retry_enabled") or "true") == "true"
  738. count = int(await get_setting(db, "ftp_retry_count") or "3")
  739. delay = float(await get_setting(db, "ftp_retry_delay") or "2")
  740. timeout = float(await get_setting(db, "ftp_timeout") or "30")
  741. return enabled, count, delay, timeout
  742. async def with_ftp_retry(
  743. operation: Callable[..., Awaitable[T]],
  744. *args,
  745. max_retries: int = 3,
  746. retry_delay: float = 2.0,
  747. operation_name: str = "FTP operation",
  748. non_retry_exceptions: tuple[type[BaseException], ...] = (),
  749. **kwargs,
  750. ) -> T | None:
  751. """Execute FTP operation with retry logic.
  752. Args:
  753. operation: Async function to execute
  754. *args: Positional arguments for the operation
  755. max_retries: Number of retry attempts (default: 3)
  756. retry_delay: Seconds to wait between retries (default: 2.0)
  757. operation_name: Name for logging purposes
  758. non_retry_exceptions: Exception types that should immediately abort retries
  759. **kwargs: Keyword arguments for the operation
  760. Returns:
  761. Result of the operation, or None if all attempts fail
  762. """
  763. last_error = None
  764. for attempt in range(max_retries + 1):
  765. try:
  766. result = await operation(*args, **kwargs)
  767. # Check for "falsy" success indicators
  768. if result not in (False, None, []):
  769. if attempt > 0:
  770. logger.info("%s succeeded on attempt %s/%s", operation_name, attempt + 1, max_retries + 1)
  771. return result
  772. # Operation returned failure indicator
  773. if attempt > 0:
  774. logger.info("%s attempt %s/%s returned failure", operation_name, attempt + 1, max_retries + 1)
  775. except Exception as e:
  776. if non_retry_exceptions and isinstance(e, non_retry_exceptions):
  777. raise
  778. last_error = e
  779. logger.warning("%s attempt %s/%s failed: %s", operation_name, attempt + 1, max_retries + 1, e)
  780. # Don't wait after the last attempt
  781. if attempt < max_retries:
  782. logger.info("%s will retry in %ss...", operation_name, retry_delay)
  783. await asyncio.sleep(retry_delay)
  784. logger.error("%s failed after %s attempts", operation_name, max_retries + 1)
  785. if last_error:
  786. logger.debug("Last error: %s", last_error)
  787. return None