main.py 85 KB

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