print_scheduler.py 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import zipfile
  7. from datetime import datetime, timezone
  8. from pathlib import Path
  9. import defusedxml.ElementTree as ET
  10. from sqlalchemy import func, select
  11. from sqlalchemy.ext.asyncio import AsyncSession
  12. from backend.app.core.config import settings
  13. from backend.app.core.database import async_session
  14. from backend.app.models.archive import PrintArchive
  15. from backend.app.models.library import LibraryFile
  16. from backend.app.models.print_queue import PrintQueueItem
  17. from backend.app.models.printer import Printer
  18. from backend.app.models.settings import Settings
  19. from backend.app.models.smart_plug import SmartPlug
  20. from backend.app.services.bambu_ftp import delete_file_async, get_ftp_retry_settings, upload_file_async, with_ftp_retry
  21. from backend.app.services.notification_service import notification_service
  22. from backend.app.services.printer_manager import printer_manager, supports_drying
  23. from backend.app.services.smart_plug_manager import smart_plug_manager
  24. from backend.app.utils.printer_models import normalize_printer_model
  25. from backend.app.utils.threemf_tools import extract_nozzle_mapping_from_3mf
  26. logger = logging.getLogger(__name__)
  27. # Filament type equivalence groups — types within the same group are
  28. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  29. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  30. ["PA-CF", "PA12-CF", "PAHT-CF"],
  31. ]
  32. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  33. for _group in _FILAMENT_TYPE_GROUPS:
  34. _canonical = _group[0].upper()
  35. for _t in _group:
  36. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  37. def _canonical_filament_type(ftype: str) -> str:
  38. """Return canonical type for equivalence matching."""
  39. upper = ftype.upper()
  40. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  41. class PrintScheduler:
  42. """Background scheduler that processes the print queue."""
  43. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  44. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  45. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  46. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  47. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  48. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  49. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  50. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  51. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  52. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  53. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  54. }
  55. def __init__(self):
  56. self._running = False
  57. self._check_interval = 30 # seconds
  58. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  59. self._power_on_check_interval = 10 # seconds between connection checks
  60. self._min_drying_seconds = 1800 # 30 minutes minimum before humidity re-check can stop drying
  61. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  62. self._drying_in_progress: dict[int, float] = {}
  63. # Defensive in-memory dispatch hold (#1157): a printer that just received
  64. # a project_file command must not get a second dispatch until either it
  65. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  66. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  67. # during that window the DB busy_printers seed is empirically unreliable
  68. # (multi-plate batches double-/triple-dispatched onto the same printer
  69. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  70. # or revert.
  71. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  72. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  73. # Minimum cooldown between dispatches to the same printer (covers the
  74. # H2D's project_file digestion window).
  75. self._dispatch_min_cooldown = 60.0
  76. # Hard timeout — drop the hold even if we never observed a transition,
  77. # so a lost MQTT session can't lock a printer out of the queue forever.
  78. # Matches the watchdog timeout (90 s) plus a safety margin so the
  79. # watchdog runs first on the unhappy path.
  80. self._dispatch_max_hold = 180.0
  81. async def run(self):
  82. """Main loop - check queue every interval."""
  83. self._running = True
  84. logger.info("Print scheduler started")
  85. while self._running:
  86. try:
  87. await self.check_queue()
  88. except Exception as e:
  89. logger.error("Scheduler error: %s", e)
  90. await asyncio.sleep(self._check_interval)
  91. def stop(self):
  92. """Stop the scheduler."""
  93. self._running = False
  94. logger.info("Print scheduler stopped")
  95. async def check_queue(self):
  96. """Check for prints ready to start."""
  97. async with async_session() as db:
  98. # Check if shortest-job-first scheduling is enabled
  99. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  100. # Get all pending items, ordered by printer and position (or SJF order)
  101. if sjf_enabled:
  102. # SJF: group by printer (and target_model for model-based jobs),
  103. # then items already jumped get top priority (starvation guard),
  104. # then sort by print_time ascending. Items with no print time go last.
  105. result = await db.execute(
  106. select(PrintQueueItem)
  107. .where(PrintQueueItem.status == "pending")
  108. .order_by(
  109. PrintQueueItem.printer_id,
  110. PrintQueueItem.target_model,
  111. PrintQueueItem.been_jumped.desc(),
  112. PrintQueueItem.print_time_seconds.asc().nullslast(),
  113. PrintQueueItem.position,
  114. )
  115. )
  116. else:
  117. result = await db.execute(
  118. select(PrintQueueItem)
  119. .where(PrintQueueItem.status == "pending")
  120. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  121. )
  122. items = list(result.scalars().all())
  123. # Read plate-clear setting once per queue check
  124. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=True)
  125. if not items:
  126. # No pending items — still check auto-drying on idle printers
  127. await self._check_auto_drying(db, [], set(), require_plate_clear=require_plate_clear)
  128. return
  129. logger.info(
  130. "Queue check: found %d pending items: %s",
  131. len(items),
  132. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  133. )
  134. # Seed busy_printers with printers that already have an item in 'printing'
  135. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  136. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  137. # lag several seconds behind the print command, so the next check_queue
  138. # tick still sees IDLE and would double-dispatch onto the same printer.
  139. # Without this guard, two pending items targeting the same printer
  140. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  141. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  142. busy_result = await db.execute(
  143. select(PrintQueueItem.printer_id)
  144. .where(PrintQueueItem.status == "printing")
  145. .where(PrintQueueItem.printer_id.is_not(None))
  146. )
  147. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  148. # Defense-in-depth (#1157): augment busy_printers with any printer
  149. # still in its post-dispatch hold window. Empirically, the DB seed
  150. # above can miss in-flight items in a multi-plate batch — same-file
  151. # plates were being dispatched 30 s apart while the H2D was still
  152. # digesting the first project_file. The hold is keyed in-memory and
  153. # released by the watchdog on the success path, so it adds a layer
  154. # that doesn't depend on DB row visibility or completion-callback
  155. # timing.
  156. for held_printer_id in list(self._dispatch_holds.keys()):
  157. if self._printer_in_dispatch_hold(held_printer_id):
  158. busy_printers.add(held_printer_id)
  159. # Log skip reasons once per queue check (not per item)
  160. skip_reasons: dict[str, int] = {}
  161. for item in items:
  162. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  163. if item.scheduled_time:
  164. sched = item.scheduled_time
  165. if sched.tzinfo is None:
  166. sched = sched.replace(tzinfo=timezone.utc)
  167. if sched > datetime.now(timezone.utc):
  168. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  169. continue
  170. # Skip items that require manual start
  171. if item.manual_start:
  172. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  173. continue
  174. if item.printer_id:
  175. # Specific printer assignment (existing behavior)
  176. if item.printer_id in busy_printers:
  177. continue
  178. # Check if printer is idle
  179. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  180. printer_connected = printer_manager.is_connected(item.printer_id)
  181. # If printer not connected, try to power on via smart plug
  182. if not printer_connected:
  183. plugs = await self._get_smart_plugs(db, item.printer_id)
  184. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  185. if auto_on_plugs:
  186. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  187. # Power on using the first auto_on plug (the printer power plug)
  188. powered_on = await self._power_on_and_wait(auto_on_plugs[0], item.printer_id, db)
  189. if powered_on:
  190. # Also turn on any remaining auto_on plugs (e.g., filter)
  191. for extra_plug in auto_on_plugs[1:]:
  192. try:
  193. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  194. await service.turn_on(extra_plug)
  195. logger.info(
  196. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  197. )
  198. except Exception as e:
  199. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  200. printer_connected = True
  201. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  202. else:
  203. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  204. busy_printers.add(item.printer_id)
  205. continue
  206. else:
  207. # No plug or auto_on disabled
  208. busy_printers.add(item.printer_id)
  209. continue
  210. # Check if printer is idle (busy with another print)
  211. if not printer_idle:
  212. # If printer is drying (not truly busy), handle based on queue_drying_block
  213. if self._drying_in_progress.get(item.printer_id):
  214. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  215. if block_for_drying:
  216. # Drying blocks queue — skip this printer
  217. busy_printers.add(item.printer_id)
  218. continue
  219. else:
  220. # Print takes priority — stop drying
  221. await self._stop_drying(item.printer_id)
  222. # Re-check idle after stopping drying
  223. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  224. if not printer_idle:
  225. busy_printers.add(item.printer_id)
  226. continue
  227. else:
  228. busy_printers.add(item.printer_id)
  229. continue
  230. # Check condition (previous print success)
  231. if item.require_previous_success:
  232. if not await self._check_previous_success(db, item):
  233. item.status = "skipped"
  234. item.error_message = "Previous print failed or was aborted"
  235. item.completed_at = datetime.now(timezone.utc)
  236. await db.commit()
  237. logger.info("Skipped queue item %s - previous print failed", item.id)
  238. # Send notification
  239. job_name = await self._get_job_name(db, item)
  240. printer = await self._get_printer(db, item.printer_id)
  241. await notification_service.on_queue_job_skipped(
  242. job_name=job_name,
  243. printer_id=item.printer_id,
  244. printer_name=printer.name if printer else "Unknown",
  245. reason="Previous print failed or was aborted",
  246. db=db,
  247. )
  248. continue
  249. # Compute AMS mapping if not already set
  250. if not item.ams_mapping:
  251. computed_mapping = await self._compute_ams_mapping_for_printer(db, item.printer_id, item)
  252. if computed_mapping:
  253. item.ams_mapping = json.dumps(computed_mapping)
  254. logger.info(
  255. f"Queue item {item.id}: Computed AMS mapping for printer {item.printer_id}: {computed_mapping}"
  256. )
  257. await db.commit()
  258. # Start the print
  259. await self._start_print(db, item)
  260. busy_printers.add(item.printer_id)
  261. # SJF starvation guard: mark items that were jumped
  262. if sjf_enabled and item.print_time_seconds is not None:
  263. for other in items:
  264. if (
  265. other.id != item.id
  266. and other.status == "pending"
  267. and other.printer_id == item.printer_id
  268. and not other.been_jumped
  269. and other.position < item.position
  270. and (
  271. other.print_time_seconds is None
  272. or other.print_time_seconds > item.print_time_seconds
  273. )
  274. ):
  275. other.been_jumped = True
  276. await db.commit()
  277. elif item.target_model:
  278. # Model-based assignment - find any idle printer of matching model
  279. # Parse required filament types if present
  280. required_types = None
  281. if item.required_filament_types:
  282. try:
  283. required_types = json.loads(item.required_filament_types)
  284. except json.JSONDecodeError:
  285. pass # Ignore malformed filament types; treat as no constraint
  286. # Parse filament overrides if present
  287. filament_overrides = None
  288. if item.filament_overrides:
  289. try:
  290. filament_overrides = json.loads(item.filament_overrides)
  291. except json.JSONDecodeError:
  292. pass
  293. # If overrides exist, use override types for validation instead
  294. effective_types = required_types
  295. if filament_overrides:
  296. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  297. if override_types:
  298. # Merge: keep original types for non-overridden slots, add override types
  299. effective_types = sorted(set(required_types or []) | set(override_types))
  300. printer_id, waiting_reason = await self._find_idle_printer_for_model(
  301. db,
  302. item.target_model,
  303. busy_printers,
  304. effective_types,
  305. item.target_location,
  306. filament_overrides=filament_overrides,
  307. require_plate_clear=require_plate_clear,
  308. )
  309. # Update waiting_reason if changed and send notification when first waiting
  310. if item.waiting_reason != waiting_reason:
  311. was_waiting = item.waiting_reason is not None
  312. item.waiting_reason = waiting_reason
  313. await db.commit()
  314. # Send waiting notification only when transitioning to waiting state
  315. # and the reason requires user action (not just "all printers busy")
  316. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  317. job_name = await self._get_job_name(db, item)
  318. await notification_service.on_queue_job_waiting(
  319. job_name=job_name,
  320. target_model=item.target_model,
  321. waiting_reason=waiting_reason,
  322. db=db,
  323. )
  324. if printer_id:
  325. # Check condition (previous print success) before assigning
  326. if item.require_previous_success:
  327. if not await self._check_previous_success(db, item):
  328. item.status = "skipped"
  329. item.error_message = "Previous print failed or was aborted"
  330. item.completed_at = datetime.now(timezone.utc)
  331. await db.commit()
  332. logger.info("Skipped queue item %s - previous print failed", item.id)
  333. # Send notification
  334. job_name = await self._get_job_name(db, item)
  335. printer = await self._get_printer(db, printer_id)
  336. await notification_service.on_queue_job_skipped(
  337. job_name=job_name,
  338. printer_id=printer_id,
  339. printer_name=printer.name if printer else "Unknown",
  340. reason="Previous print failed or was aborted",
  341. db=db,
  342. )
  343. continue
  344. # Assign printer and start - clear waiting reason
  345. item.printer_id = printer_id
  346. item.waiting_reason = None
  347. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  348. # Send assignment notification
  349. job_name = await self._get_job_name(db, item)
  350. printer = await self._get_printer(db, printer_id)
  351. await notification_service.on_queue_job_assigned(
  352. job_name=job_name,
  353. printer_id=printer_id,
  354. printer_name=printer.name if printer else "Unknown",
  355. target_model=item.target_model,
  356. db=db,
  357. )
  358. # Compute AMS mapping for the assigned printer if not already set
  359. # This is critical for model-based jobs where mapping wasn't computed upfront
  360. if not item.ams_mapping:
  361. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  362. if computed_mapping:
  363. item.ams_mapping = json.dumps(computed_mapping)
  364. logger.info(
  365. f"Queue item {item.id}: Computed AMS mapping for printer {printer_id}: {computed_mapping}"
  366. )
  367. await db.commit()
  368. await self._start_print(db, item)
  369. busy_printers.add(printer_id)
  370. # SJF starvation guard: mark model-based items that were jumped
  371. if sjf_enabled and item.print_time_seconds is not None:
  372. for other in items:
  373. if (
  374. other.id != item.id
  375. and other.status == "pending"
  376. and other.printer_id is None
  377. and other.target_model
  378. and other.target_model.upper() == item.target_model.upper()
  379. and not other.been_jumped
  380. and other.position < item.position
  381. and (
  382. other.print_time_seconds is None
  383. or other.print_time_seconds > item.print_time_seconds
  384. )
  385. ):
  386. other.been_jumped = True
  387. await db.commit()
  388. # Log summary of skip reasons (helps diagnose why queue items aren't starting)
  389. if skip_reasons:
  390. logger.info("Queue skip summary: %s", skip_reasons)
  391. if busy_printers:
  392. # Log why each printer was busy (first time it was checked)
  393. for pid in busy_printers:
  394. state = printer_manager.get_status(pid)
  395. connected = printer_manager.is_connected(pid)
  396. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  397. state_name = state.state if state else "NO_STATUS"
  398. logger.info(
  399. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  400. pid,
  401. connected,
  402. state_name,
  403. awaiting,
  404. )
  405. # Auto-drying: start drying on idle printers that have no pending queue items
  406. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  407. async def _find_idle_printer_for_model(
  408. self,
  409. db: AsyncSession,
  410. model: str,
  411. exclude_ids: set[int],
  412. required_filament_types: list[str] | None = None,
  413. target_location: str | None = None,
  414. filament_overrides: list[dict] | None = None,
  415. require_plate_clear: bool = True,
  416. ) -> tuple[int | None, str | None]:
  417. """Find an idle, connected printer matching the model with compatible filaments.
  418. Args:
  419. db: Database session
  420. model: Printer model to match (e.g., "X1C", "P1S")
  421. exclude_ids: Printer IDs to exclude (already busy)
  422. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  423. If provided, only printers with all required types loaded will match.
  424. target_location: Optional location filter. If provided, only printers in this location are considered.
  425. filament_overrides: Optional list of override dicts. Each entry may include
  426. ``force_color_match: true`` to require an exact type+color match
  427. on the printer for that slot. Without the flag the existing
  428. colour-preference logic applies.
  429. Returns:
  430. Tuple of (printer_id, waiting_reason):
  431. - (printer_id, None) if a matching printer was found
  432. - (None, reason) if no printer is available, with explanation
  433. """
  434. # Normalize model name and use case-insensitive matching
  435. normalized_model = normalize_printer_model(model) or model
  436. query = (
  437. select(Printer)
  438. .where(func.lower(Printer.model) == normalized_model.lower())
  439. .where(Printer.is_active == True) # noqa: E712
  440. )
  441. # Add location filter if specified
  442. if target_location:
  443. query = query.where(Printer.location == target_location)
  444. result = await db.execute(query)
  445. printers = list(result.scalars().all())
  446. location_suffix = f" in {target_location}" if target_location else ""
  447. if not printers:
  448. return None, f"No active {normalized_model} printers{location_suffix} configured"
  449. # Separate force-matched overrides from preference-only overrides
  450. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  451. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  452. # Track reasons for skipping printers
  453. printers_busy = []
  454. printers_offline = []
  455. printers_missing_filament: list[tuple[str, list[str]]] = []
  456. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  457. for printer in printers:
  458. if printer.id in exclude_ids:
  459. # Printer is already claimed by another job in this scheduling run.
  460. # For force-color jobs, still check if the color would match — if not,
  461. # report it as a color mismatch rather than plain "Busy" so the user
  462. # knows the job needs a filament change, not just to wait for availability.
  463. if force_overrides and not pref_overrides:
  464. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  465. if missing_colors:
  466. printers_missing_filament.append((printer.name, missing_colors))
  467. continue
  468. printers_busy.append(printer.name)
  469. continue
  470. is_connected = printer_manager.is_connected(printer.id)
  471. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  472. if not is_connected:
  473. printers_offline.append(printer.name)
  474. continue
  475. if not is_idle:
  476. # Printer is currently printing. For force-color jobs, check whether the
  477. # loaded color would satisfy the requirement — if not, surface it as a
  478. # color-mismatch reason rather than plain "Busy" so the user understands
  479. # that the job is waiting for a filament change, not just printer availability.
  480. if force_overrides and not pref_overrides:
  481. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  482. if missing_colors:
  483. printers_missing_filament.append((printer.name, missing_colors))
  484. logger.debug(
  485. "Printer %s (%s) is busy but also has wrong force-color: %s",
  486. printer.id,
  487. printer.name,
  488. missing_colors,
  489. )
  490. continue
  491. printers_busy.append(printer.name)
  492. continue
  493. # Validate filament compatibility if required types are specified
  494. if required_filament_types:
  495. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  496. if missing:
  497. # When force_overrides are present, enrich missing entries with color info
  498. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  499. if force_overrides:
  500. force_color_map = {
  501. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  502. for o in force_overrides
  503. }
  504. missing_enriched = [
  505. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  506. for t in missing
  507. ]
  508. printers_missing_filament.append((printer.name, missing_enriched))
  509. else:
  510. printers_missing_filament.append((printer.name, missing))
  511. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  512. continue
  513. # Force color match: ALL flagged slots must have an exact type+color match
  514. if force_overrides:
  515. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  516. if missing_colors:
  517. printers_missing_filament.append((printer.name, missing_colors))
  518. logger.debug(
  519. "Skipping printer %s (%s) - missing force-matched colors: %s",
  520. printer.id,
  521. printer.name,
  522. missing_colors,
  523. )
  524. continue
  525. # If preference-only overrides exist, rank by color matches (existing behaviour)
  526. if pref_overrides:
  527. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  528. if color_matches > 0:
  529. candidates.append((printer.id, color_matches))
  530. else:
  531. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  532. printers_missing_filament.append((printer.name, override_colors))
  533. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  534. continue
  535. elif force_overrides:
  536. # Passed all force checks — immediately eligible (no preference ordering needed)
  537. return printer.id, None
  538. else:
  539. # No overrides at all - take first available (existing behavior)
  540. return printer.id, None
  541. # If we have candidates from preference override matching, pick the one with most color matches
  542. if candidates:
  543. candidates.sort(key=lambda c: c[1], reverse=True)
  544. return candidates[0][0], None
  545. # Build waiting reason from what we found
  546. reasons = []
  547. if printers_missing_filament:
  548. # Filament/color mismatch is most actionable - show first
  549. if force_overrides and not pref_overrides:
  550. # All mismatches are force-color failures — use descriptive message only;
  551. # but only if there are no busy printers that DO have the matching color.
  552. # If a printer has the right color but is busy, surface "Busy" instead so
  553. # the user knows the job will start automatically once that printer is free.
  554. if not printers_busy:
  555. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  556. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  557. # else: fall through — printers_busy will be appended below
  558. else:
  559. names_and_missing = [
  560. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  561. ]
  562. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  563. if printers_busy:
  564. reasons.append(f"Busy: {', '.join(printers_busy)}")
  565. if printers_offline:
  566. reasons.append(f"Offline: {', '.join(printers_offline)}")
  567. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  568. @staticmethod
  569. def _is_busy_only(waiting_reason: str) -> bool:
  570. """Check if the waiting reason only contains 'Busy' entries.
  571. When all matching printers are simply busy printing, the queued job
  572. will start automatically once a printer finishes — no user action
  573. is required, so we skip the notification.
  574. """
  575. parts = [p.strip() for p in waiting_reason.split(" | ")]
  576. return all(p.startswith("Busy:") for p in parts)
  577. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  578. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  579. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  580. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  581. with an exact type+color match.
  582. Returns:
  583. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  584. """
  585. status = printer_manager.get_status(printer_id)
  586. if not status:
  587. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  588. # Build set of loaded type+colour pairs from AMS and external spool
  589. loaded: set[tuple[str, str]] = set()
  590. for ams_unit in status.raw_data.get("ams", []):
  591. for tray in ams_unit.get("tray", []):
  592. tray_type = tray.get("tray_type")
  593. tray_color = tray.get("tray_color", "")
  594. if tray_type:
  595. color_norm = tray_color.replace("#", "").lower()[:6]
  596. loaded.add((_canonical_filament_type(tray_type), color_norm))
  597. for vt in status.raw_data.get("vt_tray") or []:
  598. vt_type = vt.get("tray_type")
  599. if vt_type:
  600. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  601. loaded.add((_canonical_filament_type(vt_type), color_norm))
  602. missing = []
  603. for o in force_overrides:
  604. o_type = _canonical_filament_type(o.get("type") or "")
  605. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  606. if (o_type, o_color) not in loaded:
  607. color_label = o.get("color_name") or o.get("color", "?")
  608. missing.append(f"{o_type} ({color_label})")
  609. return missing
  610. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  611. """Get the list of required filament types that are not loaded on the printer.
  612. Args:
  613. printer_id: The printer ID
  614. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  615. Returns:
  616. List of missing filament types (empty if all are loaded)
  617. """
  618. status = printer_manager.get_status(printer_id)
  619. if not status:
  620. return required_types # Can't determine, assume all missing
  621. # Collect all filament types loaded on this printer (AMS units + external spool)
  622. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  623. loaded_types: set[str] = set()
  624. # Check AMS units (stored in raw_data["ams"])
  625. ams_data = status.raw_data.get("ams", [])
  626. if ams_data:
  627. for ams_unit in ams_data:
  628. for tray in ams_unit.get("tray", []):
  629. tray_type = tray.get("tray_type")
  630. if tray_type:
  631. loaded_types.add(_canonical_filament_type(tray_type))
  632. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  633. for vt in status.raw_data.get("vt_tray") or []:
  634. vt_type = vt.get("tray_type")
  635. if vt_type:
  636. loaded_types.add(_canonical_filament_type(vt_type))
  637. # Find which required types are missing (using canonical type for equivalence)
  638. missing = []
  639. for req_type in required_types:
  640. if _canonical_filament_type(req_type) not in loaded_types:
  641. missing.append(req_type)
  642. return missing
  643. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  644. """Count how many filament overrides have an exact color match on the printer.
  645. Used to prefer printers that already have the desired override colors loaded.
  646. """
  647. status = printer_manager.get_status(printer_id)
  648. if not status:
  649. return 0
  650. # Collect loaded filaments' type+color pairs
  651. loaded: set[tuple[str, str]] = set()
  652. for ams_unit in status.raw_data.get("ams", []):
  653. for tray in ams_unit.get("tray", []):
  654. tray_type = tray.get("tray_type")
  655. tray_color = tray.get("tray_color", "")
  656. if tray_type:
  657. color_norm = tray_color.replace("#", "").lower()[:6]
  658. loaded.add((tray_type.upper(), color_norm))
  659. for vt in status.raw_data.get("vt_tray") or []:
  660. vt_type = vt.get("tray_type")
  661. if vt_type:
  662. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  663. loaded.add((vt_type.upper(), color_norm))
  664. matches = 0
  665. for o in overrides:
  666. o_type = (o.get("type") or "").upper()
  667. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  668. if (o_type, o_color) in loaded:
  669. matches += 1
  670. return matches
  671. async def _compute_ams_mapping_for_printer(
  672. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  673. ) -> list[int] | None:
  674. """Compute AMS mapping for a printer based on filament requirements.
  675. Called when a queue item has no ams_mapping set — either for model-based
  676. items after printer assignment, or printer-specific items (e.g. from VP).
  677. Args:
  678. db: Database session
  679. printer_id: The assigned printer ID
  680. item: The queue item (contains archive_id or library_file_id)
  681. Returns:
  682. AMS mapping array or None if no mapping needed/possible
  683. """
  684. # Get printer status
  685. status = printer_manager.get_status(printer_id)
  686. if not status:
  687. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  688. return None
  689. # Get filament requirements from source file
  690. filament_reqs = await self._get_filament_requirements(db, item)
  691. if not filament_reqs:
  692. logger.debug("No filament requirements found for queue item %s", item.id)
  693. return None
  694. # Apply filament overrides if present
  695. if item.filament_overrides:
  696. try:
  697. overrides = json.loads(item.filament_overrides)
  698. override_map = {o["slot_id"]: o for o in overrides}
  699. for req in filament_reqs:
  700. if req["slot_id"] in override_map:
  701. override = override_map[req["slot_id"]]
  702. req["type"] = override["type"]
  703. req["color"] = override["color"]
  704. # Clear tray_info_idx so matching uses type+color instead of
  705. # the original 3MF's tray_info_idx (which would match the old filament)
  706. req["tray_info_idx"] = ""
  707. logger.debug(
  708. "Queue item %s: Override slot %d -> %s %s",
  709. item.id,
  710. req["slot_id"],
  711. override["type"],
  712. override["color"],
  713. )
  714. except (json.JSONDecodeError, KeyError, TypeError) as e:
  715. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  716. # Build loaded filaments from printer status
  717. loaded_filaments = self._build_loaded_filaments(status)
  718. if not loaded_filaments:
  719. logger.debug("No filaments loaded on printer %s", printer_id)
  720. return None
  721. # Check if user prefers lowest remaining filament when multiple spools match
  722. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  723. # Compute mapping: match required filaments to available slots
  724. return self._match_filaments_to_slots(filament_reqs, loaded_filaments, prefer_lowest)
  725. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  726. """Extract filament requirements from the source 3MF file.
  727. Args:
  728. db: Database session
  729. item: Queue item with archive_id or library_file_id
  730. Returns:
  731. List of filament requirement dicts with slot_id, type, color, used_grams
  732. """
  733. file_path: Path | None = None
  734. if item.archive_id:
  735. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  736. archive = result.scalar_one_or_none()
  737. if archive:
  738. file_path = settings.base_dir / archive.file_path
  739. elif item.library_file_id:
  740. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  741. library_file = result.scalar_one_or_none()
  742. if library_file:
  743. lib_path = Path(library_file.file_path)
  744. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  745. if not file_path or not file_path.exists():
  746. return None
  747. filaments = []
  748. try:
  749. with zipfile.ZipFile(file_path, "r") as zf:
  750. if "Metadata/slice_info.config" not in zf.namelist():
  751. return None
  752. content = zf.read("Metadata/slice_info.config").decode()
  753. root = ET.fromstring(content)
  754. # Check if plate_id is specified - use that plate's filaments
  755. plate_id = item.plate_id
  756. if plate_id:
  757. for plate_elem in root.findall("./plate"):
  758. plate_index = None
  759. for meta in plate_elem.findall("metadata"):
  760. if meta.get("key") == "index":
  761. plate_index = int(meta.get("value", "0"))
  762. break
  763. if plate_index == plate_id:
  764. for filament_elem in plate_elem.findall("./filament"):
  765. filament_id = filament_elem.get("id")
  766. filament_type = filament_elem.get("type", "")
  767. filament_color = filament_elem.get("color", "")
  768. # tray_info_idx identifies the specific spool selected when slicing
  769. tray_info_idx = filament_elem.get("tray_info_idx", "")
  770. used_g = filament_elem.get("used_g", "0")
  771. try:
  772. used_grams = float(used_g)
  773. if used_grams > 0 and filament_id:
  774. filaments.append(
  775. {
  776. "slot_id": int(filament_id),
  777. "type": filament_type,
  778. "color": filament_color,
  779. "tray_info_idx": tray_info_idx,
  780. "used_grams": round(used_grams, 1),
  781. }
  782. )
  783. except (ValueError, TypeError):
  784. pass # Skip filament entry with unparseable usage data
  785. break
  786. else:
  787. # No plate_id - extract all filaments with used_g > 0
  788. for filament_elem in root.findall("./filament"):
  789. filament_id = filament_elem.get("id")
  790. filament_type = filament_elem.get("type", "")
  791. filament_color = filament_elem.get("color", "")
  792. # tray_info_idx identifies the specific spool selected when slicing
  793. tray_info_idx = filament_elem.get("tray_info_idx", "")
  794. used_g = filament_elem.get("used_g", "0")
  795. try:
  796. used_grams = float(used_g)
  797. if used_grams > 0 and filament_id:
  798. filaments.append(
  799. {
  800. "slot_id": int(filament_id),
  801. "type": filament_type,
  802. "color": filament_color,
  803. "tray_info_idx": tray_info_idx,
  804. "used_grams": round(used_grams, 1),
  805. }
  806. )
  807. except (ValueError, TypeError):
  808. pass # Skip filament entry with unparseable usage data
  809. filaments.sort(key=lambda x: x["slot_id"])
  810. # Enrich with nozzle mapping for dual-nozzle printers
  811. nozzle_mapping = extract_nozzle_mapping_from_3mf(zf)
  812. if nozzle_mapping:
  813. for filament in filaments:
  814. filament["nozzle_id"] = nozzle_mapping.get(filament["slot_id"])
  815. except Exception as e:
  816. logger.warning("Failed to parse filament requirements: %s", e)
  817. return None
  818. return filaments if filaments else None
  819. def _build_loaded_filaments(self, status) -> list[dict]:
  820. """Build list of loaded filaments from printer status.
  821. Args:
  822. status: PrinterState from printer_manager
  823. Returns:
  824. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  825. """
  826. filaments = []
  827. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  828. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  829. # Parse AMS units from raw_data
  830. ams_data = status.raw_data.get("ams", [])
  831. for ams_unit in ams_data:
  832. ams_id = int(ams_unit.get("id", 0))
  833. trays = ams_unit.get("tray", [])
  834. is_ht = len(trays) == 1 # AMS-HT has single tray
  835. for tray in trays:
  836. tray_type = tray.get("tray_type")
  837. if tray_type:
  838. tray_id = int(tray.get("id", 0))
  839. tray_color = tray.get("tray_color", "")
  840. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  841. tray_info_idx = tray.get("tray_info_idx", "")
  842. # Normalize color: remove alpha, add hash
  843. color = self._normalize_color(tray_color)
  844. # Calculate global tray ID
  845. # AMS-HT units have IDs starting at 128 with a single tray
  846. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  847. filaments.append(
  848. {
  849. "type": tray_type,
  850. "color": color,
  851. "tray_info_idx": tray_info_idx,
  852. "ams_id": ams_id,
  853. "tray_id": tray_id,
  854. "is_ht": is_ht,
  855. "is_external": False,
  856. "global_tray_id": global_tray_id,
  857. "extruder_id": ams_extruder_map.get(str(ams_id)),
  858. "remain": tray.get("remain", -1),
  859. }
  860. )
  861. # Check external spool(s) (vt_tray is a list)
  862. for idx, vt in enumerate(status.raw_data.get("vt_tray") or []):
  863. if vt.get("tray_type"):
  864. color = self._normalize_color(vt.get("tray_color", ""))
  865. tray_id = int(vt.get("id", 254))
  866. filaments.append(
  867. {
  868. "type": vt["tray_type"],
  869. "color": color,
  870. "tray_info_idx": vt.get("tray_info_idx", ""),
  871. "ams_id": -1,
  872. "tray_id": idx,
  873. "is_ht": False,
  874. "is_external": True,
  875. "global_tray_id": tray_id,
  876. "extruder_id": (255 - tray_id) if ams_extruder_map else None,
  877. "remain": vt.get("remain", -1),
  878. }
  879. )
  880. return filaments
  881. def _normalize_color(self, color: str | None) -> str:
  882. """Normalize color to #RRGGBB format."""
  883. if not color:
  884. return "#808080"
  885. hex_color = color.replace("#", "")[:6]
  886. return f"#{hex_color}"
  887. def _normalize_color_for_compare(self, color: str | None) -> str:
  888. """Normalize color for comparison (lowercase, no hash)."""
  889. if not color:
  890. return ""
  891. return color.replace("#", "").lower()[:6]
  892. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  893. """Check if two colors are visually similar within a threshold."""
  894. hex1 = self._normalize_color_for_compare(color1)
  895. hex2 = self._normalize_color_for_compare(color2)
  896. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  897. return False
  898. try:
  899. r1 = int(hex1[0:2], 16)
  900. g1 = int(hex1[2:4], 16)
  901. b1 = int(hex1[4:6], 16)
  902. r2 = int(hex2[0:2], 16)
  903. g2 = int(hex2[2:4], 16)
  904. b2 = int(hex2[4:6], 16)
  905. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  906. except ValueError:
  907. return False
  908. def _match_filaments_to_slots(
  909. self, required: list[dict], loaded: list[dict], prefer_lowest: bool = False
  910. ) -> list[int] | None:
  911. """Match required filaments to loaded filaments and build AMS mapping.
  912. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  913. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  914. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  915. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  916. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  917. matching among those trays.
  918. Args:
  919. required: List of required filaments with slot_id, type, color, tray_info_idx
  920. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  921. Returns:
  922. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  923. """
  924. if not required:
  925. return None
  926. # Track used trays to avoid duplicate assignment
  927. used_tray_ids: set[int] = set()
  928. comparisons = []
  929. for req in required:
  930. req_type = (req.get("type") or "").upper()
  931. req_color = req.get("color", "")
  932. req_tray_info_idx = req.get("tray_info_idx", "")
  933. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  934. idx_match = None
  935. exact_match = None
  936. similar_match = None
  937. type_only_match = None
  938. # Get available trays (not already used)
  939. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  940. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  941. # Hard filter — cross-nozzle assignment causes print failures
  942. # ("position of left hotend is abnormal"), so never fall back.
  943. req_nozzle_id = req.get("nozzle_id")
  944. if req_nozzle_id is not None:
  945. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  946. # Sort by remaining filament (ascending) so lowest-remain spool wins .find()
  947. if prefer_lowest:
  948. available.sort(key=lambda f: f.get("remain", -1) if f.get("remain", -1) >= 0 else 101)
  949. # Check if tray_info_idx is unique among available trays
  950. if req_tray_info_idx:
  951. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  952. if len(idx_matches) == 1:
  953. # Unique tray_info_idx - use it as definitive match
  954. idx_match = idx_matches[0]
  955. logger.debug(
  956. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  957. f"-> tray {idx_match['global_tray_id']}"
  958. )
  959. elif len(idx_matches) > 1:
  960. # Multiple trays with same tray_info_idx - use color matching among them
  961. logger.debug(
  962. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  963. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  964. )
  965. if prefer_lowest:
  966. idx_matches.sort(key=lambda f: f.get("remain", -1) if f.get("remain", -1) >= 0 else 101)
  967. # Use color matching within this subset
  968. for f in idx_matches:
  969. f_color = f.get("color", "")
  970. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  971. if not exact_match:
  972. exact_match = f
  973. elif self._colors_are_similar(f_color, req_color):
  974. if not similar_match:
  975. similar_match = f
  976. elif not type_only_match:
  977. type_only_match = f
  978. # If no idx_match yet, do standard type/color matching on all available trays
  979. if not idx_match and not exact_match and not similar_match and not type_only_match:
  980. for f in available:
  981. f_type = (f.get("type") or "").upper()
  982. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  983. continue
  984. # Type matches - check color
  985. f_color = f.get("color", "")
  986. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  987. if not exact_match:
  988. exact_match = f
  989. elif self._colors_are_similar(f_color, req_color):
  990. if not similar_match:
  991. similar_match = f
  992. elif not type_only_match:
  993. type_only_match = f
  994. match = idx_match or exact_match or similar_match or type_only_match
  995. if match:
  996. used_tray_ids.add(match["global_tray_id"])
  997. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  998. else:
  999. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  1000. # Build mapping array
  1001. if not comparisons:
  1002. return None
  1003. max_slot_id = max(c["slot_id"] for c in comparisons)
  1004. if max_slot_id <= 0:
  1005. return None
  1006. mapping = [-1] * max_slot_id
  1007. for c in comparisons:
  1008. slot_id = c["slot_id"]
  1009. if slot_id and slot_id > 0:
  1010. mapping[slot_id - 1] = c["global_tray_id"]
  1011. return mapping
  1012. def _mark_printer_dispatched(
  1013. self,
  1014. printer_id: int,
  1015. pre_state: str | None,
  1016. pre_subtask_id: str | None,
  1017. ) -> None:
  1018. """Record that a print command was just sent to ``printer_id``.
  1019. Held until either the watchdog observes a state/subtask transition
  1020. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  1021. """
  1022. if not pre_state:
  1023. # No pre_state means we can't detect a transition — fall back to a
  1024. # pure time-based hold using empty string as a sentinel that won't
  1025. # match any real printer state.
  1026. pre_state = ""
  1027. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  1028. def _release_dispatch_hold(self, printer_id: int) -> None:
  1029. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  1030. self._dispatch_holds.pop(printer_id, None)
  1031. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  1032. """True if ``printer_id`` is still inside its post-dispatch hold window.
  1033. Returns False (and clears the hold) once any of these are true:
  1034. - hard timeout (``_dispatch_max_hold``) has elapsed
  1035. - the printer has transitioned out of pre_state and we're past the
  1036. minimum cooldown
  1037. - the printer's subtask_id has advanced past pre_subtask_id and we're
  1038. past the minimum cooldown
  1039. Otherwise the printer is held — caller should treat it as busy.
  1040. """
  1041. entry = self._dispatch_holds.get(printer_id)
  1042. if not entry:
  1043. return False
  1044. started_at, pre_state, pre_subtask_id = entry
  1045. elapsed = time.monotonic() - started_at
  1046. if elapsed >= self._dispatch_max_hold:
  1047. self._dispatch_holds.pop(printer_id, None)
  1048. return False
  1049. # Without a pre_state we can't detect a transition — fall back to the
  1050. # min cooldown alone, then drop the hold.
  1051. if not pre_state:
  1052. if elapsed >= self._dispatch_min_cooldown:
  1053. self._dispatch_holds.pop(printer_id, None)
  1054. return False
  1055. return True
  1056. status = printer_manager.get_status(printer_id)
  1057. current_state = getattr(status, "state", None) if status else None
  1058. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  1059. transitioned = (current_state is not None and current_state != pre_state) or (
  1060. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  1061. )
  1062. if transitioned and elapsed >= self._dispatch_min_cooldown:
  1063. self._dispatch_holds.pop(printer_id, None)
  1064. return False
  1065. return True
  1066. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  1067. """Check if a printer is connected and idle."""
  1068. if not printer_manager.is_connected(printer_id):
  1069. logger.debug("Printer %d: not connected", printer_id)
  1070. return False
  1071. state = printer_manager.get_status(printer_id)
  1072. if not state:
  1073. logger.debug("Printer %d: no status available", printer_id)
  1074. return False
  1075. # Plate-clear gate: if the printer finished/failed a previous print and the user
  1076. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  1077. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  1078. # printer, it boots back into IDLE with no memory of the previous finish; without
  1079. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  1080. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  1081. logger.debug(
  1082. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  1083. printer_id,
  1084. state.state,
  1085. )
  1086. return False
  1087. idle = state.state in ("IDLE", "FINISH", "FAILED")
  1088. if not idle:
  1089. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  1090. return idle
  1091. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  1092. """Read a setting value from the database."""
  1093. result = await db.execute(select(Settings).where(Settings.key == key))
  1094. setting = result.scalar_one_or_none()
  1095. return setting.value if setting else None
  1096. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  1097. """Read a boolean setting from the database."""
  1098. result = await db.execute(select(Settings).where(Settings.key == key))
  1099. setting = result.scalar_one_or_none()
  1100. if setting:
  1101. return setting.value.lower() == "true"
  1102. return default
  1103. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  1104. """Get drying presets (user-configured or built-in defaults)."""
  1105. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  1106. setting = result.scalar_one_or_none()
  1107. if setting and setting.value:
  1108. try:
  1109. presets = json.loads(setting.value)
  1110. if isinstance(presets, dict) and presets:
  1111. return presets
  1112. except json.JSONDecodeError:
  1113. pass
  1114. return self.DEFAULT_DRYING_PRESETS
  1115. def _get_conservative_drying_params(
  1116. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  1117. ) -> tuple[int, int, str] | None:
  1118. """Get the most conservative drying params for mixed filament types in an AMS unit.
  1119. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  1120. """
  1121. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  1122. hours_key = f"{temp_key}_hours"
  1123. min_temp = None
  1124. max_hours = None
  1125. filament_type = ""
  1126. for tray in trays:
  1127. tray_type = tray.get("tray_type", "")
  1128. if not tray_type:
  1129. continue
  1130. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  1131. base_type = tray_type.split()[0].upper()
  1132. preset = presets.get(base_type)
  1133. if not preset:
  1134. continue
  1135. temp = preset.get(temp_key, 55)
  1136. hours = preset.get(hours_key, 12)
  1137. # Conservative: lowest temp, longest duration
  1138. if min_temp is None or temp < min_temp:
  1139. min_temp = temp
  1140. if max_hours is None or hours > max_hours:
  1141. max_hours = hours
  1142. if not filament_type:
  1143. filament_type = base_type
  1144. if min_temp is None:
  1145. return None
  1146. return (min_temp, max_hours or 12, filament_type)
  1147. async def _check_auto_drying(
  1148. self,
  1149. db: AsyncSession,
  1150. queue_items: list[PrintQueueItem],
  1151. busy_printers: set[int],
  1152. *,
  1153. require_plate_clear: bool = True,
  1154. ):
  1155. """Start drying on idle printers based on humidity.
  1156. Two modes (can both be enabled):
  1157. - queue_drying_enabled: Dry between scheduled queue prints
  1158. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  1159. """
  1160. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  1161. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  1162. if not queue_drying_enabled and not ambient_drying_enabled:
  1163. # Stop active drying on all printers if both features disabled
  1164. if self._drying_in_progress:
  1165. for pid in list(self._drying_in_progress):
  1166. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  1167. await self._stop_drying(pid)
  1168. return
  1169. # Update drying state from printer status (handles backend restart)
  1170. self._sync_drying_state()
  1171. # Find printers with scheduled items (for queue drying mode)
  1172. printers_with_scheduled: set[int] = set()
  1173. printers_with_items: set[int] = set()
  1174. for item in queue_items:
  1175. if item.printer_id:
  1176. printers_with_items.add(item.printer_id)
  1177. if item.scheduled_time and not item.manual_start:
  1178. printers_with_scheduled.add(item.printer_id)
  1179. # If only queue mode is on and no printers have scheduled items, stop drying
  1180. if not ambient_drying_enabled and not printers_with_scheduled:
  1181. for pid in list(self._drying_in_progress):
  1182. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  1183. await self._stop_drying(pid)
  1184. return
  1185. # Get humidity threshold
  1186. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  1187. setting = result.scalar_one_or_none()
  1188. humidity_threshold = int(setting.value) if setting else 60
  1189. # Get drying presets
  1190. presets = await self._get_drying_presets(db)
  1191. # Determine if drying should be skipped for printers with pending items
  1192. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  1193. # Get all active printers
  1194. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  1195. for printer in all_printers.scalars():
  1196. pid = printer.id
  1197. if pid in busy_printers:
  1198. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  1199. continue
  1200. # In queue-only mode, only dry printers that have scheduled prints
  1201. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  1202. if self._drying_in_progress.get(pid):
  1203. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  1204. await self._stop_drying(pid)
  1205. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  1206. continue
  1207. # When block mode is on, don't START new drying on printers with pending items.
  1208. # But allow already-drying printers through so humidity auto-stop logic still runs.
  1209. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  1210. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  1211. continue
  1212. if not printer_manager.is_connected(pid):
  1213. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  1214. continue
  1215. if not self._is_printer_idle(pid, require_plate_clear):
  1216. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  1217. continue
  1218. # Check if this printer supports drying
  1219. state = printer_manager.get_status(pid)
  1220. if not state:
  1221. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  1222. continue
  1223. model = printer_manager.get_model(pid)
  1224. firmware = state.firmware_version
  1225. if not supports_drying(model, firmware):
  1226. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  1227. continue
  1228. # Check each AMS unit from raw_data
  1229. ams_list = state.raw_data.get("ams", [])
  1230. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  1231. for ams_data in ams_list:
  1232. module_type = str(ams_data.get("module_type") or "")
  1233. ams_id = int(ams_data.get("id", 0))
  1234. # Only n3f/n3s support drying
  1235. if module_type not in ("n3f", "n3s"):
  1236. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  1237. continue
  1238. dry_time = int(ams_data.get("dry_time") or 0)
  1239. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  1240. humidity = None
  1241. h_raw = ams_data.get("humidity_raw")
  1242. if h_raw is not None:
  1243. try:
  1244. humidity = int(h_raw)
  1245. except (ValueError, TypeError):
  1246. pass
  1247. if humidity is None:
  1248. h_idx = ams_data.get("humidity")
  1249. if h_idx is not None:
  1250. try:
  1251. humidity = int(h_idx)
  1252. except (ValueError, TypeError):
  1253. pass
  1254. # Already drying — check if humidity dropped below threshold (with minimum drying time)
  1255. if dry_time > 0:
  1256. if pid not in self._drying_in_progress:
  1257. # Drying we didn't start (manual or from before restart) — track but don't stop
  1258. self._drying_in_progress[pid] = time.monotonic()
  1259. started_at = self._drying_in_progress[pid]
  1260. elapsed = time.monotonic() - started_at
  1261. if humidity is not None and humidity <= humidity_threshold and elapsed >= self._min_drying_seconds:
  1262. logger.info(
  1263. "Auto-drying: printer %d AMS %d — humidity %d%% <= threshold %d%% after %dm, stopping drying",
  1264. pid,
  1265. ams_id,
  1266. humidity,
  1267. humidity_threshold,
  1268. int(elapsed / 60),
  1269. )
  1270. printer_manager.send_drying_command(pid, ams_id, temp=0, duration=0, mode=0)
  1271. else:
  1272. logger.debug(
  1273. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%, elapsed %dm/%dm min)",
  1274. pid,
  1275. ams_id,
  1276. dry_time,
  1277. humidity,
  1278. int(elapsed / 60),
  1279. self._min_drying_seconds // 60,
  1280. )
  1281. continue
  1282. # Humidity below threshold — no need to start drying
  1283. if humidity is None or humidity <= humidity_threshold:
  1284. logger.debug(
  1285. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  1286. pid,
  1287. ams_id,
  1288. humidity,
  1289. humidity_threshold,
  1290. )
  1291. continue
  1292. # Check cannot-dry reasons (power constraints etc.)
  1293. sf_reasons = ams_data.get("dry_sf_reason", [])
  1294. if sf_reasons:
  1295. logger.debug(
  1296. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  1297. pid,
  1298. ams_id,
  1299. sf_reasons,
  1300. )
  1301. continue
  1302. # Get conservative drying params for mixed filaments
  1303. trays = ams_data.get("tray", [])
  1304. params = self._get_conservative_drying_params(trays, module_type, presets)
  1305. if not params:
  1306. logger.debug(
  1307. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  1308. )
  1309. continue
  1310. temp, duration_hours, filament_type = params
  1311. # Start drying
  1312. logger.info(
  1313. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  1314. "starting %s drying at %d°C for %dh",
  1315. pid,
  1316. ams_id,
  1317. humidity,
  1318. humidity_threshold,
  1319. filament_type,
  1320. temp,
  1321. duration_hours,
  1322. )
  1323. success = printer_manager.send_drying_command(
  1324. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  1325. )
  1326. if success:
  1327. self._drying_in_progress[pid] = time.monotonic()
  1328. def _sync_drying_state(self):
  1329. """Sync in-memory drying state with actual printer status.
  1330. Handles backend restart — if a printer is drying but we don't know about it,
  1331. update our state. If we think it's drying but it's not, clear it.
  1332. """
  1333. to_remove = []
  1334. for pid in self._drying_in_progress:
  1335. state = printer_manager.get_status(pid)
  1336. if not state:
  1337. to_remove.append(pid)
  1338. continue
  1339. # Check if any AMS unit is still drying
  1340. ams_list = state.raw_data.get("ams", [])
  1341. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  1342. if not any_drying:
  1343. to_remove.append(pid)
  1344. for pid in to_remove:
  1345. self._drying_in_progress.pop(pid, None)
  1346. async def _stop_drying(self, printer_id: int):
  1347. """Stop all active drying on a printer (print takes priority)."""
  1348. state = printer_manager.get_status(printer_id)
  1349. if not state:
  1350. self._drying_in_progress.pop(printer_id, None)
  1351. return
  1352. ams_list = state.raw_data.get("ams", [])
  1353. for ams_data in ams_list:
  1354. dry_time = int(ams_data.get("dry_time") or 0)
  1355. if dry_time > 0:
  1356. ams_id = int(ams_data.get("id", 0))
  1357. logger.info(
  1358. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  1359. printer_id,
  1360. ams_id,
  1361. )
  1362. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  1363. self._drying_in_progress.pop(printer_id, None)
  1364. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  1365. """Get all smart plugs associated with a printer."""
  1366. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1367. return list(result.scalars().all())
  1368. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  1369. """Turn on smart plug and wait for printer to connect.
  1370. Returns True if printer connected successfully within timeout.
  1371. """
  1372. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  1373. service = await smart_plug_manager.get_service_for_plug(plug, db)
  1374. # Check current plug state
  1375. status = await service.get_status(plug)
  1376. if not status.get("reachable"):
  1377. logger.warning("Smart plug '%s' is not reachable", plug.name)
  1378. return False
  1379. # Turn on if not already on
  1380. if status.get("state") != "ON":
  1381. success = await service.turn_on(plug)
  1382. if not success:
  1383. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  1384. return False
  1385. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  1386. # Get printer from database for connection
  1387. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1388. printer = result.scalar_one_or_none()
  1389. if not printer:
  1390. logger.error("Printer %s not found in database", printer_id)
  1391. return False
  1392. # Wait for printer to boot (give it some time before trying to connect)
  1393. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  1394. await asyncio.sleep(30)
  1395. # Try to connect to the printer periodically
  1396. elapsed = 30 # Already waited 30s
  1397. while elapsed < self._power_on_wait_time:
  1398. # Try to connect
  1399. logger.info("Attempting to connect to printer %s...", printer_id)
  1400. try:
  1401. connected = await printer_manager.connect_printer(printer)
  1402. if connected:
  1403. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  1404. # Give it a moment to stabilize and get status
  1405. await asyncio.sleep(5)
  1406. return True
  1407. except Exception as e:
  1408. logger.debug("Connection attempt failed: %s", e)
  1409. await asyncio.sleep(self._power_on_check_interval)
  1410. elapsed += self._power_on_check_interval
  1411. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  1412. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  1413. return False
  1414. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  1415. """Check if the previous print on this printer succeeded."""
  1416. # Find the most recent completed queue item for this printer
  1417. result = await db.execute(
  1418. select(PrintQueueItem)
  1419. .where(PrintQueueItem.printer_id == item.printer_id)
  1420. .where(PrintQueueItem.id != item.id)
  1421. .where(PrintQueueItem.status.in_(["completed", "failed", "skipped", "aborted"]))
  1422. .order_by(PrintQueueItem.completed_at.desc())
  1423. .limit(1)
  1424. )
  1425. prev_item = result.scalar_one_or_none()
  1426. # If no previous item, assume success (first in queue)
  1427. if not prev_item:
  1428. return True
  1429. return prev_item.status == "completed"
  1430. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  1431. """Power off printer if auto_off_after is enabled (waits for cooldown)."""
  1432. if not item.auto_off_after:
  1433. return
  1434. plugs = await self._get_smart_plugs(db, item.printer_id)
  1435. plug_ids = [p.id for p in plugs if p.enabled]
  1436. if plug_ids:
  1437. logger.info("Auto-off: Waiting for printer %s to cool down before power off...", item.printer_id)
  1438. # Wait for cooldown (up to 10 minutes)
  1439. await printer_manager.wait_for_cooldown(item.printer_id, target_temp=50.0, timeout=600)
  1440. # Re-fetch plugs in a fresh session after the long cooldown wait
  1441. async with async_session() as new_db:
  1442. for plug_id in plug_ids:
  1443. try:
  1444. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  1445. plug = result.scalar_one_or_none()
  1446. if plug and plug.enabled:
  1447. logger.info("Auto-off: Powering off plug '%s' for printer %s", plug.name, item.printer_id)
  1448. service = await smart_plug_manager.get_service_for_plug(plug, new_db)
  1449. await service.turn_off(plug)
  1450. except Exception as e:
  1451. logger.warning(
  1452. "Auto-off: Failed to power off plug %s for printer %s: %s", plug_id, item.printer_id, e
  1453. )
  1454. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  1455. """Get a human-readable name for a queue item."""
  1456. if item.archive_id:
  1457. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1458. archive = result.scalar_one_or_none()
  1459. if archive:
  1460. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1461. if item.library_file_id:
  1462. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1463. library_file = result.scalar_one_or_none()
  1464. if library_file:
  1465. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  1466. return f"Job #{item.id}"
  1467. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  1468. """Get printer by ID."""
  1469. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1470. return result.scalar_one_or_none()
  1471. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  1472. """Upload file and start print for a queue item.
  1473. Supports two sources:
  1474. - archive_id: Print from an existing archive
  1475. - library_file_id: Print from a library file (file manager)
  1476. """
  1477. logger.info("Starting queue item %s", item.id)
  1478. # Get printer first (needed for both paths)
  1479. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  1480. printer = result.scalar_one_or_none()
  1481. if not printer:
  1482. item.status = "failed"
  1483. item.error_message = "Printer not found"
  1484. item.completed_at = datetime.now(timezone.utc)
  1485. await db.commit()
  1486. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  1487. await self._power_off_if_needed(db, item)
  1488. return
  1489. # Check printer is connected
  1490. if not printer_manager.is_connected(item.printer_id):
  1491. item.status = "failed"
  1492. item.error_message = "Printer not connected"
  1493. item.completed_at = datetime.now(timezone.utc)
  1494. await db.commit()
  1495. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  1496. await self._power_off_if_needed(db, item)
  1497. return
  1498. # Determine source: archive or library file
  1499. archive = None
  1500. library_file = None
  1501. file_path = None
  1502. filename = None
  1503. if item.archive_id:
  1504. # Print from archive
  1505. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  1506. archive = result.scalar_one_or_none()
  1507. if not archive:
  1508. item.status = "failed"
  1509. item.error_message = "Archive not found"
  1510. item.completed_at = datetime.now(timezone.utc)
  1511. await db.commit()
  1512. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  1513. await self._power_off_if_needed(db, item)
  1514. return
  1515. file_path = settings.base_dir / archive.file_path
  1516. filename = archive.filename
  1517. elif item.library_file_id:
  1518. # Print from library file (file manager)
  1519. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  1520. library_file = result.scalar_one_or_none()
  1521. if not library_file:
  1522. item.status = "failed"
  1523. item.error_message = "Library file not found"
  1524. item.completed_at = datetime.now(timezone.utc)
  1525. await db.commit()
  1526. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  1527. await self._power_off_if_needed(db, item)
  1528. return
  1529. # Library files store absolute paths
  1530. lib_path = Path(library_file.file_path)
  1531. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  1532. filename = library_file.filename
  1533. # Create archive from library file so usage tracking has access to the 3MF
  1534. try:
  1535. from backend.app.services.archive import ArchiveService
  1536. archive_service = ArchiveService(db)
  1537. archive = await archive_service.archive_print(
  1538. printer_id=item.printer_id,
  1539. source_file=file_path,
  1540. original_filename=filename,
  1541. created_by_id=item.created_by_id,
  1542. project_id=item.project_id,
  1543. )
  1544. if archive:
  1545. item.archive_id = archive.id
  1546. await db.flush()
  1547. logger.info(
  1548. "Queue item %s: Created archive %s from library file %s",
  1549. item.id,
  1550. archive.id,
  1551. item.library_file_id,
  1552. )
  1553. except Exception as e:
  1554. logger.warning("Queue item %s: Failed to create archive from library file: %s", item.id, e)
  1555. else:
  1556. # Neither archive nor library file specified
  1557. item.status = "failed"
  1558. item.error_message = "No source file specified"
  1559. item.completed_at = datetime.now(timezone.utc)
  1560. await db.commit()
  1561. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  1562. await self._power_off_if_needed(db, item)
  1563. return
  1564. # Check file exists on disk
  1565. if not file_path.exists():
  1566. item.status = "failed"
  1567. item.error_message = "Source file not found on disk"
  1568. item.completed_at = datetime.now(timezone.utc)
  1569. await db.commit()
  1570. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  1571. await self._power_off_if_needed(db, item)
  1572. return
  1573. # G-code injection for auto-print systems (#422)
  1574. injected_path = None
  1575. if item.gcode_injection:
  1576. try:
  1577. snippets_raw = await self._get_setting(db, "gcode_snippets")
  1578. if snippets_raw:
  1579. snippets = json.loads(snippets_raw)
  1580. model_snippets = snippets.get(printer.model, {})
  1581. start_gc = (model_snippets.get("start_gcode") or "").strip()
  1582. end_gc = (model_snippets.get("end_gcode") or "").strip()
  1583. if start_gc or end_gc:
  1584. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  1585. injected_path = inject_gcode_into_3mf(
  1586. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  1587. )
  1588. if injected_path:
  1589. file_path = injected_path
  1590. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  1591. else:
  1592. logger.warning(
  1593. "Queue item %s: G-code injection returned no result, using original", item.id
  1594. )
  1595. except Exception as e:
  1596. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  1597. # Upload file to printer via FTP
  1598. # Use a clean filename to avoid issues with double extensions like .gcode.3mf
  1599. base_name = filename
  1600. if base_name.endswith(".gcode.3mf"):
  1601. base_name = base_name[:-10] # Remove .gcode.3mf
  1602. elif base_name.endswith(".3mf"):
  1603. base_name = base_name[:-4] # Remove .3mf
  1604. remote_filename = f"{base_name}.3mf"
  1605. # Sanitize: firmware parses ftp://{filename} as a URL, spaces break it
  1606. remote_filename = remote_filename.replace(" ", "_")
  1607. # Upload to root directory (not /cache/) - the start_print command references
  1608. # files by name only (ftp://{filename}), so they must be in the root
  1609. remote_path = f"/{remote_filename}"
  1610. # Get FTP retry settings
  1611. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1612. logger.info(
  1613. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  1614. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  1615. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  1616. )
  1617. # Delete existing file if present (avoids 553 error on overwrite)
  1618. try:
  1619. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  1620. delete_result = await delete_file_async(
  1621. printer.ip_address,
  1622. printer.access_code,
  1623. remote_path,
  1624. socket_timeout=ftp_timeout,
  1625. printer_model=printer.model,
  1626. )
  1627. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  1628. except Exception as e:
  1629. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  1630. try:
  1631. if ftp_retry_enabled:
  1632. uploaded = await with_ftp_retry(
  1633. upload_file_async,
  1634. printer.ip_address,
  1635. printer.access_code,
  1636. file_path,
  1637. remote_path,
  1638. socket_timeout=ftp_timeout,
  1639. printer_model=printer.model,
  1640. max_retries=ftp_retry_count,
  1641. retry_delay=ftp_retry_delay,
  1642. operation_name=f"Upload print to {printer.name}",
  1643. )
  1644. else:
  1645. uploaded = await upload_file_async(
  1646. printer.ip_address,
  1647. printer.access_code,
  1648. file_path,
  1649. remote_path,
  1650. socket_timeout=ftp_timeout,
  1651. printer_model=printer.model,
  1652. )
  1653. except Exception as e:
  1654. uploaded = False
  1655. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  1656. # Clean up injected temp file after upload attempt
  1657. if injected_path and injected_path.exists():
  1658. injected_path.unlink(missing_ok=True)
  1659. if not uploaded:
  1660. error_msg = (
  1661. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  1662. "See server logs for detailed diagnostics."
  1663. )
  1664. item.status = "failed"
  1665. item.error_message = error_msg
  1666. item.completed_at = datetime.now(timezone.utc)
  1667. await db.commit()
  1668. logger.error(
  1669. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  1670. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  1671. )
  1672. # Send failure notification
  1673. await notification_service.on_queue_job_failed(
  1674. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1675. printer_id=printer.id,
  1676. printer_name=printer.name,
  1677. reason="Failed to upload file to printer",
  1678. db=db,
  1679. )
  1680. await self._power_off_if_needed(db, item)
  1681. return
  1682. # Parse AMS mapping if stored
  1683. ams_mapping = None
  1684. if item.ams_mapping:
  1685. try:
  1686. ams_mapping = json.loads(item.ams_mapping)
  1687. except json.JSONDecodeError:
  1688. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  1689. # Register as expected print so we don't create a duplicate archive
  1690. # Only applicable for archive-based prints
  1691. if archive:
  1692. from backend.app.main import register_expected_print
  1693. register_expected_print(
  1694. item.printer_id,
  1695. remote_filename,
  1696. archive.id,
  1697. ams_mapping=ams_mapping,
  1698. created_by_id=item.created_by_id,
  1699. )
  1700. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  1701. # This prevents phantom reprints if the backend crashes/restarts after the
  1702. # print command is sent but before the status update is committed.
  1703. # If we crash after this commit but before start_print(), the item will be
  1704. # in "printing" status without actually printing - but that's safer than
  1705. # accidentally reprinting the same file hours later.
  1706. item.status = "printing"
  1707. item.started_at = datetime.now(timezone.utc)
  1708. await db.commit()
  1709. # Clear the awaiting-plate-clear flag now that we're starting a new print
  1710. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  1711. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  1712. # Capture state before dispatch so the watchdog can detect whether the
  1713. # printer actually transitioned (#967). Also capture subtask_id so the
  1714. # watchdog can recognise "command landed but state hasn't flipped yet"
  1715. # on slow H2D transitions (#1078).
  1716. pre_status = printer_manager.get_status(item.printer_id)
  1717. pre_state = getattr(pre_status, "state", None) if pre_status else None
  1718. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  1719. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  1720. # Start the print with AMS mapping, plate_id and print options
  1721. started = printer_manager.start_print(
  1722. item.printer_id,
  1723. remote_filename,
  1724. plate_id=item.plate_id or 1,
  1725. ams_mapping=ams_mapping,
  1726. bed_levelling=item.bed_levelling,
  1727. flow_cali=item.flow_cali,
  1728. vibration_cali=item.vibration_cali,
  1729. layer_inspect=item.layer_inspect,
  1730. timelapse=item.timelapse,
  1731. use_ams=item.use_ams,
  1732. )
  1733. if started:
  1734. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  1735. # Hold the printer against further dispatches until the watchdog
  1736. # confirms the printer transitioned (or until the hard timeout).
  1737. # Prevents multi-plate batches from triple-dispatching onto the
  1738. # same H2D Pro while it digests the first project_file (#1157).
  1739. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  1740. # Watchdog: if the printer never transitions out of pre_state AND
  1741. # never advances subtask_id, the MQTT publish was accepted locally but
  1742. # didn't reach the printer (half-broken session — same shape as
  1743. # #887/#936). Revert the queue item so the next dispatch can pick it
  1744. # up instead of leaving it stuck in "printing" (#967). subtask_id
  1745. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  1746. # that would otherwise cause the item to re-dispatch as a reprint
  1747. # of the just-finished job (#1078).
  1748. if pre_state:
  1749. asyncio.create_task(
  1750. self._watchdog_print_start(
  1751. item.id,
  1752. item.printer_id,
  1753. pre_state,
  1754. pre_subtask_id,
  1755. pre_gcode_file,
  1756. )
  1757. )
  1758. # Get estimated time for notification
  1759. estimated_time = None
  1760. if archive and archive.print_time_seconds:
  1761. estimated_time = archive.print_time_seconds
  1762. elif library_file and library_file.print_time_seconds:
  1763. estimated_time = library_file.print_time_seconds
  1764. # Send job started notification
  1765. await notification_service.on_queue_job_started(
  1766. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1767. printer_id=printer.id,
  1768. printer_name=printer.name,
  1769. db=db,
  1770. estimated_time=estimated_time,
  1771. )
  1772. # MQTT relay - publish queue job started
  1773. try:
  1774. from backend.app.services.mqtt_relay import mqtt_relay
  1775. await mqtt_relay.on_queue_job_started(
  1776. job_id=item.id,
  1777. filename=filename,
  1778. printer_id=printer.id,
  1779. printer_name=printer.name,
  1780. printer_serial=printer.serial_number,
  1781. )
  1782. except Exception:
  1783. pass # Don't fail if MQTT fails
  1784. else:
  1785. # Clean up uploaded file from SD card to prevent phantom prints
  1786. try:
  1787. await delete_file_async(
  1788. printer.ip_address,
  1789. printer.access_code,
  1790. remote_path,
  1791. printer_model=printer.model,
  1792. )
  1793. except Exception:
  1794. pass # Best-effort — don't fail the error handler
  1795. # Print command failed - revert status
  1796. item.status = "failed"
  1797. item.error_message = "Failed to send print command to printer"
  1798. item.completed_at = datetime.now(timezone.utc)
  1799. await db.commit()
  1800. logger.error(
  1801. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  1802. f"printer_manager.start_print() returned False. "
  1803. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  1804. f"Check printer status and backend logs for details."
  1805. )
  1806. # Send failure notification
  1807. await notification_service.on_queue_job_failed(
  1808. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  1809. printer_id=printer.id,
  1810. printer_name=printer.name,
  1811. reason="Failed to send print command to printer - check printer connection and status",
  1812. db=db,
  1813. )
  1814. await self._power_off_if_needed(db, item)
  1815. @staticmethod
  1816. async def _watchdog_print_start(
  1817. queue_item_id: int,
  1818. printer_id: int,
  1819. pre_state: str,
  1820. pre_subtask_id: str | None = None,
  1821. pre_gcode_file: str | None = None,
  1822. timeout: float = 90.0,
  1823. poll_interval: float = 3.0,
  1824. ) -> None:
  1825. """Revert a queue item if the printer never acknowledges the start command.
  1826. Bambuddy optimistically marks the queue item as "printing" right after the
  1827. MQTT project_file publish succeeds locally. If the printer drops/ignores the
  1828. command (half-broken MQTT session — #887/#936), the state never transitions
  1829. and the item would otherwise stay stuck in "printing" forever (#967).
  1830. Exit paths (printer picked up the job — no revert):
  1831. - gcode_state changed from pre_state, OR
  1832. - subtask_id advanced past pre_subtask_id — the printer echoes our
  1833. per-dispatch identity back on push_status, so a subtask_id change is
  1834. a definitive "command landed" signal even while state is still FINISH.
  1835. H2D can sit at FINISH for ~50 s after accepting project_file before
  1836. transitioning to PREPARE, which used to trip the state-only watchdog
  1837. and caused the scheduler to revert + re-dispatch the item; the next
  1838. successful dispatch then looked like a reprint of the just-finished
  1839. job (#1078).
  1840. Timeout raised from 45 s → 90 s as belt-and-braces for slow transitions
  1841. that also don't emit an early subtask_id tick.
  1842. """
  1843. deadline = time.monotonic() + timeout
  1844. last_status = None
  1845. while time.monotonic() < deadline:
  1846. await asyncio.sleep(poll_interval)
  1847. status = printer_manager.get_status(printer_id)
  1848. if not status:
  1849. # Printer disconnected — don't mess with the DB. Drop the
  1850. # in-memory dispatch hold too so a fresh dispatch can retry
  1851. # once the printer comes back; the hard timeout would
  1852. # otherwise hold the printer unnecessarily.
  1853. scheduler._release_dispatch_hold(printer_id)
  1854. return
  1855. last_status = status
  1856. if status.state != pre_state:
  1857. # Printer picked up the job (state transition) — release the
  1858. # post-dispatch hold so the next pending item for this printer
  1859. # can be evaluated normally.
  1860. scheduler._release_dispatch_hold(printer_id)
  1861. return
  1862. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  1863. # Printer picked up the job (subtask_id advanced)
  1864. scheduler._release_dispatch_hold(printer_id)
  1865. return
  1866. # No transition. Revert the item so the scheduler can retry.
  1867. # Drop the in-memory hold so the retry isn't blocked by it.
  1868. scheduler._release_dispatch_hold(printer_id)
  1869. async with async_session() as db:
  1870. item = await db.get(PrintQueueItem, queue_item_id)
  1871. if not item or item.status != "printing":
  1872. return # Already moved on (completed/cancelled/etc.)
  1873. item.status = "pending"
  1874. item.started_at = None
  1875. await db.commit()
  1876. logger.warning(
  1877. "Queue item %s: printer %d did not respond to print command within "
  1878. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  1879. "for retry (#967)",
  1880. queue_item_id,
  1881. printer_id,
  1882. timeout,
  1883. pre_state,
  1884. pre_subtask_id,
  1885. )
  1886. # Same #1150 / #887/#936 discriminator as background_dispatch: if the
  1887. # printer's gcode_file changed since pre-dispatch, the project_file
  1888. # command landed and the printer is parsing — a forced reconnect
  1889. # mid-parse triggers 0500_4003. If gcode_file is unchanged, the
  1890. # publish was silently swallowed (#887/#936) and the original
  1891. # force_reconnect recovery is what we want.
  1892. client = printer_manager.get_client(printer_id)
  1893. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  1894. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  1895. if publish_landed:
  1896. logger.warning(
  1897. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  1898. "received the command and is parsing slowly. Skipping forced "
  1899. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  1900. queue_item_id,
  1901. current_gcode_file,
  1902. pre_gcode_file,
  1903. )
  1904. elif client and hasattr(client, "force_reconnect_stale_session"):
  1905. client.force_reconnect_stale_session(
  1906. f"queue print command unacknowledged after {timeout:.0f}s "
  1907. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  1908. )
  1909. # Global scheduler instance
  1910. scheduler = PrintScheduler()