main.py 107 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  1. import asyncio
  2. import logging
  3. from contextlib import asynccontextmanager
  4. from datetime import UTC, datetime, timedelta
  5. from logging.handlers import RotatingFileHandler
  6. from fastapi import FastAPI
  7. # Import settings first for logging configuration
  8. from backend.app.core.config import APP_VERSION, settings as app_settings
  9. # Configure logging based on settings
  10. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  11. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  12. log_level = getattr(logging, log_level_str, logging.INFO)
  13. log_format = "%(asctime)s %(levelname)s [%(name)s] %(message)s"
  14. # Create root logger
  15. root_logger = logging.getLogger()
  16. root_logger.setLevel(log_level)
  17. # Console handler - always enabled
  18. console_handler = logging.StreamHandler()
  19. console_handler.setLevel(log_level)
  20. console_handler.setFormatter(logging.Formatter(log_format))
  21. root_logger.addHandler(console_handler)
  22. # File handler - only in production or if explicitly enabled
  23. if app_settings.log_to_file:
  24. log_file = app_settings.log_dir / "bambuddy.log"
  25. file_handler = RotatingFileHandler(
  26. log_file,
  27. maxBytes=5 * 1024 * 1024, # 5MB
  28. backupCount=3,
  29. encoding="utf-8",
  30. )
  31. file_handler.setLevel(log_level)
  32. file_handler.setFormatter(logging.Formatter(log_format))
  33. root_logger.addHandler(file_handler)
  34. logging.info(f"Logging to file: {log_file}")
  35. # Reduce noise from third-party libraries in production
  36. if not app_settings.debug:
  37. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  38. logging.getLogger("httpcore").setLevel(logging.WARNING)
  39. logging.getLogger("httpx").setLevel(logging.WARNING)
  40. logging.info(f"Bambuddy starting - debug={app_settings.debug}, log_level={log_level_str}")
  41. from fastapi.responses import FileResponse
  42. from fastapi.staticfiles import StaticFiles
  43. from sqlalchemy import delete, or_, select
  44. from backend.app.api.routes import (
  45. ams_history,
  46. api_keys,
  47. archives,
  48. auth,
  49. camera,
  50. cloud,
  51. discovery,
  52. external_links,
  53. filaments,
  54. firmware,
  55. kprofiles,
  56. library,
  57. maintenance,
  58. notification_templates,
  59. notifications,
  60. pending_uploads,
  61. print_queue,
  62. printers,
  63. projects,
  64. settings as settings_routes,
  65. smart_plugs,
  66. spoolman,
  67. support,
  68. system,
  69. updates,
  70. users,
  71. webhook,
  72. websocket,
  73. )
  74. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  75. from backend.app.api.routes.support import init_debug_logging
  76. from backend.app.core.database import async_session, init_db
  77. from backend.app.core.websocket import ws_manager
  78. from backend.app.models.smart_plug import SmartPlug
  79. from backend.app.services.archive import ArchiveService
  80. from backend.app.services.bambu_ftp import download_file_async, get_ftp_retry_settings, with_ftp_retry
  81. from backend.app.services.bambu_mqtt import PrinterState
  82. from backend.app.services.homeassistant import homeassistant_service
  83. from backend.app.services.mqtt_relay import mqtt_relay
  84. from backend.app.services.notification_service import notification_service
  85. from backend.app.services.print_scheduler import scheduler as print_scheduler
  86. from backend.app.services.printer_manager import (
  87. init_printer_connections,
  88. printer_manager,
  89. printer_state_to_dict,
  90. )
  91. from backend.app.services.smart_plug_manager import smart_plug_manager
  92. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  93. from backend.app.services.tasmota import tasmota_service
  94. # Track active prints: {(printer_id, filename): archive_id}
  95. _active_prints: dict[tuple[int, str], int] = {}
  96. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  97. # {(printer_id, filename): archive_id}
  98. _expected_prints: dict[tuple[int, str], int] = {}
  99. # Track starting energy for prints: {archive_id: starting_kwh}
  100. _print_energy_start: dict[int, float] = {}
  101. # Track reprints to add costs on completion: {archive_id}
  102. _reprint_archives: set[int] = set()
  103. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  104. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  105. _last_progress_milestone: dict[int, int] = {}
  106. async def _get_plug_energy(plug, db) -> dict | None:
  107. """Get energy from plug regardless of type (Tasmota or Home Assistant).
  108. For HA plugs, configures the service with current settings from DB.
  109. """
  110. if plug.plug_type == "homeassistant":
  111. from backend.app.api.routes.settings import get_setting
  112. ha_url = await get_setting(db, "ha_url") or ""
  113. ha_token = await get_setting(db, "ha_token") or ""
  114. homeassistant_service.configure(ha_url, ha_token)
  115. return await homeassistant_service.get_energy(plug)
  116. else:
  117. return await tasmota_service.get_energy(plug)
  118. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  119. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  120. # Store with multiple filename variations to catch different naming patterns
  121. _expected_prints[(printer_id, filename)] = archive_id
  122. # Also store without .3mf extension if present
  123. if filename.endswith(".3mf"):
  124. base = filename[:-4]
  125. _expected_prints[(printer_id, base)] = archive_id
  126. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  127. logging.getLogger(__name__).info(
  128. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  129. )
  130. _last_status_broadcast: dict[int, str] = {}
  131. _nozzle_count_updated: set[int] = set() # Track printers where we've updated nozzle_count
  132. async def _report_spoolman_usage(printer_id: int, archive_id: int, logger):
  133. """Report filament usage to Spoolman after print completion.
  134. This finds the spool by RFID tag_uid from current AMS state and reports
  135. the filament_used_grams from the archive metadata.
  136. """
  137. async with async_session() as db:
  138. from backend.app.api.routes.settings import get_setting
  139. from backend.app.models.archive import PrintArchive
  140. # Check if Spoolman is enabled
  141. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  142. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  143. return
  144. # Get Spoolman URL
  145. spoolman_url = await get_setting(db, "spoolman_url")
  146. if not spoolman_url:
  147. return
  148. # Get or create Spoolman client
  149. client = await get_spoolman_client()
  150. if not client:
  151. client = await init_spoolman_client(spoolman_url)
  152. # Check if Spoolman is reachable
  153. if not await client.health_check():
  154. logger.warning("Spoolman not reachable for usage reporting")
  155. return
  156. # Get archive to find filament usage
  157. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  158. archive = result.scalar_one_or_none()
  159. if not archive or not archive.filament_used_grams:
  160. logger.debug(f"No filament usage data for archive {archive_id}")
  161. return
  162. filament_used = archive.filament_used_grams
  163. logger.info(f"[SPOOLMAN] Archive {archive_id} used {filament_used}g of filament")
  164. # Get current AMS state from printer to find the active spool
  165. state = printer_manager.get_status(printer_id)
  166. if not state or not state.raw_data:
  167. logger.debug("No printer state available for usage reporting")
  168. return
  169. ams_data = state.raw_data.get("ams")
  170. if not ams_data:
  171. logger.debug("No AMS data available for usage reporting")
  172. return
  173. # Find spools with RFID tags in Spoolman and report usage
  174. # For now, we report usage to the first spool found with a matching tag
  175. # TODO: In future, track which specific trays were used during the print
  176. spools_updated = 0
  177. for ams_unit in ams_data:
  178. trays = ams_unit.get("tray", [])
  179. for tray_data in trays:
  180. tag_uid = tray_data.get("tag_uid")
  181. if not tag_uid:
  182. continue
  183. # Find spool in Spoolman by tag
  184. spool = await client.find_spool_by_tag(tag_uid)
  185. if spool:
  186. # Report usage to Spoolman
  187. result = await client.use_spool(spool["id"], filament_used)
  188. if result:
  189. logger.info(
  190. f"[SPOOLMAN] Reported {filament_used}g usage to spool {spool['id']} (tag: {tag_uid})"
  191. )
  192. spools_updated += 1
  193. # Only report to one spool for single-material prints
  194. # Multi-material prints would need more sophisticated tracking
  195. return
  196. if spools_updated == 0:
  197. logger.debug(f"No matching Spoolman spools found for printer {printer_id}")
  198. async def on_printer_status_change(printer_id: int, state: PrinterState):
  199. """Handle printer status changes - broadcast via WebSocket."""
  200. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  201. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  202. temps = state.temperatures or {}
  203. nozzle_temp = round(temps.get("nozzle", 0))
  204. bed_temp = round(temps.get("bed", 0))
  205. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  206. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  207. # Auto-detect dual-nozzle printers from MQTT temperature data
  208. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  209. _nozzle_count_updated.add(printer_id)
  210. # Update nozzle_count in database
  211. async with async_session() as db:
  212. from backend.app.models.printer import Printer
  213. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  214. printer = result.scalar_one_or_none()
  215. if printer and printer.nozzle_count != 2:
  216. printer.nozzle_count = 2
  217. await db.commit()
  218. logging.getLogger(__name__).info(
  219. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  220. )
  221. # Include target temps for heating phase detection
  222. bed_target = round(temps.get("bed_target", 0))
  223. nozzle_target = round(temps.get("nozzle_target", 0))
  224. status_key = (
  225. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  226. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  227. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  228. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  229. f"{state.chamber_light}:{state.active_extruder}"
  230. )
  231. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  232. try:
  233. printer_info = printer_manager.get_printer(printer_id)
  234. if printer_info:
  235. await mqtt_relay.on_printer_status(printer_id, state, printer_info.name, printer_info.serial_number)
  236. except Exception:
  237. pass # Don't fail status callback if MQTT fails
  238. if _last_status_broadcast.get(printer_id) == status_key:
  239. return # No change, skip WebSocket broadcast
  240. _last_status_broadcast[printer_id] = status_key
  241. # Check for progress milestone notifications (25%, 50%, 75%)
  242. progress = state.progress or 0
  243. is_printing = state.state in ("RUNNING", "PRINTING")
  244. if is_printing and progress > 0:
  245. # Determine which milestone we've reached
  246. current_milestone = 0
  247. if progress >= 75:
  248. current_milestone = 75
  249. elif progress >= 50:
  250. current_milestone = 50
  251. elif progress >= 25:
  252. current_milestone = 25
  253. last_milestone = _last_progress_milestone.get(printer_id, 0)
  254. # If we've crossed a new milestone, send notification
  255. if current_milestone > last_milestone:
  256. _last_progress_milestone[printer_id] = current_milestone
  257. try:
  258. async with async_session() as db:
  259. from backend.app.models.printer import Printer
  260. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  261. printer = result.scalar_one_or_none()
  262. printer_name = printer.name if printer else f"Printer {printer_id}"
  263. filename = state.subtask_name or state.gcode_file or "Unknown"
  264. remaining_time = state.remaining_time
  265. await notification_service.on_print_progress(
  266. printer_id, printer_name, filename, current_milestone, db, remaining_time
  267. )
  268. except Exception as e:
  269. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  270. elif progress < 5:
  271. # Reset milestone tracking when print restarts or new print begins
  272. _last_progress_milestone[printer_id] = 0
  273. await ws_manager.send_printer_status(
  274. printer_id,
  275. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  276. )
  277. async def on_ams_change(printer_id: int, ams_data: list):
  278. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  279. import logging
  280. logger = logging.getLogger(__name__)
  281. # MQTT relay - publish AMS change
  282. try:
  283. printer_info = printer_manager.get_printer(printer_id)
  284. if printer_info:
  285. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  286. except Exception:
  287. pass # Don't fail AMS callback if MQTT fails
  288. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  289. # This ensures frontend gets immediate updates when AMS slots are configured
  290. try:
  291. state = printer_manager.get_status(printer_id)
  292. if state:
  293. logger.info(f"[Printer {printer_id}] Broadcasting AMS change via WebSocket")
  294. await ws_manager.send_printer_status(
  295. printer_id,
  296. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  297. )
  298. except Exception as e:
  299. logger.warning(f"Failed to broadcast AMS change for printer {printer_id}: {e}")
  300. try:
  301. async with async_session() as db:
  302. from backend.app.api.routes.settings import get_setting
  303. from backend.app.models.printer import Printer
  304. # Check if Spoolman is enabled
  305. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  306. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  307. return
  308. # Check sync mode
  309. sync_mode = await get_setting(db, "spoolman_sync_mode")
  310. if sync_mode and sync_mode != "auto":
  311. return # Only sync on auto mode
  312. # Get Spoolman URL
  313. spoolman_url = await get_setting(db, "spoolman_url")
  314. if not spoolman_url:
  315. return
  316. # Get or create Spoolman client
  317. client = await get_spoolman_client()
  318. if not client:
  319. client = await init_spoolman_client(spoolman_url)
  320. # Check if Spoolman is reachable
  321. if not await client.health_check():
  322. logger.warning(f"Spoolman not reachable at {spoolman_url}")
  323. return
  324. # Get printer name for location
  325. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  326. printer = result.scalar_one_or_none()
  327. printer_name = printer.name if printer else f"Printer {printer_id}"
  328. # Sync each AMS tray
  329. synced = 0
  330. for ams_unit in ams_data:
  331. ams_id = int(ams_unit.get("id", 0))
  332. trays = ams_unit.get("tray", [])
  333. for tray_data in trays:
  334. tray = client.parse_ams_tray(ams_id, tray_data)
  335. if not tray:
  336. continue # Empty tray
  337. try:
  338. result = await client.sync_ams_tray(tray, printer_name)
  339. if result:
  340. synced += 1
  341. except Exception as e:
  342. logger.error(f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}")
  343. if synced > 0:
  344. logger.info(f"Auto-synced {synced} AMS trays to Spoolman for printer {printer_id}")
  345. except Exception as e:
  346. import logging
  347. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  348. async def _send_print_start_notification(
  349. printer_id: int,
  350. data: dict,
  351. archive_data: dict | None = None,
  352. logger=None,
  353. ):
  354. """Helper to send print start notification with optional archive data."""
  355. if logger is None:
  356. import logging
  357. logger = logging.getLogger(__name__)
  358. try:
  359. async with async_session() as db:
  360. from backend.app.models.printer import Printer
  361. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  362. printer = result.scalar_one_or_none()
  363. printer_name = printer.name if printer else f"Printer {printer_id}"
  364. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  365. except Exception as e:
  366. logger.warning(f"Notification on_print_start failed: {e}")
  367. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  368. """Extract printable objects from an archive's 3MF file and store in printer state."""
  369. try:
  370. from backend.app.services.archive import extract_printable_objects_from_3mf
  371. file_path = app_settings.base_dir / archive.file_path
  372. if file_path.exists() and str(file_path).endswith(".3mf"):
  373. with open(file_path, "rb") as f:
  374. threemf_data = f.read()
  375. # Extract with positions for UI overlay
  376. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  377. if printable_objects:
  378. client = printer_manager.get_client(printer_id)
  379. if client:
  380. client.state.printable_objects = printable_objects
  381. client.state.printable_objects_bbox_all = bbox_all
  382. client.state.skipped_objects = []
  383. logger.info(f"Loaded {len(printable_objects)} printable objects for printer {printer_id}")
  384. except Exception as e:
  385. logger.debug(f"Failed to extract printable objects from archive: {e}")
  386. async def on_print_start(printer_id: int, data: dict):
  387. """Handle print start - archive the 3MF file immediately."""
  388. import logging
  389. logger = logging.getLogger(__name__)
  390. logger.info(f"[CALLBACK] on_print_start called for printer {printer_id}, data keys: {list(data.keys())}")
  391. await ws_manager.send_print_start(printer_id, data)
  392. # MQTT relay - publish print start
  393. try:
  394. printer_info = printer_manager.get_printer(printer_id)
  395. if printer_info:
  396. await mqtt_relay.on_print_start(
  397. printer_id,
  398. printer_info.name,
  399. printer_info.serial_number,
  400. data.get("filename", ""),
  401. data.get("subtask_name", ""),
  402. )
  403. except Exception:
  404. pass # Don't fail print start callback if MQTT fails
  405. # Track if notification was sent (to avoid sending twice)
  406. notification_sent = False
  407. # Smart plug automation: turn on plug when print starts
  408. try:
  409. async with async_session() as db:
  410. await smart_plug_manager.on_print_start(printer_id, db)
  411. except Exception as e:
  412. logger.warning(f"Smart plug on_print_start failed: {e}")
  413. async with async_session() as db:
  414. from backend.app.models.printer import Printer
  415. from backend.app.services.bambu_ftp import list_files_async
  416. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  417. printer = result.scalar_one_or_none()
  418. # Plate detection check - pause if objects detected on build plate
  419. if printer and printer.plate_detection_enabled:
  420. try:
  421. from backend.app.services.plate_detection import check_plate_empty
  422. # Build ROI tuple from printer settings if available
  423. roi = None
  424. if all(
  425. [
  426. printer.plate_detection_roi_x is not None,
  427. printer.plate_detection_roi_y is not None,
  428. printer.plate_detection_roi_w is not None,
  429. printer.plate_detection_roi_h is not None,
  430. ]
  431. ):
  432. roi = (
  433. printer.plate_detection_roi_x,
  434. printer.plate_detection_roi_y,
  435. printer.plate_detection_roi_w,
  436. printer.plate_detection_roi_h,
  437. )
  438. logger.info(f"[PLATE CHECK] Running plate detection for printer {printer_id}")
  439. plate_result = await check_plate_empty(
  440. printer_id=printer_id,
  441. ip_address=printer.ip_address,
  442. access_code=printer.access_code,
  443. model=printer.model,
  444. include_debug_image=False,
  445. external_camera_url=printer.external_camera_url,
  446. external_camera_type=printer.external_camera_type,
  447. use_external=printer.external_camera_enabled,
  448. roi=roi,
  449. )
  450. if not plate_result.needs_calibration and not plate_result.is_empty:
  451. # Objects detected - pause the print!
  452. logger.warning(
  453. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  454. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  455. )
  456. client = printer_manager.get_client(printer_id)
  457. if client:
  458. client.pause_print()
  459. logger.info(f"[PLATE CHECK] Print paused for printer {printer_id}")
  460. # Send notification about plate not empty
  461. await ws_manager.broadcast(
  462. {
  463. "type": "plate_not_empty",
  464. "printer_id": printer_id,
  465. "printer_name": printer.name,
  466. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  467. }
  468. )
  469. # Also send push notification
  470. try:
  471. await notification_service.send_notification(
  472. printer_id=printer_id,
  473. printer_name=printer.name,
  474. event_type="plate_not_empty",
  475. title=f"⚠️ {printer.name}: Plate Not Empty!",
  476. body="Objects detected on build plate. Print has been paused. Please clear the plate and resume.",
  477. db=db,
  478. )
  479. except Exception as notif_err:
  480. logger.warning(f"[PLATE CHECK] Failed to send notification: {notif_err}")
  481. else:
  482. logger.info(f"[PLATE CHECK] Plate is empty for printer {printer_id}, proceeding with print")
  483. except Exception as plate_err:
  484. # Don't block print on plate detection errors
  485. logger.warning(f"[PLATE CHECK] Plate detection failed for printer {printer_id}: {plate_err}")
  486. if not printer or not printer.auto_archive:
  487. # Send notification without archive data (auto-archive disabled)
  488. logger.info(
  489. f"[CALLBACK] Skipping archive - printer: {printer is not None}, auto_archive: {printer.auto_archive if printer else 'N/A'}"
  490. )
  491. if not notification_sent:
  492. await _send_print_start_notification(printer_id, data, logger=logger)
  493. return
  494. # Get the filename and subtask_name
  495. filename = data.get("filename", "")
  496. subtask_name = data.get("subtask_name", "")
  497. logger.info(f"[CALLBACK] Print start detected - filename: {filename}, subtask: {subtask_name}")
  498. if not filename and not subtask_name:
  499. # Send notification without archive data (no filename)
  500. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  501. if not notification_sent:
  502. await _send_print_start_notification(printer_id, data, logger=logger)
  503. return
  504. # Check if this is an expected print from reprint/scheduled
  505. # Build list of possible keys to check
  506. expected_keys = []
  507. if subtask_name:
  508. expected_keys.append((printer_id, subtask_name))
  509. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  510. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  511. if filename:
  512. fname = filename.split("/")[-1] if "/" in filename else filename
  513. expected_keys.append((printer_id, fname))
  514. # Strip extensions to match
  515. base = fname.replace(".gcode", "").replace(".3mf", "")
  516. expected_keys.append((printer_id, base))
  517. expected_keys.append((printer_id, f"{base}.3mf"))
  518. expected_archive_id = None
  519. for key in expected_keys:
  520. expected_archive_id = _expected_prints.pop(key, None)
  521. if expected_archive_id:
  522. # Clean up other possible keys for this print
  523. for other_key in expected_keys:
  524. _expected_prints.pop(other_key, None)
  525. break
  526. if expected_archive_id:
  527. # This is a reprint/scheduled print - use existing archive, don't create new one
  528. logger.info(f"Using expected archive {expected_archive_id} for print (skipping duplicate)")
  529. from backend.app.models.archive import PrintArchive
  530. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  531. archive = result.scalar_one_or_none()
  532. if archive:
  533. # Update archive status to printing
  534. archive.status = "printing"
  535. archive.started_at = datetime.now()
  536. await db.commit()
  537. # Track as active print
  538. _active_prints[(printer_id, archive.filename)] = archive.id
  539. if subtask_name:
  540. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  541. # Mark as reprint so we add cost on completion
  542. _reprint_archives.add(archive.id)
  543. logger.info(f"Marked archive {archive.id} as reprint for cost addition on completion")
  544. # Set up energy tracking
  545. try:
  546. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  547. plug = plug_result.scalar_one_or_none()
  548. logger.info(
  549. f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  550. )
  551. if plug:
  552. energy = await _get_plug_energy(plug, db)
  553. logger.info(f"[ENERGY] Energy response from plug: {energy}")
  554. if energy and energy.get("total") is not None:
  555. _print_energy_start[archive.id] = energy["total"]
  556. logger.info(
  557. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  558. )
  559. else:
  560. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  561. else:
  562. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  563. except Exception as e:
  564. logger.warning(f"Failed to record starting energy: {e}")
  565. await ws_manager.send_archive_updated(
  566. {
  567. "id": archive.id,
  568. "status": "printing",
  569. }
  570. )
  571. # Send notification with archive data (reprint/scheduled)
  572. if not notification_sent:
  573. archive_data = {"print_time_seconds": archive.print_time_seconds}
  574. await _send_print_start_notification(printer_id, data, archive_data, logger)
  575. # Extract printable objects from the archived 3MF file
  576. _load_objects_from_archive(archive, printer_id, logger)
  577. return # Skip creating a new archive
  578. # Check if there's already a "printing" archive for this printer/file
  579. # This prevents duplicates when backend restarts during an active print
  580. from backend.app.models.archive import PrintArchive
  581. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  582. existing = await db.execute(
  583. select(PrintArchive)
  584. .where(PrintArchive.printer_id == printer_id)
  585. .where(PrintArchive.status == "printing")
  586. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  587. .order_by(PrintArchive.created_at.desc())
  588. .limit(1)
  589. )
  590. existing_archive = existing.scalar_one_or_none()
  591. if existing_archive:
  592. # Check if archive is stale (older than 4 hours) - likely a failed/cancelled print
  593. # that didn't get properly updated
  594. archive_age = datetime.now(UTC) - existing_archive.created_at.replace(tzinfo=UTC)
  595. if archive_age.total_seconds() > 4 * 60 * 60: # 4 hours
  596. logger.warning(
  597. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}), "
  598. f"marking as cancelled and creating new archive"
  599. )
  600. existing_archive.status = "cancelled"
  601. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  602. await db.commit()
  603. # Fall through to create new archive (don't return)
  604. existing_archive = None # Clear so we don't use stale archive
  605. else:
  606. logger.info(
  607. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  608. )
  609. # Track this as the active print
  610. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  611. # Also set up energy tracking if not already tracked
  612. if existing_archive.id not in _print_energy_start:
  613. try:
  614. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  615. plug = plug_result.scalar_one_or_none()
  616. if plug:
  617. energy = await _get_plug_energy(plug, db)
  618. if energy and energy.get("total") is not None:
  619. _print_energy_start[existing_archive.id] = energy["total"]
  620. logger.info(
  621. f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh"
  622. )
  623. except Exception as e:
  624. logger.warning(f"Failed to record starting energy for existing archive: {e}")
  625. # Send notification with archive data (existing archive)
  626. if not notification_sent:
  627. archive_data = {"print_time_seconds": existing_archive.print_time_seconds}
  628. await _send_print_start_notification(printer_id, data, archive_data, logger)
  629. # Extract printable objects from the archived 3MF file
  630. _load_objects_from_archive(existing_archive, printer_id, logger)
  631. return
  632. # Build list of possible 3MF filenames to try
  633. possible_names = []
  634. # Bambu printers typically store files as "Name.gcode.3mf"
  635. # The subtask_name is usually the best source for the filename
  636. if subtask_name:
  637. # Try common Bambu naming patterns
  638. possible_names.append(f"{subtask_name}.gcode.3mf")
  639. possible_names.append(f"{subtask_name}.3mf")
  640. # Try original filename with .3mf extension
  641. if filename:
  642. # Extract just the filename part, not the full path
  643. fname = filename.split("/")[-1] if "/" in filename else filename
  644. if fname.endswith(".3mf"):
  645. possible_names.append(fname)
  646. elif fname.endswith(".gcode"):
  647. base = fname.rsplit(".", 1)[0]
  648. possible_names.append(f"{base}.gcode.3mf")
  649. possible_names.append(f"{base}.3mf")
  650. else:
  651. possible_names.append(f"{fname}.gcode.3mf")
  652. possible_names.append(f"{fname}.3mf")
  653. # Remove duplicates while preserving order
  654. seen = set()
  655. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  656. logger.info(f"Trying filenames: {possible_names}")
  657. # Try to find and download the 3MF file
  658. temp_path = None
  659. downloaded_filename = None
  660. # Get FTP retry settings
  661. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  662. for try_filename in possible_names:
  663. if not try_filename.endswith(".3mf"):
  664. continue
  665. remote_paths = [
  666. f"/cache/{try_filename}",
  667. f"/model/{try_filename}",
  668. f"/data/{try_filename}",
  669. f"/data/Metadata/{try_filename}",
  670. f"/{try_filename}",
  671. ]
  672. temp_path = app_settings.archive_dir / "temp" / try_filename
  673. temp_path.parent.mkdir(parents=True, exist_ok=True)
  674. for remote_path in remote_paths:
  675. logger.debug(f"Trying FTP download: {remote_path}")
  676. try:
  677. if ftp_retry_enabled:
  678. downloaded = await with_ftp_retry(
  679. download_file_async,
  680. printer.ip_address,
  681. printer.access_code,
  682. remote_path,
  683. temp_path,
  684. socket_timeout=ftp_timeout,
  685. printer_model=printer.model,
  686. max_retries=ftp_retry_count,
  687. retry_delay=ftp_retry_delay,
  688. operation_name=f"Download 3MF from {remote_path}",
  689. )
  690. else:
  691. downloaded = await download_file_async(
  692. printer.ip_address,
  693. printer.access_code,
  694. remote_path,
  695. temp_path,
  696. socket_timeout=ftp_timeout,
  697. printer_model=printer.model,
  698. )
  699. if downloaded:
  700. downloaded_filename = try_filename
  701. logger.info(f"Downloaded: {remote_path}")
  702. break
  703. except Exception as e:
  704. logger.debug(f"FTP download failed for {remote_path}: {e}")
  705. if downloaded_filename:
  706. break
  707. # If still not found, try listing directories to find matching file
  708. # Different printer models use different directory structures
  709. if not downloaded_filename and (filename or subtask_name):
  710. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  711. logger.info(f"Direct FTP download failed, searching directories for '{search_term}'")
  712. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  713. for search_dir in search_dirs:
  714. if downloaded_filename:
  715. break
  716. try:
  717. dir_files = await list_files_async(printer.ip_address, printer.access_code, search_dir)
  718. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  719. if threemf_files:
  720. logger.info(
  721. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  722. )
  723. for f in dir_files:
  724. if f.get("is_directory"):
  725. continue
  726. fname = f.get("name", "")
  727. if fname.endswith(".3mf") and search_term in fname.lower():
  728. logger.info(f"Found matching file in {search_dir}: {fname}")
  729. temp_path = app_settings.archive_dir / "temp" / fname
  730. temp_path.parent.mkdir(parents=True, exist_ok=True)
  731. if ftp_retry_enabled:
  732. downloaded = await with_ftp_retry(
  733. download_file_async,
  734. printer.ip_address,
  735. printer.access_code,
  736. f"{search_dir}/{fname}",
  737. temp_path,
  738. max_retries=ftp_retry_count,
  739. retry_delay=ftp_retry_delay,
  740. operation_name=f"Download 3MF from {search_dir}/{fname}",
  741. )
  742. else:
  743. downloaded = await download_file_async(
  744. printer.ip_address,
  745. printer.access_code,
  746. f"{search_dir}/{fname}",
  747. temp_path,
  748. )
  749. if downloaded:
  750. downloaded_filename = fname
  751. logger.info(f"Found and downloaded from {search_dir}: {fname}")
  752. break
  753. except Exception as e:
  754. logger.debug(f"Failed to list {search_dir}: {e}")
  755. if not downloaded_filename or not temp_path:
  756. logger.warning(f"Could not find 3MF file for print: {filename or subtask_name}")
  757. # Create a fallback archive without 3MF data so the print is still tracked
  758. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  759. try:
  760. from backend.app.models.archive import PrintArchive
  761. # Derive print name from subtask_name or filename
  762. print_name = subtask_name or filename
  763. if print_name:
  764. # Clean up the name (remove extensions, path parts)
  765. print_name = print_name.split("/")[-1]
  766. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  767. else:
  768. print_name = "Unknown Print"
  769. # Create minimal archive entry
  770. fallback_archive = PrintArchive(
  771. printer_id=printer_id,
  772. filename=filename or f"{print_name}.3mf",
  773. file_path="", # Empty - no 3MF file available
  774. file_size=0,
  775. print_name=print_name,
  776. status="printing",
  777. started_at=datetime.now(),
  778. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  779. )
  780. db.add(fallback_archive)
  781. await db.commit()
  782. await db.refresh(fallback_archive)
  783. logger.info(f"Created fallback archive {fallback_archive.id} for {print_name} (no 3MF available)")
  784. # Start timelapse session if external camera is enabled
  785. if printer.external_camera_enabled and printer.external_camera_url:
  786. from backend.app.services.layer_timelapse import start_session
  787. start_session(
  788. printer_id,
  789. fallback_archive.id,
  790. printer.external_camera_url,
  791. printer.external_camera_type or "mjpeg",
  792. )
  793. logger.info(f"Started layer timelapse for printer {printer_id}, archive {fallback_archive.id}")
  794. # Track as active print
  795. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  796. if filename:
  797. _active_prints[(printer_id, filename)] = fallback_archive.id
  798. if subtask_name:
  799. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  800. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  801. # Record starting energy if smart plug available
  802. try:
  803. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  804. plug = plug_result.scalar_one_or_none()
  805. if plug:
  806. energy = await _get_plug_energy(plug, db)
  807. if energy and energy.get("total") is not None:
  808. _print_energy_start[fallback_archive.id] = energy["total"]
  809. logger.info(
  810. f"[ENERGY] Recorded starting energy for fallback archive {fallback_archive.id}: {energy['total']} kWh"
  811. )
  812. except Exception as e:
  813. logger.warning(f"Failed to record starting energy for fallback: {e}")
  814. # Send WebSocket notification
  815. await ws_manager.send_archive_created(
  816. {
  817. "id": fallback_archive.id,
  818. "printer_id": fallback_archive.printer_id,
  819. "filename": fallback_archive.filename,
  820. "print_name": fallback_archive.print_name,
  821. "status": fallback_archive.status,
  822. }
  823. )
  824. # MQTT relay - publish archive created
  825. try:
  826. await mqtt_relay.on_archive_created(
  827. archive_id=fallback_archive.id,
  828. print_name=fallback_archive.print_name,
  829. printer_name=printer.name,
  830. status=fallback_archive.status,
  831. )
  832. except Exception:
  833. pass # Don't fail if MQTT fails
  834. # Send notification without archive data (file not found)
  835. if not notification_sent:
  836. await _send_print_start_notification(printer_id, data, logger=logger)
  837. return
  838. except Exception as e:
  839. logger.error(f"Failed to create fallback archive: {e}")
  840. # Send notification without archive data (file not found)
  841. if not notification_sent:
  842. await _send_print_start_notification(printer_id, data, logger=logger)
  843. return
  844. try:
  845. # Archive the file with status "printing"
  846. service = ArchiveService(db)
  847. archive = await service.archive_print(
  848. printer_id=printer_id,
  849. source_file=temp_path,
  850. print_data={**data, "status": "printing"},
  851. )
  852. if archive:
  853. # Track this active print (use both original filename and downloaded filename)
  854. _active_prints[(printer_id, downloaded_filename)] = archive.id
  855. if filename and filename != downloaded_filename:
  856. _active_prints[(printer_id, filename)] = archive.id
  857. if subtask_name:
  858. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  859. logger.info(f"Created archive {archive.id} for {downloaded_filename}")
  860. # Start timelapse session if external camera is enabled
  861. if printer.external_camera_enabled and printer.external_camera_url:
  862. from backend.app.services.layer_timelapse import start_session
  863. start_session(
  864. printer_id,
  865. archive.id,
  866. printer.external_camera_url,
  867. printer.external_camera_type or "mjpeg",
  868. )
  869. logger.info(f"Started layer timelapse for printer {printer_id}, archive {archive.id}")
  870. # Record starting energy from smart plug if available
  871. try:
  872. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  873. plug = plug_result.scalar_one_or_none()
  874. logger.info(
  875. f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  876. )
  877. if plug:
  878. energy = await _get_plug_energy(plug, db)
  879. logger.info(f"[ENERGY] Auto-archive energy response: {energy}")
  880. if energy and energy.get("total") is not None:
  881. _print_energy_start[archive.id] = energy["total"]
  882. logger.info(
  883. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  884. )
  885. else:
  886. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  887. else:
  888. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  889. except Exception as e:
  890. logger.warning(f"Failed to record starting energy: {e}")
  891. await ws_manager.send_archive_created(
  892. {
  893. "id": archive.id,
  894. "printer_id": archive.printer_id,
  895. "filename": archive.filename,
  896. "print_name": archive.print_name,
  897. "status": archive.status,
  898. }
  899. )
  900. # MQTT relay - publish archive created
  901. try:
  902. await mqtt_relay.on_archive_created(
  903. archive_id=archive.id,
  904. print_name=archive.print_name,
  905. printer_name=printer.name,
  906. status=archive.status,
  907. )
  908. except Exception:
  909. pass # Don't fail if MQTT fails
  910. # Send notification with archive data (new archive created)
  911. if not notification_sent:
  912. archive_data = {"print_time_seconds": archive.print_time_seconds}
  913. await _send_print_start_notification(printer_id, data, archive_data, logger)
  914. notification_sent = True
  915. # Extract printable objects for skip object functionality
  916. try:
  917. from backend.app.services.archive import extract_printable_objects_from_3mf
  918. with open(temp_path, "rb") as f:
  919. threemf_data = f.read()
  920. # Extract with positions for UI overlay
  921. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  922. threemf_data, include_positions=True
  923. )
  924. if printable_objects:
  925. # Store objects in printer state
  926. client = printer_manager.get_client(printer_id)
  927. if client:
  928. client.state.printable_objects = printable_objects
  929. client.state.printable_objects_bbox_all = bbox_all
  930. client.state.skipped_objects = [] # Reset skipped objects for new print
  931. logger.info(f"Loaded {len(printable_objects)} printable objects for printer {printer_id}")
  932. except Exception as e:
  933. logger.debug(f"Failed to extract printable objects: {e}")
  934. finally:
  935. if temp_path and temp_path.exists():
  936. temp_path.unlink()
  937. async def _scan_for_timelapse_with_retries(archive_id: int):
  938. """
  939. Scan for timelapse with retries.
  940. The printer encodes the timelapse quickly after print completion.
  941. We just need a short delay then grab the most recent file.
  942. Since we KNOW timelapse was active (from MQTT ipcam data), the most recent
  943. file in /timelapse is our target. Retries handle FTP connection issues.
  944. """
  945. import logging
  946. logger = logging.getLogger(__name__)
  947. # Short delays - printer usually finishes encoding within seconds
  948. retry_delays = [5, 10, 20]
  949. for attempt, delay in enumerate(retry_delays, 1):
  950. logger.info(
  951. f"[TIMELAPSE] Attempt {attempt}/{len(retry_delays)}: waiting {delay}s before scanning for archive {archive_id}"
  952. )
  953. await asyncio.sleep(delay)
  954. try:
  955. async with async_session() as db:
  956. from backend.app.models.printer import Printer
  957. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  958. # Get archive (ArchiveService from module-level import)
  959. service = ArchiveService(db)
  960. archive = await service.get_archive(archive_id)
  961. if not archive:
  962. logger.warning(f"[TIMELAPSE] Archive {archive_id} not found, stopping retries")
  963. return
  964. if archive.timelapse_path:
  965. logger.info(f"[TIMELAPSE] Archive {archive_id} already has timelapse attached, stopping retries")
  966. return
  967. if not archive.printer_id:
  968. logger.warning(f"[TIMELAPSE] Archive {archive_id} has no printer, stopping retries")
  969. return
  970. # Get printer
  971. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  972. printer = result.scalar_one_or_none()
  973. if not printer:
  974. logger.warning(f"[TIMELAPSE] Printer not found for archive {archive_id}, stopping retries")
  975. return
  976. # Scan timelapse directory on printer
  977. # H2D may store in different locations than X1C
  978. files = []
  979. found_path = None
  980. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  981. try:
  982. found_files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  983. if found_files:
  984. files = found_files
  985. found_path = timelapse_path
  986. logger.info(f"[TIMELAPSE] Attempt {attempt}: Found {len(files)} files in {timelapse_path}")
  987. break
  988. except Exception as e:
  989. logger.debug(f"[TIMELAPSE] Path {timelapse_path} failed: {e}")
  990. continue
  991. if not files:
  992. logger.info(f"[TIMELAPSE] Attempt {attempt}: No timelapse files found on printer, will retry")
  993. continue
  994. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  995. # Log ALL mp4 files found for debugging
  996. logger.info(f"[TIMELAPSE] Attempt {attempt}: Found {len(mp4_files)} MP4 files in {found_path}")
  997. for f in mp4_files[:5]: # Log first 5
  998. logger.info(f"[TIMELAPSE] - {f.get('name')}, mtime={f.get('mtime')}")
  999. if not mp4_files:
  1000. logger.info(f"[TIMELAPSE] Attempt {attempt}: No MP4 files found, will retry")
  1001. continue
  1002. # Sort by mtime descending to get most recent file
  1003. mp4_files_with_mtime = [f for f in mp4_files if f.get("mtime")]
  1004. if not mp4_files_with_mtime:
  1005. logger.info(f"[TIMELAPSE] Attempt {attempt}: No MP4 files with mtime found, will retry")
  1006. continue
  1007. mp4_files_with_mtime.sort(key=lambda x: x.get("mtime"), reverse=True)
  1008. most_recent = mp4_files_with_mtime[0]
  1009. file_name = most_recent.get("name")
  1010. logger.info(f"[TIMELAPSE] Attempt {attempt}: Most recent file: {file_name}")
  1011. # Since we KNOW timelapse was active (from MQTT), just grab the most recent file
  1012. remote_path = most_recent.get("path") or f"/timelapse/{file_name}"
  1013. logger.info(f"[TIMELAPSE] Downloading {file_name} for archive {archive_id}")
  1014. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  1015. if timelapse_data:
  1016. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  1017. if success:
  1018. logger.info(f"[TIMELAPSE] Successfully attached timelapse to archive {archive_id}")
  1019. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  1020. return # Success!
  1021. else:
  1022. logger.warning(f"[TIMELAPSE] Failed to attach timelapse to archive {archive_id}")
  1023. else:
  1024. logger.warning(f"[TIMELAPSE] Attempt {attempt}: Failed to download, will retry")
  1025. except Exception as e:
  1026. logger.warning(f"[TIMELAPSE] Attempt {attempt} failed with error: {e}")
  1027. logger.warning(f"[TIMELAPSE] All {len(retry_delays)} attempts exhausted for archive {archive_id}, giving up")
  1028. async def on_print_complete(printer_id: int, data: dict):
  1029. """Handle print completion - update the archive status."""
  1030. import logging
  1031. import time
  1032. logger = logging.getLogger(__name__)
  1033. start_time = time.time()
  1034. def log_timing(section: str):
  1035. elapsed = time.time() - start_time
  1036. logger.info(f"[TIMING] {section}: {elapsed:.3f}s elapsed")
  1037. logger.info(f"[CALLBACK] on_print_complete started for printer {printer_id}")
  1038. try:
  1039. ws_data = {
  1040. "status": data.get("status"),
  1041. "filename": data.get("filename"),
  1042. "subtask_name": data.get("subtask_name"),
  1043. "timelapse_was_active": data.get("timelapse_was_active"),
  1044. }
  1045. await ws_manager.send_print_complete(printer_id, ws_data)
  1046. log_timing("WebSocket send_print_complete")
  1047. except Exception as e:
  1048. logger.warning(f"[CALLBACK] WebSocket send_print_complete failed: {e}")
  1049. # MQTT relay - publish print complete
  1050. try:
  1051. printer_info = printer_manager.get_printer(printer_id)
  1052. if printer_info:
  1053. await mqtt_relay.on_print_complete(
  1054. printer_id,
  1055. printer_info.name,
  1056. printer_info.serial_number,
  1057. data.get("filename", ""),
  1058. data.get("subtask_name", ""),
  1059. data.get("status", "completed"),
  1060. )
  1061. except Exception:
  1062. pass # Don't fail print complete callback if MQTT fails
  1063. filename = data.get("filename", "")
  1064. subtask_name = data.get("subtask_name", "")
  1065. if not filename and not subtask_name:
  1066. logger.warning("Print complete without filename or subtask_name")
  1067. return
  1068. logger.info(f"Print complete - filename: {filename}, subtask: {subtask_name}, status: {data.get('status')}")
  1069. # Build list of possible keys to try (matching how they were registered in on_print_start)
  1070. possible_keys = []
  1071. # Try subtask_name variations first (most reliable for matching)
  1072. if subtask_name:
  1073. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  1074. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  1075. possible_keys.append((printer_id, subtask_name))
  1076. # Try filename variations
  1077. if filename:
  1078. # Extract just the filename if it's a path
  1079. fname = filename.split("/")[-1] if "/" in filename else filename
  1080. if fname.endswith(".3mf"):
  1081. possible_keys.append((printer_id, fname))
  1082. elif fname.endswith(".gcode"):
  1083. base_name = fname.rsplit(".", 1)[0]
  1084. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  1085. possible_keys.append((printer_id, f"{base_name}.3mf"))
  1086. possible_keys.append((printer_id, fname))
  1087. else:
  1088. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  1089. possible_keys.append((printer_id, f"{fname}.3mf"))
  1090. possible_keys.append((printer_id, fname))
  1091. # Also try full path versions
  1092. if filename.endswith(".3mf"):
  1093. possible_keys.append((printer_id, filename))
  1094. elif filename.endswith(".gcode"):
  1095. base_name = filename.rsplit(".", 1)[0]
  1096. possible_keys.append((printer_id, f"{base_name}.3mf"))
  1097. possible_keys.append((printer_id, filename))
  1098. else:
  1099. possible_keys.append((printer_id, f"{filename}.3mf"))
  1100. possible_keys.append((printer_id, filename))
  1101. # Find the archive for this print
  1102. logger.info(f"Looking for archive in _active_prints, keys to try: {possible_keys[:5]}...")
  1103. logger.info(f"Current _active_prints: {list(_active_prints.keys())}")
  1104. archive_id = None
  1105. for key in possible_keys:
  1106. archive_id = _active_prints.pop(key, None)
  1107. if archive_id:
  1108. logger.info(f"Found archive {archive_id} with key {key}")
  1109. # Also clean up any other keys pointing to this archive
  1110. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  1111. for k in keys_to_remove:
  1112. _active_prints.pop(k, None)
  1113. break
  1114. if not archive_id:
  1115. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  1116. async with async_session() as db:
  1117. from backend.app.models.archive import PrintArchive
  1118. # Try matching by subtask_name (stored as print_name) first
  1119. if subtask_name:
  1120. result = await db.execute(
  1121. select(PrintArchive)
  1122. .where(PrintArchive.printer_id == printer_id)
  1123. .where(PrintArchive.status == "printing")
  1124. .where(
  1125. or_(
  1126. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  1127. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  1128. )
  1129. )
  1130. .order_by(PrintArchive.created_at.desc())
  1131. .limit(1)
  1132. )
  1133. archive = result.scalar_one_or_none()
  1134. if archive:
  1135. archive_id = archive.id
  1136. logger.info(f"Found archive {archive_id} by subtask_name match: {subtask_name}")
  1137. # Also try by filename
  1138. if not archive_id and filename:
  1139. result = await db.execute(
  1140. select(PrintArchive)
  1141. .where(PrintArchive.printer_id == printer_id)
  1142. .where(PrintArchive.filename == filename)
  1143. .where(PrintArchive.status == "printing")
  1144. .order_by(PrintArchive.created_at.desc())
  1145. .limit(1)
  1146. )
  1147. archive = result.scalar_one_or_none()
  1148. if archive:
  1149. archive_id = archive.id
  1150. if not archive_id:
  1151. logger.warning(f"Could not find archive for print complete: filename={filename}, subtask={subtask_name}")
  1152. return
  1153. log_timing("Archive lookup")
  1154. # Update archive status
  1155. logger.info(f"[ARCHIVE] Updating archive {archive_id} status...")
  1156. try:
  1157. async with async_session() as db:
  1158. service = ArchiveService(db)
  1159. status = data.get("status", "completed")
  1160. # Auto-detect failure reason
  1161. failure_reason = None
  1162. if status == "aborted":
  1163. failure_reason = "User cancelled"
  1164. logger.info("[ARCHIVE] Print was aborted by user, setting failure_reason='User cancelled'")
  1165. elif status == "failed":
  1166. # Try to determine failure reason from HMS errors
  1167. hms_errors = data.get("hms_errors", [])
  1168. if hms_errors:
  1169. logger.info(f"[ARCHIVE] HMS errors at failure: {hms_errors}")
  1170. # Map known HMS error modules to failure reasons
  1171. # Module 0x07 = Filament, 0x0C = MC (Motion Controller), etc.
  1172. for err in hms_errors:
  1173. module = err.get("module", 0)
  1174. if module == 0x07: # Filament module
  1175. failure_reason = "Filament runout"
  1176. break
  1177. elif module == 0x0C: # Motion controller
  1178. failure_reason = "Layer shift"
  1179. break
  1180. elif module == 0x05: # Nozzle/extruder
  1181. failure_reason = "Clogged nozzle"
  1182. break
  1183. if failure_reason:
  1184. logger.info(f"[ARCHIVE] Detected failure_reason from HMS: {failure_reason}")
  1185. else:
  1186. logger.info("[ARCHIVE] No HMS errors available to determine failure reason")
  1187. await service.update_archive_status(
  1188. archive_id,
  1189. status=status,
  1190. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  1191. failure_reason=failure_reason,
  1192. )
  1193. logger.info(f"[ARCHIVE] Archive {archive_id} status updated to {status}, failure_reason={failure_reason}")
  1194. # Add cost for reprints (first prints have cost set in archive_print())
  1195. if status == "completed" and archive_id in _reprint_archives:
  1196. _reprint_archives.discard(archive_id)
  1197. try:
  1198. await service.add_reprint_cost(archive_id)
  1199. logger.info(f"[ARCHIVE] Added reprint cost for archive {archive_id}")
  1200. except Exception as e:
  1201. logger.warning(f"[ARCHIVE] Failed to add reprint cost for archive {archive_id}: {e}")
  1202. await ws_manager.send_archive_updated(
  1203. {
  1204. "id": archive_id,
  1205. "status": status,
  1206. }
  1207. )
  1208. logger.info(f"[ARCHIVE] WebSocket notification sent for archive {archive_id}")
  1209. # MQTT relay - publish archive updated
  1210. try:
  1211. await mqtt_relay.on_archive_updated(
  1212. archive_id=archive_id,
  1213. print_name=filename or subtask_name,
  1214. status=status,
  1215. )
  1216. except Exception:
  1217. pass # Don't fail if MQTT fails
  1218. except Exception as e:
  1219. logger.error(f"[ARCHIVE] Failed to update archive {archive_id} status: {e}", exc_info=True)
  1220. # Continue with other operations even if archive update fails
  1221. log_timing("Archive status update")
  1222. # Report filament usage to Spoolman if print completed successfully
  1223. if data.get("status") == "completed":
  1224. try:
  1225. await _report_spoolman_usage(printer_id, archive_id, logger)
  1226. log_timing("Spoolman usage report")
  1227. except Exception as e:
  1228. logger.warning(f"Spoolman usage reporting failed: {e}")
  1229. # Run slow operations as background tasks to avoid blocking the event loop
  1230. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  1231. starting_kwh = _print_energy_start.pop(archive_id, None)
  1232. async def _background_energy_calculation():
  1233. """Calculate and save energy usage in background."""
  1234. try:
  1235. logger.info(f"[ENERGY-BG] Starting energy calculation for archive {archive_id}")
  1236. async with async_session() as db:
  1237. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1238. plug = plug_result.scalar_one_or_none()
  1239. if plug:
  1240. energy = await _get_plug_energy(plug, db)
  1241. logger.info(f"[ENERGY-BG] Energy response: {energy}")
  1242. energy_used = None
  1243. if starting_kwh is not None and energy and energy.get("total") is not None:
  1244. ending_kwh = energy["total"]
  1245. energy_used = round(ending_kwh - starting_kwh, 4)
  1246. logger.info(f"[ENERGY-BG] Per-print energy: {energy_used} kWh")
  1247. if energy_used is not None and energy_used >= 0:
  1248. from backend.app.api.routes.settings import get_setting
  1249. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  1250. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  1251. energy_cost = round(energy_used * cost_per_kwh, 2)
  1252. from backend.app.models.archive import PrintArchive
  1253. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1254. archive = result.scalar_one_or_none()
  1255. if archive:
  1256. archive.energy_kwh = energy_used
  1257. archive.energy_cost = energy_cost
  1258. await db.commit()
  1259. logger.info(f"[ENERGY-BG] Saved: {energy_used} kWh, cost={energy_cost}")
  1260. else:
  1261. logger.info(f"[ENERGY-BG] No smart plug for printer {printer_id}")
  1262. except Exception as e:
  1263. logger.warning(f"[ENERGY-BG] Failed: {e}")
  1264. async def _background_finish_photo() -> str | None:
  1265. """Capture finish photo in background. Returns photo filename if captured."""
  1266. try:
  1267. logger.info(f"[PHOTO-BG] Starting finish photo capture for archive {archive_id}")
  1268. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1269. async with async_session() as db:
  1270. from backend.app.api.routes.settings import get_setting
  1271. capture_enabled = await get_setting(db, "capture_finish_photo")
  1272. if capture_enabled is None or capture_enabled.lower() == "true":
  1273. from backend.app.models.printer import Printer
  1274. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1275. printer = result.scalar_one_or_none()
  1276. if printer and archive_id:
  1277. from backend.app.models.archive import PrintArchive
  1278. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1279. archive = result.scalar_one_or_none()
  1280. if archive:
  1281. import uuid
  1282. from datetime import datetime
  1283. from pathlib import Path
  1284. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  1285. photo_filename = None
  1286. # Check for external camera first
  1287. if printer.external_camera_enabled and printer.external_camera_url:
  1288. logger.info("[PHOTO-BG] Using external camera")
  1289. from backend.app.services.external_camera import capture_frame
  1290. frame_data = await capture_frame(
  1291. printer.external_camera_url, printer.external_camera_type or "mjpeg"
  1292. )
  1293. if frame_data:
  1294. photos_dir = archive_dir / "photos"
  1295. photos_dir.mkdir(parents=True, exist_ok=True)
  1296. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1297. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  1298. photo_path = photos_dir / photo_filename
  1299. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  1300. logger.info(f"[PHOTO-BG] Saved external camera frame: {photo_filename}")
  1301. else:
  1302. # Check if camera stream is active - use buffered frame to avoid freeze
  1303. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  1304. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1305. active_chamber_for_printer = [
  1306. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  1307. ]
  1308. buffered_frame = get_buffered_frame(printer_id)
  1309. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  1310. # Use frame from active stream
  1311. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  1312. photos_dir = archive_dir / "photos"
  1313. photos_dir.mkdir(parents=True, exist_ok=True)
  1314. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1315. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  1316. photo_path = photos_dir / photo_filename
  1317. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  1318. logger.info(f"[PHOTO-BG] Saved buffered frame: {photo_filename}")
  1319. else:
  1320. # No active stream - capture new frame
  1321. from backend.app.services.camera import capture_finish_photo
  1322. photo_filename = await capture_finish_photo(
  1323. printer_id=printer_id,
  1324. ip_address=printer.ip_address,
  1325. access_code=printer.access_code,
  1326. model=printer.model,
  1327. archive_dir=archive_dir,
  1328. )
  1329. if photo_filename:
  1330. photos = archive.photos or []
  1331. photos.append(photo_filename)
  1332. archive.photos = photos
  1333. await db.commit()
  1334. logger.info(f"[PHOTO-BG] Saved: {photo_filename}")
  1335. return photo_filename
  1336. return None
  1337. except Exception as e:
  1338. logger.warning(f"[PHOTO-BG] Failed: {e}")
  1339. return None
  1340. asyncio.create_task(_background_energy_calculation())
  1341. # Photo capture task - result will be used by notifications
  1342. photo_task = asyncio.create_task(_background_finish_photo())
  1343. log_timing("Background tasks scheduled (energy, photo)")
  1344. # Also run smart plug, notifications, and maintenance as background tasks
  1345. print_status = data.get("status", "completed")
  1346. async def _background_smart_plug():
  1347. """Handle smart plug automation in background."""
  1348. try:
  1349. logger.info(f"[AUTO-OFF-BG] Starting smart plug automation for printer {printer_id}")
  1350. async with async_session() as db:
  1351. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  1352. logger.info("[AUTO-OFF-BG] Completed")
  1353. except Exception as e:
  1354. logger.warning(f"[AUTO-OFF-BG] Failed: {e}")
  1355. async def _background_notifications(finish_photo_filename: str | None = None):
  1356. """Send print complete notifications in background."""
  1357. try:
  1358. logger.info(f"[NOTIFY-BG] Starting notifications for printer {printer_id}, photo={finish_photo_filename}")
  1359. async with async_session() as db:
  1360. from backend.app.models.archive import PrintArchive
  1361. from backend.app.models.printer import Printer
  1362. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1363. printer = result.scalar_one_or_none()
  1364. printer_name = printer.name if printer else f"Printer {printer_id}"
  1365. archive_data = None
  1366. if archive_id:
  1367. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1368. archive = archive_result.scalar_one_or_none()
  1369. if archive:
  1370. archive_data = {
  1371. "print_time_seconds": archive.print_time_seconds,
  1372. "actual_filament_grams": archive.filament_used_grams,
  1373. "failure_reason": archive.failure_reason,
  1374. }
  1375. # Add finish photo URL if available
  1376. if finish_photo_filename:
  1377. from backend.app.api.routes.settings import get_setting
  1378. external_url = await get_setting(db, "external_url")
  1379. if external_url:
  1380. external_url = external_url.rstrip("/")
  1381. archive_data["finish_photo_url"] = (
  1382. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  1383. )
  1384. else:
  1385. # Fallback to relative URL (won't work for external services)
  1386. archive_data["finish_photo_url"] = (
  1387. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  1388. )
  1389. await notification_service.on_print_complete(
  1390. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  1391. )
  1392. logger.info("[NOTIFY-BG] Completed")
  1393. except Exception as e:
  1394. logger.warning(f"[NOTIFY-BG] Failed: {e}")
  1395. async def _background_maintenance_check():
  1396. """Check for maintenance due in background."""
  1397. if print_status != "completed":
  1398. return
  1399. try:
  1400. logger.info(f"[MAINT-BG] Starting maintenance check for printer {printer_id}")
  1401. async with async_session() as db:
  1402. from backend.app.models.printer import Printer
  1403. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1404. printer = result.scalar_one_or_none()
  1405. printer_name = printer.name if printer else f"Printer {printer_id}"
  1406. await ensure_default_types(db)
  1407. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  1408. items_needing_attention = [
  1409. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  1410. for item in overview.maintenance_items
  1411. if item.enabled and (item.is_due or item.is_warning)
  1412. ]
  1413. if items_needing_attention:
  1414. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  1415. logger.info(f"[MAINT-BG] Sent notification: {len(items_needing_attention)} items need attention")
  1416. # MQTT relay - publish maintenance alerts
  1417. for item in items_needing_attention:
  1418. try:
  1419. await mqtt_relay.on_maintenance_alert(
  1420. printer_id=printer_id,
  1421. printer_name=printer_name,
  1422. maintenance_type=item["name"],
  1423. current_value=0, # Not easily available here
  1424. threshold=0, # Not easily available here
  1425. )
  1426. except Exception:
  1427. pass # Don't fail if MQTT fails
  1428. else:
  1429. logger.info("[MAINT-BG] Completed (no items need attention)")
  1430. except Exception as e:
  1431. logger.warning(f"[MAINT-BG] Failed: {e}")
  1432. asyncio.create_task(_background_smart_plug())
  1433. asyncio.create_task(_background_maintenance_check())
  1434. # Notification task waits for photo capture to complete first
  1435. async def _photo_then_notify():
  1436. """Wait for photo capture, then send notification with photo URL."""
  1437. try:
  1438. finish_photo = await photo_task
  1439. logger.info(f"[PHOTO-NOTIFY] Photo task returned: {finish_photo}")
  1440. await _background_notifications(finish_photo)
  1441. except Exception as e:
  1442. logger.warning(f"[PHOTO-NOTIFY] Failed: {e}")
  1443. # Still try to send notification without photo
  1444. await _background_notifications(None)
  1445. asyncio.create_task(_photo_then_notify())
  1446. # Stitch external camera layer timelapse if session was active
  1447. print_status = data.get("status", "completed")
  1448. async def _background_layer_timelapse():
  1449. """Stitch layer timelapse and attach to archive."""
  1450. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  1451. try:
  1452. if print_status == "completed":
  1453. logger.info(f"[LAYER-TL] Stitching layer timelapse for printer {printer_id}")
  1454. timelapse_path = await tl_complete(printer_id)
  1455. if timelapse_path and archive_id:
  1456. logger.info(f"[LAYER-TL] Attaching timelapse {timelapse_path} to archive {archive_id}")
  1457. async with async_session() as db:
  1458. service = ArchiveService(db)
  1459. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  1460. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  1461. # Clean up the temp file
  1462. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  1463. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  1464. elif timelapse_path:
  1465. # Timelapse created but no archive - just clean up
  1466. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  1467. else:
  1468. # Print failed or cancelled - cancel timelapse session
  1469. cancel_session(printer_id)
  1470. logger.info(f"[LAYER-TL] Cancelled layer timelapse for printer {printer_id} (status: {print_status})")
  1471. except Exception as e:
  1472. logger.warning(f"[LAYER-TL] Failed: {e}")
  1473. # Try to cancel session on error
  1474. try:
  1475. cancel_session(printer_id)
  1476. except Exception:
  1477. pass
  1478. asyncio.create_task(_background_layer_timelapse())
  1479. log_timing("All background tasks scheduled")
  1480. # Auto-scan for timelapse if recording was active during the print
  1481. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  1482. logger.info(f"[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive {archive_id}")
  1483. # Schedule timelapse scan as background task with retries
  1484. # The printer needs time to encode the video after print completion
  1485. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id))
  1486. log_timing("Timelapse scan scheduled")
  1487. # Update queue item if this was a scheduled print
  1488. try:
  1489. async with async_session() as db:
  1490. from backend.app.models.print_queue import PrintQueueItem
  1491. # Note: SmartPlug is already imported at module level (line 56)
  1492. # Do NOT import it here as it would shadow the module-level import
  1493. # and cause "cannot access local variable" errors earlier in this function
  1494. result = await db.execute(
  1495. select(PrintQueueItem)
  1496. .where(PrintQueueItem.printer_id == printer_id)
  1497. .where(PrintQueueItem.status == "printing")
  1498. )
  1499. queue_item = result.scalar_one_or_none()
  1500. if queue_item:
  1501. status = data.get("status", "completed")
  1502. queue_item.status = status
  1503. queue_item.completed_at = datetime.now()
  1504. await db.commit()
  1505. logger.info(f"Updated queue item {queue_item.id} status to {status}")
  1506. # MQTT relay - publish queue job completed
  1507. try:
  1508. printer_info = printer_manager.get_printer(printer_id)
  1509. await mqtt_relay.on_queue_job_completed(
  1510. job_id=queue_item.id,
  1511. filename=filename or subtask_name,
  1512. printer_id=printer_id,
  1513. printer_name=printer_info.name if printer_info else "Unknown",
  1514. status=status,
  1515. )
  1516. except Exception:
  1517. pass # Don't fail if MQTT fails
  1518. # Handle auto_off_after - power off printer if requested (after cooldown)
  1519. if queue_item.auto_off_after:
  1520. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1521. plug = result.scalar_one_or_none()
  1522. if plug and plug.enabled:
  1523. logger.info(f"Auto-off requested for printer {printer_id}, waiting for cooldown...")
  1524. async def cooldown_and_poweroff(pid: int, plug_id: int):
  1525. # Wait for nozzle to cool down
  1526. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  1527. # Re-fetch plug in new session
  1528. async with async_session() as new_db:
  1529. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  1530. p = result.scalar_one_or_none()
  1531. if p and p.enabled:
  1532. success = await tasmota_service.turn_off(p)
  1533. if success:
  1534. logger.info(f"Powered off printer {pid} via smart plug '{p.name}'")
  1535. else:
  1536. logger.warning(f"Failed to power off printer {pid} via smart plug")
  1537. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  1538. except Exception as e:
  1539. import logging
  1540. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  1541. log_timing("Queue item update")
  1542. logger.info(f"[CALLBACK] on_print_complete finished for printer {printer_id}, archive {archive_id}")
  1543. # AMS sensor history recording
  1544. _ams_history_task: asyncio.Task | None = None
  1545. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  1546. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  1547. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  1548. _ams_alarm_cooldown: dict[str, datetime] = {} # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  1549. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  1550. async def record_ams_history():
  1551. """Background task to record AMS humidity and temperature data."""
  1552. import logging
  1553. logger = logging.getLogger(__name__)
  1554. # Wait a short time for MQTT connections to establish on startup
  1555. await asyncio.sleep(10)
  1556. while True:
  1557. try:
  1558. from backend.app.models.ams_history import AMSSensorHistory
  1559. from backend.app.models.printer import Printer
  1560. from backend.app.models.settings import Settings
  1561. async with async_session() as db:
  1562. # Get all active printers
  1563. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1564. printers = result.scalars().all()
  1565. # Get alarm thresholds from settings
  1566. humidity_threshold = 60.0 # Default: fair threshold
  1567. temp_threshold = 35.0 # Default: fair threshold
  1568. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1569. setting = result.scalar_one_or_none()
  1570. if setting:
  1571. try:
  1572. humidity_threshold = float(setting.value)
  1573. except (ValueError, TypeError):
  1574. pass
  1575. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  1576. setting = result.scalar_one_or_none()
  1577. if setting:
  1578. try:
  1579. temp_threshold = float(setting.value)
  1580. except (ValueError, TypeError):
  1581. pass
  1582. recorded_count = 0
  1583. for printer in printers:
  1584. # Get current state from printer manager
  1585. state = printer_manager.get_status(printer.id)
  1586. if not state or not state.connected or not state.raw_data:
  1587. continue # Skip disconnected printers - don't use stale data
  1588. raw_data = state.raw_data
  1589. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  1590. continue
  1591. # Record data for each AMS unit
  1592. for ams_data in raw_data["ams"]:
  1593. ams_id = int(ams_data.get("id", 0))
  1594. # Get humidity (prefer humidity_raw)
  1595. humidity_raw = ams_data.get("humidity_raw")
  1596. humidity_idx = ams_data.get("humidity")
  1597. humidity = None
  1598. if humidity_raw is not None:
  1599. try:
  1600. humidity = float(humidity_raw)
  1601. except (ValueError, TypeError):
  1602. pass
  1603. if humidity is None and humidity_idx is not None:
  1604. try:
  1605. humidity = float(humidity_idx)
  1606. except (ValueError, TypeError):
  1607. pass
  1608. # Get temperature
  1609. temperature = None
  1610. temp_str = ams_data.get("temp")
  1611. if temp_str is not None:
  1612. try:
  1613. temperature = float(temp_str)
  1614. except (ValueError, TypeError):
  1615. pass
  1616. # Skip if no data
  1617. if humidity is None and temperature is None:
  1618. continue
  1619. # Record the data point
  1620. history = AMSSensorHistory(
  1621. printer_id=printer.id,
  1622. ams_id=ams_id,
  1623. humidity=humidity,
  1624. humidity_raw=float(humidity_raw) if humidity_raw else None,
  1625. temperature=temperature,
  1626. )
  1627. db.add(history)
  1628. recorded_count += 1
  1629. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  1630. is_ams_ht = ams_id >= 128
  1631. if is_ams_ht:
  1632. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  1633. else:
  1634. ams_label = f"AMS-{chr(65 + ams_id)}"
  1635. # Check humidity alarm (only if above threshold)
  1636. if humidity is not None and humidity > humidity_threshold:
  1637. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  1638. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1639. now = datetime.now()
  1640. if (
  1641. last_alarm is None
  1642. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  1643. ):
  1644. _ams_alarm_cooldown[cooldown_key] = now
  1645. logger.info(
  1646. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  1647. )
  1648. try:
  1649. # Call different notification method based on AMS type
  1650. if is_ams_ht:
  1651. await notification_service.on_ams_ht_humidity_high(
  1652. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1653. )
  1654. else:
  1655. await notification_service.on_ams_humidity_high(
  1656. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1657. )
  1658. except Exception as e:
  1659. logger.warning(f"Failed to send humidity alarm: {e}")
  1660. # Check temperature alarm (only if above threshold)
  1661. if temperature is not None and temperature > temp_threshold:
  1662. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  1663. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1664. now = datetime.now()
  1665. if (
  1666. last_alarm is None
  1667. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  1668. ):
  1669. _ams_alarm_cooldown[cooldown_key] = now
  1670. logger.info(
  1671. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  1672. )
  1673. try:
  1674. # Call different notification method based on AMS type
  1675. if is_ams_ht:
  1676. await notification_service.on_ams_ht_temperature_high(
  1677. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1678. )
  1679. else:
  1680. await notification_service.on_ams_temperature_high(
  1681. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1682. )
  1683. except Exception as e:
  1684. logger.warning(f"Failed to send temperature alarm: {e}")
  1685. await db.commit()
  1686. if recorded_count > 0:
  1687. logger.info(f"Recorded {recorded_count} AMS sensor history entries")
  1688. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  1689. global _ams_cleanup_counter
  1690. _ams_cleanup_counter += 1
  1691. if _ams_cleanup_counter >= 288:
  1692. _ams_cleanup_counter = 0
  1693. # Get retention days from settings
  1694. from backend.app.models.settings import Settings
  1695. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  1696. setting = result.scalar_one_or_none()
  1697. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  1698. cutoff = datetime.now() - timedelta(days=retention_days)
  1699. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  1700. await db.commit()
  1701. if result.rowcount > 0:
  1702. logger.info(
  1703. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  1704. )
  1705. # Wait until next recording interval
  1706. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  1707. except asyncio.CancelledError:
  1708. break
  1709. except Exception as e:
  1710. logger.warning(f"AMS history recording failed: {e}")
  1711. await asyncio.sleep(60) # Wait a bit before retrying
  1712. def start_ams_history_recording():
  1713. """Start the AMS history recording background task."""
  1714. global _ams_history_task
  1715. if _ams_history_task is None:
  1716. _ams_history_task = asyncio.create_task(record_ams_history())
  1717. logging.getLogger(__name__).info("AMS history recording started")
  1718. def stop_ams_history_recording():
  1719. """Stop the AMS history recording background task."""
  1720. global _ams_history_task
  1721. if _ams_history_task:
  1722. _ams_history_task.cancel()
  1723. _ams_history_task = None
  1724. logging.getLogger(__name__).info("AMS history recording stopped")
  1725. # Printer runtime tracking
  1726. _runtime_tracking_task: asyncio.Task | None = None
  1727. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  1728. async def track_printer_runtime():
  1729. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  1730. import logging
  1731. logger = logging.getLogger(__name__)
  1732. # Wait for MQTT connections to establish on startup
  1733. await asyncio.sleep(15)
  1734. while True:
  1735. try:
  1736. from backend.app.models.printer import Printer
  1737. async with async_session() as db:
  1738. # Get all active printers
  1739. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1740. printers = result.scalars().all()
  1741. now = datetime.now()
  1742. updated_count = 0
  1743. needs_commit = False
  1744. for printer in printers:
  1745. # Get current state from printer manager
  1746. state = printer_manager.get_status(printer.id)
  1747. if not state:
  1748. logger.debug(f"[{printer.name}] Runtime tracking: no state available")
  1749. continue
  1750. if not state.connected:
  1751. logger.debug(f"[{printer.name}] Runtime tracking: not connected")
  1752. continue
  1753. # Check if printer is in an active state (RUNNING or PAUSE)
  1754. if state.state in ("RUNNING", "PAUSE"):
  1755. # Calculate time since last update
  1756. if printer.last_runtime_update:
  1757. elapsed = (now - printer.last_runtime_update).total_seconds()
  1758. if elapsed > 0:
  1759. printer.runtime_seconds += int(elapsed)
  1760. updated_count += 1
  1761. needs_commit = True
  1762. logger.debug(
  1763. f"[{printer.name}] Runtime tracking: added {int(elapsed)}s, "
  1764. f"total={printer.runtime_seconds}s ({printer.runtime_seconds / 3600:.2f}h)"
  1765. )
  1766. else:
  1767. # First time seeing printer active - need to commit to save timestamp
  1768. needs_commit = True
  1769. logger.debug(f"[{printer.name}] Runtime tracking: first active detection")
  1770. printer.last_runtime_update = now
  1771. else:
  1772. # Printer is idle/offline - clear last_runtime_update
  1773. if printer.last_runtime_update is not None:
  1774. logger.debug(
  1775. f"[{printer.name}] Runtime tracking: state={state.state}, clearing last_runtime_update"
  1776. )
  1777. printer.last_runtime_update = None
  1778. needs_commit = True
  1779. if needs_commit:
  1780. await db.commit()
  1781. if updated_count > 0:
  1782. logger.debug(f"Updated runtime for {updated_count} printer(s)")
  1783. except asyncio.CancelledError:
  1784. logger.info("Runtime tracking cancelled")
  1785. break
  1786. except Exception as e:
  1787. logger.warning(f"Runtime tracking failed: {e}")
  1788. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  1789. def start_runtime_tracking():
  1790. """Start the printer runtime tracking background task."""
  1791. global _runtime_tracking_task
  1792. if _runtime_tracking_task is None:
  1793. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  1794. logging.getLogger(__name__).info("Printer runtime tracking started")
  1795. def stop_runtime_tracking():
  1796. """Stop the printer runtime tracking background task."""
  1797. global _runtime_tracking_task
  1798. if _runtime_tracking_task:
  1799. _runtime_tracking_task.cancel()
  1800. _runtime_tracking_task = None
  1801. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  1802. @asynccontextmanager
  1803. async def lifespan(app: FastAPI):
  1804. # Startup
  1805. await init_db()
  1806. # Restore debug logging state from previous session
  1807. await init_debug_logging()
  1808. # Set up printer manager callbacks
  1809. loop = asyncio.get_event_loop()
  1810. printer_manager.set_event_loop(loop)
  1811. printer_manager.set_status_change_callback(on_printer_status_change)
  1812. printer_manager.set_print_start_callback(on_print_start)
  1813. printer_manager.set_print_complete_callback(on_print_complete)
  1814. printer_manager.set_ams_change_callback(on_ams_change)
  1815. # Layer change callback for external camera timelapse
  1816. async def on_layer_change(printer_id: int, layer_num: int):
  1817. """Capture timelapse frame on layer change."""
  1818. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  1819. await tl_layer_change(printer_id, layer_num)
  1820. printer_manager.set_layer_change_callback(on_layer_change)
  1821. # Initialize MQTT relay from settings
  1822. async with async_session() as db:
  1823. from backend.app.api.routes.settings import get_setting
  1824. mqtt_settings = {
  1825. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  1826. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  1827. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  1828. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  1829. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  1830. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  1831. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  1832. }
  1833. await mqtt_relay.configure(mqtt_settings)
  1834. # Connect to all active printers
  1835. async with async_session() as db:
  1836. await init_printer_connections(db)
  1837. # Auto-connect to Spoolman if enabled
  1838. async with async_session() as db:
  1839. from backend.app.api.routes.settings import get_setting
  1840. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1841. spoolman_url = await get_setting(db, "spoolman_url")
  1842. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  1843. try:
  1844. client = await init_spoolman_client(spoolman_url)
  1845. if await client.health_check():
  1846. logging.info(f"Auto-connected to Spoolman at {spoolman_url}")
  1847. # Ensure the 'tag' extra field exists for RFID/UUID storage
  1848. await client.ensure_tag_extra_field()
  1849. else:
  1850. logging.warning(f"Spoolman at {spoolman_url} is not reachable")
  1851. except Exception as e:
  1852. logging.warning(f"Failed to auto-connect to Spoolman: {e}")
  1853. # Start the print scheduler
  1854. asyncio.create_task(print_scheduler.run())
  1855. # Start the smart plug scheduler for time-based on/off
  1856. smart_plug_manager.start_scheduler()
  1857. # Resume any pending auto-offs that were interrupted by restart
  1858. await smart_plug_manager.resume_pending_auto_offs()
  1859. # Start the notification digest scheduler
  1860. notification_service.start_digest_scheduler()
  1861. # Start AMS history recording
  1862. start_ams_history_recording()
  1863. # Start printer runtime tracking
  1864. start_runtime_tracking()
  1865. # Initialize virtual printer manager
  1866. from backend.app.services.virtual_printer import virtual_printer_manager
  1867. virtual_printer_manager.set_session_factory(async_session)
  1868. # Auto-start virtual printer if enabled
  1869. async with async_session() as db:
  1870. from backend.app.api.routes.settings import get_setting
  1871. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  1872. if vp_enabled and vp_enabled.lower() == "true":
  1873. vp_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1874. vp_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  1875. vp_model = await get_setting(db, "virtual_printer_model") or ""
  1876. if vp_access_code:
  1877. try:
  1878. await virtual_printer_manager.configure(
  1879. enabled=True,
  1880. access_code=vp_access_code,
  1881. mode=vp_mode,
  1882. model=vp_model,
  1883. )
  1884. logging.info(f"Virtual printer started (model={vp_model or 'default'})")
  1885. except Exception as e:
  1886. logging.warning(f"Failed to start virtual printer: {e}")
  1887. yield
  1888. # Shutdown
  1889. print_scheduler.stop()
  1890. smart_plug_manager.stop_scheduler()
  1891. notification_service.stop_digest_scheduler()
  1892. stop_ams_history_recording()
  1893. stop_runtime_tracking()
  1894. printer_manager.disconnect_all()
  1895. await close_spoolman_client()
  1896. # Stop virtual printer if running
  1897. if virtual_printer_manager.is_enabled:
  1898. await virtual_printer_manager.configure(enabled=False)
  1899. app = FastAPI(
  1900. title=app_settings.app_name,
  1901. description="Archive and manage Bambu Lab 3MF files",
  1902. version=APP_VERSION,
  1903. lifespan=lifespan,
  1904. )
  1905. # API routes
  1906. app.include_router(auth.router, prefix=app_settings.api_prefix)
  1907. app.include_router(users.router, prefix=app_settings.api_prefix)
  1908. app.include_router(printers.router, prefix=app_settings.api_prefix)
  1909. app.include_router(archives.router, prefix=app_settings.api_prefix)
  1910. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  1911. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  1912. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  1913. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  1914. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  1915. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  1916. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  1917. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  1918. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  1919. app.include_router(updates.router, prefix=app_settings.api_prefix)
  1920. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  1921. app.include_router(camera.router, prefix=app_settings.api_prefix)
  1922. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  1923. app.include_router(projects.router, prefix=app_settings.api_prefix)
  1924. app.include_router(library.router, prefix=app_settings.api_prefix)
  1925. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  1926. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  1927. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  1928. app.include_router(system.router, prefix=app_settings.api_prefix)
  1929. app.include_router(support.router, prefix=app_settings.api_prefix)
  1930. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  1931. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  1932. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  1933. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  1934. # Serve static files (React build)
  1935. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  1936. app.mount(
  1937. "/assets",
  1938. StaticFiles(directory=app_settings.static_dir / "assets"),
  1939. name="assets",
  1940. )
  1941. if (app_settings.static_dir / "img").exists():
  1942. app.mount(
  1943. "/img",
  1944. StaticFiles(directory=app_settings.static_dir / "img"),
  1945. name="img",
  1946. )
  1947. if (app_settings.static_dir / "icons").exists():
  1948. app.mount(
  1949. "/icons",
  1950. StaticFiles(directory=app_settings.static_dir / "icons"),
  1951. name="icons",
  1952. )
  1953. @app.get("/")
  1954. async def serve_frontend():
  1955. """Serve the React frontend."""
  1956. index_file = app_settings.static_dir / "index.html"
  1957. if index_file.exists():
  1958. return FileResponse(index_file)
  1959. return {
  1960. "message": "Bambuddy API",
  1961. "docs": "/docs",
  1962. "frontend": "Build and place React app in /static directory",
  1963. }
  1964. @app.get("/health")
  1965. async def health_check():
  1966. """Health check endpoint."""
  1967. return {"status": "healthy"}
  1968. @app.get("/manifest.json")
  1969. async def serve_manifest():
  1970. """Serve PWA manifest."""
  1971. manifest_file = app_settings.static_dir / "manifest.json"
  1972. if manifest_file.exists():
  1973. return FileResponse(manifest_file, media_type="application/manifest+json")
  1974. return {"error": "Manifest not found"}
  1975. @app.get("/sw.js")
  1976. async def serve_service_worker():
  1977. """Serve service worker."""
  1978. sw_file = app_settings.static_dir / "sw.js"
  1979. if sw_file.exists():
  1980. return FileResponse(sw_file, media_type="application/javascript")
  1981. return {"error": "Service worker not found"}
  1982. # Catch-all route for React Router (must be last)
  1983. @app.get("/{full_path:path}")
  1984. async def serve_spa(full_path: str):
  1985. """Serve React app for client-side routing."""
  1986. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  1987. if full_path.startswith("api/"):
  1988. from fastapi import HTTPException
  1989. raise HTTPException(status_code=404, detail="Not found")
  1990. index_file = app_settings.static_dir / "index.html"
  1991. if index_file.exists():
  1992. return FileResponse(index_file)
  1993. return {"error": "Frontend not built"}