print_scheduler.py 120 KB

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