print_scheduler.py 114 KB

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