main.py 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889
  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. camera,
  49. cloud,
  50. discovery,
  51. external_links,
  52. filaments,
  53. kprofiles,
  54. maintenance,
  55. notification_templates,
  56. notifications,
  57. pending_uploads,
  58. print_queue,
  59. printers,
  60. projects,
  61. settings as settings_routes,
  62. smart_plugs,
  63. spoolman,
  64. system,
  65. updates,
  66. webhook,
  67. websocket,
  68. )
  69. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  70. from backend.app.core.database import async_session, init_db
  71. from backend.app.core.websocket import ws_manager
  72. from backend.app.models.smart_plug import SmartPlug
  73. from backend.app.services.archive import ArchiveService
  74. from backend.app.services.bambu_ftp import download_file_async
  75. from backend.app.services.bambu_mqtt import PrinterState
  76. from backend.app.services.notification_service import notification_service
  77. from backend.app.services.print_scheduler import scheduler as print_scheduler
  78. from backend.app.services.printer_manager import (
  79. init_printer_connections,
  80. printer_manager,
  81. printer_state_to_dict,
  82. )
  83. from backend.app.services.smart_plug_manager import smart_plug_manager
  84. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  85. from backend.app.services.tasmota import tasmota_service
  86. from backend.app.services.telemetry import start_telemetry_loop
  87. # Track active prints: {(printer_id, filename): archive_id}
  88. _active_prints: dict[tuple[int, str], int] = {}
  89. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  90. # {(printer_id, filename): archive_id}
  91. _expected_prints: dict[tuple[int, str], int] = {}
  92. # Track starting energy for prints: {archive_id: starting_kwh}
  93. _print_energy_start: dict[int, float] = {}
  94. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  95. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  96. # Store with multiple filename variations to catch different naming patterns
  97. _expected_prints[(printer_id, filename)] = archive_id
  98. # Also store without .3mf extension if present
  99. if filename.endswith(".3mf"):
  100. base = filename[:-4]
  101. _expected_prints[(printer_id, base)] = archive_id
  102. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  103. logging.getLogger(__name__).info(
  104. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  105. )
  106. _last_status_broadcast: dict[int, str] = {}
  107. _nozzle_count_updated: set[int] = set() # Track printers where we've updated nozzle_count
  108. async def _report_spoolman_usage(printer_id: int, archive_id: int, logger):
  109. """Report filament usage to Spoolman after print completion.
  110. This finds the spool by RFID tag_uid from current AMS state and reports
  111. the filament_used_grams from the archive metadata.
  112. """
  113. async with async_session() as db:
  114. from backend.app.api.routes.settings import get_setting
  115. from backend.app.models.archive import PrintArchive
  116. # Check if Spoolman is enabled
  117. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  118. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  119. return
  120. # Get Spoolman URL
  121. spoolman_url = await get_setting(db, "spoolman_url")
  122. if not spoolman_url:
  123. return
  124. # Get or create Spoolman client
  125. client = await get_spoolman_client()
  126. if not client:
  127. client = await init_spoolman_client(spoolman_url)
  128. # Check if Spoolman is reachable
  129. if not await client.health_check():
  130. logger.warning("Spoolman not reachable for usage reporting")
  131. return
  132. # Get archive to find filament usage
  133. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  134. archive = result.scalar_one_or_none()
  135. if not archive or not archive.filament_used_grams:
  136. logger.debug(f"No filament usage data for archive {archive_id}")
  137. return
  138. filament_used = archive.filament_used_grams
  139. logger.info(f"[SPOOLMAN] Archive {archive_id} used {filament_used}g of filament")
  140. # Get current AMS state from printer to find the active spool
  141. state = printer_manager.get_status(printer_id)
  142. if not state or not state.raw_data:
  143. logger.debug("No printer state available for usage reporting")
  144. return
  145. ams_data = state.raw_data.get("ams")
  146. if not ams_data:
  147. logger.debug("No AMS data available for usage reporting")
  148. return
  149. # Find spools with RFID tags in Spoolman and report usage
  150. # For now, we report usage to the first spool found with a matching tag
  151. # TODO: In future, track which specific trays were used during the print
  152. spools_updated = 0
  153. for ams_unit in ams_data:
  154. trays = ams_unit.get("tray", [])
  155. for tray_data in trays:
  156. tag_uid = tray_data.get("tag_uid")
  157. if not tag_uid:
  158. continue
  159. # Find spool in Spoolman by tag
  160. spool = await client.find_spool_by_tag(tag_uid)
  161. if spool:
  162. # Report usage to Spoolman
  163. result = await client.use_spool(spool["id"], filament_used)
  164. if result:
  165. logger.info(
  166. f"[SPOOLMAN] Reported {filament_used}g usage to spool {spool['id']} (tag: {tag_uid})"
  167. )
  168. spools_updated += 1
  169. # Only report to one spool for single-material prints
  170. # Multi-material prints would need more sophisticated tracking
  171. return
  172. if spools_updated == 0:
  173. logger.debug(f"No matching Spoolman spools found for printer {printer_id}")
  174. async def on_printer_status_change(printer_id: int, state: PrinterState):
  175. """Handle printer status changes - broadcast via WebSocket."""
  176. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  177. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  178. temps = state.temperatures or {}
  179. nozzle_temp = round(temps.get("nozzle", 0))
  180. bed_temp = round(temps.get("bed", 0))
  181. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  182. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  183. # Auto-detect dual-nozzle printers from MQTT temperature data
  184. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  185. _nozzle_count_updated.add(printer_id)
  186. # Update nozzle_count in database
  187. async with async_session() as db:
  188. from backend.app.models.printer import Printer
  189. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  190. printer = result.scalar_one_or_none()
  191. if printer and printer.nozzle_count != 2:
  192. printer.nozzle_count = 2
  193. await db.commit()
  194. logging.getLogger(__name__).info(
  195. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  196. )
  197. # Include target temps for heating phase detection
  198. bed_target = round(temps.get("bed_target", 0))
  199. nozzle_target = round(temps.get("nozzle_target", 0))
  200. status_key = (
  201. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  202. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  203. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  204. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}"
  205. )
  206. if _last_status_broadcast.get(printer_id) == status_key:
  207. return # No change, skip broadcast
  208. _last_status_broadcast[printer_id] = status_key
  209. await ws_manager.send_printer_status(
  210. printer_id,
  211. printer_state_to_dict(state, printer_id),
  212. )
  213. async def on_ams_change(printer_id: int, ams_data: list):
  214. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  215. import logging
  216. logger = logging.getLogger(__name__)
  217. try:
  218. async with async_session() as db:
  219. from backend.app.api.routes.settings import get_setting
  220. from backend.app.models.printer import Printer
  221. # Check if Spoolman is enabled
  222. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  223. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  224. return
  225. # Check sync mode
  226. sync_mode = await get_setting(db, "spoolman_sync_mode")
  227. if sync_mode and sync_mode != "auto":
  228. return # Only sync on auto mode
  229. # Get Spoolman URL
  230. spoolman_url = await get_setting(db, "spoolman_url")
  231. if not spoolman_url:
  232. return
  233. # Get or create Spoolman client
  234. client = await get_spoolman_client()
  235. if not client:
  236. client = await init_spoolman_client(spoolman_url)
  237. # Check if Spoolman is reachable
  238. if not await client.health_check():
  239. logger.warning(f"Spoolman not reachable at {spoolman_url}")
  240. return
  241. # Get printer name for location
  242. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  243. printer = result.scalar_one_or_none()
  244. printer_name = printer.name if printer else f"Printer {printer_id}"
  245. # Sync each AMS tray
  246. synced = 0
  247. for ams_unit in ams_data:
  248. ams_id = int(ams_unit.get("id", 0))
  249. trays = ams_unit.get("tray", [])
  250. for tray_data in trays:
  251. tray = client.parse_ams_tray(ams_id, tray_data)
  252. if not tray:
  253. continue # Empty tray
  254. try:
  255. result = await client.sync_ams_tray(tray, printer_name)
  256. if result:
  257. synced += 1
  258. except Exception as e:
  259. logger.error(f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}")
  260. if synced > 0:
  261. logger.info(f"Auto-synced {synced} AMS trays to Spoolman for printer {printer_id}")
  262. except Exception as e:
  263. import logging
  264. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  265. async def _send_print_start_notification(
  266. printer_id: int,
  267. data: dict,
  268. archive_data: dict | None = None,
  269. logger=None,
  270. ):
  271. """Helper to send print start notification with optional archive data."""
  272. if logger is None:
  273. import logging
  274. logger = logging.getLogger(__name__)
  275. try:
  276. async with async_session() as db:
  277. from backend.app.models.printer import Printer
  278. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  279. printer = result.scalar_one_or_none()
  280. printer_name = printer.name if printer else f"Printer {printer_id}"
  281. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  282. except Exception as e:
  283. logger.warning(f"Notification on_print_start failed: {e}")
  284. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  285. """Extract printable objects from an archive's 3MF file and store in printer state."""
  286. try:
  287. from backend.app.services.archive import extract_printable_objects_from_3mf
  288. file_path = app_settings.base_dir / archive.file_path
  289. if file_path.exists() and str(file_path).endswith(".3mf"):
  290. with open(file_path, "rb") as f:
  291. threemf_data = f.read()
  292. # Extract with positions for UI overlay
  293. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  294. if printable_objects:
  295. client = printer_manager.get_client(printer_id)
  296. if client:
  297. client.state.printable_objects = printable_objects
  298. client.state.printable_objects_bbox_all = bbox_all
  299. client.state.skipped_objects = []
  300. logger.info(f"Loaded {len(printable_objects)} printable objects for printer {printer_id}")
  301. except Exception as e:
  302. logger.debug(f"Failed to extract printable objects from archive: {e}")
  303. async def on_print_start(printer_id: int, data: dict):
  304. """Handle print start - archive the 3MF file immediately."""
  305. import logging
  306. logger = logging.getLogger(__name__)
  307. logger.info(f"[CALLBACK] on_print_start called for printer {printer_id}, data keys: {list(data.keys())}")
  308. await ws_manager.send_print_start(printer_id, data)
  309. # Track if notification was sent (to avoid sending twice)
  310. notification_sent = False
  311. # Smart plug automation: turn on plug when print starts
  312. try:
  313. async with async_session() as db:
  314. await smart_plug_manager.on_print_start(printer_id, db)
  315. except Exception as e:
  316. logger.warning(f"Smart plug on_print_start failed: {e}")
  317. async with async_session() as db:
  318. from backend.app.models.printer import Printer
  319. from backend.app.services.bambu_ftp import list_files_async
  320. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  321. printer = result.scalar_one_or_none()
  322. if not printer or not printer.auto_archive:
  323. # Send notification without archive data (auto-archive disabled)
  324. logger.info(
  325. f"[CALLBACK] Skipping archive - printer: {printer is not None}, auto_archive: {printer.auto_archive if printer else 'N/A'}"
  326. )
  327. if not notification_sent:
  328. await _send_print_start_notification(printer_id, data, logger=logger)
  329. return
  330. # Get the filename and subtask_name
  331. filename = data.get("filename", "")
  332. subtask_name = data.get("subtask_name", "")
  333. logger.info(f"[CALLBACK] Print start detected - filename: {filename}, subtask: {subtask_name}")
  334. if not filename and not subtask_name:
  335. # Send notification without archive data (no filename)
  336. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  337. if not notification_sent:
  338. await _send_print_start_notification(printer_id, data, logger=logger)
  339. return
  340. # Check if this is an expected print from reprint/scheduled
  341. # Build list of possible keys to check
  342. expected_keys = []
  343. if subtask_name:
  344. expected_keys.append((printer_id, subtask_name))
  345. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  346. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  347. if filename:
  348. fname = filename.split("/")[-1] if "/" in filename else filename
  349. expected_keys.append((printer_id, fname))
  350. # Strip extensions to match
  351. base = fname.replace(".gcode", "").replace(".3mf", "")
  352. expected_keys.append((printer_id, base))
  353. expected_keys.append((printer_id, f"{base}.3mf"))
  354. expected_archive_id = None
  355. for key in expected_keys:
  356. expected_archive_id = _expected_prints.pop(key, None)
  357. if expected_archive_id:
  358. # Clean up other possible keys for this print
  359. for other_key in expected_keys:
  360. _expected_prints.pop(other_key, None)
  361. break
  362. if expected_archive_id:
  363. # This is a reprint/scheduled print - use existing archive, don't create new one
  364. logger.info(f"Using expected archive {expected_archive_id} for print (skipping duplicate)")
  365. from datetime import datetime
  366. from backend.app.models.archive import PrintArchive
  367. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  368. archive = result.scalar_one_or_none()
  369. if archive:
  370. # Update archive status to printing
  371. archive.status = "printing"
  372. archive.started_at = datetime.now()
  373. await db.commit()
  374. # Track as active print
  375. _active_prints[(printer_id, archive.filename)] = archive.id
  376. if subtask_name:
  377. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  378. # Set up energy tracking
  379. try:
  380. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  381. plug = plug_result.scalar_one_or_none()
  382. logger.info(
  383. f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  384. )
  385. if plug:
  386. energy = await tasmota_service.get_energy(plug)
  387. logger.info(f"[ENERGY] Energy response from plug: {energy}")
  388. if energy and energy.get("total") is not None:
  389. _print_energy_start[archive.id] = energy["total"]
  390. logger.info(
  391. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  392. )
  393. else:
  394. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  395. else:
  396. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  397. except Exception as e:
  398. logger.warning(f"Failed to record starting energy: {e}")
  399. await ws_manager.send_archive_updated(
  400. {
  401. "id": archive.id,
  402. "status": "printing",
  403. }
  404. )
  405. # Send notification with archive data (reprint/scheduled)
  406. if not notification_sent:
  407. archive_data = {"print_time_seconds": archive.print_time_seconds}
  408. await _send_print_start_notification(printer_id, data, archive_data, logger)
  409. # Extract printable objects from the archived 3MF file
  410. _load_objects_from_archive(archive, printer_id, logger)
  411. return # Skip creating a new archive
  412. # Check if there's already a "printing" archive for this printer/file
  413. # This prevents duplicates when backend restarts during an active print
  414. from backend.app.models.archive import PrintArchive
  415. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  416. existing = await db.execute(
  417. select(PrintArchive)
  418. .where(PrintArchive.printer_id == printer_id)
  419. .where(PrintArchive.status == "printing")
  420. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  421. .order_by(PrintArchive.created_at.desc())
  422. .limit(1)
  423. )
  424. existing_archive = existing.scalar_one_or_none()
  425. if existing_archive:
  426. # Check if archive is stale (older than 4 hours) - likely a failed/cancelled print
  427. # that didn't get properly updated
  428. archive_age = datetime.now(UTC) - existing_archive.created_at.replace(tzinfo=UTC)
  429. if archive_age.total_seconds() > 4 * 60 * 60: # 4 hours
  430. logger.warning(
  431. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}), "
  432. f"marking as cancelled and creating new archive"
  433. )
  434. existing_archive.status = "cancelled"
  435. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  436. await db.commit()
  437. # Fall through to create new archive (don't return)
  438. existing_archive = None # Clear so we don't use stale archive
  439. else:
  440. logger.info(
  441. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  442. )
  443. # Track this as the active print
  444. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  445. # Also set up energy tracking if not already tracked
  446. if existing_archive.id not in _print_energy_start:
  447. try:
  448. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  449. plug = plug_result.scalar_one_or_none()
  450. if plug:
  451. energy = await tasmota_service.get_energy(plug)
  452. if energy and energy.get("total") is not None:
  453. _print_energy_start[existing_archive.id] = energy["total"]
  454. logger.info(
  455. f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh"
  456. )
  457. except Exception as e:
  458. logger.warning(f"Failed to record starting energy for existing archive: {e}")
  459. # Send notification with archive data (existing archive)
  460. if not notification_sent:
  461. archive_data = {"print_time_seconds": existing_archive.print_time_seconds}
  462. await _send_print_start_notification(printer_id, data, archive_data, logger)
  463. # Extract printable objects from the archived 3MF file
  464. _load_objects_from_archive(existing_archive, printer_id, logger)
  465. return
  466. # Build list of possible 3MF filenames to try
  467. possible_names = []
  468. # Bambu printers typically store files as "Name.gcode.3mf"
  469. # The subtask_name is usually the best source for the filename
  470. if subtask_name:
  471. # Try common Bambu naming patterns
  472. possible_names.append(f"{subtask_name}.gcode.3mf")
  473. possible_names.append(f"{subtask_name}.3mf")
  474. # Try original filename with .3mf extension
  475. if filename:
  476. # Extract just the filename part, not the full path
  477. fname = filename.split("/")[-1] if "/" in filename else filename
  478. if fname.endswith(".3mf"):
  479. possible_names.append(fname)
  480. elif fname.endswith(".gcode"):
  481. base = fname.rsplit(".", 1)[0]
  482. possible_names.append(f"{base}.gcode.3mf")
  483. possible_names.append(f"{base}.3mf")
  484. else:
  485. possible_names.append(f"{fname}.gcode.3mf")
  486. possible_names.append(f"{fname}.3mf")
  487. # Remove duplicates while preserving order
  488. seen = set()
  489. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  490. logger.info(f"Trying filenames: {possible_names}")
  491. # Try to find and download the 3MF file
  492. temp_path = None
  493. downloaded_filename = None
  494. for try_filename in possible_names:
  495. if not try_filename.endswith(".3mf"):
  496. continue
  497. remote_paths = [
  498. f"/cache/{try_filename}",
  499. f"/model/{try_filename}",
  500. f"/{try_filename}",
  501. ]
  502. temp_path = app_settings.archive_dir / "temp" / try_filename
  503. temp_path.parent.mkdir(parents=True, exist_ok=True)
  504. for remote_path in remote_paths:
  505. logger.debug(f"Trying FTP download: {remote_path}")
  506. try:
  507. if await download_file_async(
  508. printer.ip_address,
  509. printer.access_code,
  510. remote_path,
  511. temp_path,
  512. ):
  513. downloaded_filename = try_filename
  514. logger.info(f"Downloaded: {remote_path}")
  515. break
  516. except Exception as e:
  517. logger.debug(f"FTP download failed for {remote_path}: {e}")
  518. if downloaded_filename:
  519. break
  520. # If still not found, try listing /cache to find matching file
  521. if not downloaded_filename and (filename or subtask_name):
  522. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  523. logger.info(f"Direct FTP download failed, listing /cache to find '{search_term}'")
  524. try:
  525. cache_files = await list_files_async(printer.ip_address, printer.access_code, "/cache")
  526. threemf_files = [f.get("name") for f in cache_files if f.get("name", "").endswith(".3mf")]
  527. logger.info(
  528. f"Found {len(threemf_files)} 3MF files in /cache: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  529. )
  530. for f in cache_files:
  531. if f.get("is_directory"):
  532. continue
  533. fname = f.get("name", "")
  534. if fname.endswith(".3mf") and search_term in fname.lower():
  535. logger.info(f"Found matching file: {fname}")
  536. temp_path = app_settings.archive_dir / "temp" / fname
  537. temp_path.parent.mkdir(parents=True, exist_ok=True)
  538. if await download_file_async(
  539. printer.ip_address,
  540. printer.access_code,
  541. f"/cache/{fname}",
  542. temp_path,
  543. ):
  544. downloaded_filename = fname
  545. logger.info(f"Found and downloaded from cache: {fname}")
  546. break
  547. except Exception as e:
  548. logger.warning(f"Failed to list cache: {e}")
  549. if not downloaded_filename or not temp_path:
  550. logger.warning(f"Could not find 3MF file for print: {filename or subtask_name}")
  551. # Create a fallback archive without 3MF data so the print is still tracked
  552. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  553. try:
  554. from backend.app.models.archive import PrintArchive
  555. # Derive print name from subtask_name or filename
  556. print_name = subtask_name or filename
  557. if print_name:
  558. # Clean up the name (remove extensions, path parts)
  559. print_name = print_name.split("/")[-1]
  560. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  561. else:
  562. print_name = "Unknown Print"
  563. # Create minimal archive entry
  564. fallback_archive = PrintArchive(
  565. printer_id=printer_id,
  566. filename=filename or f"{print_name}.3mf",
  567. file_path="", # Empty - no 3MF file available
  568. file_size=0,
  569. print_name=print_name,
  570. status="printing",
  571. started_at=datetime.now(),
  572. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  573. )
  574. db.add(fallback_archive)
  575. await db.commit()
  576. await db.refresh(fallback_archive)
  577. logger.info(f"Created fallback archive {fallback_archive.id} for {print_name} (no 3MF available)")
  578. # Track as active print
  579. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  580. if filename:
  581. _active_prints[(printer_id, filename)] = fallback_archive.id
  582. if subtask_name:
  583. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  584. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  585. # Record starting energy if smart plug available
  586. try:
  587. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  588. plug = plug_result.scalar_one_or_none()
  589. if plug:
  590. energy = await tasmota_service.get_energy(plug)
  591. if energy and energy.get("total") is not None:
  592. _print_energy_start[fallback_archive.id] = energy["total"]
  593. logger.info(
  594. f"[ENERGY] Recorded starting energy for fallback archive {fallback_archive.id}: {energy['total']} kWh"
  595. )
  596. except Exception as e:
  597. logger.warning(f"Failed to record starting energy for fallback: {e}")
  598. # Send WebSocket notification
  599. await ws_manager.send_archive_created(
  600. {
  601. "id": fallback_archive.id,
  602. "printer_id": fallback_archive.printer_id,
  603. "filename": fallback_archive.filename,
  604. "print_name": fallback_archive.print_name,
  605. "status": fallback_archive.status,
  606. }
  607. )
  608. # Send notification without archive data (file not found)
  609. if not notification_sent:
  610. await _send_print_start_notification(printer_id, data, logger=logger)
  611. return
  612. except Exception as e:
  613. logger.error(f"Failed to create fallback archive: {e}")
  614. # Send notification without archive data (file not found)
  615. if not notification_sent:
  616. await _send_print_start_notification(printer_id, data, logger=logger)
  617. return
  618. try:
  619. # Archive the file with status "printing"
  620. service = ArchiveService(db)
  621. archive = await service.archive_print(
  622. printer_id=printer_id,
  623. source_file=temp_path,
  624. print_data={**data, "status": "printing"},
  625. )
  626. if archive:
  627. # Track this active print (use both original filename and downloaded filename)
  628. _active_prints[(printer_id, downloaded_filename)] = archive.id
  629. if filename and filename != downloaded_filename:
  630. _active_prints[(printer_id, filename)] = archive.id
  631. if subtask_name:
  632. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  633. logger.info(f"Created archive {archive.id} for {downloaded_filename}")
  634. # Record starting energy from smart plug if available
  635. try:
  636. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  637. plug = plug_result.scalar_one_or_none()
  638. logger.info(
  639. f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  640. )
  641. if plug:
  642. energy = await tasmota_service.get_energy(plug)
  643. logger.info(f"[ENERGY] Auto-archive energy response: {energy}")
  644. if energy and energy.get("total") is not None:
  645. _print_energy_start[archive.id] = energy["total"]
  646. logger.info(
  647. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  648. )
  649. else:
  650. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  651. else:
  652. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  653. except Exception as e:
  654. logger.warning(f"Failed to record starting energy: {e}")
  655. await ws_manager.send_archive_created(
  656. {
  657. "id": archive.id,
  658. "printer_id": archive.printer_id,
  659. "filename": archive.filename,
  660. "print_name": archive.print_name,
  661. "status": archive.status,
  662. }
  663. )
  664. # Send notification with archive data (new archive created)
  665. if not notification_sent:
  666. archive_data = {"print_time_seconds": archive.print_time_seconds}
  667. await _send_print_start_notification(printer_id, data, archive_data, logger)
  668. notification_sent = True
  669. # Extract printable objects for skip object functionality
  670. try:
  671. from backend.app.services.archive import extract_printable_objects_from_3mf
  672. with open(temp_path, "rb") as f:
  673. threemf_data = f.read()
  674. # Extract with positions for UI overlay
  675. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  676. threemf_data, include_positions=True
  677. )
  678. if printable_objects:
  679. # Store objects in printer state
  680. client = printer_manager.get_client(printer_id)
  681. if client:
  682. client.state.printable_objects = printable_objects
  683. client.state.printable_objects_bbox_all = bbox_all
  684. client.state.skipped_objects = [] # Reset skipped objects for new print
  685. logger.info(f"Loaded {len(printable_objects)} printable objects for printer {printer_id}")
  686. except Exception as e:
  687. logger.debug(f"Failed to extract printable objects: {e}")
  688. finally:
  689. if temp_path and temp_path.exists():
  690. temp_path.unlink()
  691. async def _scan_for_timelapse_with_retries(archive_id: int):
  692. """
  693. Scan for timelapse with retries.
  694. The printer encodes the timelapse quickly after print completion.
  695. We just need a short delay then grab the most recent file.
  696. Since we KNOW timelapse was active (from MQTT ipcam data), the most recent
  697. file in /timelapse is our target. Retries handle FTP connection issues.
  698. """
  699. import logging
  700. logger = logging.getLogger(__name__)
  701. # Short delays - printer usually finishes encoding within seconds
  702. retry_delays = [5, 10, 20]
  703. for attempt, delay in enumerate(retry_delays, 1):
  704. logger.info(
  705. f"[TIMELAPSE] Attempt {attempt}/{len(retry_delays)}: waiting {delay}s before scanning for archive {archive_id}"
  706. )
  707. await asyncio.sleep(delay)
  708. try:
  709. async with async_session() as db:
  710. from backend.app.models.printer import Printer
  711. from backend.app.services.bambu_ftp import download_file_bytes_async, list_files_async
  712. # Get archive (ArchiveService from module-level import)
  713. service = ArchiveService(db)
  714. archive = await service.get_archive(archive_id)
  715. if not archive:
  716. logger.warning(f"[TIMELAPSE] Archive {archive_id} not found, stopping retries")
  717. return
  718. if archive.timelapse_path:
  719. logger.info(f"[TIMELAPSE] Archive {archive_id} already has timelapse attached, stopping retries")
  720. return
  721. if not archive.printer_id:
  722. logger.warning(f"[TIMELAPSE] Archive {archive_id} has no printer, stopping retries")
  723. return
  724. # Get printer
  725. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  726. printer = result.scalar_one_or_none()
  727. if not printer:
  728. logger.warning(f"[TIMELAPSE] Printer not found for archive {archive_id}, stopping retries")
  729. return
  730. # Scan timelapse directory on printer
  731. # H2D may store in different locations than X1C
  732. files = []
  733. found_path = None
  734. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  735. try:
  736. found_files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  737. if found_files:
  738. files = found_files
  739. found_path = timelapse_path
  740. logger.info(f"[TIMELAPSE] Attempt {attempt}: Found {len(files)} files in {timelapse_path}")
  741. break
  742. except Exception as e:
  743. logger.debug(f"[TIMELAPSE] Path {timelapse_path} failed: {e}")
  744. continue
  745. if not files:
  746. logger.info(f"[TIMELAPSE] Attempt {attempt}: No timelapse files found on printer, will retry")
  747. continue
  748. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  749. # Log ALL mp4 files found for debugging
  750. logger.info(f"[TIMELAPSE] Attempt {attempt}: Found {len(mp4_files)} MP4 files in {found_path}")
  751. for f in mp4_files[:5]: # Log first 5
  752. logger.info(f"[TIMELAPSE] - {f.get('name')}, mtime={f.get('mtime')}")
  753. if not mp4_files:
  754. logger.info(f"[TIMELAPSE] Attempt {attempt}: No MP4 files found, will retry")
  755. continue
  756. # Sort by mtime descending to get most recent file
  757. mp4_files_with_mtime = [f for f in mp4_files if f.get("mtime")]
  758. if not mp4_files_with_mtime:
  759. logger.info(f"[TIMELAPSE] Attempt {attempt}: No MP4 files with mtime found, will retry")
  760. continue
  761. mp4_files_with_mtime.sort(key=lambda x: x.get("mtime"), reverse=True)
  762. most_recent = mp4_files_with_mtime[0]
  763. file_name = most_recent.get("name")
  764. logger.info(f"[TIMELAPSE] Attempt {attempt}: Most recent file: {file_name}")
  765. # Since we KNOW timelapse was active (from MQTT), just grab the most recent file
  766. remote_path = most_recent.get("path") or f"/timelapse/{file_name}"
  767. logger.info(f"[TIMELAPSE] Downloading {file_name} for archive {archive_id}")
  768. timelapse_data = await download_file_bytes_async(printer.ip_address, printer.access_code, remote_path)
  769. if timelapse_data:
  770. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  771. if success:
  772. logger.info(f"[TIMELAPSE] Successfully attached timelapse to archive {archive_id}")
  773. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  774. return # Success!
  775. else:
  776. logger.warning(f"[TIMELAPSE] Failed to attach timelapse to archive {archive_id}")
  777. else:
  778. logger.warning(f"[TIMELAPSE] Attempt {attempt}: Failed to download, will retry")
  779. except Exception as e:
  780. logger.warning(f"[TIMELAPSE] Attempt {attempt} failed with error: {e}")
  781. logger.warning(f"[TIMELAPSE] All {len(retry_delays)} attempts exhausted for archive {archive_id}, giving up")
  782. async def on_print_complete(printer_id: int, data: dict):
  783. """Handle print completion - update the archive status."""
  784. import logging
  785. import time
  786. logger = logging.getLogger(__name__)
  787. start_time = time.time()
  788. def log_timing(section: str):
  789. elapsed = time.time() - start_time
  790. logger.info(f"[TIMING] {section}: {elapsed:.3f}s elapsed")
  791. logger.info(f"[CALLBACK] on_print_complete started for printer {printer_id}")
  792. try:
  793. ws_data = {
  794. "status": data.get("status"),
  795. "filename": data.get("filename"),
  796. "subtask_name": data.get("subtask_name"),
  797. "timelapse_was_active": data.get("timelapse_was_active"),
  798. }
  799. await ws_manager.send_print_complete(printer_id, ws_data)
  800. log_timing("WebSocket send_print_complete")
  801. except Exception as e:
  802. logger.warning(f"[CALLBACK] WebSocket send_print_complete failed: {e}")
  803. filename = data.get("filename", "")
  804. subtask_name = data.get("subtask_name", "")
  805. if not filename and not subtask_name:
  806. logger.warning("Print complete without filename or subtask_name")
  807. return
  808. logger.info(f"Print complete - filename: {filename}, subtask: {subtask_name}, status: {data.get('status')}")
  809. # Build list of possible keys to try (matching how they were registered in on_print_start)
  810. possible_keys = []
  811. # Try subtask_name variations first (most reliable for matching)
  812. if subtask_name:
  813. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  814. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  815. possible_keys.append((printer_id, subtask_name))
  816. # Try filename variations
  817. if filename:
  818. # Extract just the filename if it's a path
  819. fname = filename.split("/")[-1] if "/" in filename else filename
  820. if fname.endswith(".3mf"):
  821. possible_keys.append((printer_id, fname))
  822. elif fname.endswith(".gcode"):
  823. base_name = fname.rsplit(".", 1)[0]
  824. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  825. possible_keys.append((printer_id, f"{base_name}.3mf"))
  826. possible_keys.append((printer_id, fname))
  827. else:
  828. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  829. possible_keys.append((printer_id, f"{fname}.3mf"))
  830. possible_keys.append((printer_id, fname))
  831. # Also try full path versions
  832. if filename.endswith(".3mf"):
  833. possible_keys.append((printer_id, filename))
  834. elif filename.endswith(".gcode"):
  835. base_name = filename.rsplit(".", 1)[0]
  836. possible_keys.append((printer_id, f"{base_name}.3mf"))
  837. possible_keys.append((printer_id, filename))
  838. else:
  839. possible_keys.append((printer_id, f"{filename}.3mf"))
  840. possible_keys.append((printer_id, filename))
  841. # Find the archive for this print
  842. logger.info(f"Looking for archive in _active_prints, keys to try: {possible_keys[:5]}...")
  843. logger.info(f"Current _active_prints: {list(_active_prints.keys())}")
  844. archive_id = None
  845. for key in possible_keys:
  846. archive_id = _active_prints.pop(key, None)
  847. if archive_id:
  848. logger.info(f"Found archive {archive_id} with key {key}")
  849. # Also clean up any other keys pointing to this archive
  850. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  851. for k in keys_to_remove:
  852. _active_prints.pop(k, None)
  853. break
  854. if not archive_id:
  855. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  856. async with async_session() as db:
  857. from backend.app.models.archive import PrintArchive
  858. # Try matching by subtask_name (stored as print_name) first
  859. if subtask_name:
  860. result = await db.execute(
  861. select(PrintArchive)
  862. .where(PrintArchive.printer_id == printer_id)
  863. .where(PrintArchive.status == "printing")
  864. .where(
  865. or_(
  866. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  867. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  868. )
  869. )
  870. .order_by(PrintArchive.created_at.desc())
  871. .limit(1)
  872. )
  873. archive = result.scalar_one_or_none()
  874. if archive:
  875. archive_id = archive.id
  876. logger.info(f"Found archive {archive_id} by subtask_name match: {subtask_name}")
  877. # Also try by filename
  878. if not archive_id and filename:
  879. result = await db.execute(
  880. select(PrintArchive)
  881. .where(PrintArchive.printer_id == printer_id)
  882. .where(PrintArchive.filename == filename)
  883. .where(PrintArchive.status == "printing")
  884. .order_by(PrintArchive.created_at.desc())
  885. .limit(1)
  886. )
  887. archive = result.scalar_one_or_none()
  888. if archive:
  889. archive_id = archive.id
  890. if not archive_id:
  891. logger.warning(f"Could not find archive for print complete: filename={filename}, subtask={subtask_name}")
  892. return
  893. log_timing("Archive lookup")
  894. # Update archive status
  895. logger.info(f"[ARCHIVE] Updating archive {archive_id} status...")
  896. try:
  897. async with async_session() as db:
  898. service = ArchiveService(db)
  899. status = data.get("status", "completed")
  900. # Auto-detect failure reason
  901. failure_reason = None
  902. if status == "aborted":
  903. failure_reason = "User cancelled"
  904. logger.info("[ARCHIVE] Print was aborted by user, setting failure_reason='User cancelled'")
  905. elif status == "failed":
  906. # Try to determine failure reason from HMS errors
  907. hms_errors = data.get("hms_errors", [])
  908. if hms_errors:
  909. logger.info(f"[ARCHIVE] HMS errors at failure: {hms_errors}")
  910. # Map known HMS error modules to failure reasons
  911. # Module 0x07 = Filament, 0x0C = MC (Motion Controller), etc.
  912. for err in hms_errors:
  913. module = err.get("module", 0)
  914. if module == 0x07: # Filament module
  915. failure_reason = "Filament runout"
  916. break
  917. elif module == 0x0C: # Motion controller
  918. failure_reason = "Layer shift"
  919. break
  920. elif module == 0x05: # Nozzle/extruder
  921. failure_reason = "Clogged nozzle"
  922. break
  923. if failure_reason:
  924. logger.info(f"[ARCHIVE] Detected failure_reason from HMS: {failure_reason}")
  925. else:
  926. logger.info("[ARCHIVE] No HMS errors available to determine failure reason")
  927. await service.update_archive_status(
  928. archive_id,
  929. status=status,
  930. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  931. failure_reason=failure_reason,
  932. )
  933. logger.info(f"[ARCHIVE] Archive {archive_id} status updated to {status}, failure_reason={failure_reason}")
  934. await ws_manager.send_archive_updated(
  935. {
  936. "id": archive_id,
  937. "status": status,
  938. }
  939. )
  940. logger.info(f"[ARCHIVE] WebSocket notification sent for archive {archive_id}")
  941. except Exception as e:
  942. logger.error(f"[ARCHIVE] Failed to update archive {archive_id} status: {e}", exc_info=True)
  943. # Continue with other operations even if archive update fails
  944. log_timing("Archive status update")
  945. # Report filament usage to Spoolman if print completed successfully
  946. if data.get("status") == "completed":
  947. try:
  948. await _report_spoolman_usage(printer_id, archive_id, logger)
  949. log_timing("Spoolman usage report")
  950. except Exception as e:
  951. logger.warning(f"Spoolman usage reporting failed: {e}")
  952. # Run slow operations as background tasks to avoid blocking the event loop
  953. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  954. starting_kwh = _print_energy_start.pop(archive_id, None)
  955. async def _background_energy_calculation():
  956. """Calculate and save energy usage in background."""
  957. try:
  958. logger.info(f"[ENERGY-BG] Starting energy calculation for archive {archive_id}")
  959. async with async_session() as db:
  960. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  961. plug = plug_result.scalar_one_or_none()
  962. if plug:
  963. energy = await tasmota_service.get_energy(plug)
  964. logger.info(f"[ENERGY-BG] Energy response: {energy}")
  965. energy_used = None
  966. if starting_kwh is not None and energy and energy.get("total") is not None:
  967. ending_kwh = energy["total"]
  968. energy_used = round(ending_kwh - starting_kwh, 4)
  969. logger.info(f"[ENERGY-BG] Per-print energy: {energy_used} kWh")
  970. if energy_used is not None and energy_used >= 0:
  971. from backend.app.api.routes.settings import get_setting
  972. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  973. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  974. energy_cost = round(energy_used * cost_per_kwh, 2)
  975. from backend.app.models.archive import PrintArchive
  976. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  977. archive = result.scalar_one_or_none()
  978. if archive:
  979. archive.energy_kwh = energy_used
  980. archive.energy_cost = energy_cost
  981. await db.commit()
  982. logger.info(f"[ENERGY-BG] Saved: {energy_used} kWh, cost={energy_cost}")
  983. else:
  984. logger.info(f"[ENERGY-BG] No smart plug for printer {printer_id}")
  985. except Exception as e:
  986. logger.warning(f"[ENERGY-BG] Failed: {e}")
  987. async def _background_finish_photo():
  988. """Capture finish photo in background."""
  989. try:
  990. logger.info(f"[PHOTO-BG] Starting finish photo capture for archive {archive_id}")
  991. from backend.app.api.routes.camera import _active_streams, get_buffered_frame
  992. async with async_session() as db:
  993. from backend.app.api.routes.settings import get_setting
  994. capture_enabled = await get_setting(db, "capture_finish_photo")
  995. if capture_enabled is None or capture_enabled.lower() == "true":
  996. from backend.app.models.printer import Printer
  997. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  998. printer = result.scalar_one_or_none()
  999. if printer and archive_id:
  1000. from backend.app.models.archive import PrintArchive
  1001. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1002. archive = result.scalar_one_or_none()
  1003. if archive:
  1004. import uuid
  1005. from datetime import datetime
  1006. from pathlib import Path
  1007. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  1008. photo_filename = None
  1009. # Check if camera stream is active - use buffered frame to avoid freeze
  1010. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1011. buffered_frame = get_buffered_frame(printer_id)
  1012. if active_for_printer and buffered_frame:
  1013. # Use frame from active stream
  1014. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  1015. photos_dir = archive_dir / "photos"
  1016. photos_dir.mkdir(parents=True, exist_ok=True)
  1017. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1018. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  1019. photo_path = photos_dir / photo_filename
  1020. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  1021. logger.info(f"[PHOTO-BG] Saved buffered frame: {photo_filename}")
  1022. else:
  1023. # No active stream - capture new frame
  1024. from backend.app.services.camera import capture_finish_photo
  1025. photo_filename = await capture_finish_photo(
  1026. printer_id=printer_id,
  1027. ip_address=printer.ip_address,
  1028. access_code=printer.access_code,
  1029. model=printer.model,
  1030. archive_dir=archive_dir,
  1031. )
  1032. if photo_filename:
  1033. photos = archive.photos or []
  1034. photos.append(photo_filename)
  1035. archive.photos = photos
  1036. await db.commit()
  1037. logger.info(f"[PHOTO-BG] Saved: {photo_filename}")
  1038. except Exception as e:
  1039. logger.warning(f"[PHOTO-BG] Failed: {e}")
  1040. asyncio.create_task(_background_energy_calculation())
  1041. asyncio.create_task(_background_finish_photo()) # Skips if camera stream active
  1042. log_timing("Background tasks scheduled (energy, photo)")
  1043. # Also run smart plug, notifications, and maintenance as background tasks
  1044. print_status = data.get("status", "completed")
  1045. async def _background_smart_plug():
  1046. """Handle smart plug automation in background."""
  1047. try:
  1048. logger.info(f"[AUTO-OFF-BG] Starting smart plug automation for printer {printer_id}")
  1049. async with async_session() as db:
  1050. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  1051. logger.info("[AUTO-OFF-BG] Completed")
  1052. except Exception as e:
  1053. logger.warning(f"[AUTO-OFF-BG] Failed: {e}")
  1054. async def _background_notifications():
  1055. """Send print complete notifications in background."""
  1056. try:
  1057. logger.info(f"[NOTIFY-BG] Starting notifications for printer {printer_id}")
  1058. async with async_session() as db:
  1059. from backend.app.models.archive import PrintArchive
  1060. from backend.app.models.printer import Printer
  1061. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1062. printer = result.scalar_one_or_none()
  1063. printer_name = printer.name if printer else f"Printer {printer_id}"
  1064. archive_data = None
  1065. if archive_id:
  1066. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1067. archive = archive_result.scalar_one_or_none()
  1068. if archive:
  1069. archive_data = {
  1070. "print_time_seconds": archive.print_time_seconds,
  1071. "actual_filament_grams": archive.filament_used_grams,
  1072. "failure_reason": archive.failure_reason,
  1073. }
  1074. await notification_service.on_print_complete(
  1075. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  1076. )
  1077. logger.info("[NOTIFY-BG] Completed")
  1078. except Exception as e:
  1079. logger.warning(f"[NOTIFY-BG] Failed: {e}")
  1080. async def _background_maintenance_check():
  1081. """Check for maintenance due in background."""
  1082. if print_status != "completed":
  1083. return
  1084. try:
  1085. logger.info(f"[MAINT-BG] Starting maintenance check for printer {printer_id}")
  1086. async with async_session() as db:
  1087. from backend.app.models.printer import Printer
  1088. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1089. printer = result.scalar_one_or_none()
  1090. printer_name = printer.name if printer else f"Printer {printer_id}"
  1091. await ensure_default_types(db)
  1092. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  1093. items_needing_attention = [
  1094. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  1095. for item in overview.maintenance_items
  1096. if item.enabled and (item.is_due or item.is_warning)
  1097. ]
  1098. if items_needing_attention:
  1099. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  1100. logger.info(f"[MAINT-BG] Sent notification: {len(items_needing_attention)} items need attention")
  1101. else:
  1102. logger.info("[MAINT-BG] Completed (no items need attention)")
  1103. except Exception as e:
  1104. logger.warning(f"[MAINT-BG] Failed: {e}")
  1105. asyncio.create_task(_background_smart_plug())
  1106. asyncio.create_task(_background_notifications())
  1107. asyncio.create_task(_background_maintenance_check())
  1108. log_timing("All background tasks scheduled")
  1109. # Auto-scan for timelapse if recording was active during the print
  1110. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  1111. logger.info(f"[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive {archive_id}")
  1112. # Schedule timelapse scan as background task with retries
  1113. # The printer needs time to encode the video after print completion
  1114. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id))
  1115. log_timing("Timelapse scan scheduled")
  1116. # Update queue item if this was a scheduled print
  1117. try:
  1118. async with async_session() as db:
  1119. from backend.app.models.print_queue import PrintQueueItem
  1120. # Note: SmartPlug is already imported at module level (line 56)
  1121. # Do NOT import it here as it would shadow the module-level import
  1122. # and cause "cannot access local variable" errors earlier in this function
  1123. result = await db.execute(
  1124. select(PrintQueueItem)
  1125. .where(PrintQueueItem.printer_id == printer_id)
  1126. .where(PrintQueueItem.status == "printing")
  1127. )
  1128. queue_item = result.scalar_one_or_none()
  1129. if queue_item:
  1130. status = data.get("status", "completed")
  1131. queue_item.status = status
  1132. queue_item.completed_at = datetime.now()
  1133. await db.commit()
  1134. logger.info(f"Updated queue item {queue_item.id} status to {status}")
  1135. # Handle auto_off_after - power off printer if requested (after cooldown)
  1136. if queue_item.auto_off_after:
  1137. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1138. plug = result.scalar_one_or_none()
  1139. if plug and plug.enabled:
  1140. logger.info(f"Auto-off requested for printer {printer_id}, waiting for cooldown...")
  1141. async def cooldown_and_poweroff(pid: int, plug_id: int):
  1142. # Wait for nozzle to cool down
  1143. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  1144. # Re-fetch plug in new session
  1145. async with async_session() as new_db:
  1146. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  1147. p = result.scalar_one_or_none()
  1148. if p and p.enabled:
  1149. success = await tasmota_service.turn_off(p)
  1150. if success:
  1151. logger.info(f"Powered off printer {pid} via smart plug '{p.name}'")
  1152. else:
  1153. logger.warning(f"Failed to power off printer {pid} via smart plug")
  1154. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  1155. except Exception as e:
  1156. import logging
  1157. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  1158. log_timing("Queue item update")
  1159. logger.info(f"[CALLBACK] on_print_complete finished for printer {printer_id}, archive {archive_id}")
  1160. # AMS sensor history recording
  1161. _ams_history_task: asyncio.Task | None = None
  1162. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  1163. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  1164. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  1165. _ams_alarm_cooldown: dict[str, datetime] = {} # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  1166. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  1167. async def record_ams_history():
  1168. """Background task to record AMS humidity and temperature data."""
  1169. import logging
  1170. logger = logging.getLogger(__name__)
  1171. # Wait a short time for MQTT connections to establish on startup
  1172. await asyncio.sleep(10)
  1173. while True:
  1174. try:
  1175. from backend.app.models.ams_history import AMSSensorHistory
  1176. from backend.app.models.printer import Printer
  1177. from backend.app.models.settings import Settings
  1178. async with async_session() as db:
  1179. # Get all active printers
  1180. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1181. printers = result.scalars().all()
  1182. # Get alarm thresholds from settings
  1183. humidity_threshold = 60.0 # Default: fair threshold
  1184. temp_threshold = 35.0 # Default: fair threshold
  1185. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1186. setting = result.scalar_one_or_none()
  1187. if setting:
  1188. try:
  1189. humidity_threshold = float(setting.value)
  1190. except (ValueError, TypeError):
  1191. pass
  1192. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  1193. setting = result.scalar_one_or_none()
  1194. if setting:
  1195. try:
  1196. temp_threshold = float(setting.value)
  1197. except (ValueError, TypeError):
  1198. pass
  1199. recorded_count = 0
  1200. for printer in printers:
  1201. # Get current state from printer manager
  1202. state = printer_manager.get_status(printer.id)
  1203. if not state or not state.connected or not state.raw_data:
  1204. continue # Skip disconnected printers - don't use stale data
  1205. raw_data = state.raw_data
  1206. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  1207. continue
  1208. # Record data for each AMS unit
  1209. for ams_data in raw_data["ams"]:
  1210. ams_id = int(ams_data.get("id", 0))
  1211. # Get humidity (prefer humidity_raw)
  1212. humidity_raw = ams_data.get("humidity_raw")
  1213. humidity_idx = ams_data.get("humidity")
  1214. humidity = None
  1215. if humidity_raw is not None:
  1216. try:
  1217. humidity = float(humidity_raw)
  1218. except (ValueError, TypeError):
  1219. pass
  1220. if humidity is None and humidity_idx is not None:
  1221. try:
  1222. humidity = float(humidity_idx)
  1223. except (ValueError, TypeError):
  1224. pass
  1225. # Get temperature
  1226. temperature = None
  1227. temp_str = ams_data.get("temp")
  1228. if temp_str is not None:
  1229. try:
  1230. temperature = float(temp_str)
  1231. except (ValueError, TypeError):
  1232. pass
  1233. # Skip if no data
  1234. if humidity is None and temperature is None:
  1235. continue
  1236. # Record the data point
  1237. history = AMSSensorHistory(
  1238. printer_id=printer.id,
  1239. ams_id=ams_id,
  1240. humidity=humidity,
  1241. humidity_raw=float(humidity_raw) if humidity_raw else None,
  1242. temperature=temperature,
  1243. )
  1244. db.add(history)
  1245. recorded_count += 1
  1246. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  1247. is_ams_ht = ams_id >= 128
  1248. if is_ams_ht:
  1249. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  1250. else:
  1251. ams_label = f"AMS-{chr(65 + ams_id)}"
  1252. # Check humidity alarm (only if above threshold)
  1253. if humidity is not None and humidity > humidity_threshold:
  1254. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  1255. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1256. now = datetime.now()
  1257. if (
  1258. last_alarm is None
  1259. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  1260. ):
  1261. _ams_alarm_cooldown[cooldown_key] = now
  1262. logger.info(
  1263. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  1264. )
  1265. try:
  1266. # Call different notification method based on AMS type
  1267. if is_ams_ht:
  1268. await notification_service.on_ams_ht_humidity_high(
  1269. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1270. )
  1271. else:
  1272. await notification_service.on_ams_humidity_high(
  1273. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1274. )
  1275. except Exception as e:
  1276. logger.warning(f"Failed to send humidity alarm: {e}")
  1277. # Check temperature alarm (only if above threshold)
  1278. if temperature is not None and temperature > temp_threshold:
  1279. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  1280. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1281. now = datetime.now()
  1282. if (
  1283. last_alarm is None
  1284. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  1285. ):
  1286. _ams_alarm_cooldown[cooldown_key] = now
  1287. logger.info(
  1288. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  1289. )
  1290. try:
  1291. # Call different notification method based on AMS type
  1292. if is_ams_ht:
  1293. await notification_service.on_ams_ht_temperature_high(
  1294. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1295. )
  1296. else:
  1297. await notification_service.on_ams_temperature_high(
  1298. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1299. )
  1300. except Exception as e:
  1301. logger.warning(f"Failed to send temperature alarm: {e}")
  1302. await db.commit()
  1303. if recorded_count > 0:
  1304. logger.info(f"Recorded {recorded_count} AMS sensor history entries")
  1305. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  1306. global _ams_cleanup_counter
  1307. _ams_cleanup_counter += 1
  1308. if _ams_cleanup_counter >= 288:
  1309. _ams_cleanup_counter = 0
  1310. # Get retention days from settings
  1311. from backend.app.models.settings import Settings
  1312. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  1313. setting = result.scalar_one_or_none()
  1314. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  1315. cutoff = datetime.now() - timedelta(days=retention_days)
  1316. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  1317. await db.commit()
  1318. if result.rowcount > 0:
  1319. logger.info(
  1320. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  1321. )
  1322. # Wait until next recording interval
  1323. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  1324. except asyncio.CancelledError:
  1325. break
  1326. except Exception as e:
  1327. logger.warning(f"AMS history recording failed: {e}")
  1328. await asyncio.sleep(60) # Wait a bit before retrying
  1329. def start_ams_history_recording():
  1330. """Start the AMS history recording background task."""
  1331. global _ams_history_task
  1332. if _ams_history_task is None:
  1333. _ams_history_task = asyncio.create_task(record_ams_history())
  1334. logging.getLogger(__name__).info("AMS history recording started")
  1335. def stop_ams_history_recording():
  1336. """Stop the AMS history recording background task."""
  1337. global _ams_history_task
  1338. if _ams_history_task:
  1339. _ams_history_task.cancel()
  1340. _ams_history_task = None
  1341. logging.getLogger(__name__).info("AMS history recording stopped")
  1342. # Printer runtime tracking
  1343. _runtime_tracking_task: asyncio.Task | None = None
  1344. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  1345. async def track_printer_runtime():
  1346. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  1347. import logging
  1348. logger = logging.getLogger(__name__)
  1349. # Wait for MQTT connections to establish on startup
  1350. await asyncio.sleep(15)
  1351. while True:
  1352. try:
  1353. from backend.app.models.printer import Printer
  1354. async with async_session() as db:
  1355. # Get all active printers
  1356. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1357. printers = result.scalars().all()
  1358. now = datetime.now()
  1359. updated_count = 0
  1360. needs_commit = False
  1361. for printer in printers:
  1362. # Get current state from printer manager
  1363. state = printer_manager.get_status(printer.id)
  1364. if not state:
  1365. logger.debug(f"[{printer.name}] Runtime tracking: no state available")
  1366. continue
  1367. if not state.connected:
  1368. logger.debug(f"[{printer.name}] Runtime tracking: not connected")
  1369. continue
  1370. # Check if printer is in an active state (RUNNING or PAUSE)
  1371. if state.state in ("RUNNING", "PAUSE"):
  1372. # Calculate time since last update
  1373. if printer.last_runtime_update:
  1374. elapsed = (now - printer.last_runtime_update).total_seconds()
  1375. # Sanity check: don't add more than 2x the interval (handles server restarts)
  1376. if elapsed > 0 and elapsed < RUNTIME_TRACKING_INTERVAL * 2:
  1377. printer.runtime_seconds += int(elapsed)
  1378. updated_count += 1
  1379. needs_commit = True
  1380. logger.debug(
  1381. f"[{printer.name}] Runtime tracking: added {int(elapsed)}s, "
  1382. f"total={printer.runtime_seconds}s ({printer.runtime_seconds / 3600:.2f}h)"
  1383. )
  1384. else:
  1385. logger.warning(
  1386. f"[{printer.name}] Runtime tracking: skipped elapsed={elapsed:.1f}s "
  1387. f"(outside valid range 0-{RUNTIME_TRACKING_INTERVAL * 2}s)"
  1388. )
  1389. else:
  1390. # First time seeing printer active - need to commit to save timestamp
  1391. needs_commit = True
  1392. logger.debug(f"[{printer.name}] Runtime tracking: first active detection")
  1393. printer.last_runtime_update = now
  1394. else:
  1395. # Printer is idle/offline - clear last_runtime_update
  1396. if printer.last_runtime_update is not None:
  1397. logger.debug(
  1398. f"[{printer.name}] Runtime tracking: state={state.state}, clearing last_runtime_update"
  1399. )
  1400. printer.last_runtime_update = None
  1401. needs_commit = True
  1402. if needs_commit:
  1403. await db.commit()
  1404. if updated_count > 0:
  1405. logger.debug(f"Updated runtime for {updated_count} printer(s)")
  1406. except asyncio.CancelledError:
  1407. logger.info("Runtime tracking cancelled")
  1408. break
  1409. except Exception as e:
  1410. logger.warning(f"Runtime tracking failed: {e}")
  1411. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  1412. def start_runtime_tracking():
  1413. """Start the printer runtime tracking background task."""
  1414. global _runtime_tracking_task
  1415. if _runtime_tracking_task is None:
  1416. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  1417. logging.getLogger(__name__).info("Printer runtime tracking started")
  1418. def stop_runtime_tracking():
  1419. """Stop the printer runtime tracking background task."""
  1420. global _runtime_tracking_task
  1421. if _runtime_tracking_task:
  1422. _runtime_tracking_task.cancel()
  1423. _runtime_tracking_task = None
  1424. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  1425. @asynccontextmanager
  1426. async def lifespan(app: FastAPI):
  1427. # Startup
  1428. await init_db()
  1429. # Set up printer manager callbacks
  1430. loop = asyncio.get_event_loop()
  1431. printer_manager.set_event_loop(loop)
  1432. printer_manager.set_status_change_callback(on_printer_status_change)
  1433. printer_manager.set_print_start_callback(on_print_start)
  1434. printer_manager.set_print_complete_callback(on_print_complete)
  1435. printer_manager.set_ams_change_callback(on_ams_change)
  1436. # Connect to all active printers
  1437. async with async_session() as db:
  1438. await init_printer_connections(db)
  1439. # Auto-connect to Spoolman if enabled
  1440. async with async_session() as db:
  1441. from backend.app.api.routes.settings import get_setting
  1442. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1443. spoolman_url = await get_setting(db, "spoolman_url")
  1444. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  1445. try:
  1446. client = await init_spoolman_client(spoolman_url)
  1447. if await client.health_check():
  1448. logging.info(f"Auto-connected to Spoolman at {spoolman_url}")
  1449. else:
  1450. logging.warning(f"Spoolman at {spoolman_url} is not reachable")
  1451. except Exception as e:
  1452. logging.warning(f"Failed to auto-connect to Spoolman: {e}")
  1453. # Start the print scheduler
  1454. asyncio.create_task(print_scheduler.run())
  1455. # Start the smart plug scheduler for time-based on/off
  1456. smart_plug_manager.start_scheduler()
  1457. # Resume any pending auto-offs that were interrupted by restart
  1458. await smart_plug_manager.resume_pending_auto_offs()
  1459. # Start the notification digest scheduler
  1460. notification_service.start_digest_scheduler()
  1461. # Start AMS history recording
  1462. start_ams_history_recording()
  1463. # Start printer runtime tracking
  1464. start_runtime_tracking()
  1465. # Start anonymous telemetry (opt-out via settings)
  1466. asyncio.create_task(start_telemetry_loop(async_session))
  1467. # Initialize virtual printer manager
  1468. from backend.app.services.virtual_printer import virtual_printer_manager
  1469. virtual_printer_manager.set_session_factory(async_session)
  1470. # Auto-start virtual printer if enabled
  1471. async with async_session() as db:
  1472. from backend.app.api.routes.settings import get_setting
  1473. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  1474. if vp_enabled and vp_enabled.lower() == "true":
  1475. vp_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  1476. vp_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  1477. vp_model = await get_setting(db, "virtual_printer_model") or ""
  1478. if vp_access_code:
  1479. try:
  1480. await virtual_printer_manager.configure(
  1481. enabled=True,
  1482. access_code=vp_access_code,
  1483. mode=vp_mode,
  1484. model=vp_model,
  1485. )
  1486. logging.info(f"Virtual printer started (model={vp_model or 'default'})")
  1487. except Exception as e:
  1488. logging.warning(f"Failed to start virtual printer: {e}")
  1489. yield
  1490. # Shutdown
  1491. print_scheduler.stop()
  1492. smart_plug_manager.stop_scheduler()
  1493. notification_service.stop_digest_scheduler()
  1494. stop_ams_history_recording()
  1495. stop_runtime_tracking()
  1496. printer_manager.disconnect_all()
  1497. await close_spoolman_client()
  1498. # Stop virtual printer if running
  1499. if virtual_printer_manager.is_enabled:
  1500. await virtual_printer_manager.configure(enabled=False)
  1501. app = FastAPI(
  1502. title=app_settings.app_name,
  1503. description="Archive and manage Bambu Lab 3MF files",
  1504. version=APP_VERSION,
  1505. lifespan=lifespan,
  1506. )
  1507. # API routes
  1508. app.include_router(printers.router, prefix=app_settings.api_prefix)
  1509. app.include_router(archives.router, prefix=app_settings.api_prefix)
  1510. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  1511. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  1512. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  1513. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  1514. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  1515. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  1516. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  1517. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  1518. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  1519. app.include_router(updates.router, prefix=app_settings.api_prefix)
  1520. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  1521. app.include_router(camera.router, prefix=app_settings.api_prefix)
  1522. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  1523. app.include_router(projects.router, prefix=app_settings.api_prefix)
  1524. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  1525. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  1526. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  1527. app.include_router(system.router, prefix=app_settings.api_prefix)
  1528. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  1529. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  1530. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  1531. # Serve static files (React build)
  1532. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  1533. app.mount(
  1534. "/assets",
  1535. StaticFiles(directory=app_settings.static_dir / "assets"),
  1536. name="assets",
  1537. )
  1538. if (app_settings.static_dir / "img").exists():
  1539. app.mount(
  1540. "/img",
  1541. StaticFiles(directory=app_settings.static_dir / "img"),
  1542. name="img",
  1543. )
  1544. if (app_settings.static_dir / "icons").exists():
  1545. app.mount(
  1546. "/icons",
  1547. StaticFiles(directory=app_settings.static_dir / "icons"),
  1548. name="icons",
  1549. )
  1550. @app.get("/")
  1551. async def serve_frontend():
  1552. """Serve the React frontend."""
  1553. index_file = app_settings.static_dir / "index.html"
  1554. if index_file.exists():
  1555. return FileResponse(index_file)
  1556. return {
  1557. "message": "Bambuddy API",
  1558. "docs": "/docs",
  1559. "frontend": "Build and place React app in /static directory",
  1560. }
  1561. @app.get("/health")
  1562. async def health_check():
  1563. """Health check endpoint."""
  1564. return {"status": "healthy"}
  1565. @app.get("/manifest.json")
  1566. async def serve_manifest():
  1567. """Serve PWA manifest."""
  1568. manifest_file = app_settings.static_dir / "manifest.json"
  1569. if manifest_file.exists():
  1570. return FileResponse(manifest_file, media_type="application/manifest+json")
  1571. return {"error": "Manifest not found"}
  1572. @app.get("/sw.js")
  1573. async def serve_service_worker():
  1574. """Serve service worker."""
  1575. sw_file = app_settings.static_dir / "sw.js"
  1576. if sw_file.exists():
  1577. return FileResponse(sw_file, media_type="application/javascript")
  1578. return {"error": "Service worker not found"}
  1579. # Catch-all route for React Router (must be last)
  1580. @app.get("/{full_path:path}")
  1581. async def serve_spa(full_path: str):
  1582. """Serve React app for client-side routing."""
  1583. # Don't intercept API routes
  1584. if full_path.startswith("api/"):
  1585. return {"error": "Not found"}
  1586. index_file = app_settings.static_dir / "index.html"
  1587. if index_file.exists():
  1588. return FileResponse(index_file)
  1589. return {"error": "Frontend not built"}