main.py 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. import asyncio
  2. import logging
  3. import os
  4. from datetime import datetime, timedelta
  5. from contextlib import asynccontextmanager
  6. from pathlib import Path
  7. from logging.handlers import RotatingFileHandler
  8. from fastapi import FastAPI
  9. # Import settings first for logging configuration
  10. from backend.app.core.config import settings as app_settings, APP_VERSION
  11. # Configure logging based on settings
  12. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  13. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  14. log_level = getattr(logging, log_level_str, logging.INFO)
  15. log_format = '%(asctime)s %(levelname)s [%(name)s] %(message)s'
  16. # Create root logger
  17. root_logger = logging.getLogger()
  18. root_logger.setLevel(log_level)
  19. # Console handler - always enabled
  20. console_handler = logging.StreamHandler()
  21. console_handler.setLevel(log_level)
  22. console_handler.setFormatter(logging.Formatter(log_format))
  23. root_logger.addHandler(console_handler)
  24. # File handler - only in production or if explicitly enabled
  25. if app_settings.log_to_file:
  26. log_file = app_settings.log_dir / "bambuddy.log"
  27. file_handler = RotatingFileHandler(
  28. log_file,
  29. maxBytes=5*1024*1024, # 5MB
  30. backupCount=3,
  31. encoding='utf-8'
  32. )
  33. file_handler.setLevel(log_level)
  34. file_handler.setFormatter(logging.Formatter(log_format))
  35. root_logger.addHandler(file_handler)
  36. logging.info(f"Logging to file: {log_file}")
  37. # Reduce noise from third-party libraries in production
  38. if not app_settings.debug:
  39. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  40. logging.getLogger("httpcore").setLevel(logging.WARNING)
  41. logging.getLogger("httpx").setLevel(logging.WARNING)
  42. logging.info(f"Bambuddy starting - debug={app_settings.debug}, log_level={log_level_str}")
  43. from fastapi.staticfiles import StaticFiles
  44. from fastapi.responses import FileResponse
  45. from backend.app.core.database import init_db, async_session
  46. from sqlalchemy import select, or_, delete
  47. from backend.app.core.websocket import ws_manager
  48. from backend.app.api.routes import printers, archives, websocket, filaments, cloud, smart_plugs, print_queue, kprofiles, notifications, notification_templates, spoolman, updates, maintenance, camera, external_links, projects, api_keys, webhook, ams_history, system
  49. from backend.app.api.routes import settings as settings_routes
  50. from backend.app.services.notification_service import notification_service
  51. from backend.app.services.printer_manager import (
  52. printer_manager,
  53. printer_state_to_dict,
  54. init_printer_connections,
  55. )
  56. from backend.app.services.print_scheduler import scheduler as print_scheduler
  57. from backend.app.services.bambu_mqtt import PrinterState
  58. from backend.app.services.archive import ArchiveService
  59. from backend.app.services.bambu_ftp import download_file_async
  60. from backend.app.services.smart_plug_manager import smart_plug_manager
  61. from backend.app.services.tasmota import tasmota_service
  62. from backend.app.models.smart_plug import SmartPlug
  63. from backend.app.services.spoolman import get_spoolman_client, init_spoolman_client, close_spoolman_client
  64. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  65. from backend.app.services.telemetry import start_telemetry_loop
  66. # Track active prints: {(printer_id, filename): archive_id}
  67. _active_prints: dict[tuple[int, str], int] = {}
  68. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  69. # {(printer_id, filename): archive_id}
  70. _expected_prints: dict[tuple[int, str], int] = {}
  71. # Track starting energy for prints: {archive_id: starting_kwh}
  72. _print_energy_start: dict[int, float] = {}
  73. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  74. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  75. # Store with multiple filename variations to catch different naming patterns
  76. _expected_prints[(printer_id, filename)] = archive_id
  77. # Also store without .3mf extension if present
  78. if filename.endswith(".3mf"):
  79. base = filename[:-4]
  80. _expected_prints[(printer_id, base)] = archive_id
  81. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  82. logging.getLogger(__name__).info(
  83. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  84. )
  85. _last_status_broadcast: dict[int, str] = {}
  86. _nozzle_count_updated: set[int] = set() # Track printers where we've updated nozzle_count
  87. async def _report_spoolman_usage(printer_id: int, archive_id: int, logger):
  88. """Report filament usage to Spoolman after print completion.
  89. This finds the spool by RFID tag_uid from current AMS state and reports
  90. the filament_used_grams from the archive metadata.
  91. """
  92. async with async_session() as db:
  93. from backend.app.api.routes.settings import get_setting
  94. from backend.app.models.archive import PrintArchive
  95. # Check if Spoolman is enabled
  96. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  97. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  98. return
  99. # Get Spoolman URL
  100. spoolman_url = await get_setting(db, "spoolman_url")
  101. if not spoolman_url:
  102. return
  103. # Get or create Spoolman client
  104. client = await get_spoolman_client()
  105. if not client:
  106. client = await init_spoolman_client(spoolman_url)
  107. # Check if Spoolman is reachable
  108. if not await client.health_check():
  109. logger.warning(f"Spoolman not reachable for usage reporting")
  110. return
  111. # Get archive to find filament usage
  112. result = await db.execute(
  113. select(PrintArchive).where(PrintArchive.id == archive_id)
  114. )
  115. archive = result.scalar_one_or_none()
  116. if not archive or not archive.filament_used_grams:
  117. logger.debug(f"No filament usage data for archive {archive_id}")
  118. return
  119. filament_used = archive.filament_used_grams
  120. logger.info(f"[SPOOLMAN] Archive {archive_id} used {filament_used}g of filament")
  121. # Get current AMS state from printer to find the active spool
  122. state = printer_manager.get_status(printer_id)
  123. if not state or not state.raw_data:
  124. logger.debug(f"No printer state available for usage reporting")
  125. return
  126. ams_data = state.raw_data.get("ams")
  127. if not ams_data:
  128. logger.debug(f"No AMS data available for usage reporting")
  129. return
  130. # Find spools with RFID tags in Spoolman and report usage
  131. # For now, we report usage to the first spool found with a matching tag
  132. # TODO: In future, track which specific trays were used during the print
  133. spools_updated = 0
  134. for ams_unit in ams_data:
  135. ams_id = int(ams_unit.get("id", 0))
  136. trays = ams_unit.get("tray", [])
  137. for tray_data in trays:
  138. tag_uid = tray_data.get("tag_uid")
  139. if not tag_uid:
  140. continue
  141. # Find spool in Spoolman by tag
  142. spool = await client.find_spool_by_tag(tag_uid)
  143. if spool:
  144. # Report usage to Spoolman
  145. result = await client.use_spool(spool["id"], filament_used)
  146. if result:
  147. logger.info(
  148. f"[SPOOLMAN] Reported {filament_used}g usage to spool {spool['id']} "
  149. f"(tag: {tag_uid})"
  150. )
  151. spools_updated += 1
  152. # Only report to one spool for single-material prints
  153. # Multi-material prints would need more sophisticated tracking
  154. return
  155. if spools_updated == 0:
  156. logger.debug(f"No matching Spoolman spools found for printer {printer_id}")
  157. async def on_printer_status_change(printer_id: int, state: PrinterState):
  158. """Handle printer status changes - broadcast via WebSocket."""
  159. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  160. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  161. temps = state.temperatures or {}
  162. nozzle_temp = round(temps.get("nozzle", 0))
  163. bed_temp = round(temps.get("bed", 0))
  164. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  165. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  166. # Auto-detect dual-nozzle printers from MQTT temperature data
  167. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  168. _nozzle_count_updated.add(printer_id)
  169. # Update nozzle_count in database
  170. async with async_session() as db:
  171. from backend.app.models.printer import Printer
  172. result = await db.execute(
  173. select(Printer).where(Printer.id == printer_id)
  174. )
  175. printer = result.scalar_one_or_none()
  176. if printer and printer.nozzle_count != 2:
  177. printer.nozzle_count = 2
  178. await db.commit()
  179. logging.getLogger(__name__).info(
  180. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  181. )
  182. status_key = (
  183. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  184. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}"
  185. )
  186. if _last_status_broadcast.get(printer_id) == status_key:
  187. return # No change, skip broadcast
  188. _last_status_broadcast[printer_id] = status_key
  189. await ws_manager.send_printer_status(
  190. printer_id,
  191. printer_state_to_dict(state, printer_id),
  192. )
  193. async def on_ams_change(printer_id: int, ams_data: list):
  194. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  195. import logging
  196. logger = logging.getLogger(__name__)
  197. try:
  198. async with async_session() as db:
  199. from backend.app.api.routes.settings import get_setting
  200. from backend.app.models.printer import Printer
  201. # Check if Spoolman is enabled
  202. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  203. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  204. return
  205. # Check sync mode
  206. sync_mode = await get_setting(db, "spoolman_sync_mode")
  207. if sync_mode and sync_mode != "auto":
  208. return # Only sync on auto mode
  209. # Get Spoolman URL
  210. spoolman_url = await get_setting(db, "spoolman_url")
  211. if not spoolman_url:
  212. return
  213. # Get or create Spoolman client
  214. client = await get_spoolman_client()
  215. if not client:
  216. client = await init_spoolman_client(spoolman_url)
  217. # Check if Spoolman is reachable
  218. if not await client.health_check():
  219. logger.warning(f"Spoolman not reachable at {spoolman_url}")
  220. return
  221. # Get printer name for location
  222. result = await db.execute(
  223. select(Printer).where(Printer.id == printer_id)
  224. )
  225. printer = result.scalar_one_or_none()
  226. printer_name = printer.name if printer else f"Printer {printer_id}"
  227. # Sync each AMS tray
  228. synced = 0
  229. for ams_unit in ams_data:
  230. ams_id = int(ams_unit.get("id", 0))
  231. trays = ams_unit.get("tray", [])
  232. for tray_data in trays:
  233. tray = client.parse_ams_tray(ams_id, tray_data)
  234. if not tray:
  235. continue # Empty tray
  236. try:
  237. result = await client.sync_ams_tray(tray, printer_name)
  238. if result:
  239. synced += 1
  240. except Exception as e:
  241. logger.error(f"Error syncing AMS {ams_id} tray {tray.tray_id}: {e}")
  242. if synced > 0:
  243. logger.info(f"Auto-synced {synced} AMS trays to Spoolman for printer {printer_id}")
  244. except Exception as e:
  245. import logging
  246. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  247. async def _send_print_start_notification(
  248. printer_id: int,
  249. data: dict,
  250. archive_data: dict | None = None,
  251. logger=None,
  252. ):
  253. """Helper to send print start notification with optional archive data."""
  254. if logger is None:
  255. import logging
  256. logger = logging.getLogger(__name__)
  257. try:
  258. async with async_session() as db:
  259. from backend.app.models.printer import Printer
  260. result = await db.execute(
  261. select(Printer).where(Printer.id == printer_id)
  262. )
  263. printer = result.scalar_one_or_none()
  264. printer_name = printer.name if printer else f"Printer {printer_id}"
  265. await notification_service.on_print_start(
  266. printer_id, printer_name, data, db, archive_data=archive_data
  267. )
  268. except Exception as e:
  269. logger.warning(f"Notification on_print_start failed: {e}")
  270. async def on_print_start(printer_id: int, data: dict):
  271. """Handle print start - archive the 3MF file immediately."""
  272. import logging
  273. logger = logging.getLogger(__name__)
  274. await ws_manager.send_print_start(printer_id, data)
  275. # Track if notification was sent (to avoid sending twice)
  276. notification_sent = False
  277. # Smart plug automation: turn on plug when print starts
  278. try:
  279. async with async_session() as db:
  280. await smart_plug_manager.on_print_start(printer_id, db)
  281. except Exception as e:
  282. logger.warning(f"Smart plug on_print_start failed: {e}")
  283. async with async_session() as db:
  284. from backend.app.models.printer import Printer
  285. from backend.app.services.bambu_ftp import list_files_async
  286. result = await db.execute(
  287. select(Printer).where(Printer.id == printer_id)
  288. )
  289. printer = result.scalar_one_or_none()
  290. if not printer or not printer.auto_archive:
  291. # Send notification without archive data (auto-archive disabled)
  292. if not notification_sent:
  293. await _send_print_start_notification(printer_id, data, logger=logger)
  294. return
  295. # Get the filename and subtask_name
  296. filename = data.get("filename", "")
  297. subtask_name = data.get("subtask_name", "")
  298. logger.info(f"Print start detected - filename: {filename}, subtask: {subtask_name}")
  299. if not filename and not subtask_name:
  300. # Send notification without archive data (no filename)
  301. if not notification_sent:
  302. await _send_print_start_notification(printer_id, data, logger=logger)
  303. return
  304. # Check if this is an expected print from reprint/scheduled
  305. # Build list of possible keys to check
  306. expected_keys = []
  307. if subtask_name:
  308. expected_keys.append((printer_id, subtask_name))
  309. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  310. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  311. if filename:
  312. fname = filename.split("/")[-1] if "/" in filename else filename
  313. expected_keys.append((printer_id, fname))
  314. # Strip extensions to match
  315. base = fname.replace(".gcode", "").replace(".3mf", "")
  316. expected_keys.append((printer_id, base))
  317. expected_keys.append((printer_id, f"{base}.3mf"))
  318. expected_archive_id = None
  319. for key in expected_keys:
  320. expected_archive_id = _expected_prints.pop(key, None)
  321. if expected_archive_id:
  322. # Clean up other possible keys for this print
  323. for other_key in expected_keys:
  324. _expected_prints.pop(other_key, None)
  325. break
  326. if expected_archive_id:
  327. # This is a reprint/scheduled print - use existing archive, don't create new one
  328. logger.info(f"Using expected archive {expected_archive_id} for print (skipping duplicate)")
  329. from backend.app.models.archive import PrintArchive
  330. from datetime import datetime
  331. result = await db.execute(
  332. select(PrintArchive).where(PrintArchive.id == expected_archive_id)
  333. )
  334. archive = result.scalar_one_or_none()
  335. if archive:
  336. # Update archive status to printing
  337. archive.status = "printing"
  338. archive.started_at = datetime.now()
  339. await db.commit()
  340. # Track as active print
  341. _active_prints[(printer_id, archive.filename)] = archive.id
  342. if subtask_name:
  343. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  344. # Set up energy tracking
  345. try:
  346. plug_result = await db.execute(
  347. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  348. )
  349. plug = plug_result.scalar_one_or_none()
  350. logger.info(f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}")
  351. if plug:
  352. energy = await tasmota_service.get_energy(plug)
  353. logger.info(f"[ENERGY] Energy response from plug: {energy}")
  354. if energy and energy.get("total") is not None:
  355. _print_energy_start[archive.id] = energy["total"]
  356. logger.info(f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh")
  357. else:
  358. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  359. else:
  360. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  361. except Exception as e:
  362. logger.warning(f"Failed to record starting energy: {e}")
  363. await ws_manager.send_archive_updated({
  364. "id": archive.id,
  365. "status": "printing",
  366. })
  367. # Send notification with archive data (reprint/scheduled)
  368. if not notification_sent:
  369. archive_data = {"print_time_seconds": archive.print_time_seconds}
  370. await _send_print_start_notification(printer_id, data, archive_data, logger)
  371. return # Skip creating a new archive
  372. # Check if there's already a "printing" archive for this printer/file
  373. # This prevents duplicates when backend restarts during an active print
  374. from backend.app.models.archive import PrintArchive
  375. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  376. existing = await db.execute(
  377. select(PrintArchive)
  378. .where(PrintArchive.printer_id == printer_id)
  379. .where(PrintArchive.status == "printing")
  380. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  381. .order_by(PrintArchive.created_at.desc())
  382. .limit(1)
  383. )
  384. existing_archive = existing.scalar_one_or_none()
  385. if existing_archive:
  386. logger.info(f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}")
  387. # Track this as the active print
  388. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  389. # Also set up energy tracking if not already tracked
  390. if existing_archive.id not in _print_energy_start:
  391. try:
  392. plug_result = await db.execute(
  393. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  394. )
  395. plug = plug_result.scalar_one_or_none()
  396. if plug:
  397. energy = await tasmota_service.get_energy(plug)
  398. if energy and energy.get("total") is not None:
  399. _print_energy_start[existing_archive.id] = energy["total"]
  400. logger.info(f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh")
  401. except Exception as e:
  402. logger.warning(f"Failed to record starting energy for existing archive: {e}")
  403. # Send notification with archive data (existing archive)
  404. if not notification_sent:
  405. archive_data = {"print_time_seconds": existing_archive.print_time_seconds}
  406. await _send_print_start_notification(printer_id, data, archive_data, logger)
  407. return
  408. # Build list of possible 3MF filenames to try
  409. possible_names = []
  410. # Bambu printers typically store files as "Name.gcode.3mf"
  411. # The subtask_name is usually the best source for the filename
  412. if subtask_name:
  413. # Try common Bambu naming patterns
  414. possible_names.append(f"{subtask_name}.gcode.3mf")
  415. possible_names.append(f"{subtask_name}.3mf")
  416. # Try original filename with .3mf extension
  417. if filename:
  418. # Extract just the filename part, not the full path
  419. fname = filename.split("/")[-1] if "/" in filename else filename
  420. if fname.endswith(".3mf"):
  421. possible_names.append(fname)
  422. elif fname.endswith(".gcode"):
  423. base = fname.rsplit(".", 1)[0]
  424. possible_names.append(f"{base}.gcode.3mf")
  425. possible_names.append(f"{base}.3mf")
  426. else:
  427. possible_names.append(f"{fname}.gcode.3mf")
  428. possible_names.append(f"{fname}.3mf")
  429. # Remove duplicates while preserving order
  430. seen = set()
  431. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  432. logger.info(f"Trying filenames: {possible_names}")
  433. # Try to find and download the 3MF file
  434. temp_path = None
  435. downloaded_filename = None
  436. for try_filename in possible_names:
  437. if not try_filename.endswith(".3mf"):
  438. continue
  439. remote_paths = [
  440. f"/cache/{try_filename}",
  441. f"/model/{try_filename}",
  442. f"/{try_filename}",
  443. ]
  444. temp_path = app_settings.archive_dir / "temp" / try_filename
  445. temp_path.parent.mkdir(parents=True, exist_ok=True)
  446. for remote_path in remote_paths:
  447. logger.debug(f"Trying FTP download: {remote_path}")
  448. try:
  449. if await download_file_async(
  450. printer.ip_address,
  451. printer.access_code,
  452. remote_path,
  453. temp_path,
  454. ):
  455. downloaded_filename = try_filename
  456. logger.info(f"Downloaded: {remote_path}")
  457. break
  458. except Exception as e:
  459. logger.debug(f"FTP download failed for {remote_path}: {e}")
  460. if downloaded_filename:
  461. break
  462. # If still not found, try listing /cache to find matching file
  463. if not downloaded_filename and (filename or subtask_name):
  464. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  465. try:
  466. cache_files = await list_files_async(printer.ip_address, printer.access_code, "/cache")
  467. for f in cache_files:
  468. if f.get("is_directory"):
  469. continue
  470. fname = f.get("name", "")
  471. if fname.endswith(".3mf") and search_term in fname.lower():
  472. temp_path = app_settings.archive_dir / "temp" / fname
  473. temp_path.parent.mkdir(parents=True, exist_ok=True)
  474. if await download_file_async(
  475. printer.ip_address,
  476. printer.access_code,
  477. f"/cache/{fname}",
  478. temp_path,
  479. ):
  480. downloaded_filename = fname
  481. logger.info(f"Found and downloaded from cache: {fname}")
  482. break
  483. except Exception as e:
  484. logger.warning(f"Failed to list cache: {e}")
  485. if not downloaded_filename or not temp_path:
  486. logger.warning(f"Could not find 3MF file for print: {filename or subtask_name}")
  487. # Send notification without archive data (file not found)
  488. if not notification_sent:
  489. await _send_print_start_notification(printer_id, data, logger=logger)
  490. return
  491. try:
  492. # Archive the file with status "printing"
  493. service = ArchiveService(db)
  494. archive = await service.archive_print(
  495. printer_id=printer_id,
  496. source_file=temp_path,
  497. print_data={**data, "status": "printing"},
  498. )
  499. if archive:
  500. # Track this active print (use both original filename and downloaded filename)
  501. _active_prints[(printer_id, downloaded_filename)] = archive.id
  502. if filename and filename != downloaded_filename:
  503. _active_prints[(printer_id, filename)] = archive.id
  504. if subtask_name:
  505. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  506. logger.info(f"Created archive {archive.id} for {downloaded_filename}")
  507. # Record starting energy from smart plug if available
  508. try:
  509. plug_result = await db.execute(
  510. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  511. )
  512. plug = plug_result.scalar_one_or_none()
  513. logger.info(f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}")
  514. if plug:
  515. energy = await tasmota_service.get_energy(plug)
  516. logger.info(f"[ENERGY] Auto-archive energy response: {energy}")
  517. if energy and energy.get("total") is not None:
  518. _print_energy_start[archive.id] = energy["total"]
  519. logger.info(f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh")
  520. else:
  521. logger.warning(f"[ENERGY] No 'total' in energy response for archive {archive.id}")
  522. else:
  523. logger.info(f"[ENERGY] No smart plug found for printer {printer_id}")
  524. except Exception as e:
  525. logger.warning(f"Failed to record starting energy: {e}")
  526. await ws_manager.send_archive_created({
  527. "id": archive.id,
  528. "printer_id": archive.printer_id,
  529. "filename": archive.filename,
  530. "print_name": archive.print_name,
  531. "status": archive.status,
  532. })
  533. # Send notification with archive data (new archive created)
  534. if not notification_sent:
  535. archive_data = {"print_time_seconds": archive.print_time_seconds}
  536. await _send_print_start_notification(printer_id, data, archive_data, logger)
  537. notification_sent = True
  538. finally:
  539. if temp_path and temp_path.exists():
  540. temp_path.unlink()
  541. async def on_print_complete(printer_id: int, data: dict):
  542. """Handle print completion - update the archive status."""
  543. import logging
  544. logger = logging.getLogger(__name__)
  545. logger.info(f"[CALLBACK] on_print_complete started for printer {printer_id}")
  546. try:
  547. await ws_manager.send_print_complete(printer_id, data)
  548. except Exception as e:
  549. logger.warning(f"[CALLBACK] WebSocket send_print_complete failed: {e}")
  550. filename = data.get("filename", "")
  551. subtask_name = data.get("subtask_name", "")
  552. if not filename and not subtask_name:
  553. logger.warning(f"Print complete without filename or subtask_name")
  554. return
  555. logger.info(f"Print complete - filename: {filename}, subtask: {subtask_name}, status: {data.get('status')}")
  556. # Build list of possible keys to try (matching how they were registered in on_print_start)
  557. possible_keys = []
  558. # Try subtask_name variations first (most reliable for matching)
  559. if subtask_name:
  560. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  561. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  562. possible_keys.append((printer_id, subtask_name))
  563. # Try filename variations
  564. if filename:
  565. # Extract just the filename if it's a path
  566. fname = filename.split("/")[-1] if "/" in filename else filename
  567. if fname.endswith(".3mf"):
  568. possible_keys.append((printer_id, fname))
  569. elif fname.endswith(".gcode"):
  570. base_name = fname.rsplit(".", 1)[0]
  571. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  572. possible_keys.append((printer_id, f"{base_name}.3mf"))
  573. possible_keys.append((printer_id, fname))
  574. else:
  575. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  576. possible_keys.append((printer_id, f"{fname}.3mf"))
  577. possible_keys.append((printer_id, fname))
  578. # Also try full path versions
  579. if filename.endswith(".3mf"):
  580. possible_keys.append((printer_id, filename))
  581. elif filename.endswith(".gcode"):
  582. base_name = filename.rsplit(".", 1)[0]
  583. possible_keys.append((printer_id, f"{base_name}.3mf"))
  584. possible_keys.append((printer_id, filename))
  585. else:
  586. possible_keys.append((printer_id, f"{filename}.3mf"))
  587. possible_keys.append((printer_id, filename))
  588. # Find the archive for this print
  589. logger.info(f"Looking for archive in _active_prints, keys to try: {possible_keys[:5]}...")
  590. logger.info(f"Current _active_prints: {list(_active_prints.keys())}")
  591. archive_id = None
  592. for key in possible_keys:
  593. archive_id = _active_prints.pop(key, None)
  594. if archive_id:
  595. logger.info(f"Found archive {archive_id} with key {key}")
  596. # Also clean up any other keys pointing to this archive
  597. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  598. for k in keys_to_remove:
  599. _active_prints.pop(k, None)
  600. break
  601. if not archive_id:
  602. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  603. async with async_session() as db:
  604. from backend.app.models.archive import PrintArchive
  605. # Try matching by subtask_name (stored as print_name) first
  606. if subtask_name:
  607. result = await db.execute(
  608. select(PrintArchive)
  609. .where(PrintArchive.printer_id == printer_id)
  610. .where(PrintArchive.status == "printing")
  611. .where(or_(
  612. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  613. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  614. ))
  615. .order_by(PrintArchive.created_at.desc())
  616. .limit(1)
  617. )
  618. archive = result.scalar_one_or_none()
  619. if archive:
  620. archive_id = archive.id
  621. logger.info(f"Found archive {archive_id} by subtask_name match: {subtask_name}")
  622. # Also try by filename
  623. if not archive_id and filename:
  624. result = await db.execute(
  625. select(PrintArchive)
  626. .where(PrintArchive.printer_id == printer_id)
  627. .where(PrintArchive.filename == filename)
  628. .where(PrintArchive.status == "printing")
  629. .order_by(PrintArchive.created_at.desc())
  630. .limit(1)
  631. )
  632. archive = result.scalar_one_or_none()
  633. if archive:
  634. archive_id = archive.id
  635. if not archive_id:
  636. logger.warning(f"Could not find archive for print complete: filename={filename}, subtask={subtask_name}")
  637. return
  638. # Update archive status
  639. logger.info(f"[ARCHIVE] Updating archive {archive_id} status...")
  640. try:
  641. async with async_session() as db:
  642. service = ArchiveService(db)
  643. status = data.get("status", "completed")
  644. await service.update_archive_status(
  645. archive_id,
  646. status=status,
  647. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  648. )
  649. logger.info(f"[ARCHIVE] Archive {archive_id} status updated to {status}")
  650. await ws_manager.send_archive_updated({
  651. "id": archive_id,
  652. "status": status,
  653. })
  654. logger.info(f"[ARCHIVE] WebSocket notification sent for archive {archive_id}")
  655. except Exception as e:
  656. logger.error(f"[ARCHIVE] Failed to update archive {archive_id} status: {e}", exc_info=True)
  657. # Continue with other operations even if archive update fails
  658. # Report filament usage to Spoolman if print completed successfully
  659. if data.get("status") == "completed":
  660. try:
  661. await _report_spoolman_usage(printer_id, archive_id, logger)
  662. except Exception as e:
  663. logger.warning(f"Spoolman usage reporting failed: {e}")
  664. # Calculate energy used for this print (always per-print: end - start)
  665. try:
  666. starting_kwh = _print_energy_start.pop(archive_id, None)
  667. logger.info(f"[ENERGY] Print complete for archive {archive_id}, starting_kwh={starting_kwh}")
  668. async with async_session() as db:
  669. # Get smart plug for this printer (SmartPlug is imported at module level)
  670. plug_result = await db.execute(
  671. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  672. )
  673. plug = plug_result.scalar_one_or_none()
  674. if plug:
  675. energy = await tasmota_service.get_energy(plug)
  676. logger.info(f"[ENERGY] Print complete - energy response: {energy}")
  677. energy_used = None
  678. # Calculate per-print energy: end total - start total
  679. if starting_kwh is not None and energy and energy.get("total") is not None:
  680. ending_kwh = energy["total"]
  681. energy_used = round(ending_kwh - starting_kwh, 4)
  682. logger.info(f"[ENERGY] Per-print energy: ending={ending_kwh}, starting={starting_kwh}, used={energy_used}")
  683. elif starting_kwh is None:
  684. logger.info(f"[ENERGY] No starting energy recorded for this archive")
  685. else:
  686. logger.warning(f"[ENERGY] No 'total' in ending energy response")
  687. if energy_used is not None and energy_used >= 0:
  688. # Get energy cost per kWh from settings (default to 0.15)
  689. from backend.app.api.routes.settings import get_setting
  690. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  691. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  692. energy_cost = round(energy_used * cost_per_kwh, 2)
  693. # Update archive with energy data
  694. from backend.app.models.archive import PrintArchive
  695. result = await db.execute(
  696. select(PrintArchive).where(PrintArchive.id == archive_id)
  697. )
  698. archive = result.scalar_one_or_none()
  699. if archive:
  700. archive.energy_kwh = energy_used
  701. archive.energy_cost = energy_cost
  702. await db.commit()
  703. logger.info(f"[ENERGY] Saved to archive {archive_id}: {energy_used} kWh, cost={energy_cost}")
  704. else:
  705. logger.warning(f"[ENERGY] Archive {archive_id} not found when saving energy")
  706. else:
  707. logger.info(f"[ENERGY] No smart plug found for printer {printer_id} at print complete")
  708. except Exception as e:
  709. import logging
  710. logging.getLogger(__name__).warning(f"Failed to calculate energy: {e}")
  711. # Capture finish photo from printer camera
  712. logger.info(f"[PHOTO] Starting finish photo capture for archive {archive_id}")
  713. try:
  714. async with async_session() as db:
  715. # Check if finish photo capture is enabled
  716. from backend.app.api.routes.settings import get_setting
  717. capture_enabled = await get_setting(db, "capture_finish_photo")
  718. logger.info(f"[PHOTO] capture_finish_photo setting: {capture_enabled}")
  719. if capture_enabled is None or capture_enabled.lower() == "true":
  720. # Get printer details
  721. from backend.app.models.printer import Printer
  722. result = await db.execute(
  723. select(Printer).where(Printer.id == printer_id)
  724. )
  725. printer = result.scalar_one_or_none()
  726. if printer and archive_id:
  727. # Get archive to find its directory
  728. from backend.app.models.archive import PrintArchive
  729. result = await db.execute(
  730. select(PrintArchive).where(PrintArchive.id == archive_id)
  731. )
  732. archive = result.scalar_one_or_none()
  733. if archive:
  734. from backend.app.services.camera import capture_finish_photo
  735. from pathlib import Path
  736. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  737. photo_filename = await capture_finish_photo(
  738. printer_id=printer_id,
  739. ip_address=printer.ip_address,
  740. access_code=printer.access_code,
  741. model=printer.model,
  742. archive_dir=archive_dir,
  743. )
  744. if photo_filename:
  745. # Add photo to archive's photos list
  746. photos = archive.photos or []
  747. photos.append(photo_filename)
  748. archive.photos = photos
  749. await db.commit()
  750. logger.info(f"Added finish photo to archive {archive_id}: {photo_filename}")
  751. except Exception as e:
  752. import logging
  753. logging.getLogger(__name__).warning(f"Finish photo capture failed: {e}")
  754. # Smart plug automation: schedule turn off when print completes
  755. logger.info(f"[AUTO-OFF] Calling smart_plug_manager.on_print_complete for printer {printer_id}")
  756. try:
  757. async with async_session() as db:
  758. status = data.get("status", "completed")
  759. await smart_plug_manager.on_print_complete(printer_id, status, db)
  760. logger.info(f"[AUTO-OFF] smart_plug_manager.on_print_complete completed")
  761. except Exception as e:
  762. import logging
  763. logging.getLogger(__name__).warning(f"Smart plug on_print_complete failed: {e}")
  764. # Send print complete notifications
  765. try:
  766. async with async_session() as db:
  767. from backend.app.models.printer import Printer
  768. from backend.app.models.archive import PrintArchive
  769. result = await db.execute(
  770. select(Printer).where(Printer.id == printer_id)
  771. )
  772. printer = result.scalar_one_or_none()
  773. printer_name = printer.name if printer else f"Printer {printer_id}"
  774. status = data.get("status", "completed")
  775. # Fetch archive data for notification variables
  776. archive_data = None
  777. if archive_id:
  778. archive_result = await db.execute(
  779. select(PrintArchive).where(PrintArchive.id == archive_id)
  780. )
  781. archive = archive_result.scalar_one_or_none()
  782. if archive:
  783. archive_data = {
  784. "print_time_seconds": archive.print_time_seconds,
  785. "actual_filament_grams": archive.filament_used_grams,
  786. "failure_reason": archive.failure_reason,
  787. }
  788. # on_print_complete handles all status types: completed, failed, aborted, stopped
  789. await notification_service.on_print_complete(
  790. printer_id, printer_name, status, data, db, archive_data=archive_data
  791. )
  792. except Exception as e:
  793. import logging
  794. logging.getLogger(__name__).warning(f"Notification on_print_complete failed: {e}")
  795. # Check for maintenance due and send notifications (only for completed prints)
  796. if data.get("status") == "completed":
  797. try:
  798. async with async_session() as db:
  799. from backend.app.models.printer import Printer
  800. # Get printer name
  801. result = await db.execute(
  802. select(Printer).where(Printer.id == printer_id)
  803. )
  804. printer = result.scalar_one_or_none()
  805. printer_name = printer.name if printer else f"Printer {printer_id}"
  806. # Get maintenance overview for this printer
  807. await ensure_default_types(db)
  808. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  809. # Check for any items that are due or have warnings
  810. items_needing_attention = [
  811. {
  812. "name": item.maintenance_type_name,
  813. "is_due": item.is_due,
  814. "is_warning": item.is_warning,
  815. }
  816. for item in overview.maintenance_items
  817. if item.enabled and (item.is_due or item.is_warning)
  818. ]
  819. if items_needing_attention:
  820. await notification_service.on_maintenance_due(
  821. printer_id, printer_name, items_needing_attention, db
  822. )
  823. logger.info(
  824. f"Sent maintenance notification for printer {printer_id}: "
  825. f"{len(items_needing_attention)} items need attention"
  826. )
  827. except Exception as e:
  828. import logging
  829. logging.getLogger(__name__).warning(f"Maintenance notification check failed: {e}")
  830. # Auto-scan for timelapse if recording was active during the print
  831. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  832. logger.info(f"[TIMELAPSE] Timelapse was active during print, auto-scanning for archive {archive_id}")
  833. try:
  834. # Small delay to allow timelapse file to be finalized
  835. await asyncio.sleep(5)
  836. async with async_session() as db:
  837. from backend.app.models.printer import Printer
  838. from backend.app.models.archive import PrintArchive
  839. from backend.app.services.archive import ArchiveService
  840. from backend.app.services.bambu_ftp import list_files_async, download_file_bytes_async
  841. from pathlib import Path
  842. import re
  843. from datetime import timedelta
  844. # Get archive
  845. service = ArchiveService(db)
  846. archive = await service.get_archive(archive_id)
  847. if not archive:
  848. logger.warning(f"[TIMELAPSE] Archive {archive_id} not found")
  849. elif archive.timelapse_path:
  850. logger.info(f"[TIMELAPSE] Archive {archive_id} already has timelapse attached")
  851. elif not archive.printer_id:
  852. logger.warning(f"[TIMELAPSE] Archive {archive_id} has no printer")
  853. else:
  854. # Get printer
  855. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  856. printer = result.scalar_one_or_none()
  857. if printer:
  858. # Scan timelapse directory on printer
  859. files = []
  860. for timelapse_path in ["/timelapse", "/timelapse/video"]:
  861. try:
  862. files = await list_files_async(printer.ip_address, printer.access_code, timelapse_path)
  863. if files:
  864. break
  865. except Exception:
  866. continue
  867. if files:
  868. mp4_files = [f for f in files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  869. # Strategy: Find most recent timelapse by mtime
  870. # Since we know timelapse was active during this print, use the most recent file
  871. if mp4_files:
  872. # Sort by mtime descending
  873. mp4_files_with_mtime = [f for f in mp4_files if f.get("mtime")]
  874. if mp4_files_with_mtime:
  875. mp4_files_with_mtime.sort(key=lambda x: x.get("mtime"), reverse=True)
  876. most_recent = mp4_files_with_mtime[0]
  877. # Verify the file was modified within reasonable time of print completion
  878. file_mtime = most_recent.get("mtime")
  879. archive_completed = archive.completed_at or datetime.now()
  880. if file_mtime and abs(file_mtime - archive_completed) < timedelta(minutes=30):
  881. # Download and attach
  882. logger.info(f"[TIMELAPSE] Downloading timelapse {most_recent['name']} for archive {archive_id}")
  883. remote_path = most_recent.get('path') or f"/timelapse/{most_recent['name']}"
  884. timelapse_data = await download_file_bytes_async(
  885. printer.ip_address, printer.access_code, remote_path
  886. )
  887. if timelapse_data:
  888. success = await service.attach_timelapse(
  889. archive_id, timelapse_data, most_recent["name"]
  890. )
  891. if success:
  892. logger.info(f"[TIMELAPSE] Successfully attached timelapse to archive {archive_id}")
  893. await ws_manager.send_archive_updated({
  894. "id": archive_id,
  895. "timelapse_attached": True,
  896. })
  897. else:
  898. logger.warning(f"[TIMELAPSE] Failed to attach timelapse to archive {archive_id}")
  899. else:
  900. logger.warning(f"[TIMELAPSE] Failed to download timelapse file")
  901. else:
  902. logger.info(f"[TIMELAPSE] Most recent timelapse mtime too far from print completion")
  903. else:
  904. logger.info(f"[TIMELAPSE] No timelapse files with mtime found")
  905. else:
  906. logger.info(f"[TIMELAPSE] No timelapse files found on printer")
  907. else:
  908. logger.warning(f"[TIMELAPSE] Printer not found for archive {archive_id}")
  909. except Exception as e:
  910. import logging
  911. logging.getLogger(__name__).warning(f"Timelapse auto-scan failed: {e}")
  912. # Update queue item if this was a scheduled print
  913. try:
  914. async with async_session() as db:
  915. from backend.app.models.print_queue import PrintQueueItem
  916. # Note: SmartPlug is already imported at module level (line 56)
  917. # Do NOT import it here as it would shadow the module-level import
  918. # and cause "cannot access local variable" errors earlier in this function
  919. result = await db.execute(
  920. select(PrintQueueItem)
  921. .where(PrintQueueItem.printer_id == printer_id)
  922. .where(PrintQueueItem.status == "printing")
  923. )
  924. queue_item = result.scalar_one_or_none()
  925. if queue_item:
  926. status = data.get("status", "completed")
  927. queue_item.status = status
  928. queue_item.completed_at = datetime.now()
  929. await db.commit()
  930. logger.info(f"Updated queue item {queue_item.id} status to {status}")
  931. # Handle auto_off_after - power off printer if requested (after cooldown)
  932. if queue_item.auto_off_after:
  933. result = await db.execute(
  934. select(SmartPlug).where(SmartPlug.printer_id == printer_id)
  935. )
  936. plug = result.scalar_one_or_none()
  937. if plug and plug.enabled:
  938. logger.info(f"Auto-off requested for printer {printer_id}, waiting for cooldown...")
  939. async def cooldown_and_poweroff(pid: int, plug_id: int):
  940. # Wait for nozzle to cool down
  941. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  942. # Re-fetch plug in new session
  943. async with async_session() as new_db:
  944. result = await new_db.execute(
  945. select(SmartPlug).where(SmartPlug.id == plug_id)
  946. )
  947. p = result.scalar_one_or_none()
  948. if p and p.enabled:
  949. success = await tasmota_service.turn_off(p)
  950. if success:
  951. logger.info(f"Powered off printer {pid} via smart plug '{p.name}'")
  952. else:
  953. logger.warning(f"Failed to power off printer {pid} via smart plug")
  954. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  955. except Exception as e:
  956. import logging
  957. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  958. logger.info(f"[CALLBACK] on_print_complete finished for printer {printer_id}, archive {archive_id}")
  959. # AMS sensor history recording
  960. _ams_history_task: asyncio.Task | None = None
  961. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  962. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  963. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  964. _ams_alarm_cooldown: dict[str, datetime] = {} # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  965. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  966. async def record_ams_history():
  967. """Background task to record AMS humidity and temperature data."""
  968. import logging
  969. logger = logging.getLogger(__name__)
  970. # Wait a short time for MQTT connections to establish on startup
  971. await asyncio.sleep(10)
  972. while True:
  973. try:
  974. from backend.app.models.ams_history import AMSSensorHistory
  975. from backend.app.models.printer import Printer
  976. from backend.app.models.settings import Settings
  977. async with async_session() as db:
  978. # Get all active printers
  979. result = await db.execute(
  980. select(Printer).where(Printer.is_active == True)
  981. )
  982. printers = result.scalars().all()
  983. # Get alarm thresholds from settings
  984. humidity_threshold = 60.0 # Default: fair threshold
  985. temp_threshold = 35.0 # Default: fair threshold
  986. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  987. setting = result.scalar_one_or_none()
  988. if setting:
  989. try:
  990. humidity_threshold = float(setting.value)
  991. except (ValueError, TypeError):
  992. pass
  993. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  994. setting = result.scalar_one_or_none()
  995. if setting:
  996. try:
  997. temp_threshold = float(setting.value)
  998. except (ValueError, TypeError):
  999. pass
  1000. recorded_count = 0
  1001. for printer in printers:
  1002. # Get current state from printer manager
  1003. state = printer_manager.get_status(printer.id)
  1004. if not state or not state.raw_data:
  1005. continue
  1006. raw_data = state.raw_data
  1007. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  1008. continue
  1009. # Record data for each AMS unit
  1010. for ams_data in raw_data["ams"]:
  1011. ams_id = int(ams_data.get("id", 0))
  1012. # Get humidity (prefer humidity_raw)
  1013. humidity_raw = ams_data.get("humidity_raw")
  1014. humidity_idx = ams_data.get("humidity")
  1015. humidity = None
  1016. if humidity_raw is not None:
  1017. try:
  1018. humidity = float(humidity_raw)
  1019. except (ValueError, TypeError):
  1020. pass
  1021. if humidity is None and humidity_idx is not None:
  1022. try:
  1023. humidity = float(humidity_idx)
  1024. except (ValueError, TypeError):
  1025. pass
  1026. # Get temperature
  1027. temperature = None
  1028. temp_str = ams_data.get("temp")
  1029. if temp_str is not None:
  1030. try:
  1031. temperature = float(temp_str)
  1032. except (ValueError, TypeError):
  1033. pass
  1034. # Skip if no data
  1035. if humidity is None and temperature is None:
  1036. continue
  1037. # Record the data point
  1038. history = AMSSensorHistory(
  1039. printer_id=printer.id,
  1040. ams_id=ams_id,
  1041. humidity=humidity,
  1042. humidity_raw=float(humidity_raw) if humidity_raw else None,
  1043. temperature=temperature,
  1044. )
  1045. db.add(history)
  1046. recorded_count += 1
  1047. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  1048. is_ams_ht = ams_id >= 128
  1049. if is_ams_ht:
  1050. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  1051. else:
  1052. ams_label = f"AMS-{chr(65 + ams_id)}"
  1053. # Check humidity alarm (only if above threshold)
  1054. if humidity is not None and humidity > humidity_threshold:
  1055. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  1056. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1057. now = datetime.now()
  1058. if last_alarm is None or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60:
  1059. _ams_alarm_cooldown[cooldown_key] = now
  1060. logger.info(f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%")
  1061. try:
  1062. # Call different notification method based on AMS type
  1063. if is_ams_ht:
  1064. await notification_service.on_ams_ht_humidity_high(
  1065. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1066. )
  1067. else:
  1068. await notification_service.on_ams_humidity_high(
  1069. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  1070. )
  1071. except Exception as e:
  1072. logger.warning(f"Failed to send humidity alarm: {e}")
  1073. # Check temperature alarm (only if above threshold)
  1074. if temperature is not None and temperature > temp_threshold:
  1075. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  1076. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  1077. now = datetime.now()
  1078. if last_alarm is None or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60:
  1079. _ams_alarm_cooldown[cooldown_key] = now
  1080. logger.info(f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C")
  1081. try:
  1082. # Call different notification method based on AMS type
  1083. if is_ams_ht:
  1084. await notification_service.on_ams_ht_temperature_high(
  1085. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1086. )
  1087. else:
  1088. await notification_service.on_ams_temperature_high(
  1089. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  1090. )
  1091. except Exception as e:
  1092. logger.warning(f"Failed to send temperature alarm: {e}")
  1093. await db.commit()
  1094. if recorded_count > 0:
  1095. logger.info(f"Recorded {recorded_count} AMS sensor history entries")
  1096. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  1097. global _ams_cleanup_counter
  1098. _ams_cleanup_counter += 1
  1099. if _ams_cleanup_counter >= 288:
  1100. _ams_cleanup_counter = 0
  1101. # Get retention days from settings
  1102. from backend.app.models.settings import Settings
  1103. result = await db.execute(
  1104. select(Settings).where(Settings.key == "ams_history_retention_days")
  1105. )
  1106. setting = result.scalar_one_or_none()
  1107. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  1108. cutoff = datetime.now() - timedelta(days=retention_days)
  1109. result = await db.execute(
  1110. delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff)
  1111. )
  1112. await db.commit()
  1113. if result.rowcount > 0:
  1114. logger.info(f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)")
  1115. # Wait until next recording interval
  1116. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  1117. except asyncio.CancelledError:
  1118. break
  1119. except Exception as e:
  1120. logger.warning(f"AMS history recording failed: {e}")
  1121. await asyncio.sleep(60) # Wait a bit before retrying
  1122. def start_ams_history_recording():
  1123. """Start the AMS history recording background task."""
  1124. global _ams_history_task
  1125. if _ams_history_task is None:
  1126. _ams_history_task = asyncio.create_task(record_ams_history())
  1127. logging.getLogger(__name__).info("AMS history recording started")
  1128. def stop_ams_history_recording():
  1129. """Stop the AMS history recording background task."""
  1130. global _ams_history_task
  1131. if _ams_history_task:
  1132. _ams_history_task.cancel()
  1133. _ams_history_task = None
  1134. logging.getLogger(__name__).info("AMS history recording stopped")
  1135. @asynccontextmanager
  1136. async def lifespan(app: FastAPI):
  1137. # Startup
  1138. await init_db()
  1139. # Set up printer manager callbacks
  1140. loop = asyncio.get_event_loop()
  1141. printer_manager.set_event_loop(loop)
  1142. printer_manager.set_status_change_callback(on_printer_status_change)
  1143. printer_manager.set_print_start_callback(on_print_start)
  1144. printer_manager.set_print_complete_callback(on_print_complete)
  1145. printer_manager.set_ams_change_callback(on_ams_change)
  1146. # Connect to all active printers
  1147. async with async_session() as db:
  1148. await init_printer_connections(db)
  1149. # Auto-connect to Spoolman if enabled
  1150. async with async_session() as db:
  1151. from backend.app.api.routes.settings import get_setting
  1152. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  1153. spoolman_url = await get_setting(db, "spoolman_url")
  1154. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  1155. try:
  1156. client = await init_spoolman_client(spoolman_url)
  1157. if await client.health_check():
  1158. logging.info(f"Auto-connected to Spoolman at {spoolman_url}")
  1159. else:
  1160. logging.warning(f"Spoolman at {spoolman_url} is not reachable")
  1161. except Exception as e:
  1162. logging.warning(f"Failed to auto-connect to Spoolman: {e}")
  1163. # Start the print scheduler
  1164. asyncio.create_task(print_scheduler.run())
  1165. # Start the smart plug scheduler for time-based on/off
  1166. smart_plug_manager.start_scheduler()
  1167. # Resume any pending auto-offs that were interrupted by restart
  1168. await smart_plug_manager.resume_pending_auto_offs()
  1169. # Start the notification digest scheduler
  1170. notification_service.start_digest_scheduler()
  1171. # Start AMS history recording
  1172. start_ams_history_recording()
  1173. # Start anonymous telemetry (opt-out via settings)
  1174. asyncio.create_task(start_telemetry_loop(async_session))
  1175. yield
  1176. # Shutdown
  1177. print_scheduler.stop()
  1178. smart_plug_manager.stop_scheduler()
  1179. notification_service.stop_digest_scheduler()
  1180. stop_ams_history_recording()
  1181. printer_manager.disconnect_all()
  1182. await close_spoolman_client()
  1183. app = FastAPI(
  1184. title=app_settings.app_name,
  1185. description="Archive and manage Bambu Lab 3MF files",
  1186. version=APP_VERSION,
  1187. lifespan=lifespan,
  1188. )
  1189. # API routes
  1190. app.include_router(printers.router, prefix=app_settings.api_prefix)
  1191. app.include_router(archives.router, prefix=app_settings.api_prefix)
  1192. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  1193. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  1194. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  1195. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  1196. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  1197. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  1198. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  1199. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  1200. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  1201. app.include_router(updates.router, prefix=app_settings.api_prefix)
  1202. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  1203. app.include_router(camera.router, prefix=app_settings.api_prefix)
  1204. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  1205. app.include_router(projects.router, prefix=app_settings.api_prefix)
  1206. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  1207. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  1208. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  1209. app.include_router(system.router, prefix=app_settings.api_prefix)
  1210. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  1211. # Serve static files (React build)
  1212. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  1213. app.mount(
  1214. "/assets",
  1215. StaticFiles(directory=app_settings.static_dir / "assets"),
  1216. name="assets",
  1217. )
  1218. if (app_settings.static_dir / "img").exists():
  1219. app.mount(
  1220. "/img",
  1221. StaticFiles(directory=app_settings.static_dir / "img"),
  1222. name="img",
  1223. )
  1224. if (app_settings.static_dir / "icons").exists():
  1225. app.mount(
  1226. "/icons",
  1227. StaticFiles(directory=app_settings.static_dir / "icons"),
  1228. name="icons",
  1229. )
  1230. @app.get("/")
  1231. async def serve_frontend():
  1232. """Serve the React frontend."""
  1233. index_file = app_settings.static_dir / "index.html"
  1234. if index_file.exists():
  1235. return FileResponse(index_file)
  1236. return {
  1237. "message": "Bambuddy API",
  1238. "docs": "/docs",
  1239. "frontend": "Build and place React app in /static directory",
  1240. }
  1241. @app.get("/health")
  1242. async def health_check():
  1243. """Health check endpoint."""
  1244. return {"status": "healthy"}
  1245. @app.get("/manifest.json")
  1246. async def serve_manifest():
  1247. """Serve PWA manifest."""
  1248. manifest_file = app_settings.static_dir / "manifest.json"
  1249. if manifest_file.exists():
  1250. return FileResponse(manifest_file, media_type="application/manifest+json")
  1251. return {"error": "Manifest not found"}
  1252. @app.get("/sw.js")
  1253. async def serve_service_worker():
  1254. """Serve service worker."""
  1255. sw_file = app_settings.static_dir / "sw.js"
  1256. if sw_file.exists():
  1257. return FileResponse(sw_file, media_type="application/javascript")
  1258. return {"error": "Service worker not found"}
  1259. # Catch-all route for React Router (must be last)
  1260. @app.get("/{full_path:path}")
  1261. async def serve_spa(full_path: str):
  1262. """Serve React app for client-side routing."""
  1263. # Don't intercept API routes
  1264. if full_path.startswith("api/"):
  1265. return {"error": "Not found"}
  1266. index_file = app_settings.static_dir / "index.html"
  1267. if index_file.exists():
  1268. return FileResponse(index_file)
  1269. return {"error": "Frontend not built"}