bambu_ftp.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  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. # Wait for the server's 226 "Transfer complete" response to confirm
  367. # the file has been flushed to the SD card. Without this, the printer
  368. # may try to read an incomplete file when the print command is sent,
  369. # causing 0500-C010 "MicroSD Card read/write exception" errors.
  370. # See: https://bugs.python.org/issue25458 (ftplib response desync)
  371. try:
  372. old_timeout = self._ftp.sock.gettimeout()
  373. # Use a generous timeout — H2D printers can take 30+ seconds
  374. # to send the 226 after the data channel closes.
  375. self._ftp.sock.settimeout(max(self.timeout, 60))
  376. try:
  377. resp = self._ftp.voidresp()
  378. logger.info("FTP STOR confirmed for %s: %s", remote_path, resp.strip())
  379. finally:
  380. self._ftp.sock.settimeout(old_timeout)
  381. except Exception as e:
  382. # Timeout or error reading 226 — log but proceed, the data
  383. # was fully sent so the file is likely on the SD card.
  384. logger.warning(
  385. "FTP STOR confirmation not received for %s (proceeding): %s (%s)",
  386. remote_path,
  387. e,
  388. type(e).__name__,
  389. )
  390. if callback_exception is not None:
  391. cleanup_ok = False
  392. try:
  393. cleanup_ok = self.delete_file(remote_path)
  394. except Exception as cleanup_error:
  395. logger.warning("FTP cancel cleanup failed for %s: %s", remote_path, cleanup_error)
  396. if cleanup_ok:
  397. logger.info("FTP cancel cleanup succeeded for %s", remote_path)
  398. raise callback_exception
  399. raise RuntimeError(
  400. f"Upload cancelled but failed to remove partial file {remote_path} from printer"
  401. ) from callback_exception
  402. elapsed = time.monotonic() - t0
  403. speed_kbs = (file_size / 1024) / elapsed if elapsed > 0 else 0
  404. logger.info(
  405. "FTP upload complete: %s (%s bytes in %.1fs, %.0f KB/s)",
  406. remote_path,
  407. file_size,
  408. elapsed,
  409. speed_kbs,
  410. )
  411. return True
  412. except ftplib.error_perm as e:
  413. # Permanent FTP error (4xx/5xx response)
  414. error_code = str(e)[:3] if str(e) else "unknown"
  415. logger.error("FTP upload failed for %s: %s (error code: %s)", remote_path, e, error_code)
  416. if error_code == "553":
  417. logger.error(
  418. "FTP 553 error - Could not create file. Possible causes: "
  419. "1) No SD card inserted, 2) SD card full, 3) SD card not formatted correctly (needs FAT32/exFAT), "
  420. "4) Printer busy/not ready, 5) File path issue"
  421. )
  422. elif error_code == "550":
  423. logger.error("FTP 550 error - File/directory not found or permission denied")
  424. elif error_code == "552":
  425. logger.error("FTP 552 error - Storage quota exceeded (SD card full?)")
  426. return False
  427. except (OSError, ftplib.Error) as e:
  428. logger.error("FTP upload failed for %s: %s (type: %s)", remote_path, e, type(e).__name__)
  429. return False
  430. def upload_bytes(self, data: bytes, remote_path: str) -> bool:
  431. """Upload bytes to the printer."""
  432. if not self._ftp:
  433. return False
  434. try:
  435. # Use manual transfer instead of storbinary() for A1 compatibility
  436. conn = self._ftp.transfercmd(f"STOR {remote_path}")
  437. conn.setblocking(True)
  438. conn.settimeout(self.timeout)
  439. try:
  440. # Send data in chunks
  441. offset = 0
  442. while offset < len(data):
  443. chunk = data[offset : offset + self.CHUNK_SIZE]
  444. conn.sendall(chunk)
  445. offset += len(chunk)
  446. except OSError as e:
  447. logger.error("FTP connection lost during upload_bytes: %s", e)
  448. raise
  449. finally:
  450. try:
  451. conn.close()
  452. except OSError:
  453. pass
  454. # Wait for 226 confirmation (see upload_file for rationale)
  455. try:
  456. old_timeout = self._ftp.sock.gettimeout()
  457. self._ftp.sock.settimeout(max(self.timeout, 60))
  458. try:
  459. self._ftp.voidresp()
  460. finally:
  461. self._ftp.sock.settimeout(old_timeout)
  462. except Exception:
  463. pass # Best-effort — data was sent, proceed
  464. return True
  465. except (OSError, ftplib.Error):
  466. return False
  467. def delete_file(self, remote_path: str) -> bool:
  468. """Delete a file from the printer."""
  469. if not self._ftp:
  470. return False
  471. try:
  472. self._ftp.delete(remote_path)
  473. return True
  474. except (OSError, ftplib.Error) as e:
  475. logger.warning("Failed to delete %s: %s", remote_path, e)
  476. return False
  477. def get_file_size(self, remote_path: str) -> int | None:
  478. """Get the size of a file."""
  479. if not self._ftp:
  480. return None
  481. try:
  482. return self._ftp.size(remote_path)
  483. except (OSError, ftplib.Error):
  484. return None
  485. def get_storage_info(self) -> dict | None:
  486. """Get storage information from the printer."""
  487. if not self._ftp:
  488. return None
  489. result = {}
  490. # Try AVBL command (available space) - some FTP servers support this
  491. try:
  492. response = self._ftp.sendcmd("AVBL")
  493. logger.debug("AVBL response: %s", response)
  494. # Response format: "213 <bytes available>"
  495. if response.startswith("213"):
  496. parts = response.split()
  497. if len(parts) >= 2:
  498. result["free_bytes"] = int(parts[1])
  499. except (OSError, ftplib.Error) as e:
  500. logger.debug("AVBL command not supported: %s", e)
  501. # Try STAT command as fallback
  502. try:
  503. response = self._ftp.sendcmd("STAT")
  504. logger.debug("STAT response: %s", response)
  505. except (OSError, ftplib.Error):
  506. pass # Both AVBL and STAT unsupported; storage info will rely on directory scan
  507. # Calculate used space by listing root directories
  508. try:
  509. total_used = 0
  510. dirs_to_scan = ["/cache", "/timelapse", "/model", "/data", "/data/Metadata", "/"]
  511. for dir_path in dirs_to_scan:
  512. try:
  513. self._ftp.cwd(dir_path)
  514. items = []
  515. self._ftp.retrlines("LIST", items.append)
  516. for item in items:
  517. parts = item.split()
  518. if len(parts) >= 5 and not item.startswith("d"):
  519. try:
  520. total_used += int(parts[4])
  521. except ValueError:
  522. pass # Skip entries with non-numeric size fields
  523. except (OSError, ftplib.Error):
  524. pass # Directory may not exist on this printer model; skip it
  525. result["used_bytes"] = total_used
  526. except (OSError, ftplib.Error):
  527. pass # Storage scan failed; return whatever info was collected above
  528. return result if result else None
  529. async def download_file_async(
  530. ip_address: str,
  531. access_code: str,
  532. remote_path: str,
  533. local_path: Path,
  534. timeout: float = 60.0,
  535. socket_timeout: float | None = None,
  536. printer_model: str | None = None,
  537. ) -> bool:
  538. """Async wrapper for downloading a file with timeout.
  539. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  540. to prot_c if the download fails. The working mode is cached for future operations.
  541. Args:
  542. ip_address: Printer IP address
  543. access_code: Printer access code
  544. remote_path: Remote file path on printer
  545. local_path: Local path to save file
  546. timeout: Overall operation timeout (asyncio)
  547. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  548. printer_model: Printer model for A1-specific workarounds
  549. """
  550. loop = asyncio.get_event_loop()
  551. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  552. def _download(force_prot_c: bool = False) -> bool:
  553. mode_str = "prot_c" if force_prot_c else "prot_p"
  554. client = BambuFTPClient(
  555. ip_address, access_code, timeout=socket_timeout, printer_model=printer_model, force_prot_c=force_prot_c
  556. )
  557. if client.connect():
  558. try:
  559. result = client.download_to_file(remote_path, local_path)
  560. if result:
  561. # Cache the working mode
  562. BambuFTPClient.cache_mode(ip_address, mode_str)
  563. return result
  564. finally:
  565. client.disconnect()
  566. return False
  567. try:
  568. # Check if we have a cached mode for this printer
  569. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  570. if cached_mode:
  571. # Use cached mode
  572. force_prot_c = cached_mode == "prot_c"
  573. return await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(force_prot_c)), timeout=timeout)
  574. # No cached mode - try prot_p first
  575. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(False)), timeout=timeout)
  576. if result:
  577. return True
  578. # Download failed - for A1 models, try prot_c fallback
  579. if is_a1:
  580. logger.info("FTP download failed with prot_p for A1 model, trying prot_c fallback...")
  581. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _download(True)), timeout=timeout)
  582. return result
  583. return False
  584. except TimeoutError:
  585. logger.warning("FTP download timed out after %ss for %s", timeout, remote_path)
  586. return False
  587. async def download_file_try_paths_async(
  588. ip_address: str,
  589. access_code: str,
  590. remote_paths: list[str],
  591. local_path: Path,
  592. socket_timeout: float | None = None,
  593. printer_model: str | None = None,
  594. ) -> bool:
  595. """Try downloading a file from multiple paths using a single connection.
  596. Args:
  597. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  598. printer_model: Printer model for A1-specific workarounds
  599. """
  600. loop = asyncio.get_event_loop()
  601. def _download():
  602. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  603. if not client.connect():
  604. return False
  605. try:
  606. return any(client.download_to_file(remote_path, local_path) for remote_path in remote_paths)
  607. finally:
  608. client.disconnect()
  609. return await loop.run_in_executor(None, _download)
  610. async def upload_file_async(
  611. ip_address: str,
  612. access_code: str,
  613. local_path: Path,
  614. remote_path: str,
  615. timeout: float = 600.0,
  616. progress_callback: Callable[[int, int], None] | None = None,
  617. socket_timeout: float | None = None,
  618. printer_model: str | None = None,
  619. ) -> bool:
  620. """Async wrapper for uploading a file with timeout and progress callback.
  621. For A1/A1 Mini printers, automatically tries prot_p first, then falls back
  622. to prot_c if the upload fails. The working mode is cached for future uploads.
  623. Args:
  624. ip_address: Printer IP address
  625. access_code: Printer access code
  626. local_path: Local file path to upload
  627. remote_path: Remote path on printer
  628. timeout: Overall operation timeout (asyncio)
  629. progress_callback: Optional callback for progress updates
  630. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  631. printer_model: Printer model for A1-specific workarounds
  632. """
  633. loop = asyncio.get_event_loop()
  634. is_a1 = printer_model in BambuFTPClient.A1_MODELS if printer_model else False
  635. def _upload(force_prot_c: bool = False) -> bool:
  636. mode_str = "prot_c" if force_prot_c else "prot_p"
  637. logger.info(
  638. f"FTP connecting to {ip_address} for upload (model={printer_model}, "
  639. f"mode={mode_str}, socket_timeout={socket_timeout}s)..."
  640. )
  641. client = BambuFTPClient(
  642. ip_address, access_code, timeout=socket_timeout, printer_model=printer_model, force_prot_c=force_prot_c
  643. )
  644. if client.connect():
  645. logger.info("FTP connected to %s", ip_address)
  646. try:
  647. result = client.upload_file(local_path, remote_path, progress_callback)
  648. if result:
  649. # Cache the working mode
  650. BambuFTPClient.cache_mode(ip_address, mode_str)
  651. return result
  652. finally:
  653. client.disconnect()
  654. logger.warning("FTP connection failed to %s", ip_address)
  655. return False
  656. try:
  657. # Check if we have a cached mode for this printer
  658. cached_mode = BambuFTPClient._mode_cache.get(ip_address)
  659. if cached_mode:
  660. # Use cached mode
  661. force_prot_c = cached_mode == "prot_c"
  662. return await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(force_prot_c)), timeout=timeout)
  663. # No cached mode - try prot_p first
  664. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(False)), timeout=timeout)
  665. if result:
  666. return True
  667. # Upload failed - for A1 models, try prot_c fallback
  668. if is_a1:
  669. logger.info("FTP upload failed with prot_p for A1 model, trying prot_c fallback...")
  670. result = await asyncio.wait_for(loop.run_in_executor(None, lambda: _upload(True)), timeout=timeout)
  671. return result
  672. return False
  673. except TimeoutError:
  674. logger.warning("FTP upload timed out after %ss for %s", timeout, remote_path)
  675. return False
  676. async def list_files_async(
  677. ip_address: str,
  678. access_code: str,
  679. path: str = "/",
  680. timeout: float = 30.0,
  681. socket_timeout: float | None = None,
  682. printer_model: str | None = None,
  683. ) -> list[dict]:
  684. """Async wrapper for listing files with timeout.
  685. Args:
  686. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  687. printer_model: Printer model for A1-specific workarounds
  688. """
  689. loop = asyncio.get_event_loop()
  690. def _list():
  691. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  692. if client.connect():
  693. try:
  694. return client.list_files(path)
  695. finally:
  696. client.disconnect()
  697. return []
  698. try:
  699. return await asyncio.wait_for(loop.run_in_executor(None, _list), timeout=timeout)
  700. except TimeoutError:
  701. logger.warning("FTP list_files timed out after %ss for %s", timeout, path)
  702. return []
  703. async def delete_file_async(
  704. ip_address: str,
  705. access_code: str,
  706. remote_path: str,
  707. socket_timeout: float | None = None,
  708. printer_model: str | None = None,
  709. ) -> bool:
  710. """Async wrapper for deleting a file.
  711. Args:
  712. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  713. printer_model: Printer model for A1-specific workarounds
  714. """
  715. loop = asyncio.get_event_loop()
  716. def _delete():
  717. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  718. if client.connect():
  719. try:
  720. return client.delete_file(remote_path)
  721. finally:
  722. client.disconnect()
  723. return False
  724. return await loop.run_in_executor(None, _delete)
  725. async def download_file_bytes_async(
  726. ip_address: str,
  727. access_code: str,
  728. remote_path: str,
  729. socket_timeout: float | None = None,
  730. printer_model: str | None = None,
  731. ) -> bytes | None:
  732. """Async wrapper for downloading file as bytes.
  733. Args:
  734. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  735. printer_model: Printer model for A1-specific workarounds
  736. """
  737. loop = asyncio.get_event_loop()
  738. def _download():
  739. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  740. if client.connect():
  741. try:
  742. return client.download_file(remote_path)
  743. finally:
  744. client.disconnect()
  745. return None
  746. return await loop.run_in_executor(None, _download)
  747. async def get_storage_info_async(
  748. ip_address: str,
  749. access_code: str,
  750. socket_timeout: float | None = None,
  751. printer_model: str | None = None,
  752. ) -> dict | None:
  753. """Async wrapper for getting storage info.
  754. Args:
  755. socket_timeout: FTP socket timeout for slow connections (e.g., A1 printers)
  756. printer_model: Printer model for A1-specific workarounds
  757. """
  758. loop = asyncio.get_event_loop()
  759. def _get_storage():
  760. client = BambuFTPClient(ip_address, access_code, timeout=socket_timeout, printer_model=printer_model)
  761. if client.connect():
  762. try:
  763. return client.get_storage_info()
  764. finally:
  765. client.disconnect()
  766. return None
  767. return await loop.run_in_executor(None, _get_storage)
  768. async def get_ftp_retry_settings() -> tuple[bool, int, float, float]:
  769. """Get FTP retry settings from database.
  770. Returns:
  771. Tuple of (retry_enabled, retry_count, retry_delay, timeout)
  772. """
  773. from backend.app.api.routes.settings import get_setting
  774. from backend.app.core.database import async_session
  775. async with async_session() as db:
  776. enabled = (await get_setting(db, "ftp_retry_enabled") or "true") == "true"
  777. count = int(await get_setting(db, "ftp_retry_count") or "3")
  778. delay = float(await get_setting(db, "ftp_retry_delay") or "2")
  779. timeout = float(await get_setting(db, "ftp_timeout") or "30")
  780. return enabled, count, delay, timeout
  781. async def with_ftp_retry(
  782. operation: Callable[..., Awaitable[T]],
  783. *args,
  784. max_retries: int = 3,
  785. retry_delay: float = 2.0,
  786. operation_name: str = "FTP operation",
  787. non_retry_exceptions: tuple[type[BaseException], ...] = (),
  788. **kwargs,
  789. ) -> T | None:
  790. """Execute FTP operation with retry logic.
  791. Args:
  792. operation: Async function to execute
  793. *args: Positional arguments for the operation
  794. max_retries: Number of retry attempts (default: 3)
  795. retry_delay: Seconds to wait between retries (default: 2.0)
  796. operation_name: Name for logging purposes
  797. non_retry_exceptions: Exception types that should immediately abort retries
  798. **kwargs: Keyword arguments for the operation
  799. Returns:
  800. Result of the operation, or None if all attempts fail
  801. """
  802. last_error = None
  803. for attempt in range(max_retries + 1):
  804. try:
  805. result = await operation(*args, **kwargs)
  806. # Check for "falsy" success indicators
  807. if result not in (False, None, []):
  808. if attempt > 0:
  809. logger.info("%s succeeded on attempt %s/%s", operation_name, attempt + 1, max_retries + 1)
  810. return result
  811. # Operation returned failure indicator
  812. if attempt > 0:
  813. logger.info("%s attempt %s/%s returned failure", operation_name, attempt + 1, max_retries + 1)
  814. except Exception as e:
  815. if non_retry_exceptions and isinstance(e, non_retry_exceptions):
  816. raise
  817. last_error = e
  818. logger.warning("%s attempt %s/%s failed: %s", operation_name, attempt + 1, max_retries + 1, e)
  819. # Don't wait after the last attempt
  820. if attempt < max_retries:
  821. logger.info("%s will retry in %ss...", operation_name, retry_delay)
  822. await asyncio.sleep(retry_delay)
  823. logger.error("%s failed after %s attempts", operation_name, max_retries + 1)
  824. if last_error:
  825. logger.debug("Last error: %s", last_error)
  826. return None