firmware_update.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. """
  2. Firmware Update Service
  3. Orchestrates firmware updates for Bambu Lab printers:
  4. 1. Check prerequisites (SD card, space, update available)
  5. 2. Download firmware from Bambu Lab
  6. 3. Upload to printer's SD card via FTP
  7. 4. Notify user to trigger update from printer screen
  8. """
  9. import logging
  10. from dataclasses import dataclass
  11. from sqlalchemy import select
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from backend.app.core.compat import StrEnum
  14. from backend.app.core.tasks import spawn_background_task
  15. from backend.app.models.printer import Printer
  16. from backend.app.services.bambu_ftp import (
  17. get_ftp_retry_settings,
  18. get_storage_info_async,
  19. upload_file_async,
  20. with_ftp_retry,
  21. )
  22. from backend.app.services.firmware_check import get_firmware_service
  23. from backend.app.services.printer_manager import printer_manager
  24. logger = logging.getLogger(__name__)
  25. class FirmwareUploadStatus(StrEnum):
  26. """Status of a firmware upload operation."""
  27. IDLE = "idle"
  28. PREPARING = "preparing"
  29. DOWNLOADING = "downloading"
  30. UPLOADING = "uploading"
  31. COMPLETE = "complete"
  32. ERROR = "error"
  33. @dataclass
  34. class FirmwareUploadState:
  35. """State of a firmware upload operation for a printer."""
  36. status: FirmwareUploadStatus = FirmwareUploadStatus.IDLE
  37. progress: int = 0 # 0-100
  38. message: str = ""
  39. error: str | None = None
  40. firmware_filename: str | None = None
  41. firmware_version: str | None = None
  42. # Track upload state per printer
  43. _upload_states: dict[int, FirmwareUploadState] = {}
  44. def get_upload_state(printer_id: int) -> FirmwareUploadState:
  45. """Get the current upload state for a printer."""
  46. if printer_id not in _upload_states:
  47. _upload_states[printer_id] = FirmwareUploadState()
  48. return _upload_states[printer_id]
  49. def reset_upload_state(printer_id: int):
  50. """Reset the upload state for a printer."""
  51. _upload_states[printer_id] = FirmwareUploadState()
  52. class FirmwareUpdateService:
  53. """Service for managing firmware updates."""
  54. # Minimum free space required (100MB buffer)
  55. MIN_FREE_SPACE_BYTES = 100 * 1024 * 1024
  56. async def prepare_update(
  57. self,
  58. printer_id: int,
  59. db: AsyncSession,
  60. target_version: str | None = None,
  61. ) -> dict:
  62. """
  63. Check prerequisites for firmware update.
  64. Returns:
  65. Dict with:
  66. - can_proceed: bool
  67. - sd_card_present: bool
  68. - sd_card_free_space: int (bytes, -1 if unknown)
  69. - firmware_size: int (bytes, estimated)
  70. - space_sufficient: bool
  71. - update_available: bool
  72. - current_version: str | None
  73. - latest_version: str | None
  74. - firmware_filename: str | None
  75. - errors: list[str]
  76. """
  77. result = {
  78. "can_proceed": False,
  79. "sd_card_present": False,
  80. "sd_card_free_space": -1,
  81. "firmware_size": 0,
  82. "space_sufficient": False,
  83. "update_available": False,
  84. "current_version": None,
  85. "latest_version": None,
  86. "target_version": target_version,
  87. "firmware_filename": None,
  88. "errors": [],
  89. }
  90. # Get printer from database
  91. stmt = select(Printer).where(Printer.id == printer_id)
  92. db_result = await db.execute(stmt)
  93. printer = db_result.scalar_one_or_none()
  94. if not printer:
  95. result["errors"].append("Printer not found")
  96. return result
  97. # Check printer is connected
  98. mqtt_client = printer_manager.get_client(printer_id)
  99. if not mqtt_client or not mqtt_client.state:
  100. result["errors"].append("Printer not connected")
  101. return result
  102. state = mqtt_client.state
  103. # Get current firmware version
  104. result["current_version"] = state.firmware_version
  105. # Check SD card
  106. result["sd_card_present"] = state.sdcard
  107. if not state.sdcard:
  108. result["errors"].append("No SD card inserted in printer")
  109. # Get storage info via FTP
  110. if state.sdcard:
  111. try:
  112. storage_info = await get_storage_info_async(
  113. printer.ip_address,
  114. printer.access_code,
  115. printer_model=printer.model,
  116. )
  117. if storage_info and "free_bytes" in storage_info:
  118. result["sd_card_free_space"] = storage_info["free_bytes"]
  119. except Exception as e:
  120. logger.warning("Could not get storage info: %s", e)
  121. # Check for firmware update
  122. firmware_service = get_firmware_service()
  123. model = printer.model or "Unknown"
  124. if state.firmware_version:
  125. update_info = await firmware_service.check_for_update(model, state.firmware_version)
  126. result["update_available"] = update_info["update_available"]
  127. result["latest_version"] = update_info["latest_version"]
  128. else:
  129. # If we don't know current version, just get latest
  130. latest = await firmware_service.get_latest_version(model)
  131. if latest:
  132. result["latest_version"] = latest.version
  133. result["update_available"] = True # Assume update needed
  134. # Get firmware file info (for target_version if specified, else latest)
  135. file_info = await firmware_service.get_firmware_file_info(model, version=target_version)
  136. if file_info:
  137. result["firmware_filename"] = file_info["filename"]
  138. # Estimate size (typical firmware is 50-150MB)
  139. # We'll get actual size during download
  140. result["firmware_size"] = 100 * 1024 * 1024 # 100MB estimate
  141. elif target_version:
  142. # Requested specific version has no download URL. Distinguish
  143. # "Bambu doesn't list this file" from "we couldn't reach Bambu's
  144. # download page" (Cloudflare 403 reported in #1350) so users in
  145. # affected regions get an actionable error instead of believing
  146. # the firmware doesn't exist.
  147. if firmware_service.download_page_unreachable:
  148. result["errors"].append(
  149. f"Could not reach Bambu Lab's firmware download page to fetch the file URL for "
  150. f"{target_version}. Version is listed on the Bambu wiki but the download endpoint "
  151. f"is unreachable from this network. Try again later, or download the firmware "
  152. f"manually from bambulab.com and copy it to the printer's SD card."
  153. )
  154. else:
  155. result["errors"].append(f"Firmware file for {target_version} is not available from Bambu Lab")
  156. # If a target version is requested, allow proceeding even if it equals or
  157. # is older than the current version (explicit downgrade/reinstall).
  158. if target_version:
  159. result["update_available"] = bool(file_info)
  160. elif not result["update_available"]:
  161. result["errors"].append("Firmware is already up to date")
  162. # Check space
  163. if result["sd_card_free_space"] > 0:
  164. # Need firmware size + buffer
  165. required = result["firmware_size"] + self.MIN_FREE_SPACE_BYTES
  166. result["space_sufficient"] = result["sd_card_free_space"] >= required
  167. if not result["space_sufficient"]:
  168. result["errors"].append(
  169. f"Insufficient SD card space. Need {required // (1024 * 1024)}MB, "
  170. f"have {result['sd_card_free_space'] // (1024 * 1024)}MB"
  171. )
  172. elif result["sd_card_present"]:
  173. # Couldn't determine space, assume sufficient
  174. result["space_sufficient"] = True
  175. # Final check
  176. result["can_proceed"] = (
  177. result["sd_card_present"]
  178. and result["space_sufficient"]
  179. and result["update_available"]
  180. and len(result["errors"]) == 0
  181. )
  182. return result
  183. async def start_upload(
  184. self,
  185. printer_id: int,
  186. db: AsyncSession,
  187. target_version: str | None = None,
  188. ) -> bool:
  189. """
  190. Start the firmware upload process.
  191. This runs asynchronously and broadcasts progress via WebSocket.
  192. Returns True if upload started successfully.
  193. """
  194. state = get_upload_state(printer_id)
  195. # Check if already in progress
  196. if state.status in (FirmwareUploadStatus.DOWNLOADING, FirmwareUploadStatus.UPLOADING):
  197. logger.warning("Firmware upload already in progress for printer %s", printer_id)
  198. return False
  199. # Get printer
  200. stmt = select(Printer).where(Printer.id == printer_id)
  201. db_result = await db.execute(stmt)
  202. printer = db_result.scalar_one_or_none()
  203. if not printer:
  204. state.status = FirmwareUploadStatus.ERROR
  205. state.error = "Printer not found"
  206. return False
  207. # Get printer model
  208. model = printer.model or "Unknown"
  209. # Reset state
  210. reset_upload_state(printer_id)
  211. state = get_upload_state(printer_id)
  212. state.status = FirmwareUploadStatus.PREPARING
  213. state.message = "Preparing firmware update..."
  214. # Run the upload in background
  215. spawn_background_task(
  216. self._do_upload(
  217. printer_id=printer_id,
  218. ip_address=printer.ip_address,
  219. access_code=printer.access_code,
  220. model=model,
  221. target_version=target_version,
  222. ),
  223. name=f"firmware-upload-{printer_id}",
  224. )
  225. return True
  226. async def _do_upload(
  227. self,
  228. printer_id: int,
  229. ip_address: str,
  230. access_code: str,
  231. model: str,
  232. target_version: str | None = None,
  233. ):
  234. """Perform the actual firmware download and upload."""
  235. state = get_upload_state(printer_id)
  236. firmware_service = get_firmware_service()
  237. try:
  238. # Download firmware (quick, usually cached)
  239. state.status = FirmwareUploadStatus.DOWNLOADING
  240. state.progress = 0
  241. state.message = "Preparing firmware..."
  242. firmware_path = await firmware_service.download_firmware(model, version=target_version)
  243. if not firmware_path:
  244. raise Exception("Failed to download firmware")
  245. state.firmware_filename = firmware_path.name
  246. # Get firmware version for state
  247. if target_version:
  248. state.firmware_version = target_version
  249. else:
  250. latest = await firmware_service.get_latest_version(model)
  251. if latest:
  252. state.firmware_version = latest.version
  253. # Upload to printer (0-100% progress shown here)
  254. state.status = FirmwareUploadStatus.UPLOADING
  255. state.progress = 0
  256. state.message = f"Uploading {firmware_path.name} to printer..."
  257. # Upload to root of SD card (where printer expects firmware)
  258. remote_path = f"/{firmware_path.name}"
  259. logger.info("Uploading firmware to printer %s: %s", printer_id, remote_path)
  260. # Track real progress via FTP callback; the UI polls the upload status
  261. last_progress = 0
  262. def on_upload_progress(uploaded: int, total: int):
  263. nonlocal last_progress
  264. if total > 0:
  265. progress = int((uploaded / total) * 100)
  266. if progress > last_progress:
  267. last_progress = progress
  268. state.progress = min(99, progress) # Cap at 99 until complete
  269. # Get FTP retry settings
  270. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  271. if ftp_retry_enabled:
  272. success = await with_ftp_retry(
  273. upload_file_async,
  274. ip_address,
  275. access_code,
  276. firmware_path,
  277. remote_path,
  278. progress_callback=on_upload_progress,
  279. socket_timeout=ftp_timeout,
  280. printer_model=model,
  281. # Someone pressed "update firmware" and is watching a
  282. # progress bar. Bounded and user-initiated, like a print
  283. # dispatch, so it does not spend its retries on a cool-off
  284. # meant for the background sweeps (#2898).
  285. respect_handshake_cooloff=False,
  286. max_retries=ftp_retry_count,
  287. retry_delay=ftp_retry_delay,
  288. operation_name=f"Upload firmware to printer {printer_id}",
  289. )
  290. else:
  291. success = await upload_file_async(
  292. ip_address,
  293. access_code,
  294. firmware_path,
  295. remote_path,
  296. progress_callback=on_upload_progress,
  297. socket_timeout=ftp_timeout,
  298. printer_model=model,
  299. respect_handshake_cooloff=False,
  300. )
  301. if not success:
  302. raise Exception("Failed to upload firmware to printer")
  303. # Complete
  304. state.status = FirmwareUploadStatus.COMPLETE
  305. state.progress = 100
  306. state.message = (
  307. f"Firmware {state.firmware_version or ''} uploaded successfully! "
  308. "Please go to printer screen and trigger the update from Settings > Firmware."
  309. )
  310. logger.info("Firmware upload complete for printer %s", printer_id)
  311. except Exception as e:
  312. logger.error("Firmware upload failed for printer %s: %s", printer_id, e)
  313. state.status = FirmwareUploadStatus.ERROR
  314. state.error = str(e)
  315. state.message = f"Firmware upload failed: {e}"
  316. # Singleton instance
  317. _firmware_update_service: FirmwareUpdateService | None = None
  318. def get_firmware_update_service() -> FirmwareUpdateService:
  319. """Get the singleton firmware update service instance."""
  320. global _firmware_update_service
  321. if _firmware_update_service is None:
  322. _firmware_update_service = FirmwareUpdateService()
  323. return _firmware_update_service