bambu_ftp.py 33 KB

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