main.py 82 KB

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