print_scheduler.py 259 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214
  1. """Print scheduler service - processes the print queue."""
  2. import asyncio
  3. import json
  4. import logging
  5. import time
  6. import uuid
  7. from dataclasses import dataclass
  8. from datetime import datetime, timezone
  9. from pathlib import Path
  10. from fastapi import HTTPException
  11. from sqlalchemy import func, select, update
  12. from sqlalchemy.ext.asyncio import AsyncSession
  13. from sqlalchemy.orm import selectinload
  14. from backend.app.core.config import settings
  15. from backend.app.core.database import async_session, run_with_retry
  16. from backend.app.core.tasks import spawn_background_task
  17. from backend.app.core.websocket import ws_manager
  18. from backend.app.models.archive import PrintArchive
  19. from backend.app.models.library import LibraryFile
  20. from backend.app.models.print_queue import PrintQueueItem, PrintQueueVariant
  21. from backend.app.models.printer import Printer
  22. from backend.app.models.settings import Settings
  23. from backend.app.models.smart_plug import SmartPlug
  24. from backend.app.models.spool_assignment import SpoolAssignment
  25. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  26. from backend.app.services import print_dispatch_context
  27. from backend.app.services.bambu_ftp import (
  28. UploadCancelled,
  29. cache_3mf_download,
  30. delete_file_async,
  31. get_ftp_retry_settings,
  32. upload_file_async,
  33. with_ftp_retry,
  34. )
  35. from backend.app.services.bambu_mqtt import HMS_MQTT_VERIFY_FAILED
  36. from backend.app.services.filament_deficit import compute_deficit_for_queue_item
  37. from backend.app.services.finance_budget import (
  38. create_budget_reservation,
  39. release_budget_reservation,
  40. validate_print_budget,
  41. )
  42. from backend.app.services.ha_sensor_manager import ha_sensor_manager
  43. from backend.app.services.notification_service import notification_service
  44. from backend.app.services.print_cost_estimate import estimate_queue_source_cost
  45. from backend.app.services.printer_manager import (
  46. printer_manager,
  47. supports_airduct,
  48. supports_chamber_heater,
  49. supports_chamber_temp,
  50. supports_drying,
  51. supports_drying_while_printing,
  52. )
  53. from backend.app.services.smart_plug_manager import smart_plug_manager
  54. from backend.app.utils.filename import derive_remote_filename
  55. from backend.app.utils.printer_models import is_gcode_compatible, normalize_printer_model
  56. logger = logging.getLogger(__name__)
  57. # Dispatch-toast progress throttling (#1625 follow-up). Mirrors the legacy
  58. # background_dispatch.py upload_progress_callback (200 ms time gate + 256 KB
  59. # byte gate) from before the scheduler unification. Time gate keeps small
  60. # files from going silent (a single 8 KB chunk fires once and that's it);
  61. # byte gate caps the broadcast rate on slow LAN where 200 ms covers many
  62. # chunks. uploaded >= total always emits so the bar closes cleanly even on
  63. # sub-200 ms files.
  64. _DISPATCH_PROGRESS_BYTE_STEP = 256 * 1024
  65. _DISPATCH_PROGRESS_MIN_INTERVAL_SECS = 0.2
  66. # Auto-drying re-arm guards (#2770).
  67. #
  68. # An AMS reports HIGHER relative humidity while it is warm than once it has
  69. # cooled: measured on an H2D/AMS 2 Pro at 10-13% cold against 15-20% throughout
  70. # every drying cycle, and the same unit read 16-20% across a full 12 h dry. A
  71. # threshold set inside that band therefore cannot be satisfied while the box is
  72. # hot, and the firmware is free to end a cycle whenever it decides the filament
  73. # is dry — so the next 30 s pass sees dry_time 0 with the reading still above
  74. # the threshold and arms another cycle. The reporter's log has five 12-hour
  75. # cycles armed inside four hours, one of them six seconds after the previous
  76. # ended.
  77. #
  78. # The cooldown stops the six-second re-arm; the unproductive-cycle cap stops the
  79. # loop. Neither ever stops a running cycle — both only gate STARTING one, so a
  80. # manual or firmware-run dry is untouched.
  81. AUTO_DRY_REARM_COOLDOWN_SECONDS = 30 * 60
  82. AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES = 2
  83. class _UploadProgressBridge:
  84. """Thread-safe bridge from ``upload_file_async`` to the WS broadcaster.
  85. ``upload_file_async`` runs the FTP transfer in an executor thread and
  86. invokes its ``progress_callback`` from that thread, so the callback
  87. body cannot ``await`` directly. This bridge captures the asyncio loop
  88. at construction (on the scheduler thread) and uses
  89. ``run_coroutine_threadsafe`` to hop back. The byte/time throttle
  90. matches the legacy background_dispatch.py path 1:1 so the toast feels
  91. identical to the pre-#1625 experience.
  92. Failures inside the emit are swallowed — progress is a UX nicety, the
  93. upload itself must not fail because of a WS hiccup.
  94. """
  95. def __init__(self, user_id: int | None, queue_item_id: int):
  96. self._user_id = user_id
  97. self._queue_item_id = queue_item_id
  98. try:
  99. self._loop = asyncio.get_running_loop()
  100. except RuntimeError:
  101. self._loop = None
  102. self._last_emit_bytes = 0
  103. self._last_emit_monotonic = 0.0
  104. self._has_emitted = False
  105. def __call__(self, bytes_transferred: int, total_bytes: int) -> None:
  106. if self._loop is None or total_bytes <= 0:
  107. return
  108. now = time.monotonic()
  109. # Mirrors legacy bg-dispatch: emit if first call OR upload complete
  110. # OR 200 ms elapsed OR ≥256 KB transferred since last emit. Two of
  111. # the four matter most: first-call so the user sees something even
  112. # for sub-chunk-size files; uploaded >= total so the bar locks at
  113. # 100% even when the throttle would otherwise eat it.
  114. should_emit = (
  115. not self._has_emitted
  116. or bytes_transferred >= total_bytes
  117. or now - self._last_emit_monotonic >= _DISPATCH_PROGRESS_MIN_INTERVAL_SECS
  118. or bytes_transferred - self._last_emit_bytes >= _DISPATCH_PROGRESS_BYTE_STEP
  119. )
  120. if not should_emit:
  121. return
  122. self._has_emitted = True
  123. self._last_emit_bytes = bytes_transferred
  124. self._last_emit_monotonic = now
  125. try:
  126. asyncio.run_coroutine_threadsafe(
  127. ws_manager.send_queue_item_upload_progress(
  128. user_id=self._user_id,
  129. queue_item_id=self._queue_item_id,
  130. bytes_transferred=bytes_transferred,
  131. total_bytes=total_bytes,
  132. ),
  133. self._loop,
  134. )
  135. except Exception:
  136. pass # progress is best-effort, never block the upload
  137. # Bambu firmware states that mean the project_file has actually been accepted
  138. # and the printer is now processing / running / paused mid-print. Used by the
  139. # dispatch watchdog (#1370): a transition into one of these states means the
  140. # print landed, anything else (e.g. FINISH -> IDLE after the user dismisses
  141. # a post-print prompt) is NOT a valid "command landed" signal even though the
  142. # state value did change. SLICING is included because some firmwares park
  143. # briefly in SLICING between PREPARE and RUNNING while parsing the g-code.
  144. _ACTIVE_PRINT_STATES: frozenset[str] = frozenset({"PREPARE", "SLICING", "RUNNING", "PAUSE"})
  145. # How many times the start-watchdog may revert an item to 'pending' before it
  146. # gives up and fails the row instead (#2555). Each attempt costs a full 3MF
  147. # re-upload plus the watchdog's wait, so a wedged printer left to retry forever
  148. # both never recovers and starves the other printers of dispatch slots. Three
  149. # is chosen to clear the transient causes the watchdog already recovers from —
  150. # a lost MQTT publish on a half-broken session (#887/#936) is fixed by the
  151. # force-reconnect on the very next attempt — while still bounding the loop.
  152. DISPATCH_MAX_ATTEMPTS = 3
  153. # Filament type equivalence groups — types within the same group are
  154. # interchangeable on the printer side (Bambu Lab firmware treats them as compatible).
  155. _FILAMENT_TYPE_GROUPS: list[list[str]] = [
  156. ["PA-CF", "PA12-CF", "PAHT-CF"],
  157. ]
  158. _FILAMENT_EQUIV_MAP: dict[str, str] = {}
  159. for _group in _FILAMENT_TYPE_GROUPS:
  160. _canonical = _group[0].upper()
  161. for _t in _group:
  162. _FILAMENT_EQUIV_MAP[_t.upper()] = _canonical
  163. def _canonical_filament_type(ftype: str) -> str:
  164. """Return canonical type for equivalence matching."""
  165. upper = ftype.upper()
  166. return _FILAMENT_EQUIV_MAP.get(upper, upper)
  167. @dataclass(slots=True)
  168. class _ModelCandidate:
  169. """One (file, printer model) pair the model-based matcher may try.
  170. Model-based assignment used to have exactly one of these per item, held
  171. directly in the item's own columns. Cross-model queue items (#671) have
  172. several, held in ``print_queue_variants``. Both shapes are normalised into
  173. this so the matching, the cross-model gate and the waiting-reason handling
  174. are written once and an item without variants provably takes the same path
  175. it took before variants existed.
  176. ``variant`` is None for the item's own columns and set for a real variant
  177. row, which is what :meth:`PrintScheduler._resolve_variant` writes onto the
  178. item once that candidate wins.
  179. """
  180. target_model: str | None
  181. sliced_for: str | None
  182. required_filament_types: str | None
  183. filament_overrides: str | None
  184. variant: "PrintQueueVariant | None" = None
  185. def _sliced_for_model(archive, library_file) -> str | None:
  186. """Model a 3MF declares it was sliced for, from whichever source holds it."""
  187. if archive is not None:
  188. return archive.sliced_for_model
  189. if library_file is not None and library_file.file_metadata:
  190. return library_file.file_metadata.get("sliced_for_model")
  191. return None
  192. def _candidates_for(item: PrintQueueItem) -> list[_ModelCandidate]:
  193. """Candidate files for ``item``, best first.
  194. An item with no variant rows yields exactly one candidate built from its own
  195. columns — the pre-#671 behaviour, unchanged.
  196. Variants come back least-attempted first, ties broken by the user's
  197. ``position``. On the first pass every count is zero, so this is purely the
  198. user's priority order. After a start-watchdog bounce the printer that failed
  199. drops behind, so the next lap tries the other machine rather than spending the
  200. item's whole retry budget on the one that is wedged. Once every candidate has
  201. been tried equally often they cycle again, which keeps the item-level
  202. ``DISPATCH_MAX_ATTEMPTS`` bound from #2555 intact — a job with alternatives
  203. still gives up, it just does not give up without trying them.
  204. """
  205. if not item.variants:
  206. if not item.archive_id and not item.library_file_id:
  207. # Nothing to print at all. Dispatching would fail deep in the upload
  208. # on "No archive_id or library_file_id"; the caller holds the item
  209. # with an explanation instead.
  210. return []
  211. return [
  212. _ModelCandidate(
  213. target_model=item.target_model,
  214. sliced_for=_sliced_for_model(item.archive, item.library_file),
  215. required_filament_types=item.required_filament_types,
  216. filament_overrides=item.filament_overrides,
  217. )
  218. ]
  219. # Drop candidates whose file is gone or in the trash. Both are reachable and
  220. # neither is covered by the schema: library deletes are soft (the row lives
  221. # on with ``deleted_at`` set, which no foreign key can express), and SQLite
  222. # ships with ``PRAGMA foreign_keys`` off, so the ON DELETE CASCADE never
  223. # fires there and a hard delete leaves the variant row pointing at nothing.
  224. usable = [v for v in item.variants if v.library_file is not None and v.library_file.deleted_at is None]
  225. ordered = sorted(usable, key=lambda v: (v.attempt_count or 0, v.position, v.id))
  226. return [
  227. _ModelCandidate(
  228. target_model=v.target_model,
  229. sliced_for=_sliced_for_model(None, v.library_file),
  230. required_filament_types=v.required_filament_types,
  231. filament_overrides=v.filament_overrides,
  232. variant=v,
  233. )
  234. for v in ordered
  235. ]
  236. def _collapse_waiting_reasons(per_model: list[tuple[str | None, str]]) -> str | None:
  237. """Fold one waiting reason per candidate into a single line for the item.
  238. A cross-model item produces a reason per candidate, and pasting them
  239. together unlabelled reads as gibberish ("No idle printer; PETG not loaded"
  240. — on which machine?). Each reason is prefixed with its model, except in the
  241. single-candidate case where the item already displays its target model and
  242. the prefix would be noise.
  243. Identical reasons collapse rather than repeat, so three idle-less models
  244. read as one clause.
  245. When *every* candidate is merely busy the parts are joined with the ``" | "``
  246. separator :meth:`PrintScheduler._is_busy_only` already parses, and left
  247. unprefixed. That case must keep testing busy-only: a fleet that is simply
  248. printing needs no user action, and labelling the clauses would turn each pass
  249. over a two-model item into a "job waiting" notification.
  250. """
  251. reasons = [(model, reason) for model, reason in per_model if reason]
  252. if not reasons:
  253. return None
  254. if len(reasons) == 1:
  255. return reasons[0][1]
  256. distinct = list(dict.fromkeys(reason for _model, reason in reasons))
  257. if len(distinct) == 1:
  258. return distinct[0]
  259. if all(PrintScheduler._is_busy_only(reason) for _model, reason in reasons):
  260. return " | ".join(distinct)
  261. return "; ".join(f"{model or 'unassigned'}: {reason}" for model, reason in reasons)
  262. def _candidate_model_label(candidates: list[_ModelCandidate]) -> str | None:
  263. """Human label for the models an item is waiting on ("H2S or H2C").
  264. Notifications take a single target model. For a cross-model item the item's
  265. own ``target_model`` is whichever variant happens to be first, which reads as
  266. a lie once it is the H2C that actually runs — so name all of them.
  267. """
  268. models = list(dict.fromkeys(c.target_model for c in candidates if c.target_model))
  269. if not models:
  270. return None
  271. return " or ".join(models)
  272. def _mapping_is_all_unresolved(mapping: list | None) -> bool:
  273. """True if ``mapping`` is a non-empty list whose every entry is the
  274. unresolved sentinel (-1 / None) — i.e. no required slot ever matched a tray.
  275. Such a mapping is a bug artifact: a frontend status-load race can serialize
  276. ``[-1]`` before the printer's AMS trays are known (#2589). It must be
  277. recomputed from live status at dispatch rather than trusted, otherwise it
  278. reaches the print command and is silently downgraded to external-spool mode.
  279. A partially-resolved mapping (``[-1, -1, 5]`` where slot 3 matched, or a
  280. padding ``-1`` for a slot this plate does not print) is NOT unresolved. An
  281. explicit external selection (``>= 254``) is NOT unresolved either — those
  282. keep their meaning.
  283. """
  284. if not isinstance(mapping, list) or not mapping:
  285. return False
  286. return all(t is None or (isinstance(t, int) and t < 0) for t in mapping)
  287. def _mqtt_commands_rejected(status) -> bool:
  288. """True when the printer is currently reporting that it refused a command.
  289. ``HMS_MQTT_VERIFY_FAILED`` means the firmware's authorization check rejected
  290. a control command it could not verify. Queries still answer, so the printer
  291. looks connected and idle while project_file, gcode_line and
  292. ams_change_filament are all dropped — no amount of waiting or re-uploading
  293. changes that (#2732).
  294. Tolerates a missing status and errors without a ``full_code`` (the 8-char
  295. ``print_error`` path builds HMSError differently), so this is safe to call on
  296. every watchdog poll.
  297. """
  298. for err in getattr(status, "hms_errors", None) or []:
  299. if getattr(err, "full_code", "") == HMS_MQTT_VERIFY_FAILED:
  300. return True
  301. return False
  302. def _drying_ams_ids(status) -> list[int]:
  303. """AMS unit ids currently running a drying cycle, per firmware telemetry.
  304. ``dry_time`` is minutes remaining, so >0 is the firmware's own statement that
  305. a cycle is active. Used by the dispatch watchdog to say *why* a print never
  306. started (#2758) — it is a diagnostic, not a gate.
  307. Deliberately not used to block or stop drying before dispatch. This printer
  308. class supports drying concurrently with an active print
  309. (``supports_drying_while_printing``), so drying is not incompatible with
  310. printing in general; what #2758 shows is one X2D refusing to *begin* a print
  311. while two AMS units were drying, one of them without its external PSU. Until
  312. it is known whether the blocker is drying itself or the power budget
  313. (``dry_sf_reason`` 1 / 8), acting on this would tear down drying that the
  314. hardware is perfectly happy to continue.
  315. """
  316. ids: list[int] = []
  317. for unit in (getattr(status, "raw_data", None) or {}).get("ams") or []:
  318. if not isinstance(unit, dict):
  319. continue
  320. try:
  321. if int(unit.get("dry_time") or 0) > 0:
  322. ids.append(int(unit.get("id", 0)))
  323. except (TypeError, ValueError):
  324. continue
  325. return ids
  326. def _installed_nozzle_diameters(status) -> list[float]:
  327. """Parse the installed nozzle diameters from a PrinterState (#1899).
  328. Returns the diameters the printer actually reports (e.g. [0.4] single-nozzle,
  329. [0.4, 0.6] dual-nozzle), skipping the empty-string defaults that populate a
  330. NozzleInfo before MQTT fills it in. An empty list means "the printer hasn't
  331. told us its nozzle hardware" — callers must treat that as unknown, not as a
  332. mismatch, so we never block a print on missing data.
  333. """
  334. diameters: list[float] = []
  335. for nozzle in getattr(status, "nozzles", None) or []:
  336. raw = getattr(nozzle, "nozzle_diameter", "") or ""
  337. try:
  338. value = float(raw)
  339. except (TypeError, ValueError):
  340. continue
  341. if value > 0:
  342. diameters.append(value)
  343. return diameters
  344. def _nozzle_mismatch_message(sliced_nozzle: float | None, installed: list[float]) -> str | None:
  345. """Return an actionable error message when the sliced nozzle can't be
  346. printed on any installed nozzle, else None (#1899).
  347. Fail-safe: returns None whenever we lack the data to judge — no sliced
  348. diameter, or the printer reported no nozzles — so a print is only ever
  349. blocked on a POSITIVE mismatch. On dual-nozzle printers a match against
  350. EITHER installed nozzle passes (a 0.6 slice is fine if one hotend is 0.6).
  351. The 0.05 tolerance absorbs float noise while staying well inside the 0.2
  352. gap between adjacent nozzle sizes (0.2/0.4/0.6/0.8).
  353. """
  354. if not sliced_nozzle or not installed:
  355. return None
  356. if any(abs(d - sliced_nozzle) < 0.05 for d in installed):
  357. return None
  358. installed_str = " / ".join(f"{d:g}mm" for d in installed)
  359. return (
  360. f"File sliced for a {sliced_nozzle:g}mm nozzle, but the printer has "
  361. f"{installed_str} installed. Re-slice for the installed nozzle, or "
  362. f"install the matching nozzle before printing."
  363. )
  364. def _describe_filament(entry: dict, nozzle_key: str) -> str:
  365. """One-line "PETG #000000 (left nozzle)" for an error message (#2771).
  366. Shared by the required and loaded sides, which name their extruder
  367. differently: a 3MF requirement carries ``nozzle_id``, a loaded tray carries
  368. ``extruder_id``. Both are MQTT extruder ids — 0 is the right/main nozzle,
  369. 1 the left/deputy — and both are absent on single-nozzle printers, where
  370. naming a nozzle would be noise.
  371. """
  372. parts = [(entry.get("type") or "filament").upper()]
  373. if entry.get("color"):
  374. parts.append(str(entry["color"]))
  375. nozzle = entry.get(nozzle_key)
  376. if nozzle == 0:
  377. parts.append("(right nozzle)")
  378. elif nozzle == 1:
  379. parts.append("(left nozzle)")
  380. return " ".join(parts)
  381. def _unmatched_filament_message(required: list[dict], loaded: list[dict]) -> str:
  382. """Explain that nothing loaded matches what the file needs (#2771).
  383. Only ever built for a printer with no AMS, where the loaded list is short
  384. enough to quote in full and there is no "load another spool and hit Resume"
  385. recovery — the external spool holder is all there is, so the user needs to
  386. be told which filament to put on it.
  387. """
  388. want = ", ".join(_describe_filament(r, "nozzle_id") for r in required)
  389. have = ", ".join(_describe_filament(f, "extruder_id") for f in loaded)
  390. return (
  391. f"No filament loaded on this printer matches the file. It needs {want}; "
  392. f"the printer has {have} and no AMS. Load the required filament on the "
  393. f"external spool holder, or send this job to a printer that has it."
  394. )
  395. class PrintScheduler:
  396. """Background scheduler that processes the print queue."""
  397. # Built-in drying presets per filament type (from BambuStudio filament profiles)
  398. # Format: { n3f_temp, n3s_temp, n3f_hours, n3s_hours }
  399. DEFAULT_DRYING_PRESETS: dict[str, dict[str, int]] = {
  400. "PLA": {"n3f": 45, "n3s": 45, "n3f_hours": 12, "n3s_hours": 12},
  401. "PETG": {"n3f": 65, "n3s": 65, "n3f_hours": 12, "n3s_hours": 12},
  402. "TPU": {"n3f": 65, "n3s": 75, "n3f_hours": 12, "n3s_hours": 18},
  403. "ABS": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  404. "ASA": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  405. "PA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 12},
  406. "PC": {"n3f": 65, "n3s": 80, "n3f_hours": 12, "n3s_hours": 8},
  407. "PVA": {"n3f": 65, "n3s": 85, "n3f_hours": 12, "n3s_hours": 18},
  408. }
  409. def __init__(self):
  410. self._running = False
  411. self._check_interval = 30 # seconds
  412. # After a pass that actually dispatched something, loop again almost
  413. # immediately instead of sleeping the full interval (#2555). A dispatch
  414. # changes printer state — a batch launch fans out over several passes as
  415. # printers free up, a wedged head-of-line job reverts to pending, an
  416. # upload slot opens — and the next batch of ready work should not have to
  417. # wait 30 s behind an idle sleep. When a pass dispatches nothing (all
  418. # pending items are behind printers that are genuinely busy printing),
  419. # there is nothing to react to, so we fall back to the normal interval;
  420. # that also means this can never tight-loop, since fast ticks only
  421. # continue while dispatches keep happening and the queue is draining.
  422. self._fast_check_interval = 3 # seconds
  423. self._power_on_wait_time = 180 # seconds to wait for printer after power on (3 min)
  424. self._power_on_check_interval = 10 # seconds between connection checks
  425. # Printers whose class-target power-on failed, mapped to the monotonic
  426. # time their cool-off expires (#2786).
  427. #
  428. # Without this, one printer with an unreachable plug starves every
  429. # sibling of its model forever: the wake step walks candidates in id
  430. # order, spends the pass's single attempt on the same broken printer
  431. # every time, and the healthy one two slots down is never reached. It
  432. # also costs a full ``_power_on_wait_time`` out of every 30 s pass,
  433. # which delays the whole queue, not just this job.
  434. #
  435. # Entries expire on read rather than being cleared on success: a printer
  436. # inside its cool-off is skipped before the power-on is reached, so a
  437. # live entry can never be overwritten by a success anyway. A printer
  438. # that comes back by any other route stops being a wake candidate the
  439. # moment it connects.
  440. self._wake_failures: dict[int, float] = {}
  441. self._wake_failure_cooloff = 600 # seconds
  442. # Track which printers are currently auto-drying (printer_id -> start timestamp)
  443. self._drying_in_progress: dict[int, float] = {}
  444. # Per-AMS memory of the auto-drying cycles WE armed, keyed by
  445. # (printer_id, ams_id) (#2770). Entries only exist between arming a
  446. # cycle and the humidity finally coming down, so the normal steady
  447. # state is an empty dict. Fields:
  448. # running — a cycle we armed is (or should be) on the firmware
  449. # ended_at — monotonic when we observed that cycle end
  450. # unproductive — consecutive armed cycles that ended with the reading
  451. # still above the threshold
  452. # suspended — we have stopped arming this unit and said so
  453. self._auto_dry_units: dict[tuple[int, int], dict[str, object]] = {}
  454. # Defensive in-memory dispatch hold (#1157): a printer that just received
  455. # a project_file command must not get a second dispatch until either it
  456. # transitions out of pre_state OR the hard timeout expires. The H2D Pro
  457. # can take 80–210 s to flip FINISH→PREPARE after project_file, and
  458. # during that window the DB busy_printers seed is empirically unreliable
  459. # (multi-plate batches double-/triple-dispatched onto the same printer
  460. # 30 s apart). Keyed by printer_id; cleared by the watchdog on success
  461. # or revert.
  462. # printer_id -> (monotonic_started_at, pre_state, pre_subtask_id)
  463. self._dispatch_holds: dict[int, tuple[float, str, str | None]] = {}
  464. # Minimum cooldown between dispatches to the same printer (covers the
  465. # H2D's project_file digestion window).
  466. self._dispatch_min_cooldown = 60.0
  467. # Hard timeout — drop the hold even if we never observed a transition,
  468. # so a lost MQTT session can't lock a printer out of the queue forever.
  469. # Matches the watchdog timeout (90 s) plus a safety margin so the
  470. # watchdog runs first on the unhappy path.
  471. self._dispatch_max_hold = 180.0
  472. # Refillable upload pool (#2602). Items whose FTP upload was launched by
  473. # an earlier pass and is still running. `_start_print` flips the row
  474. # pending -> printing only *after* the upload completes, so until then
  475. # the row stays `pending`: each tick, check_queue excludes these
  476. # item_ids from re-selection and their printers from new dispatch /
  477. # auto-drying, and launches only `limit - len(_inflight)` new uploads so
  478. # freed slots refill on the next fast tick. check_queue is the sole,
  479. # sequential caller and the prune done-callbacks run in the same
  480. # event-loop thread, so this dict needs no lock.
  481. # item_id -> (task, printer_id)
  482. self._inflight: dict[int, tuple[asyncio.Task, int | None]] = {}
  483. # Expected prints registered by `_start_print` that have not yet had a
  484. # print command sent. Populated at registration, dropped once
  485. # `start_print()` succeeds, and rolled back by `_dispatch_one` on every
  486. # other exit. Same threading argument as `_inflight` above: one
  487. # sequential caller, callbacks on the same loop, so no lock.
  488. # item_id -> (printer_id, remote_filename, archive_id)
  489. self._unconfirmed_expected_print: dict[int, tuple[int, str, int]] = {}
  490. # Budget reservations created for a dispatch whose print command has
  491. # not been confirmed yet. `_dispatch_one` releases these on every
  492. # unsuccessful exit; a successful start removes the item id and leaves
  493. # the reservation for finance_billing to consume with the archive.
  494. self._unconfirmed_budget_reservations: set[int] = set()
  495. async def run(self):
  496. """Main loop - check queue every interval."""
  497. self._running = True
  498. logger.info("Print scheduler started")
  499. await self._clear_stale_dispatch_claims(at_startup=True)
  500. while self._running:
  501. dispatched = False
  502. try:
  503. # No-op while any upload is in flight; on a quiet tick it releases
  504. # a claim whose best-effort clear failed (e.g. the database was
  505. # briefly unreachable), instead of leaving the row wedged until
  506. # the next restart.
  507. await self._clear_stale_dispatch_claims()
  508. dispatched = await self.check_queue()
  509. except Exception as e:
  510. logger.error("Scheduler error: %s", e)
  511. # Re-check quickly after a productive pass so a draining batch does
  512. # not stall behind the idle interval; otherwise sleep normally (#2555).
  513. await asyncio.sleep(self._fast_check_interval if dispatched else self._check_interval)
  514. async def _clear_stale_dispatch_claims(self, *, at_startup: bool = False) -> None:
  515. """Clear dispatch claims with no live dispatch coroutine behind them (#2615).
  516. A claim is only ever held by a live dispatch coroutine, so when this
  517. process has nothing in ``_inflight`` every ``dispatching_at`` in the table
  518. is stale. At startup that is trivially true — no coroutine survives a
  519. restart. It is equally true on any later tick where no upload is running,
  520. which is what makes this safe to repeat rather than only run once.
  521. Repeating it matters because ``_clear_dispatch_claim`` is best-effort: if
  522. the database is briefly unreachable at exactly the moment dispatch ends,
  523. the claim survives and the row is wedged out of the selection query. That
  524. used to last until the next restart (#2702 follow-up, seen when
  525. PostgreSQL refused a connection mid-dispatch).
  526. ``_inflight`` is populated when the task is spawned, before the coroutine
  527. claims its row, and pruned by a done-callback that cannot run before the
  528. coroutine's own ``finally`` — so "claim present, nothing in flight" has no
  529. race window and needs no age threshold. A size-derived upload deadline
  530. (``max(600s, size/25KB/s)``) has no safe fixed bound anyway.
  531. """
  532. if self._inflight:
  533. return
  534. try:
  535. async with async_session() as db:
  536. res = await db.execute(
  537. update(PrintQueueItem).where(PrintQueueItem.dispatching_at.is_not(None)).values(dispatching_at=None)
  538. )
  539. await db.commit()
  540. if res.rowcount:
  541. logger.info(
  542. "Cleared %d orphaned dispatch claim(s)%s (#2615)",
  543. res.rowcount,
  544. " at startup" if at_startup else "",
  545. )
  546. except Exception as exc:
  547. logger.error("Failed to clear orphaned dispatch claims: %s", exc)
  548. def stop(self):
  549. """Stop the scheduler."""
  550. self._running = False
  551. logger.info("Print scheduler stopped")
  552. async def check_queue(self) -> bool:
  553. """Check for prints ready to start.
  554. Returns True if this pass dispatched at least one item, so the caller
  555. can loop again quickly instead of sleeping the full interval (#2555).
  556. """
  557. async with async_session() as db:
  558. # Check if shortest-job-first scheduling is enabled
  559. sjf_enabled = await self._get_bool_setting(db, "queue_shortest_first")
  560. # Get all pending items, ordered by printer and position (or SJF order)
  561. if sjf_enabled:
  562. # SJF: group by printer (and target_model for model-based jobs),
  563. # then items already jumped get top priority (starvation guard),
  564. # then sort by print_time ascending. Items with no print time go last.
  565. result = await db.execute(
  566. select(PrintQueueItem)
  567. .where(PrintQueueItem.status == "pending")
  568. # Never re-select a row a dispatch worker has already claimed
  569. # (#2615) — belt-and-suspenders with the _inflight exclusion
  570. # below, and the guard that lets an orphaned claim be ignored
  571. # until startup reconciliation clears it.
  572. .where(PrintQueueItem.dispatching_at.is_(None))
  573. # archive/library_file are read by the cross-model gate
  574. # (#2578); eager-load once per pass instead of a lazy-load
  575. # (which would raise in async) per item.
  576. .options(
  577. selectinload(PrintQueueItem.archive),
  578. selectinload(PrintQueueItem.library_file),
  579. # Cross-model candidates (#671), plus each candidate's file
  580. # for the same cross-model gate. Lazy-loading either would
  581. # raise in async.
  582. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  583. )
  584. .order_by(
  585. PrintQueueItem.printer_id,
  586. PrintQueueItem.target_model,
  587. PrintQueueItem.been_jumped.desc(),
  588. PrintQueueItem.print_time_seconds.asc().nullslast(),
  589. PrintQueueItem.position,
  590. )
  591. )
  592. else:
  593. result = await db.execute(
  594. select(PrintQueueItem)
  595. .where(PrintQueueItem.status == "pending")
  596. # Skip rows already claimed by a dispatch worker (#2615).
  597. .where(PrintQueueItem.dispatching_at.is_(None))
  598. .options(
  599. selectinload(PrintQueueItem.archive),
  600. selectinload(PrintQueueItem.library_file),
  601. # Cross-model candidates (#671), plus each candidate's file
  602. # for the same cross-model gate. Lazy-loading either would
  603. # raise in async.
  604. selectinload(PrintQueueItem.variants).selectinload(PrintQueueVariant.library_file),
  605. )
  606. .order_by(PrintQueueItem.printer_id, PrintQueueItem.position)
  607. )
  608. items = list(result.scalars().all())
  609. # Drop rows whose upload is still in flight from an earlier pass
  610. # (#2602). They stay `pending` until the upload finishes, so without
  611. # this a fast tick would re-select and re-dispatch the same row.
  612. # Belt-and-suspenders with the printer exclusion below.
  613. if self._inflight:
  614. inflight_ids = set(self._inflight)
  615. items = [it for it in items if it.id not in inflight_ids]
  616. # Read plate-clear setting once per queue check. Default MUST be
  617. # False to match the schema (SettingsSchema.require_plate_clear
  618. # defaults False) and the frontend (toggle + card badge both treat a
  619. # missing value as off). When no settings row exists, a True default
  620. # here re-enabled the plate-clear gate the UI showed as disabled,
  621. # blocking dispatch to FINISH-state printers forever with no UI path
  622. # to clear it (#1865).
  623. require_plate_clear = await self._get_bool_setting(db, "require_plate_clear", default=False)
  624. if not items:
  625. # No dispatchable pending items — still check auto-drying on idle
  626. # printers, but keep any printer with an upload still in flight
  627. # from an earlier pass out of it (#2602): its print is imminent,
  628. # so it must not be auto-dried in the gap before the row flips to
  629. # printing. Report the pass as productive while uploads run so the
  630. # loop stays on the fast interval.
  631. inflight_printers = {pid for (_task, pid) in self._inflight.values() if pid is not None}
  632. await self._check_auto_drying(db, [], inflight_printers, require_plate_clear=require_plate_clear)
  633. return bool(self._inflight)
  634. logger.info(
  635. "Queue check: found %d pending items: %s",
  636. len(items),
  637. [(i.id, i.printer_id, i.archive_id, i.library_file_id) for i in items],
  638. )
  639. # Seed busy_printers with printers that already have an item in 'printing'
  640. # status. _is_printer_idle() alone is not sufficient as a dispatch gate —
  641. # on H2D / P1 series the MQTT state transition from IDLE to RUNNING can
  642. # lag several seconds behind the print command, so the next check_queue
  643. # tick still sees IDLE and would double-dispatch onto the same printer.
  644. # Without this guard, two pending items targeting the same printer
  645. # (e.g. a batch with quantity>1) both end up in 'printing' status —
  646. # surfaced via the "BUG: Multiple queue items" warning in on_print_complete.
  647. busy_result = await db.execute(
  648. select(PrintQueueItem.printer_id)
  649. .where(PrintQueueItem.status == "printing")
  650. .where(PrintQueueItem.printer_id.is_not(None))
  651. )
  652. busy_printers: set[int] = {pid for (pid,) in busy_result.all() if pid is not None}
  653. # Defense-in-depth (#1157): augment busy_printers with any printer
  654. # still in its post-dispatch hold window. Empirically, the DB seed
  655. # above can miss in-flight items in a multi-plate batch — same-file
  656. # plates were being dispatched 30 s apart while the H2D was still
  657. # digesting the first project_file. The hold is keyed in-memory and
  658. # released by the watchdog on the success path, so it adds a layer
  659. # that doesn't depend on DB row visibility or completion-callback
  660. # timing.
  661. for held_printer_id in list(self._dispatch_holds.keys()):
  662. if self._printer_in_dispatch_hold(held_printer_id):
  663. busy_printers.add(held_printer_id)
  664. # Exclude printers whose upload is still in flight from an earlier
  665. # pass (#2602). The row is `pending` until the upload finishes and
  666. # the printing-state seed / dispatch hold above only arm once the
  667. # upload completes, so this is what holds the printer (and, via
  668. # busy_printers, its auto-drying) out of the pass during the upload.
  669. for _task, inflight_pid in self._inflight.values():
  670. if inflight_pid is not None:
  671. busy_printers.add(inflight_pid)
  672. # Printers held by a Home Assistant sensor interlock (#1148) — an
  673. # enclosure door left open, say. The fixed-printer branch turns
  674. # this into a waiting_reason the user can act on; the model-based
  675. # branch hides these printers from the matcher so an "Any <model>"
  676. # job runs on a sibling instead of queueing behind the held one.
  677. #
  678. # Deliberately NOT merged into busy_printers, even though that set
  679. # already means "unavailable this pass". _check_auto_drying reads
  680. # it as "is currently printing" and would put an idle-but-held
  681. # printer down the mid-print drying path, which caps the drying
  682. # temperature and skips the queue-only gating. A held printer is
  683. # idle; it should dry exactly as it did before.
  684. #
  685. # Only sensors we actually read and found alerting appear here; see
  686. # ha_sensor_manager.blocked_printers. A Home Assistant that is down
  687. # holds nothing.
  688. interlocked: dict[int, str] = {}
  689. try:
  690. interlocked = await ha_sensor_manager.blocked_printers(db)
  691. except Exception as e:
  692. # Never let the interlock stop the queue running. A broken
  693. # lookup means no holds, not no dispatches.
  694. logger.warning("Home Assistant interlock check failed: %s", e)
  695. interlocked = {}
  696. # Printers a smart plug can bring back, read once for the whole pass
  697. # (#2786). Used by the model-based branch both to word "Offline" in
  698. # the waiting reason and to decide what the wake step may switch on.
  699. wakeable_printer_ids = await self._wakeable_printer_ids(db)
  700. # At most one power-on per queue check. Each one blocks this loop
  701. # for the boot wait, so a queue of ten class-targeted jobs must not
  702. # switch on ten printers inside a single pass — the next pass wakes
  703. # the next one (#2786).
  704. power_on_attempted = False
  705. # Log skip reasons once per queue check (not per item)
  706. skip_reasons: dict[str, int] = {}
  707. # Items selected for dispatch in this pass, one per printer. The
  708. # loop below only *decides* — the uploads happen afterwards, in
  709. # parallel (#2555). See _dispatch_selected().
  710. dispatch_ids: list[int] = []
  711. # Library rows queued with `cleanup_library_after_dispatch` (the
  712. # printer-card "upload and print" flow) are CONSUMED by the dispatch
  713. # that prints them: the row is deleted and the 3MF is unlinked from
  714. # disk. That was safe only because dispatch was serial. Run two of
  715. # them against the same row at once and the second DELETE matches no
  716. # row (StaleDataError), and the winner's unlink can pull the file out
  717. # from under the loser's in-flight upload.
  718. #
  719. # Only the cleanup flag mutates the row. An ordinary library print
  720. # just reads it, so the common fan-out — one file, many printers,
  721. # which is exactly the reporter's workload — still goes out fully in
  722. # parallel. Narrow the guard to the mutating case; do not serialise
  723. # the case the whole fix exists for.
  724. dispatch_libs: set[int] = set()
  725. consumed_libs: set[int] = set()
  726. def _library_row_conflict(candidate: PrintQueueItem) -> bool:
  727. """True if dispatching `candidate` now would race another item's cleanup."""
  728. lib_id = candidate.library_file_id
  729. if lib_id is None:
  730. return False
  731. if candidate.cleanup_library_after_dispatch:
  732. # We would delete a row someone else in this pass is reading.
  733. return lib_id in dispatch_libs
  734. # Someone else in this pass will delete the row out from under us.
  735. return lib_id in consumed_libs
  736. def _claim_library_row(candidate: PrintQueueItem) -> None:
  737. lib_id = candidate.library_file_id
  738. if lib_id is None:
  739. return
  740. dispatch_libs.add(lib_id)
  741. if candidate.cleanup_library_after_dispatch:
  742. consumed_libs.add(lib_id)
  743. for item in items:
  744. # Check scheduled time first (scheduled_time is stored in UTC from ISO string)
  745. if item.scheduled_time:
  746. sched = item.scheduled_time
  747. if sched.tzinfo is None:
  748. sched = sched.replace(tzinfo=timezone.utc)
  749. if sched > datetime.now(timezone.utc):
  750. skip_reasons["scheduled_future"] = skip_reasons.get("scheduled_future", 0) + 1
  751. continue
  752. # Skip items that require manual start
  753. if item.manual_start:
  754. skip_reasons["manual_start"] = skip_reasons.get("manual_start", 0) + 1
  755. continue
  756. if item.printer_id:
  757. # Held by a sensor interlock (#1148). Checked before the
  758. # busy_printers test that would otherwise swallow it
  759. # silently — "waiting for a printer" and "waiting for you
  760. # to shut the enclosure" need to read differently, and only
  761. # one of them is something the user can fix.
  762. #
  763. # The interlock is the only thing that writes a
  764. # waiting_reason on this branch — the model-based branch
  765. # nulls it at the moment it assigns a printer — so any
  766. # reason still standing once the hold lifts is stale and is
  767. # cleared here. Doing it at dispatch instead would leave a
  768. # shut door reading "Waiting on Enclosure Door" for as long
  769. # as the printer stayed busy with something else.
  770. interlock_reason = interlocked.get(item.printer_id)
  771. reason = f"Waiting on {interlock_reason}" if interlock_reason else None
  772. if item.waiting_reason != reason:
  773. item.waiting_reason = reason
  774. await db.commit()
  775. if interlock_reason:
  776. skip_reasons["sensor_interlock"] = skip_reasons.get("sensor_interlock", 0) + 1
  777. continue
  778. # Specific printer assignment (existing behavior)
  779. if item.printer_id in busy_printers:
  780. continue
  781. # Check if printer is idle
  782. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  783. printer_connected = printer_manager.is_connected(item.printer_id)
  784. # If printer not connected, try to power on via smart plug
  785. if not printer_connected:
  786. plugs = await self._get_smart_plugs(db, item.printer_id)
  787. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  788. if auto_on_plugs:
  789. logger.info("Printer %s offline, attempting to power on via smart plug(s)", item.printer_id)
  790. # Power on using the plug that actually feeds the printer, and
  791. # wait for it to boot on that one only (#2629).
  792. primary_plug = self._pick_power_plug(auto_on_plugs)
  793. powered_on = await self._power_on_and_wait(primary_plug, item.printer_id, db)
  794. if powered_on:
  795. # Also turn on any remaining auto_on plugs (e.g., filter)
  796. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  797. try:
  798. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  799. await service.turn_on(extra_plug)
  800. logger.info(
  801. "Also powered on plug '%s' for printer %s", extra_plug.name, item.printer_id
  802. )
  803. except Exception as e:
  804. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  805. printer_connected = True
  806. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  807. else:
  808. logger.warning("Could not power on printer %s via smart plug", item.printer_id)
  809. busy_printers.add(item.printer_id)
  810. continue
  811. else:
  812. # No plug or auto_on disabled
  813. busy_printers.add(item.printer_id)
  814. continue
  815. # Check if printer is idle (busy with another print)
  816. if not printer_idle:
  817. # If printer is drying (not truly busy), handle based on queue_drying_block
  818. if self._drying_in_progress.get(item.printer_id):
  819. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  820. if block_for_drying:
  821. # Drying blocks queue — skip this printer
  822. busy_printers.add(item.printer_id)
  823. continue
  824. else:
  825. # Print takes priority — stop drying
  826. await self._stop_drying(item.printer_id)
  827. # Re-check idle after stopping drying
  828. printer_idle = self._is_printer_idle(item.printer_id, require_plate_clear)
  829. if not printer_idle:
  830. busy_printers.add(item.printer_id)
  831. continue
  832. else:
  833. busy_printers.add(item.printer_id)
  834. continue
  835. # Check condition (previous print success)
  836. if item.require_previous_success:
  837. if not await self._check_previous_success(db, item):
  838. item.status = "skipped"
  839. item.error_message = "Previous print failed or was aborted"
  840. item.completed_at = datetime.now(timezone.utc)
  841. await db.commit()
  842. logger.info("Skipped queue item %s - previous print failed", item.id)
  843. # Send notification
  844. job_name = await self._get_job_name(db, item)
  845. printer = await self._get_printer(db, item.printer_id)
  846. await notification_service.on_queue_job_skipped(
  847. job_name=job_name,
  848. printer_id=item.printer_id,
  849. printer_name=printer.name if printer else "Unknown",
  850. reason="Previous print failed or was aborted",
  851. db=db,
  852. )
  853. continue
  854. # Resolve the AMS mapping when it's missing OR unresolved
  855. # (all -1). A stored all-[-1] mapping is a bug artifact — a
  856. # frontend status-load race can persist [-1] (#2589) — and
  857. # must be recomputed from live trays rather than trusted.
  858. unmappable = await self._ensure_ams_mapping(db, item.printer_id, item)
  859. if unmappable:
  860. await self._fail_unmappable_item(db, item, item.printer_id, unmappable)
  861. continue
  862. # Filament-deficit pre-dispatch check (#1496). If the
  863. # assigned spool can't satisfy any required slot grams,
  864. # promote the item to manual_start so the user must
  865. # acknowledge via the ▶ button (which re-checks live).
  866. if await self._block_on_filament_deficit(db, item):
  867. continue
  868. # Hold this item back for the next pass rather than racing
  869. # another dispatch over the same transient library row. The
  870. # printer is still marked busy so a later item does not jump
  871. # its place in this printer's queue.
  872. if _library_row_conflict(item):
  873. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  874. busy_printers.add(item.printer_id)
  875. continue
  876. # Queue the dispatch instead of running it here — see
  877. # _dispatch_selected(). busy_printers still gets the printer
  878. # immediately, so nothing else in this pass can target it.
  879. _claim_library_row(item)
  880. dispatch_ids.append(item.id)
  881. busy_printers.add(item.printer_id)
  882. # SJF starvation guard: mark items that were jumped
  883. if sjf_enabled and item.print_time_seconds is not None:
  884. for other in items:
  885. if (
  886. other.id != item.id
  887. and other.status == "pending"
  888. and other.printer_id == item.printer_id
  889. and not other.been_jumped
  890. and other.position < item.position
  891. and (
  892. other.print_time_seconds is None
  893. or other.print_time_seconds > item.print_time_seconds
  894. )
  895. ):
  896. other.been_jumped = True
  897. await db.commit()
  898. elif item.target_model or item.variants:
  899. # Model-based assignment - find any idle printer of matching model.
  900. # A plain model-based item has exactly one candidate, built from
  901. # its own columns. A cross-model item (#671) has one per sliced
  902. # variant and takes the first that matches, walking them in the
  903. # user's priority order so the pick is reproducible when more
  904. # than one printer is free in the same pass.
  905. candidates = _candidates_for(item)
  906. printer_id = None
  907. chosen: _ModelCandidate | None = None
  908. per_model_reasons: list[tuple[str | None, str]] = []
  909. # Candidates that cleared the cross-model gate below. The
  910. # smart-plug wake step may only consider these — waking a
  911. # printer for a file that can never legally run on it is
  912. # worse than not waking at all (#2786).
  913. wakeable_candidates: list[_ModelCandidate] = []
  914. if not candidates:
  915. # Every candidate file has been deleted or trashed out from
  916. # under this item. Hold it with something the user can act
  917. # on rather than letting it look dispatchable forever.
  918. per_model_reasons.append(
  919. (
  920. item.target_model,
  921. "Every file for this job has been deleted — add a file back or remove the item",
  922. )
  923. )
  924. for candidate in candidates:
  925. # Parse required filament types if present
  926. required_types = None
  927. if candidate.required_filament_types:
  928. try:
  929. required_types = json.loads(candidate.required_filament_types)
  930. except json.JSONDecodeError:
  931. pass # Ignore malformed filament types; treat as no constraint
  932. # Parse filament overrides if present
  933. filament_overrides = None
  934. if candidate.filament_overrides:
  935. try:
  936. filament_overrides = json.loads(candidate.filament_overrides)
  937. except json.JSONDecodeError:
  938. pass
  939. # If overrides exist, use override types for validation instead
  940. effective_types = required_types
  941. if filament_overrides:
  942. override_types = sorted({o["type"] for o in filament_overrides if "type" in o})
  943. if override_types:
  944. # Merge: keep original types for non-overridden slots, add override types
  945. effective_types = sorted(set(required_types or []) | set(override_types))
  946. # Cross-model safety gate (#2578): never hand a 3MF sliced
  947. # for an incompatible model to a printer, no matter how the
  948. # row got into the DB (old rows, direct API writes). Held
  949. # as pending with an actionable waiting_reason — the user
  950. # fixes it by editing the item's target model.
  951. if not is_gcode_compatible(candidate.sliced_for, candidate.target_model):
  952. per_model_reasons.append(
  953. (
  954. candidate.target_model,
  955. f"File was sliced for {candidate.sliced_for}, which is not compatible with "
  956. f"{candidate.target_model} — edit the item and fix its target model",
  957. )
  958. )
  959. skip_reasons["sliced_model_mismatch"] = skip_reasons.get("sliced_model_mismatch", 0) + 1
  960. continue
  961. wakeable_candidates.append(candidate)
  962. match_id, match_reason = await self._find_idle_printer_for_model(
  963. db,
  964. candidate.target_model,
  965. # Sensor-held printers are unavailable to the
  966. # matcher but stay out of busy_printers itself
  967. # (#1148) — see where `interlocked` is built.
  968. busy_printers | interlocked.keys(),
  969. effective_types,
  970. item.target_location,
  971. filament_overrides=filament_overrides,
  972. require_plate_clear=require_plate_clear,
  973. wakeable_ids=wakeable_printer_ids,
  974. )
  975. if match_id:
  976. printer_id = match_id
  977. chosen = candidate
  978. break
  979. per_model_reasons.append((candidate.target_model, match_reason or ""))
  980. # Nothing is available and nothing has been woken this pass:
  981. # switch one matching printer on. Assignment is left to the
  982. # next pass, which sees the booted printer's live state
  983. # instead of guessing at it seconds after connect (#2786).
  984. if printer_id is None and not power_on_attempted and wakeable_candidates:
  985. woken_id, attempted_id = await self._wake_printer_for_model(
  986. db,
  987. wakeable_candidates,
  988. item.target_location,
  989. busy_printers | interlocked.keys(),
  990. wakeable_printer_ids,
  991. require_plate_clear,
  992. )
  993. # An attempt spends the pass's one wake whether or not
  994. # it worked: it has already blocked the queue loop for
  995. # the boot wait. A failed printer is held out of later
  996. # passes by its own cool-off, deliberately NOT by
  997. # busy_printers — it is off, not busy, and labelling it
  998. # busy would both misdescribe it in every later item's
  999. # waiting reason and suppress the notification, since
  1000. # an all-busy reason is treated as needing no action.
  1001. power_on_attempted = attempted_id is not None
  1002. if woken_id is not None:
  1003. # Hold this item back rather than dispatching onto a
  1004. # printer whose AMS has not reported yet.
  1005. skip_reasons["powered_on_printer"] = skip_reasons.get("powered_on_printer", 0) + 1
  1006. continue
  1007. waiting_reason = None if printer_id else _collapse_waiting_reasons(per_model_reasons)
  1008. # Fold the winning variant's file and settings onto the item
  1009. # before anything else looks at them — the guards below and
  1010. # every step of the dispatch read the item's own columns.
  1011. if chosen is not None:
  1012. self._resolve_variant(item, chosen)
  1013. # Update waiting_reason if changed and send notification when first waiting
  1014. if item.waiting_reason != waiting_reason:
  1015. was_waiting = item.waiting_reason is not None
  1016. item.waiting_reason = waiting_reason
  1017. await db.commit()
  1018. # Send waiting notification only when transitioning to waiting state
  1019. # and the reason requires user action (not just "all printers busy")
  1020. if waiting_reason and not was_waiting and not self._is_busy_only(waiting_reason):
  1021. job_name = await self._get_job_name(db, item)
  1022. await notification_service.on_queue_job_waiting(
  1023. job_name=job_name,
  1024. target_model=_candidate_model_label(candidates) or item.target_model,
  1025. waiting_reason=waiting_reason,
  1026. db=db,
  1027. )
  1028. if printer_id:
  1029. # Before claiming the printer: hold back rather than race
  1030. # another dispatch over the same transient library row.
  1031. # Checked here so a held item does not get a printer
  1032. # assigned and then sit on it. See _library_row_conflict().
  1033. #
  1034. # No busy_printers.add() here, unlike the fixed-printer
  1035. # branch above: that one protects its printer's own queue
  1036. # ordering, but this item was never assigned to `printer_id`
  1037. # — the matcher merely offered it. Marking it busy would
  1038. # strand an idle printer for the rest of the pass.
  1039. if _library_row_conflict(item):
  1040. skip_reasons["library_row_in_use"] = skip_reasons.get("library_row_in_use", 0) + 1
  1041. continue
  1042. # Check condition (previous print success) before assigning
  1043. if item.require_previous_success:
  1044. if not await self._check_previous_success(db, item):
  1045. item.status = "skipped"
  1046. item.error_message = "Previous print failed or was aborted"
  1047. item.completed_at = datetime.now(timezone.utc)
  1048. await db.commit()
  1049. logger.info("Skipped queue item %s - previous print failed", item.id)
  1050. # Send notification
  1051. job_name = await self._get_job_name(db, item)
  1052. printer = await self._get_printer(db, printer_id)
  1053. await notification_service.on_queue_job_skipped(
  1054. job_name=job_name,
  1055. printer_id=printer_id,
  1056. printer_name=printer.name if printer else "Unknown",
  1057. reason="Previous print failed or was aborted",
  1058. db=db,
  1059. )
  1060. continue
  1061. # Assign printer and start - clear waiting reason
  1062. item.printer_id = printer_id
  1063. item.waiting_reason = None
  1064. logger.info("Model-based assignment: queue item %s assigned to printer %s", item.id, printer_id)
  1065. # Send assignment notification
  1066. job_name = await self._get_job_name(db, item)
  1067. printer = await self._get_printer(db, printer_id)
  1068. await notification_service.on_queue_job_assigned(
  1069. job_name=job_name,
  1070. printer_id=printer_id,
  1071. printer_name=printer.name if printer else "Unknown",
  1072. target_model=item.target_model,
  1073. db=db,
  1074. )
  1075. # Resolve the AMS mapping for the assigned printer when it's
  1076. # missing OR unresolved (all -1). Critical for model-based
  1077. # jobs where mapping wasn't computed upfront, and it also
  1078. # self-heals a bogus stored [-1] (#2589).
  1079. unmappable = await self._ensure_ams_mapping(db, printer_id, item)
  1080. if unmappable:
  1081. await self._fail_unmappable_item(db, item, printer_id, unmappable)
  1082. continue
  1083. # Filament-deficit pre-dispatch check (#1496).
  1084. if await self._block_on_filament_deficit(db, item):
  1085. continue
  1086. _claim_library_row(item)
  1087. dispatch_ids.append(item.id)
  1088. busy_printers.add(printer_id)
  1089. # SJF starvation guard: mark model-based items that were jumped
  1090. if sjf_enabled and item.print_time_seconds is not None:
  1091. for other in items:
  1092. if (
  1093. other.id != item.id
  1094. and other.status == "pending"
  1095. and other.printer_id is None
  1096. and other.target_model
  1097. and other.target_model.upper() == item.target_model.upper()
  1098. and not other.been_jumped
  1099. and other.position < item.position
  1100. and (
  1101. other.print_time_seconds is None
  1102. or other.print_time_seconds > item.print_time_seconds
  1103. )
  1104. ):
  1105. other.been_jumped = True
  1106. await db.commit()
  1107. # Log the decisions BEFORE dispatching. The dispatch below blocks for
  1108. # as long as the slowest upload takes (minutes on a big 3MF), and a
  1109. # skip summary that only lands after the transfers have finished is
  1110. # useless for working out why an item did not go out.
  1111. if skip_reasons:
  1112. logger.info("Queue skip summary: %s", skip_reasons)
  1113. if busy_printers:
  1114. # Log why each printer was busy (first time it was checked)
  1115. for pid in busy_printers:
  1116. state = printer_manager.get_status(pid)
  1117. connected = printer_manager.is_connected(pid)
  1118. awaiting = printer_manager.is_awaiting_plate_clear(pid)
  1119. state_name = state.state if state else "NO_STATUS"
  1120. logger.info(
  1121. "Queue: printer %d not available — connected=%s, state=%s, awaiting_plate_clear=%s",
  1122. pid,
  1123. connected,
  1124. state_name,
  1125. awaiting,
  1126. )
  1127. # Read the concurrency limit BEFORE the commit below, not inside
  1128. # _dispatch_selected(). A SELECT on this session after the commit
  1129. # implicitly opens a fresh transaction that nothing then closes, and
  1130. # it would stay open for the whole dispatch — minutes of "idle in
  1131. # transaction" on Postgres (pinned MVCC snapshot, vacuum blocked),
  1132. # and on SQLite a pinned WAL read snapshot that stops the WAL being
  1133. # checkpointed while every dispatch is writing to it.
  1134. upload_limit = max(1, await self._get_int_setting(db, "queue_max_concurrent_uploads", default=4))
  1135. # Selection is done; every decision above is recorded on `db`
  1136. # (model-based printer assignment, computed ams_mapping). Flush it
  1137. # before the dispatch tasks open their own sessions, or they will
  1138. # read a row that still says printer_id=None. This also releases the
  1139. # connection back to the pool for the duration of the dispatch.
  1140. await db.commit()
  1141. if dispatch_ids:
  1142. item_printers = {it.id: it.printer_id for it in items}
  1143. self._launch_uploads(dispatch_ids, item_printers, upload_limit)
  1144. # Auto-drying: start drying on idle printers that have no pending queue items
  1145. await self._check_auto_drying(db, items, busy_printers, require_plate_clear=require_plate_clear)
  1146. # Keep the loop on the fast interval while any upload is in flight so
  1147. # a slot freed mid-tick refills within seconds rather than after the
  1148. # 30 s idle sleep (#2602). Selecting anything this pass (launched or
  1149. # deferred because the pool was full) also counts as productive.
  1150. return bool(dispatch_ids) or bool(self._inflight)
  1151. def _launch_uploads(self, item_ids: list[int], item_printers: dict[int, int | None], limit: int) -> None:
  1152. """Launch selected uploads as a refillable pool, capped at ``limit`` (#2602).
  1153. Dispatch used to happen inline in the selection loop: ``await
  1154. _start_print(db, item)`` per item in turn. Since ``_start_print``
  1155. performs the FTP upload, that serialized every printer behind every
  1156. other printer's transfer even though the printers are independent
  1157. machines; #2555 moved it to a parallel ``asyncio.gather()``. But that
  1158. gather was awaited before ``check_queue`` returned, so the run loop
  1159. stayed blocked until the *slowest* upload in the batch finished — a
  1160. 513 s upload left 15 of 16 configured slots idle for 8.5 minutes on a
  1161. 93-printer farm even as other printers came free (#2602).
  1162. Each upload now runs as an independent background task tracked in
  1163. ``self._inflight``. check_queue excludes in-flight item_ids (still
  1164. `pending` until their upload completes) and their printers from the
  1165. next pass's selection, and this method launches at most
  1166. ``limit - len(self._inflight)`` new uploads, so a freed slot refills on
  1167. the next fast tick instead of waiting out the whole batch. The bound
  1168. exists because the printers are independent but the host is not: each
  1169. in-flight upload holds a thread in the FTP pool, a TLS session and a
  1170. file handle.
  1171. The no-overlapping-dispatch invariant the batch-await used to provide
  1172. is now carried by the in-flight exclusion in check_queue. Everything
  1173. else — the pending->printing CAS, the busy-printer guard (#2598), the
  1174. per-printer hold, and each item's independent failure handling — still
  1175. lives in ``_start_print`` and runs per task exactly as before.
  1176. Synchronous on purpose: it registers every launched task into
  1177. ``self._inflight`` before returning, so the next (sequential) tick sees
  1178. an accurate in-flight count with no interleaving await.
  1179. """
  1180. free = limit - len(self._inflight)
  1181. if free <= 0:
  1182. logger.info(
  1183. "Upload pool full (%d/%d in flight) — deferring %d item(s) to a later tick: %s",
  1184. len(self._inflight),
  1185. limit,
  1186. len(item_ids),
  1187. item_ids,
  1188. )
  1189. return
  1190. to_launch = item_ids[:free]
  1191. deferred = item_ids[free:]
  1192. logger.info(
  1193. "Launching %d upload(s) (pool %d/%d in flight)%s",
  1194. len(to_launch),
  1195. len(self._inflight),
  1196. limit,
  1197. f" — deferring {deferred} to a later tick" if deferred else "",
  1198. )
  1199. for item_id in to_launch:
  1200. task = spawn_background_task(self._dispatch_one(item_id), name=f"queue-upload-{item_id}")
  1201. self._inflight[item_id] = (task, item_printers.get(item_id))
  1202. # Prune on completion so the freed slot is refillable next tick.
  1203. # spawn_background_task already logs any uncaught exception; this
  1204. # only reclaims the pool slot (fires on success, failure, or cancel).
  1205. task.add_done_callback(lambda _t, iid=item_id: self._inflight.pop(iid, None))
  1206. async def _dispatch_one(self, item_id: int) -> None:
  1207. """Upload + start one queue item in its own session (pool worker, #2602).
  1208. Its own session: pool workers run concurrently and an AsyncSession is
  1209. not safe to share across tasks; it also keeps a slow upload from pinning
  1210. the scheduler's session (and, on SQLite, its transaction) open for the
  1211. transfer's duration.
  1212. """
  1213. async with async_session() as item_db:
  1214. # Claim the row for dispatch BEFORE reading the printer snapshot or
  1215. # touching any slow I/O (#2615). The claim is an atomic CAS on
  1216. # (status='pending', dispatching_at IS NULL); while it's held the edit
  1217. # routes reject reassignment (409), so printer_id can't change out from
  1218. # under the in-flight upload and split the queue row from the
  1219. # archive/expected-print/physical command.
  1220. if not await self._claim_for_dispatch(item_db, item_id):
  1221. logger.info(
  1222. "Queue item %s not claimable for dispatch (cancelled, removed, or already claimed) — skipping",
  1223. item_id,
  1224. )
  1225. return
  1226. try:
  1227. item = await item_db.get(PrintQueueItem, item_id)
  1228. if not item:
  1229. logger.info("Queue item %s vanished after claim — skipping", item_id)
  1230. return
  1231. await self._start_print(item_db, item)
  1232. finally:
  1233. # Undo an expected-print registration whose print command never
  1234. # went out. One choke point covers every way `_start_print` can
  1235. # end without sending: a raised exception (a DB failure mid-
  1236. # dispatch is the reported case), an early return, a cancel
  1237. # winning the #1853 CAS, or `start_print()` returning False.
  1238. # A confirmed send removes the entry itself, so this is a no-op
  1239. # on the happy path.
  1240. self._rollback_unconfirmed_expected_print(item_id)
  1241. # Mirror the pre-#1625 background-dispatch lifecycle: a
  1242. # reservation survives only after start_print() accepted the
  1243. # command. Failure, cancellation, deferral, and exceptions all
  1244. # release it here.
  1245. await asyncio.shield(self._release_unconfirmed_budget_reservation(item_id))
  1246. # Release the claim on every exit. Once dispatch has finished the
  1247. # row's status carries the lock (printing/failed/cancelled are all
  1248. # != pending), so the token is only needed for the duration of the
  1249. # upload. A row left pending (e.g. busy-printer deferral) becomes
  1250. # dispatchable again on the next tick.
  1251. await self._clear_dispatch_claim(item_db, item_id)
  1252. def _rollback_unconfirmed_expected_print(self, item_id: int) -> None:
  1253. """Drop an expectation for a print command that was never sent.
  1254. Best-effort and never raises: this runs in the ``finally`` of dispatch,
  1255. where the interesting exception is usually the one already propagating.
  1256. """
  1257. pending = self._unconfirmed_expected_print.pop(item_id, None)
  1258. if pending is None:
  1259. return
  1260. printer_id, remote_filename, archive_id = pending
  1261. try:
  1262. from backend.app.main import unregister_expected_print
  1263. unregister_expected_print(printer_id, remote_filename, archive_id)
  1264. except Exception:
  1265. logger.warning(
  1266. "Queue item %s: failed to unregister expected print (printer=%s, file=%s, archive=%s)",
  1267. item_id,
  1268. printer_id,
  1269. remote_filename,
  1270. archive_id,
  1271. exc_info=True,
  1272. )
  1273. async def _release_unconfirmed_budget_reservation(self, item_id: int) -> None:
  1274. """Release a queue reservation without touching the dispatch session."""
  1275. if item_id not in self._unconfirmed_budget_reservations:
  1276. return
  1277. for attempt in range(1, 4):
  1278. async with async_session() as cleanup_db:
  1279. try:
  1280. await release_budget_reservation(
  1281. cleanup_db,
  1282. source_type="print_queue",
  1283. source_id=item_id,
  1284. status="released",
  1285. )
  1286. await cleanup_db.commit()
  1287. self._unconfirmed_budget_reservations.discard(item_id)
  1288. return
  1289. except Exception as exc:
  1290. try:
  1291. await cleanup_db.rollback()
  1292. except Exception:
  1293. pass
  1294. if attempt == 3:
  1295. logger.error(
  1296. "Queue item %s: failed to release budget reservation after %d attempts: %s",
  1297. item_id,
  1298. attempt,
  1299. exc,
  1300. )
  1301. return
  1302. await asyncio.sleep(0.5 * attempt)
  1303. async def _claim_for_dispatch(self, db: AsyncSession, item_id: int) -> bool:
  1304. """Atomically stamp ``dispatching_at`` on a still-pending, unclaimed row.
  1305. Returns True if this call won the claim, False if the row was already
  1306. claimed, no longer pending (cancelled mid-tick), or removed. The CAS is
  1307. the load-bearing guard against reassign-during-dispatch (#2615)."""
  1308. res = await db.execute(
  1309. update(PrintQueueItem)
  1310. .where(PrintQueueItem.id == item_id)
  1311. .where(PrintQueueItem.status == "pending")
  1312. .where(PrintQueueItem.dispatching_at.is_(None))
  1313. .values(dispatching_at=datetime.now(timezone.utc))
  1314. )
  1315. await db.commit()
  1316. return res.rowcount > 0
  1317. async def _clear_dispatch_claim(self, db: AsyncSession, item_id: int) -> None:
  1318. """Clear the dispatch claim (#2615). Best-effort: a failure here must not
  1319. mask the dispatch outcome.
  1320. Retried, because the failure mode in practice is transient and narrow: a
  1321. database that is momentarily unreachable — PostgreSQL out of connection
  1322. slots is the observed case — refuses this write for a second or two while
  1323. the dispatch that just ended is still holding the row out of the selection
  1324. query. One attempt was enough to wedge the item; a couple of spaced
  1325. attempts clear it. Each attempt rolls back first, since a failed write
  1326. leaves the session needing it before it can be reused.
  1327. If every attempt fails, ``_clear_stale_dispatch_claims`` picks the row up
  1328. on the next quiet tick.
  1329. """
  1330. for attempt in range(1, 4):
  1331. try:
  1332. await db.execute(update(PrintQueueItem).where(PrintQueueItem.id == item_id).values(dispatching_at=None))
  1333. await db.commit()
  1334. return
  1335. except Exception as exc:
  1336. try:
  1337. await db.rollback()
  1338. except Exception:
  1339. pass
  1340. if attempt == 3:
  1341. logger.warning(
  1342. "Queue item %s: failed to clear dispatch claim after %d attempts: %s "
  1343. "— a later quiet tick will release it",
  1344. item_id,
  1345. attempt,
  1346. exc,
  1347. )
  1348. return
  1349. await asyncio.sleep(0.5 * attempt)
  1350. async def _printers_for_model(
  1351. self,
  1352. db: AsyncSession,
  1353. model: str,
  1354. target_location: str | None = None,
  1355. ) -> list[Printer]:
  1356. """Active printers of *model*, optionally narrowed to one location.
  1357. Shared by the matcher and by the smart-plug wake step (#2786) so both
  1358. answer "which printers can this job run on" from one query — a job can
  1359. only be woken onto a printer the matcher would also have considered.
  1360. """
  1361. normalized_model = normalize_printer_model(model) or model
  1362. query = (
  1363. select(Printer)
  1364. .where(func.lower(Printer.model) == normalized_model.lower())
  1365. .where(Printer.is_active == True) # noqa: E712
  1366. )
  1367. if target_location:
  1368. query = query.where(Printer.location == target_location)
  1369. result = await db.execute(query)
  1370. return list(result.scalars().all())
  1371. async def _wakeable_printer_ids(self, db: AsyncSession) -> set[int]:
  1372. """Printer IDs that at least one enabled ``auto_on`` plug can power on.
  1373. Read once per queue check rather than per printer: it decides both
  1374. whether the wake step has anything to do and how an offline printer is
  1375. worded in the waiting reason — "Offline" and "offline with no Auto On
  1376. plug" are different problems, and the second is the one the user has to
  1377. fix themselves (#2786).
  1378. """
  1379. result = await db.execute(
  1380. select(SmartPlug.printer_id)
  1381. .where(SmartPlug.printer_id.is_not(None))
  1382. .where(SmartPlug.enabled == True) # noqa: E712
  1383. .where(SmartPlug.auto_on == True) # noqa: E712
  1384. )
  1385. return {pid for (pid,) in result.all() if pid is not None}
  1386. def _wake_recently_failed(self, printer_id: int) -> bool:
  1387. """True while this printer's failed power-on is still cooling off (#2786)."""
  1388. deadline = self._wake_failures.get(printer_id)
  1389. if deadline is None:
  1390. return False
  1391. if time.monotonic() >= deadline:
  1392. del self._wake_failures[printer_id]
  1393. return False
  1394. return True
  1395. async def _wake_printer_for_model(
  1396. self,
  1397. db: AsyncSession,
  1398. candidates: list[_ModelCandidate],
  1399. target_location: str | None,
  1400. exclude_ids: set[int],
  1401. wakeable_ids: set[int],
  1402. require_plate_clear: bool,
  1403. ) -> tuple[int | None, int | None]:
  1404. """Power on one offline printer a model-based item could run on (#2786).
  1405. The fixed-printer branch has powered a printer on since smart plugs
  1406. existed. The model-based branch never could: its matcher drops an
  1407. offline printer into the "Offline:" waiting reason and nothing looks at
  1408. its plugs, so a class-targeted job with every matching printer switched
  1409. off sat pending forever. The reporter's log is the controlled
  1410. experiment — the same item, same plug, same Auto On setting, dispatched
  1411. the moment they edited it onto a specific printer.
  1412. Returns ``(woken_id, attempted_id)``. ``attempted_id`` is set whenever a
  1413. power-on was actually tried, so the caller can tell "nothing here was
  1414. wakeable" (both None — cheap, other items may still find something)
  1415. from "we tried and it did not come up" (only ``attempted_id`` — the
  1416. boot timeout has already been spent).
  1417. Deliberately does NOT go on to match the job: AMS trays arrive with the
  1418. first status push after connect, so a filament check against a printer
  1419. that booted seconds ago can reject the printer we just woke. The next
  1420. queue pass matches it with live state.
  1421. At most one printer per pass. Each wake blocks the queue loop for the
  1422. boot wait, and a queue of ten class-targeted jobs must not switch on
  1423. ten printers inside one check.
  1424. """
  1425. for candidate in candidates:
  1426. if not candidate.target_model:
  1427. continue
  1428. printers = await self._printers_for_model(db, candidate.target_model, target_location)
  1429. for printer in sorted(printers, key=lambda p: p.id):
  1430. if printer.id in exclude_ids or printer.id not in wakeable_ids:
  1431. continue
  1432. if printer_manager.is_connected(printer.id):
  1433. continue
  1434. if self._wake_recently_failed(printer.id):
  1435. # Its plug did not bring it back a moment ago. Move on to a
  1436. # sibling instead of spending this pass — and every pass —
  1437. # on the same printer.
  1438. continue
  1439. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer.id):
  1440. # Waking this one buys nothing: it would boot into IDLE and
  1441. # then be held by the plate-clear gate, which is exactly
  1442. # what the reporter's log shows happening for 80 minutes
  1443. # after a fixed-printer wake. The flag is Bambuddy-side and
  1444. # persisted, so it is readable while the printer is off.
  1445. logger.info(
  1446. "Not powering on printer %s for a %s job: it is awaiting plate-clear acknowledgment",
  1447. printer.id,
  1448. candidate.target_model,
  1449. )
  1450. continue
  1451. plugs = await self._get_smart_plugs(db, printer.id)
  1452. auto_on_plugs = [p for p in plugs if p.auto_on and p.enabled]
  1453. if not auto_on_plugs:
  1454. # wakeable_ids said otherwise — the plug changed under us
  1455. # mid-pass. Nothing to do but move on.
  1456. continue
  1457. logger.info(
  1458. "No %s printer available for a queued job; powering on offline printer %s via smart plug(s)",
  1459. candidate.target_model,
  1460. printer.id,
  1461. )
  1462. primary_plug = self._pick_power_plug(auto_on_plugs)
  1463. if not await self._power_on_and_wait(primary_plug, printer.id, db):
  1464. logger.warning(
  1465. "Could not power on printer %s via smart plug; not trying it again for %ss",
  1466. printer.id,
  1467. self._wake_failure_cooloff,
  1468. )
  1469. self._wake_failures[printer.id] = time.monotonic() + self._wake_failure_cooloff
  1470. return None, printer.id
  1471. for extra_plug in [p for p in auto_on_plugs if p.id != primary_plug.id]:
  1472. try:
  1473. service = await smart_plug_manager.get_service_for_plug(extra_plug, db)
  1474. await service.turn_on(extra_plug)
  1475. logger.info("Also powered on plug '%s' for printer %s", extra_plug.name, printer.id)
  1476. except Exception as e:
  1477. logger.warning("Failed to power on extra plug '%s': %s", extra_plug.name, e)
  1478. return printer.id, printer.id
  1479. return None, None
  1480. async def _find_idle_printer_for_model(
  1481. self,
  1482. db: AsyncSession,
  1483. model: str,
  1484. exclude_ids: set[int],
  1485. required_filament_types: list[str] | None = None,
  1486. target_location: str | None = None,
  1487. filament_overrides: list[dict] | None = None,
  1488. require_plate_clear: bool = True,
  1489. wakeable_ids: set[int] | None = None,
  1490. ) -> tuple[int | None, str | None]:
  1491. """Find an idle, connected printer matching the model with compatible filaments.
  1492. Args:
  1493. db: Database session
  1494. model: Printer model to match (e.g., "X1C", "P1S")
  1495. exclude_ids: Printer IDs to exclude (already busy)
  1496. required_filament_types: Optional list of filament types needed (e.g., ["PLA", "PETG"])
  1497. If provided, only printers with all required types loaded will match.
  1498. target_location: Optional location filter. If provided, only printers in this location are considered.
  1499. filament_overrides: Optional list of override dicts. Each entry may include
  1500. ``force_color_match: true`` to require an exact type+color match
  1501. on the printer for that slot. Without the flag the existing
  1502. colour-preference logic applies.
  1503. wakeable_ids: Printers a smart plug can power on (#2786). Only changes how an
  1504. offline printer is worded: one Bambuddy will switch on reads
  1505. differently from one the user has to go and switch on themselves.
  1506. Returns:
  1507. Tuple of (printer_id, waiting_reason):
  1508. - (printer_id, None) if a matching printer was found
  1509. - (None, reason) if no printer is available, with explanation
  1510. """
  1511. normalized_model = normalize_printer_model(model) or model
  1512. printers = await self._printers_for_model(db, model, target_location)
  1513. location_suffix = f" in {target_location}" if target_location else ""
  1514. if not printers:
  1515. return None, f"No active {normalized_model} printers{location_suffix} configured"
  1516. # Separate force-matched overrides from preference-only overrides
  1517. force_overrides = [o for o in (filament_overrides or []) if o.get("force_color_match")]
  1518. pref_overrides = [o for o in (filament_overrides or []) if not o.get("force_color_match")]
  1519. # Track reasons for skipping printers
  1520. printers_busy = []
  1521. printers_offline = []
  1522. printers_offline_no_plug = []
  1523. printers_missing_filament: list[tuple[str, list[str]]] = []
  1524. candidates: list[tuple[int, int]] = [] # (printer_id, color_match_count)
  1525. for printer in printers:
  1526. if printer.id in exclude_ids:
  1527. # Printer is already claimed by another job in this scheduling run.
  1528. # For force-color jobs, still check if the color would match — if not,
  1529. # report it as a color mismatch rather than plain "Busy" so the user
  1530. # knows the job needs a filament change, not just to wait for availability.
  1531. if force_overrides and not pref_overrides:
  1532. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1533. if missing_colors:
  1534. printers_missing_filament.append((printer.name, missing_colors))
  1535. continue
  1536. printers_busy.append(printer.name)
  1537. continue
  1538. is_connected = printer_manager.is_connected(printer.id)
  1539. is_idle = self._is_printer_idle(printer.id, require_plate_clear) if is_connected else False
  1540. if not is_connected:
  1541. if wakeable_ids is not None and printer.id not in wakeable_ids:
  1542. printers_offline_no_plug.append(printer.name)
  1543. else:
  1544. printers_offline.append(printer.name)
  1545. continue
  1546. if not is_idle:
  1547. # Printer is currently printing. For force-color jobs, check whether the
  1548. # loaded color would satisfy the requirement — if not, surface it as a
  1549. # color-mismatch reason rather than plain "Busy" so the user understands
  1550. # that the job is waiting for a filament change, not just printer availability.
  1551. if force_overrides and not pref_overrides:
  1552. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1553. if missing_colors:
  1554. printers_missing_filament.append((printer.name, missing_colors))
  1555. logger.debug(
  1556. "Printer %s (%s) is busy but also has wrong force-color: %s",
  1557. printer.id,
  1558. printer.name,
  1559. missing_colors,
  1560. )
  1561. continue
  1562. printers_busy.append(printer.name)
  1563. continue
  1564. # Validate filament compatibility if required types are specified
  1565. if required_filament_types:
  1566. missing = self._get_missing_filament_types(printer.id, required_filament_types)
  1567. if missing:
  1568. # When force_overrides are present, enrich missing entries with color info
  1569. # so the "Waiting on" message includes "TYPE (color)" instead of just "TYPE"
  1570. if force_overrides:
  1571. force_color_map = {
  1572. (o.get("type") or "").upper(): o.get("color_name") or o.get("color", "?")
  1573. for o in force_overrides
  1574. }
  1575. missing_enriched = [
  1576. f"{t} ({force_color_map[t_upper]})" if (t_upper := t.upper()) in force_color_map else t
  1577. for t in missing
  1578. ]
  1579. printers_missing_filament.append((printer.name, missing_enriched))
  1580. else:
  1581. printers_missing_filament.append((printer.name, missing))
  1582. logger.debug("Skipping printer %s (%s) - missing filaments: %s", printer.id, printer.name, missing)
  1583. continue
  1584. # Force color match: ALL flagged slots must have an exact type+color match
  1585. if force_overrides:
  1586. missing_colors = self._get_missing_force_color_slots(printer.id, force_overrides)
  1587. if missing_colors:
  1588. printers_missing_filament.append((printer.name, missing_colors))
  1589. logger.debug(
  1590. "Skipping printer %s (%s) - missing force-matched colors: %s",
  1591. printer.id,
  1592. printer.name,
  1593. missing_colors,
  1594. )
  1595. continue
  1596. # If preference-only overrides exist, rank by color matches (existing behaviour)
  1597. if pref_overrides:
  1598. color_matches = self._count_override_color_matches(printer.id, pref_overrides)
  1599. if color_matches > 0:
  1600. candidates.append((printer.id, color_matches))
  1601. else:
  1602. override_colors = [f"{o.get('type', '?')} ({o.get('color', '?')})" for o in pref_overrides]
  1603. printers_missing_filament.append((printer.name, override_colors))
  1604. logger.debug("Skipping printer %s (%s) - no matching override colors", printer.id, printer.name)
  1605. continue
  1606. elif force_overrides:
  1607. # Passed all force checks — immediately eligible (no preference ordering needed)
  1608. return printer.id, None
  1609. else:
  1610. # No overrides at all - take first available (existing behavior)
  1611. return printer.id, None
  1612. # If we have candidates from preference override matching, pick the one with most color matches
  1613. if candidates:
  1614. candidates.sort(key=lambda c: c[1], reverse=True)
  1615. return candidates[0][0], None
  1616. # Build waiting reason from what we found
  1617. reasons = []
  1618. if printers_missing_filament:
  1619. # Filament/color mismatch is most actionable - show first
  1620. if force_overrides and not pref_overrides:
  1621. # All mismatches are force-color failures — use descriptive message only;
  1622. # but only if there are no busy printers that DO have the matching color.
  1623. # If a printer has the right color but is busy, surface "Busy" instead so
  1624. # the user knows the job will start automatically once that printer is free.
  1625. if not printers_busy:
  1626. all_missing = sorted({c for _, cols in printers_missing_filament for c in cols})
  1627. return None, f"No matching material/color. Waiting on {', '.join(all_missing)}"
  1628. # else: fall through — printers_busy will be appended below
  1629. else:
  1630. names_and_missing = [
  1631. f"{name} (needs {', '.join(missing)})" for name, missing in printers_missing_filament
  1632. ]
  1633. reasons.append(f"Waiting for filament: {'; '.join(names_and_missing)}")
  1634. if printers_busy:
  1635. reasons.append(f"Busy: {', '.join(printers_busy)}")
  1636. if printers_offline:
  1637. reasons.append(f"Offline: {', '.join(printers_offline)}")
  1638. if printers_offline_no_plug:
  1639. # Named separately because it is the one entry on this list the
  1640. # user has to act on: no enabled Auto On plug means Bambuddy will
  1641. # never power this printer on for the queue (#2786).
  1642. reasons.append(f"Offline, no Auto On smart plug: {', '.join(printers_offline_no_plug)}")
  1643. return None, " | ".join(reasons) if reasons else f"No available {model} printers{location_suffix}"
  1644. @staticmethod
  1645. def _is_busy_only(waiting_reason: str) -> bool:
  1646. """Check if the waiting reason only contains 'Busy' entries.
  1647. When all matching printers are simply busy printing, the queued job
  1648. will start automatically once a printer finishes — no user action
  1649. is required, so we skip the notification.
  1650. """
  1651. parts = [p.strip() for p in waiting_reason.split(" | ")]
  1652. return all(p.startswith("Busy:") for p in parts)
  1653. def _get_missing_force_color_slots(self, printer_id: int, force_overrides: list[dict]) -> list[str]:
  1654. """Return descriptive strings for force_color_match slots not satisfied by the printer.
  1655. Each entry in ``force_overrides`` must have ``type`` and ``color`` fields and is expected
  1656. to carry ``force_color_match: True``. The printer must have **every** such slot loaded
  1657. with an exact type+color match.
  1658. When both the override and a candidate tray carry a ``tray_info_idx``, they must also
  1659. match on it: Bambu reports every PLA variant as ``tray_type == "PLA"``, so the
  1660. Basic/Matte/Silk distinction lives only in ``tray_info_idx`` (GFA00/GFA01/GFA06/...).
  1661. Without this, a job sliced for PLA Matte matched every white PLA regardless of variant
  1662. (#2650). If either side lacks an idx (custom/third-party spools report a blank one, and
  1663. older 3MFs carry none) we fall back to the historical type+colour behaviour so those
  1664. setups are unaffected.
  1665. Returns:
  1666. List of ``"TYPE (color)"`` strings for unmatched slots (empty list means all match).
  1667. """
  1668. status = printer_manager.get_status(printer_id)
  1669. if not status:
  1670. return [f"{o.get('type', '?')} ({o.get('color_name') or o.get('color', '?')})" for o in force_overrides]
  1671. # Build loaded (type, colour, tray_info_idx) triples from AMS and external spool.
  1672. loaded: list[tuple[str, str, str]] = []
  1673. for ams_unit in status.raw_data.get("ams", []):
  1674. for tray in ams_unit.get("tray", []):
  1675. tray_type = tray.get("tray_type")
  1676. if tray_type:
  1677. color_norm = (tray.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1678. loaded.append(
  1679. (_canonical_filament_type(tray_type), color_norm, tray.get("tray_info_idx", "") or "")
  1680. )
  1681. for vt in status.raw_data.get("vt_tray") or []:
  1682. vt_type = vt.get("tray_type")
  1683. if vt_type:
  1684. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1685. loaded.append((_canonical_filament_type(vt_type), color_norm, vt.get("tray_info_idx", "") or ""))
  1686. missing = []
  1687. for o in force_overrides:
  1688. o_type = _canonical_filament_type(o.get("type") or "")
  1689. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1690. o_idx = o.get("tray_info_idx") or ""
  1691. satisfied = any(
  1692. t_type == o_type and t_color == o_color and (not o_idx or not t_idx or o_idx == t_idx)
  1693. for t_type, t_color, t_idx in loaded
  1694. )
  1695. if not satisfied:
  1696. color_label = o.get("color_name") or o.get("color", "?")
  1697. missing.append(f"{o_type} ({color_label})")
  1698. return missing
  1699. def _get_missing_filament_types(self, printer_id: int, required_types: list[str]) -> list[str]:
  1700. """Get the list of required filament types that are not loaded on the printer.
  1701. Args:
  1702. printer_id: The printer ID
  1703. required_types: List of filament types needed (e.g., ["PLA", "PETG"])
  1704. Returns:
  1705. List of missing filament types (empty if all are loaded)
  1706. """
  1707. status = printer_manager.get_status(printer_id)
  1708. if not status:
  1709. return required_types # Can't determine, assume all missing
  1710. # Collect all filament types loaded on this printer (AMS units + external spool)
  1711. # Use canonical types so equivalence groups (e.g. PA-CF/PA12-CF/PAHT-CF) match.
  1712. loaded_types: set[str] = set()
  1713. # Check AMS units (stored in raw_data["ams"])
  1714. ams_data = status.raw_data.get("ams", [])
  1715. if ams_data:
  1716. for ams_unit in ams_data:
  1717. for tray in ams_unit.get("tray", []):
  1718. tray_type = tray.get("tray_type")
  1719. if tray_type:
  1720. loaded_types.add(_canonical_filament_type(tray_type))
  1721. # Check external spool(s) (virtual tray, stored in raw_data["vt_tray"] as list)
  1722. for vt in status.raw_data.get("vt_tray") or []:
  1723. vt_type = vt.get("tray_type")
  1724. if vt_type:
  1725. loaded_types.add(_canonical_filament_type(vt_type))
  1726. # Find which required types are missing (using canonical type for equivalence)
  1727. missing = []
  1728. for req_type in required_types:
  1729. if _canonical_filament_type(req_type) not in loaded_types:
  1730. missing.append(req_type)
  1731. return missing
  1732. def _count_override_color_matches(self, printer_id: int, overrides: list[dict]) -> int:
  1733. """Count how many filament overrides have an exact color match on the printer.
  1734. Used to prefer printers that already have the desired override colors loaded.
  1735. """
  1736. status = printer_manager.get_status(printer_id)
  1737. if not status:
  1738. return 0
  1739. # Collect loaded filaments' type+color pairs
  1740. loaded: set[tuple[str, str]] = set()
  1741. for ams_unit in status.raw_data.get("ams", []):
  1742. for tray in ams_unit.get("tray", []):
  1743. tray_type = tray.get("tray_type")
  1744. tray_color = tray.get("tray_color", "")
  1745. if tray_type:
  1746. color_norm = tray_color.replace("#", "").lower()[:6]
  1747. loaded.add((tray_type.upper(), color_norm))
  1748. for vt in status.raw_data.get("vt_tray") or []:
  1749. vt_type = vt.get("tray_type")
  1750. if vt_type:
  1751. color_norm = (vt.get("tray_color", "") or "").replace("#", "").lower()[:6]
  1752. loaded.add((vt_type.upper(), color_norm))
  1753. matches = 0
  1754. for o in overrides:
  1755. o_type = (o.get("type") or "").upper()
  1756. o_color = (o.get("color") or "").replace("#", "").lower()[:6]
  1757. if (o_type, o_color) in loaded:
  1758. matches += 1
  1759. return matches
  1760. def _resolve_variant(self, item: PrintQueueItem, candidate: _ModelCandidate) -> None:
  1761. """Fold the winning candidate's file and settings onto the queue row (#671).
  1762. This is the whole trick that keeps cross-model items cheap: the many-to-many
  1763. never escapes the selection loop. By the time the pass commits, the row
  1764. looks exactly like an ordinary single-file model-based item, so the upload,
  1765. archive creation, expected-print registration, print history and reprint
  1766. paths need no knowledge that variants exist.
  1767. No-ops for a non-variant candidate, which is already the item's own columns.
  1768. Safe to run and re-run: the item's file columns are only ever *read* when it
  1769. has no variants, so an item that gets resolved and then skipped (library-row
  1770. conflict, previous-print gate) is simply resolved again on the next pass.
  1771. """
  1772. variant = candidate.variant
  1773. if variant is None:
  1774. return
  1775. item.library_file_id = variant.library_file_id
  1776. item.library_file = variant.library_file
  1777. # The dispatcher checks archive_id first and would print that instead of
  1778. # the file we just picked. Creation refuses to combine the two, so this
  1779. # only ever fires on a hand-written row — clear it rather than silently
  1780. # dispatch something the matcher never considered.
  1781. item.archive_id = None
  1782. item.archive = None
  1783. item.target_model = variant.target_model
  1784. item.plate_id = variant.plate_id
  1785. item.ams_mapping = variant.ams_mapping
  1786. item.nozzle_mapping = variant.nozzle_mapping
  1787. item.filament_overrides = variant.filament_overrides
  1788. item.required_filament_types = variant.required_filament_types
  1789. if variant.print_time_seconds is not None:
  1790. # The row carried the shortest candidate's estimate so SJF could order
  1791. # it before a printer was known; now that one is chosen, record what is
  1792. # actually going to run so history and the ETA agree with reality.
  1793. item.print_time_seconds = variant.print_time_seconds
  1794. async def _ensure_ams_mapping(self, db: AsyncSession, printer_id: int, item: PrintQueueItem) -> str | None:
  1795. """Ensure the queue item carries a usable AMS mapping before dispatch.
  1796. Recomputes from live printer status when the stored mapping is missing OR
  1797. unresolved (all -1). A stored all-[-1] mapping is a bug artifact — a
  1798. frontend status-load race can serialize [-1] before the printer's AMS
  1799. trays are known (#2589) — and must not be trusted: downstream it would be
  1800. silently downgraded to external-spool mode and print against an empty
  1801. feed. A resolved mapping (including manual overrides, or a partially
  1802. padded one) is left untouched.
  1803. When recompute cannot resolve it either (no compatible tray loaded), the
  1804. bogus [-1] is cleared to None so it is not later mistaken for an explicit
  1805. external selection; the print command then keeps use_ams=True and the
  1806. firmware surfaces a clear AMS-mapping error instead of silently printing
  1807. to the empty external feed.
  1808. Returns an actionable message when that firmware error is the only
  1809. possible outcome — the matcher ran, matched nothing, and the printer has
  1810. no AMS to load a different spool into (#2771). The caller fails the item
  1811. on it instead of spending an upload on a print that cannot start.
  1812. Returns None everywhere else, including every case where we simply lack
  1813. the data to judge, so dispatch is only ever blocked on a positive
  1814. finding.
  1815. """
  1816. stored_mapping: list | None = None
  1817. if item.ams_mapping:
  1818. try:
  1819. stored_mapping = json.loads(item.ams_mapping)
  1820. except (json.JSONDecodeError, TypeError):
  1821. stored_mapping = None
  1822. # Already resolved (present and not all-unresolved) — keep as-is so a
  1823. # user's manual mapping is never overwritten.
  1824. if item.ams_mapping and not _mapping_is_all_unresolved(stored_mapping):
  1825. return None
  1826. computed_mapping = await self._compute_ams_mapping_for_printer(db, printer_id, item)
  1827. if computed_mapping and not _mapping_is_all_unresolved(computed_mapping):
  1828. item.ams_mapping = json.dumps(computed_mapping)
  1829. logger.info(
  1830. "Queue item %s: Computed AMS mapping for printer %s: %s",
  1831. item.id,
  1832. printer_id,
  1833. computed_mapping,
  1834. )
  1835. await db.commit()
  1836. return None
  1837. if _mapping_is_all_unresolved(stored_mapping):
  1838. logger.warning(
  1839. "Queue item %s: stored ams_mapping %s is unresolved and could not be recomputed "
  1840. "from live status on printer %s; clearing it so dispatch does not treat it as external",
  1841. item.id,
  1842. stored_mapping,
  1843. printer_id,
  1844. )
  1845. item.ams_mapping = None
  1846. await db.commit()
  1847. return await self._unmappable_without_ams_message(db, printer_id, item, computed_mapping)
  1848. async def _unmappable_without_ams_message(
  1849. self,
  1850. db: AsyncSession,
  1851. printer_id: int,
  1852. item: PrintQueueItem,
  1853. computed_mapping: list[int] | None,
  1854. ) -> str | None:
  1855. """Message for a mapping that resolved nothing on an AMS-less printer (#2771).
  1856. A print dispatched with no mapping goes out as ``use_ams: true`` with no
  1857. ``ams_mapping`` and no ``ams_mapping2``, which the firmware rejects with
  1858. 0700_8012 "Failed to get AMS mapping table" — after Bambuddy has already
  1859. uploaded several megabytes and burned its dispatch retries. With an AMS
  1860. attached that error is worth reaching: the user can load the right spool
  1861. and press Resume, so this returns None and today's behaviour stands. With
  1862. no AMS there is nothing to resume into — the external spool holder is the
  1863. whole inventory — so the useful answer is to say which filament is
  1864. missing and stop.
  1865. Fail-safe by construction, mirroring the nozzle-diameter guard (#1899):
  1866. every branch that lacks the evidence to be sure returns None.
  1867. """
  1868. # None means the matcher never ran (no requirements parsed from the 3MF,
  1869. # or nothing loaded at all) rather than "ran and matched nothing". Those
  1870. # dispatch as they always have.
  1871. if not _mapping_is_all_unresolved(computed_mapping):
  1872. return None
  1873. status = printer_manager.get_status(printer_id)
  1874. if status is None:
  1875. return None
  1876. # "No AMS" has to be a fact the printer stated, not the absence of a
  1877. # statement. `raw_data["ams"]` is written only once an AMS push has been
  1878. # handled and is preserved across partial pushes thereafter, so a missing
  1879. # key means we have not heard yet — most likely a reconnect, where the
  1880. # trays of a fully loaded AMS would be invisible for a few seconds. An
  1881. # empty list is the positive report of a printer with no AMS.
  1882. ams_units = status.raw_data.get("ams")
  1883. if not isinstance(ams_units, list) or ams_units:
  1884. return None
  1885. required = await self._get_filament_requirements(db, item)
  1886. loaded = self._build_loaded_filaments(status)
  1887. if not required or not loaded:
  1888. # Both were non-empty moments ago or the matcher could not have run.
  1889. # If the picture changed under us, say nothing rather than fail an
  1890. # item on stale evidence.
  1891. return None
  1892. self._apply_filament_overrides(item, required)
  1893. return _unmatched_filament_message(required, loaded)
  1894. async def _fail_unmappable_item(
  1895. self, db: AsyncSession, item: PrintQueueItem, printer_id: int, message: str
  1896. ) -> None:
  1897. """Fail a queue item whose filament mapping cannot resolve (#2771).
  1898. This replaces a failure, not a success: without it the item is uploaded,
  1899. rejected by the firmware with 0700_8012, retried twice more and failed
  1900. anyway with "never started the print after N dispatch attempts". So this
  1901. applies on the model-based path too, even though it means an "Any <model>"
  1902. job stops at the first printer offered rather than trying its siblings —
  1903. deferring instead would need the check to move inside
  1904. ``_find_printer_for_model``'s candidate loop, since un-assigning here just
  1905. re-assigns the same printer on the next tick.
  1906. """
  1907. item.status = "failed"
  1908. item.error_message = message
  1909. item.completed_at = datetime.now(timezone.utc)
  1910. item.waiting_reason = None
  1911. await db.commit()
  1912. logger.warning(
  1913. "Queue item %s: no usable AMS mapping on printer %s — %s",
  1914. item.id,
  1915. printer_id,
  1916. message,
  1917. )
  1918. job_name = await self._get_job_name(db, item)
  1919. printer = await self._get_printer(db, printer_id)
  1920. await notification_service.on_queue_job_failed(
  1921. job_name=job_name,
  1922. printer_id=printer_id,
  1923. printer_name=printer.name if printer else "Unknown",
  1924. reason=message,
  1925. db=db,
  1926. )
  1927. try:
  1928. await ws_manager.send_queue_item_failed(
  1929. user_id=item.created_by_id,
  1930. queue_item_id=item.id,
  1931. printer_id=printer_id,
  1932. reason="filament_unmappable",
  1933. )
  1934. except Exception:
  1935. pass
  1936. async def _compute_ams_mapping_for_printer(
  1937. self, db: AsyncSession, printer_id: int, item: PrintQueueItem
  1938. ) -> list[int] | None:
  1939. """Compute AMS mapping for a printer based on filament requirements.
  1940. Called when a queue item has no ams_mapping set — either for model-based
  1941. items after printer assignment, or printer-specific items (e.g. from VP).
  1942. Args:
  1943. db: Database session
  1944. printer_id: The assigned printer ID
  1945. item: The queue item (contains archive_id or library_file_id)
  1946. Returns:
  1947. AMS mapping array or None if no mapping needed/possible
  1948. """
  1949. # Get printer status
  1950. status = printer_manager.get_status(printer_id)
  1951. if not status:
  1952. logger.warning("Cannot compute AMS mapping: printer %s status unavailable", printer_id)
  1953. return None
  1954. # Filament Track Switch (FTS): when installed it routes any AMS slot to
  1955. # either extruder, so the per-nozzle hard filter below must NOT apply.
  1956. # Otherwise a print on one nozzle can't use a spool physically loaded in
  1957. # an AMS on the *other* nozzle, and the matcher falls through to a
  1958. # same-type wrong-colour spool on the target nozzle — the H2C + FTS
  1959. # wrong-filament bug (#2186). Mirrors the frontend skip added for #1162.
  1960. fts_installed = bool(getattr(getattr(status, "fila_switch", None), "installed", False))
  1961. # Get filament requirements from source file
  1962. filament_reqs = await self._get_filament_requirements(db, item)
  1963. if not filament_reqs:
  1964. # When the 3MF can't be read but force-color overrides are present, build a
  1965. # direct mapping from the overrides so the printer uses the correct AMS slot.
  1966. if item.filament_overrides:
  1967. try:
  1968. overrides = json.loads(item.filament_overrides)
  1969. force_overrides = [o for o in overrides if o.get("force_color_match")]
  1970. if force_overrides:
  1971. logger.info(
  1972. "Queue item %s: No filament reqs from 3MF; building AMS mapping from %d "
  1973. "force-color override(s)",
  1974. item.id,
  1975. len(force_overrides),
  1976. )
  1977. return self._build_override_direct_mapping(force_overrides, status)
  1978. except (json.JSONDecodeError, KeyError, TypeError) as e:
  1979. logger.warning("Queue item %s: Force-color fallback mapping failed: %s", item.id, e)
  1980. logger.debug("No filament requirements found for queue item %s", item.id)
  1981. return None
  1982. self._apply_filament_overrides(item, filament_reqs)
  1983. # Build loaded filaments from printer status
  1984. loaded_filaments = self._build_loaded_filaments(status)
  1985. if not loaded_filaments:
  1986. logger.debug("No filaments loaded on printer %s", printer_id)
  1987. return None
  1988. # Check if user prefers lowest remaining filament when multiple spools match
  1989. prefer_lowest = await self._get_bool_setting(db, "prefer_lowest_filament")
  1990. # Gate prefer_lowest on the printer's AMS Filament Backup state (#1766).
  1991. # Without backup, the printer will not switch to a second spool when the
  1992. # picked one runs out — so sorting toward the lowest leaves the print
  1993. # at risk of running dry mid-job. None (unknown / A1 family) preserves
  1994. # today's behaviour intentionally.
  1995. if prefer_lowest and status.ams_filament_backup is False:
  1996. logger.info("[prefer-lowest] skipped (AMS Backup OFF on printer %s)", printer_id)
  1997. prefer_lowest = False
  1998. # When the preference is on, surface Bambuddy's inventory-side
  1999. # remaining for each slot that's bound to a tracked spool, so the
  2000. # sort beats the MQTT-only blind spot (#1508). Skip the lookup
  2001. # entirely when the preference is off — no behaviour change for
  2002. # users who haven't opted in.
  2003. inventory_remain_overrides: dict[int, float] | None = None
  2004. if prefer_lowest:
  2005. inventory_remain_overrides = await self._build_inventory_remain_overrides(db, printer_id, loaded_filaments)
  2006. # Compute mapping: match required filaments to available slots
  2007. return self._match_filaments_to_slots(
  2008. filament_reqs, loaded_filaments, prefer_lowest, inventory_remain_overrides, fts_installed
  2009. )
  2010. def _apply_filament_overrides(self, item: PrintQueueItem, filament_reqs: list[dict]) -> None:
  2011. """Rewrite ``filament_reqs`` in place with the item's per-slot overrides.
  2012. Extracted from ``_compute_ams_mapping_for_printer`` so the unmappable
  2013. diagnosis (#2771) describes the filament the matcher actually looked
  2014. for, not the one the 3MF was sliced with — naming the pre-override
  2015. filament in a user-facing error would send the user to load the wrong
  2016. spool.
  2017. """
  2018. if not item.filament_overrides:
  2019. return
  2020. try:
  2021. overrides = json.loads(item.filament_overrides)
  2022. override_map = {o["slot_id"]: o for o in overrides}
  2023. for req in filament_reqs:
  2024. if req["slot_id"] in override_map:
  2025. override = override_map[req["slot_id"]]
  2026. req["type"] = override["type"]
  2027. req["color"] = override["color"]
  2028. # A manual/preference override SWAPS the slot's filament, so the
  2029. # 3MF's original tray_info_idx now points at the old spool and must
  2030. # be cleared — matching then falls back to type+colour. A
  2031. # force_color_match override is not a swap: it carries the 3MF's
  2032. # intended variant (Basic GFA00 / Matte GFA01 / Silk GFA06), so keep
  2033. # it here too, letting the matcher pin the correct variant slot on a
  2034. # printer holding two same-colour spools of different variants (#2650).
  2035. # If that variant isn't loaded the matcher falls back to type+colour,
  2036. # so an eligible printer never fails to map.
  2037. req["tray_info_idx"] = (
  2038. override.get("tray_info_idx", "") if override.get("force_color_match") else ""
  2039. )
  2040. logger.debug(
  2041. "Queue item %s: Override slot %d -> %s %s",
  2042. item.id,
  2043. req["slot_id"],
  2044. override["type"],
  2045. override["color"],
  2046. )
  2047. except (json.JSONDecodeError, KeyError, TypeError) as e:
  2048. logger.warning("Failed to apply filament overrides for queue item %s: %s", item.id, e)
  2049. def _build_override_direct_mapping(self, force_overrides: list[dict], status) -> list[int] | None:
  2050. """Build an AMS mapping directly from force-color overrides without a 3MF.
  2051. Used when ``_get_filament_requirements`` returns nothing (e.g. the 3MF's
  2052. slice_info is missing or unreadable) but ``force_color_match`` overrides
  2053. are present. Each override's ``slot_id``, ``type``, and ``color`` are
  2054. treated as the filament requirement for that slot and matched against the
  2055. current AMS state of the printer.
  2056. Returns the same format as ``_match_filaments_to_slots``, or None when
  2057. the AMS has no loaded filaments.
  2058. """
  2059. loaded = self._build_loaded_filaments(status)
  2060. if not loaded:
  2061. return None
  2062. reqs = [
  2063. {
  2064. "slot_id": o["slot_id"],
  2065. "type": o.get("type", ""),
  2066. "color": o.get("color", ""),
  2067. # These are all force_color_match overrides, so the idx (when the
  2068. # 3MF carried one) is the intended variant, not a stale swap —
  2069. # keep it so the matcher pins the right variant slot, falling back
  2070. # to type+colour when it isn't loaded (#2650).
  2071. "tray_info_idx": o.get("tray_info_idx", ""),
  2072. }
  2073. for o in force_overrides
  2074. ]
  2075. return self._match_filaments_to_slots(reqs, loaded)
  2076. async def _get_filament_requirements(self, db: AsyncSession, item: PrintQueueItem) -> list[dict] | None:
  2077. """Resolve the queue item's source 3MF and parse the per-slot
  2078. filament requirements out of it. Thin DB-resolver wrapper around
  2079. ``filament_requirements.extract_filament_requirements`` so the VP
  2080. queue-mode write path (#1188) can reuse the same parser at upload
  2081. time.
  2082. """
  2083. from backend.app.services.filament_requirements import extract_filament_requirements
  2084. file_path: Path | None = None
  2085. if item.archive_id:
  2086. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  2087. archive = result.scalar_one_or_none()
  2088. if archive:
  2089. file_path = settings.base_dir / archive.file_path
  2090. elif item.library_file_id:
  2091. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  2092. library_file = result.scalar_one_or_none()
  2093. if library_file:
  2094. lib_path = Path(library_file.file_path)
  2095. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  2096. if not file_path or not file_path.exists():
  2097. return None
  2098. filaments = extract_filament_requirements(file_path, plate_id=item.plate_id)
  2099. return filaments if filaments else None
  2100. def _build_loaded_filaments(self, status) -> list[dict]:
  2101. """Build list of loaded filaments from printer status.
  2102. Args:
  2103. status: PrinterState from printer_manager
  2104. Returns:
  2105. List of loaded filament dicts with type, color, ams_id, tray_id, global_tray_id
  2106. """
  2107. filaments = []
  2108. # Get ams_extruder_map for dual-nozzle printers (H2D, H2D Pro)
  2109. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  2110. # Dual-nozzle detection, used below to route external spools to an
  2111. # extruder (#2771). Mirrors `buildLoadedFilaments` in the frontend,
  2112. # which was corrected for #1257 while this copy kept the old signal.
  2113. #
  2114. # `ams_extruder_map` is derived from AMS info bits, so a dual-nozzle
  2115. # printer with zero AMS units reports an empty map — and every external
  2116. # spool then got `extruder_id=None`, which the nozzle-aware filter in
  2117. # `_match_filaments_to_slots` rejects outright because `None` equals
  2118. # neither 0 nor 1. On an X2D feeding from external spools only that left
  2119. # nothing to match, the mapping came back all -1, and the print went out
  2120. # with `use_ams: true` and no mapping table at all — firmware 0700_8012,
  2121. # "Failed to get AMS mapping table".
  2122. #
  2123. # `nozzles` is always a two-entry list (the state seeds it with two empty
  2124. # NozzleInfo stubs), so its length proves nothing; only a populated
  2125. # diameter on the second entry means real hardware. The other two signals
  2126. # are fallbacks for firmware revisions that surface one but not the
  2127. # other: a populated `ams_extruder_map` is dual-nozzle by construction,
  2128. # and so is more than one `vt_tray` entry, since single-nozzle printers
  2129. # expose exactly one external feed.
  2130. nozzles = getattr(status, "nozzles", None) or []
  2131. vt_trays = status.raw_data.get("vt_tray") or []
  2132. is_dual_nozzle = bool(
  2133. (len(nozzles) > 1 and getattr(nozzles[1], "nozzle_diameter", ""))
  2134. or ams_extruder_map
  2135. # isinstance, because a dict here would count its ~30 keys as trays.
  2136. # bambu_mqtt normalises vt_tray to a list before it reaches raw_data,
  2137. # so this is unreachable — but the loop below would raise on a dict
  2138. # and that is the pre-existing behaviour to keep, not to paper over.
  2139. or (isinstance(vt_trays, list) and len(vt_trays) > 1)
  2140. )
  2141. # Parse AMS units from raw_data
  2142. ams_data = status.raw_data.get("ams", [])
  2143. for ams_unit in ams_data:
  2144. ams_id = int(ams_unit.get("id", 0))
  2145. trays = ams_unit.get("tray", [])
  2146. is_ht = len(trays) == 1 # AMS-HT has single tray
  2147. for tray in trays:
  2148. tray_type = tray.get("tray_type")
  2149. if tray_type:
  2150. tray_id = int(tray.get("id", 0))
  2151. tray_color = tray.get("tray_color", "")
  2152. # tray_info_idx identifies the specific spool (e.g., "GFA00", "P4d64437")
  2153. tray_info_idx = tray.get("tray_info_idx", "")
  2154. # Normalize color: remove alpha, add hash
  2155. color = self._normalize_color(tray_color)
  2156. # Calculate global tray ID
  2157. # AMS-HT units have IDs starting at 128 with a single tray
  2158. global_tray_id = ams_id if ams_id >= 128 else ams_id * 4 + tray_id
  2159. filaments.append(
  2160. {
  2161. "type": tray_type,
  2162. "color": color,
  2163. "tray_info_idx": tray_info_idx,
  2164. "ams_id": ams_id,
  2165. "tray_id": tray_id,
  2166. "is_ht": is_ht,
  2167. "is_external": False,
  2168. "global_tray_id": global_tray_id,
  2169. "extruder_id": ams_extruder_map.get(str(ams_id)),
  2170. "remain": tray.get("remain", -1),
  2171. }
  2172. )
  2173. # Check external spool(s) (vt_tray is a list)
  2174. for idx, vt in enumerate(vt_trays):
  2175. if vt.get("tray_type"):
  2176. color = self._normalize_color(vt.get("tray_color", ""))
  2177. tray_id = int(vt.get("id", 254))
  2178. filaments.append(
  2179. {
  2180. "type": vt["tray_type"],
  2181. "color": color,
  2182. "tray_info_idx": vt.get("tray_info_idx", ""),
  2183. "ams_id": -1,
  2184. "tray_id": idx,
  2185. "is_ht": False,
  2186. "is_external": True,
  2187. "global_tray_id": tray_id,
  2188. # 254 = VIRTUAL_TRAY_DEPUTY_ID feeds extruder 1 (left),
  2189. # 255 = VIRTUAL_TRAY_MAIN_ID feeds extruder 0 (right).
  2190. "extruder_id": (255 - tray_id) if is_dual_nozzle else None,
  2191. "remain": vt.get("remain", -1),
  2192. }
  2193. )
  2194. return filaments
  2195. def _normalize_color(self, color: str | None) -> str:
  2196. """Normalize color to #RRGGBB format."""
  2197. if not color:
  2198. return "#808080"
  2199. hex_color = color.replace("#", "")[:6]
  2200. return f"#{hex_color}"
  2201. def _normalize_color_for_compare(self, color: str | None) -> str:
  2202. """Normalize color for comparison (lowercase, no hash)."""
  2203. if not color:
  2204. return ""
  2205. return color.replace("#", "").lower()[:6]
  2206. def _colors_are_similar(self, color1: str | None, color2: str | None, threshold: int = 40) -> bool:
  2207. """Check if two colors are visually similar within a threshold."""
  2208. hex1 = self._normalize_color_for_compare(color1)
  2209. hex2 = self._normalize_color_for_compare(color2)
  2210. if not hex1 or not hex2 or len(hex1) < 6 or len(hex2) < 6:
  2211. return False
  2212. try:
  2213. r1 = int(hex1[0:2], 16)
  2214. g1 = int(hex1[2:4], 16)
  2215. b1 = int(hex1[4:6], 16)
  2216. r2 = int(hex2[0:2], 16)
  2217. g2 = int(hex2[2:4], 16)
  2218. b2 = int(hex2[4:6], 16)
  2219. return abs(r1 - r2) <= threshold and abs(g1 - g2) <= threshold and abs(b1 - b2) <= threshold
  2220. except ValueError:
  2221. return False
  2222. async def _build_inventory_remain_overrides(
  2223. self, db: AsyncSession, printer_id: int, loaded: list[dict]
  2224. ) -> dict[int, float]:
  2225. """Return ``{global_tray_id: remaining_grams}`` for AMS slots the user
  2226. has bound to an inventory spool — Bambuddy-side or Spoolman-side.
  2227. The MQTT ``remain`` field on a tray is the printer firmware's
  2228. RFID-decremented value, which has two limitations the "Prefer Lowest
  2229. Remaining Filament" feature has been ignoring (#1508):
  2230. - it's only meaningful for Bambu RFID spools; everything else reports
  2231. ``-1`` (then clamped to a sentinel), so multiple non-RFID trays
  2232. compare equal and the sort collapses to AMS-slot order — the user
  2233. who's curating inventory weights gets the lower-slot pick instead
  2234. of the lower-remaining pick;
  2235. - even when set, it's the *printer's* counter, not Bambuddy's
  2236. ``label_weight - weight_used`` (internal mode) or Spoolman's
  2237. ``remaining_weight`` (Spoolman mode) — the two diverge any time the
  2238. user re-spools, swaps cardboard, or runs a print outside Bambuddy.
  2239. When the user has bound a spool to a slot, their own inventory
  2240. tracking is authoritative; this helper surfaces that value so the
  2241. sort can prefer it. Slots without a binding are absent from the
  2242. returned map — the caller then falls back to MQTT ``remain`` for
  2243. those, preserving the pre-#1508 behaviour for un-tracked spools.
  2244. Returns an empty map on any failure (no inventory bindings, DB
  2245. error, Spoolman unreachable). A best-effort lookup; "Prefer Lowest"
  2246. is a preference, not a guarantee.
  2247. """
  2248. if not loaded:
  2249. return {}
  2250. # External / virtual-tray slots are tracked separately from AMS — skip
  2251. # them so a VT-loaded spool doesn't accidentally inherit a tracked
  2252. # AMS binding (the tables use ams_id 254/255 for VT, but the cross
  2253. # match is fiddly and out of scope for this fix).
  2254. tracked_slots = [(f["ams_id"], f["tray_id"], f["global_tray_id"]) for f in loaded if not f.get("is_external")]
  2255. if not tracked_slots:
  2256. return {}
  2257. is_spoolman = await self._is_spoolman_mode(db)
  2258. overrides: dict[int, float] = {}
  2259. if is_spoolman:
  2260. result = await db.execute(
  2261. select(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id)
  2262. )
  2263. assignments = list(result.scalars().all())
  2264. by_slot = {(a.ams_id, a.tray_id): a.spoolman_spool_id for a in assignments}
  2265. from backend.app.services.filament_deficit import _spoolman_remaining_grams
  2266. for ams_id, tray_id, gtid in tracked_slots:
  2267. spoolman_id = by_slot.get((ams_id, tray_id))
  2268. if spoolman_id is None:
  2269. continue
  2270. grams = await _spoolman_remaining_grams(spoolman_id)
  2271. if grams is not None:
  2272. overrides[gtid] = grams
  2273. return overrides
  2274. # Internal inventory mode (default). selectinload matches the pattern
  2275. # used elsewhere (inventory.py, spoolman.py routes) — a single query
  2276. # plus an eager-loaded relationship rather than an explicit join, so
  2277. # the row-attribute shape is exactly what those routes already rely on.
  2278. result = await db.execute(
  2279. select(SpoolAssignment)
  2280. .options(selectinload(SpoolAssignment.spool))
  2281. .where(SpoolAssignment.printer_id == printer_id)
  2282. )
  2283. assignments = list(result.scalars().all())
  2284. by_slot = {(a.ams_id, a.tray_id): a.spool for a in assignments}
  2285. for ams_id, tray_id, gtid in tracked_slots:
  2286. spool = by_slot.get((ams_id, tray_id))
  2287. if spool is None:
  2288. continue
  2289. label = float(spool.label_weight or 0)
  2290. used = float(spool.weight_used or 0)
  2291. overrides[gtid] = max(0.0, label - used)
  2292. return overrides
  2293. @staticmethod
  2294. async def _is_spoolman_mode(db: AsyncSession) -> bool:
  2295. """Mirror of ``filament_deficit._is_spoolman_mode`` — kept private
  2296. here to avoid making this module import-dependent on that private
  2297. helper's signature."""
  2298. try:
  2299. from backend.app.api.routes.settings import get_setting
  2300. v = await get_setting(db, "spoolman_enabled")
  2301. return bool(v) and v.lower() == "true"
  2302. except Exception:
  2303. return False
  2304. @staticmethod
  2305. def _slot_priority(ams_id: int | None, tray_id: int | None) -> int:
  2306. """Deterministic slot-position tie-breaker for the prefer-lowest sort.
  2307. Three bands, matched to the emission order in ``_build_loaded_filaments``
  2308. so a tied sort produces the same physical-position order the pre-#1508
  2309. stable sort did (preserves the regression-free baseline):
  2310. - Regular AMS (``ams_id`` 0..7): ``ams_id * 4 + tray_id`` → 0..31
  2311. - AMS-HT (``ams_id`` >= 128, single tray): ``1000 + (ams_id - 128) * 4``
  2312. - External / VT (``ams_id`` < 0, or ``None``): ``10_000``
  2313. Banding ensures regular AMS < AMS-HT < external on ties, regardless of
  2314. what the raw ``ams_id`` happens to be (in particular, ``ams_id = -1``
  2315. for VT must NOT sort to a negative number or it would beat AMS slot 0).
  2316. """
  2317. if ams_id is None or ams_id < 0:
  2318. return 10_000
  2319. if ams_id >= 128:
  2320. return 1_000 + (ams_id - 128) * 4 + (tray_id or 0)
  2321. return ams_id * 4 + (tray_id or 0)
  2322. @staticmethod
  2323. def _prefer_lowest_sort_key(f: dict, overrides: dict[int, float] | None) -> tuple[int, float, int]:
  2324. """Sort key for the "Prefer Lowest Remaining Filament" preference.
  2325. Two-tier ordering: inventory-tracked spools always sort BEFORE
  2326. non-tracked spools (the user has told us they care about these
  2327. specifically), then ascending by remaining within each tier, then
  2328. ascending by AMS slot position as the deterministic tie-breaker.
  2329. Tiers are flagged by the first tuple element (0 = inventory-tracked,
  2330. 1 = MQTT-only / unknown). Cross-tier value comparisons never run
  2331. because the tier flag dominates — which is what lets us mix grams
  2332. (inventory) and percent (MQTT) without a unit conversion.
  2333. Within the MQTT tier ``remain = -1`` (unknown) is mapped to 101 so
  2334. spools the printer DOES know something about sort ahead of those
  2335. it knows nothing about — preserves pre-#1508 behaviour for the
  2336. no-inventory-binding case.
  2337. Slot tie-breaker via ``_slot_priority`` so regular AMS < AMS-HT <
  2338. external on ties, matching the legacy emission-order stable sort.
  2339. """
  2340. gtid = f.get("global_tray_id")
  2341. slot_order = PrintScheduler._slot_priority(f.get("ams_id"), f.get("tray_id"))
  2342. if overrides and gtid in overrides:
  2343. return (0, overrides[gtid], slot_order)
  2344. remain = f.get("remain", -1)
  2345. return (1, float(remain) if remain is not None and remain >= 0 else 101.0, slot_order)
  2346. def _match_filaments_to_slots(
  2347. self,
  2348. required: list[dict],
  2349. loaded: list[dict],
  2350. prefer_lowest: bool = False,
  2351. inventory_remain_overrides: dict[int, float] | None = None,
  2352. fts_installed: bool = False,
  2353. ) -> list[int] | None:
  2354. """Match required filaments to loaded filaments and build AMS mapping.
  2355. Priority: unique tray_info_idx match > exact color match > similar color match > type-only match
  2356. The tray_info_idx is a filament type identifier stored in the 3MF file when the user
  2357. slices (e.g., "GFA00" for generic PLA, "P4d64437" for custom presets). If the same
  2358. tray_info_idx appears in only ONE available tray, we use that tray. If multiple trays
  2359. have the same tray_info_idx (e.g., two spools of generic PLA), we fall back to color
  2360. matching among those trays.
  2361. Args:
  2362. required: List of required filaments with slot_id, type, color, tray_info_idx
  2363. loaded: List of loaded filaments with type, color, tray_info_idx, global_tray_id
  2364. Returns:
  2365. AMS mapping array (position = slot_id - 1, value = global_tray_id or -1)
  2366. """
  2367. if not required:
  2368. return None
  2369. # Track used trays to avoid duplicate assignment
  2370. used_tray_ids: set[int] = set()
  2371. comparisons = []
  2372. for req in required:
  2373. req_type = (req.get("type") or "").upper()
  2374. req_color = req.get("color", "")
  2375. req_tray_info_idx = req.get("tray_info_idx", "")
  2376. # Find best match: unique tray_info_idx > exact color > similar color > type-only
  2377. idx_match = None
  2378. exact_match = None
  2379. similar_match = None
  2380. type_only_match = None
  2381. # Get available trays (not already used)
  2382. available = [f for f in loaded if f["global_tray_id"] not in used_tray_ids]
  2383. # Nozzle-aware filtering: restrict to trays on the correct nozzle.
  2384. # Hard filter — cross-nozzle assignment causes print failures
  2385. # ("position of left hotend is abnormal"), so never fall back.
  2386. # Skipped when an FTS is installed: it routes any AMS slot to either
  2387. # extruder, so restricting to one nozzle would wrongly exclude the
  2388. # correct spool sitting in the other nozzle's AMS (#2186).
  2389. req_nozzle_id = req.get("nozzle_id")
  2390. if req_nozzle_id is not None and not fts_installed:
  2391. available = [f for f in available if f.get("extruder_id") == req_nozzle_id]
  2392. # Sort by remaining filament (ascending) so lowest-remain spool wins .find().
  2393. # Inventory-tracked spools sort before MQTT-only ones (#1508); see
  2394. # _prefer_lowest_sort_key for the full rationale.
  2395. if prefer_lowest:
  2396. available.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  2397. # INFO-level decision trace for "Prefer Lowest Filament" #1766.
  2398. # One line per filament req so a bug report can be diagnosed
  2399. # without enabling debug logging: shows what the matcher saw
  2400. # (req shape + sorted candidate trays with their remain values
  2401. # and any inventory override that was applied). Mirrored by
  2402. # the picked-match log at the bottom of the loop.
  2403. logger.info(
  2404. "[prefer-lowest] req slot=%s type=%r color=%r tii=%r nozzle=%s; available (sorted lowest-first): %s",
  2405. req.get("slot_id"),
  2406. req_type,
  2407. req_color,
  2408. req_tray_info_idx,
  2409. req_nozzle_id,
  2410. [
  2411. {
  2412. "gtid": f.get("global_tray_id"),
  2413. "type": f.get("type"),
  2414. "color": f.get("color"),
  2415. "tii": f.get("tray_info_idx"),
  2416. "remain": f.get("remain"),
  2417. "inv_g": (
  2418. inventory_remain_overrides.get(f.get("global_tray_id"))
  2419. if inventory_remain_overrides
  2420. else None
  2421. ),
  2422. }
  2423. for f in available
  2424. ],
  2425. )
  2426. # Check if tray_info_idx is unique among available trays
  2427. if req_tray_info_idx:
  2428. idx_matches = [f for f in available if f.get("tray_info_idx") == req_tray_info_idx]
  2429. if len(idx_matches) == 1:
  2430. # Unique tray_info_idx - use it as definitive match
  2431. idx_match = idx_matches[0]
  2432. logger.debug(
  2433. f"Matched filament slot {req.get('slot_id')} by unique tray_info_idx={req_tray_info_idx} "
  2434. f"-> tray {idx_match['global_tray_id']}"
  2435. )
  2436. elif len(idx_matches) > 1:
  2437. # Multiple trays with same tray_info_idx - use color matching among them
  2438. logger.debug(
  2439. f"Non-unique tray_info_idx={req_tray_info_idx} found in {len(idx_matches)} trays, "
  2440. f"using color matching among trays: {[f['global_tray_id'] for f in idx_matches]}"
  2441. )
  2442. if prefer_lowest:
  2443. idx_matches.sort(key=lambda f: self._prefer_lowest_sort_key(f, inventory_remain_overrides))
  2444. # Use color matching within this subset
  2445. for f in idx_matches:
  2446. f_color = f.get("color", "")
  2447. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  2448. if not exact_match:
  2449. exact_match = f
  2450. elif self._colors_are_similar(f_color, req_color):
  2451. if not similar_match:
  2452. similar_match = f
  2453. elif not type_only_match:
  2454. type_only_match = f
  2455. # If no idx_match yet, do standard type/color matching on all available trays
  2456. if not idx_match and not exact_match and not similar_match and not type_only_match:
  2457. for f in available:
  2458. f_type = (f.get("type") or "").upper()
  2459. if _canonical_filament_type(f_type) != _canonical_filament_type(req_type):
  2460. continue
  2461. # Type matches - check color
  2462. f_color = f.get("color", "")
  2463. if self._normalize_color_for_compare(f_color) == self._normalize_color_for_compare(req_color):
  2464. if not exact_match:
  2465. exact_match = f
  2466. elif self._colors_are_similar(f_color, req_color):
  2467. if not similar_match:
  2468. similar_match = f
  2469. elif not type_only_match:
  2470. type_only_match = f
  2471. match = idx_match or exact_match or similar_match or type_only_match
  2472. if match:
  2473. used_tray_ids.add(match["global_tray_id"])
  2474. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": match["global_tray_id"]})
  2475. else:
  2476. comparisons.append({"slot_id": req.get("slot_id", 0), "global_tray_id": -1})
  2477. if prefer_lowest:
  2478. # Pair with the "available (sorted)" log above so the reporter
  2479. # bundle shows BOTH what the matcher saw AND which match bucket
  2480. # won — fast triage when "Prefer Lowest Filament" picks the
  2481. # wrong slot (#1766).
  2482. if match:
  2483. bucket = (
  2484. "idx"
  2485. if idx_match is not None
  2486. else "exact_color"
  2487. if exact_match is not None
  2488. else "similar_color"
  2489. if similar_match is not None
  2490. else "type_only"
  2491. )
  2492. logger.info(
  2493. "[prefer-lowest] picked gtid=%s via %s for req slot=%s",
  2494. match["global_tray_id"],
  2495. bucket,
  2496. req.get("slot_id"),
  2497. )
  2498. else:
  2499. logger.info(
  2500. "[prefer-lowest] NO MATCH for req slot=%s (type=%r color=%r tii=%r)",
  2501. req.get("slot_id"),
  2502. req_type,
  2503. req_color,
  2504. req_tray_info_idx,
  2505. )
  2506. # Build mapping array
  2507. if not comparisons:
  2508. return None
  2509. max_slot_id = max(c["slot_id"] for c in comparisons)
  2510. if max_slot_id <= 0:
  2511. return None
  2512. mapping = [-1] * max_slot_id
  2513. for c in comparisons:
  2514. slot_id = c["slot_id"]
  2515. if slot_id and slot_id > 0:
  2516. mapping[slot_id - 1] = c["global_tray_id"]
  2517. return mapping
  2518. def _mark_printer_dispatched(
  2519. self,
  2520. printer_id: int,
  2521. pre_state: str | None,
  2522. pre_subtask_id: str | None,
  2523. ) -> None:
  2524. """Record that a print command was just sent to ``printer_id``.
  2525. Held until either the watchdog observes a state/subtask transition
  2526. (success path) or the hard timeout expires. See ``_dispatch_holds``.
  2527. """
  2528. if not pre_state:
  2529. # No pre_state means we can't detect a transition — fall back to a
  2530. # pure time-based hold using empty string as a sentinel that won't
  2531. # match any real printer state.
  2532. pre_state = ""
  2533. self._dispatch_holds[printer_id] = (time.monotonic(), pre_state, pre_subtask_id)
  2534. def _release_dispatch_hold(self, printer_id: int) -> None:
  2535. """Drop the dispatch hold for ``printer_id`` (called by the watchdog)."""
  2536. self._dispatch_holds.pop(printer_id, None)
  2537. def _printer_in_dispatch_hold(self, printer_id: int) -> bool:
  2538. """True if ``printer_id`` is still inside its post-dispatch hold window.
  2539. Returns False (and clears the hold) once any of these are true:
  2540. - hard timeout (``_dispatch_max_hold``) has elapsed
  2541. - the printer has transitioned out of pre_state and we're past the
  2542. minimum cooldown
  2543. - the printer's subtask_id has advanced past pre_subtask_id and we're
  2544. past the minimum cooldown
  2545. Otherwise the printer is held — caller should treat it as busy.
  2546. """
  2547. entry = self._dispatch_holds.get(printer_id)
  2548. if not entry:
  2549. return False
  2550. started_at, pre_state, pre_subtask_id = entry
  2551. elapsed = time.monotonic() - started_at
  2552. if elapsed >= self._dispatch_max_hold:
  2553. self._dispatch_holds.pop(printer_id, None)
  2554. return False
  2555. # Without a pre_state we can't detect a transition — fall back to the
  2556. # min cooldown alone, then drop the hold.
  2557. if not pre_state:
  2558. if elapsed >= self._dispatch_min_cooldown:
  2559. self._dispatch_holds.pop(printer_id, None)
  2560. return False
  2561. return True
  2562. status = printer_manager.get_status(printer_id)
  2563. current_state = getattr(status, "state", None) if status else None
  2564. current_subtask_id = getattr(status, "subtask_id", None) if status else None
  2565. transitioned = (current_state is not None and current_state != pre_state) or (
  2566. pre_subtask_id is not None and current_subtask_id is not None and current_subtask_id != pre_subtask_id
  2567. )
  2568. if transitioned and elapsed >= self._dispatch_min_cooldown:
  2569. self._dispatch_holds.pop(printer_id, None)
  2570. return False
  2571. return True
  2572. def _is_printer_idle(self, printer_id: int, require_plate_clear: bool = True) -> bool:
  2573. """Check if a printer is connected and idle."""
  2574. if not printer_manager.is_connected(printer_id):
  2575. logger.debug("Printer %d: not connected", printer_id)
  2576. return False
  2577. state = printer_manager.get_status(printer_id)
  2578. if not state:
  2579. logger.debug("Printer %d: no status available", printer_id)
  2580. return False
  2581. # Plate-clear gate: if the printer finished/failed a previous print and the user
  2582. # hasn't acknowledged the plate was cleared, the queue must not dispatch the next
  2583. # job — even if the printer currently reports IDLE. After Auto Off cycles the
  2584. # printer, it boots back into IDLE with no memory of the previous finish; without
  2585. # the persisted awaiting flag we'd bypass the confirmation prompt (#961).
  2586. if require_plate_clear and printer_manager.is_awaiting_plate_clear(printer_id):
  2587. logger.debug(
  2588. "Printer %d: not idle — awaiting plate-clear acknowledgment (state=%s)",
  2589. printer_id,
  2590. state.state,
  2591. )
  2592. return False
  2593. idle = state.state in ("IDLE", "FINISH", "FAILED")
  2594. if not idle:
  2595. logger.debug("Printer %d: not idle — state=%s", printer_id, state.state)
  2596. return idle
  2597. async def _get_setting(self, db: AsyncSession, key: str) -> str | None:
  2598. """Read a setting value from the database."""
  2599. result = await db.execute(select(Settings).where(Settings.key == key))
  2600. setting = result.scalar_one_or_none()
  2601. return setting.value if setting else None
  2602. async def _get_bool_setting(self, db: AsyncSession, key: str, default: bool = False) -> bool:
  2603. """Read a boolean setting from the database."""
  2604. result = await db.execute(select(Settings).where(Settings.key == key))
  2605. setting = result.scalar_one_or_none()
  2606. if setting:
  2607. return setting.value.lower() == "true"
  2608. return default
  2609. async def _get_int_setting(self, db: AsyncSession, key: str, default: int) -> int:
  2610. """Read an int setting; falls back to default on missing/unparseable rows."""
  2611. result = await db.execute(select(Settings).where(Settings.key == key))
  2612. setting = result.scalar_one_or_none()
  2613. if setting and setting.value:
  2614. try:
  2615. return int(setting.value)
  2616. except ValueError:
  2617. pass
  2618. return default
  2619. async def _get_drying_presets(self, db: AsyncSession) -> dict[str, dict[str, int]]:
  2620. """Get drying presets (user-configured or built-in defaults)."""
  2621. result = await db.execute(select(Settings).where(Settings.key == "drying_presets"))
  2622. setting = result.scalar_one_or_none()
  2623. if setting and setting.value:
  2624. try:
  2625. presets = json.loads(setting.value)
  2626. if isinstance(presets, dict) and presets:
  2627. return presets
  2628. except json.JSONDecodeError:
  2629. pass
  2630. return self.DEFAULT_DRYING_PRESETS
  2631. async def _get_humidity_thresholds(self, db: AsyncSession) -> dict[str, int]:
  2632. """Per-filament humidity thresholds (#1605).
  2633. Returns the user-configured overrides map keyed by normalized filament
  2634. type (uppercase base, e.g. ``PLA``, ``ASA``) plus a ``default`` key for
  2635. unknown / unmapped types. Empty / unset → empty dict, in which case
  2636. callers fall back to ``ams_humidity_fair``.
  2637. """
  2638. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_thresholds"))
  2639. setting = result.scalar_one_or_none()
  2640. if not setting or not setting.value:
  2641. return {}
  2642. try:
  2643. data = json.loads(setting.value)
  2644. except json.JSONDecodeError:
  2645. return {}
  2646. if not isinstance(data, dict):
  2647. return {}
  2648. out: dict[str, int] = {}
  2649. for key, value in data.items():
  2650. try:
  2651. out[str(key).upper() if key != "default" else "default"] = int(value)
  2652. except (TypeError, ValueError):
  2653. continue
  2654. return out
  2655. @staticmethod
  2656. def resolve_humidity_threshold(trays: list[dict], thresholds: dict[str, int], fallback: int) -> int:
  2657. """Resolve the effective humidity threshold for an AMS unit (#1605).
  2658. For mixed filament types loaded into one AMS, returns the most
  2659. restrictive (lowest) threshold across all loaded tray types — matches
  2660. the conservative-params strategy already used for drying temp/hours.
  2661. Empty / unloaded trays contribute no constraint. Unknown types use the
  2662. ``default`` key, falling through to ``fallback`` (= ``ams_humidity_fair``)
  2663. when no per-type map is configured at all.
  2664. """
  2665. default = thresholds.get("default", fallback)
  2666. if not thresholds:
  2667. return fallback
  2668. candidates: list[int] = []
  2669. for tray in trays:
  2670. tray_type = str(tray.get("tray_type") or "").strip()
  2671. if not tray_type:
  2672. continue
  2673. base_type = tray_type.split()[0].upper()
  2674. candidates.append(thresholds.get(base_type, default))
  2675. if not candidates:
  2676. return default
  2677. return min(candidates)
  2678. def _get_conservative_drying_params(
  2679. self, trays: list[dict], module_type: str, presets: dict[str, dict[str, int]]
  2680. ) -> tuple[int, int, str] | None:
  2681. """Get the most conservative drying params for mixed filament types in an AMS unit.
  2682. Returns (temp, duration_hours, filament_type) or None if no drying-eligible filaments.
  2683. """
  2684. temp_key = module_type if module_type in ("n3f", "n3s") else "n3f"
  2685. hours_key = f"{temp_key}_hours"
  2686. min_temp = None
  2687. max_hours = None
  2688. filament_type = ""
  2689. for tray in trays:
  2690. tray_type = tray.get("tray_type", "")
  2691. if not tray_type:
  2692. continue
  2693. # Normalize filament type for preset lookup (e.g., "PLA Basic" -> "PLA")
  2694. base_type = tray_type.split()[0].upper()
  2695. preset = presets.get(base_type)
  2696. if not preset:
  2697. continue
  2698. temp = preset.get(temp_key, 55)
  2699. hours = preset.get(hours_key, 12)
  2700. # Conservative: lowest temp, longest duration
  2701. if min_temp is None or temp < min_temp:
  2702. min_temp = temp
  2703. if max_hours is None or hours > max_hours:
  2704. max_hours = hours
  2705. if not filament_type:
  2706. filament_type = base_type
  2707. if min_temp is None:
  2708. return None
  2709. return (min_temp, max_hours or 12, filament_type)
  2710. async def _check_auto_drying(
  2711. self,
  2712. db: AsyncSession,
  2713. queue_items: list[PrintQueueItem],
  2714. busy_printers: set[int],
  2715. *,
  2716. require_plate_clear: bool = True,
  2717. ):
  2718. """Start drying on idle printers based on humidity.
  2719. Three modes (can all be enabled independently):
  2720. - queue_drying_enabled: Dry between scheduled queue prints
  2721. - ambient_drying_enabled: Dry any idle printer when humidity is high, regardless of queue
  2722. - print_drying_enabled: Also evaluate printers that are currently printing,
  2723. when model+firmware supports "Print While Drying" (gated by
  2724. supports_drying_while_printing). Drying temperature is capped at
  2725. max(40, preset_temp - 5) to protect spools mid-print.
  2726. """
  2727. queue_drying_enabled = await self._get_bool_setting(db, "queue_drying_enabled")
  2728. ambient_drying_enabled = await self._get_bool_setting(db, "ambient_drying_enabled")
  2729. print_drying_enabled = await self._get_bool_setting(db, "print_drying_enabled")
  2730. if not queue_drying_enabled and not ambient_drying_enabled:
  2731. # Stop active drying on all printers if both features disabled
  2732. if self._drying_in_progress:
  2733. for pid in list(self._drying_in_progress):
  2734. logger.info("Auto-drying: printer %d — stopping, auto-drying disabled", pid)
  2735. await self._stop_drying(pid)
  2736. return
  2737. # Update drying state from printer status (handles backend restart)
  2738. self._sync_drying_state()
  2739. # Find printers with scheduled items (for queue drying mode)
  2740. printers_with_scheduled: set[int] = set()
  2741. printers_with_items: set[int] = set()
  2742. for item in queue_items:
  2743. if item.printer_id:
  2744. printers_with_items.add(item.printer_id)
  2745. if item.scheduled_time and not item.manual_start:
  2746. printers_with_scheduled.add(item.printer_id)
  2747. # If only queue mode is on and no printers have scheduled items, stop drying
  2748. # (but skip this short-circuit when print_drying_enabled is on — busy printers
  2749. # may still be eligible for mid-print drying regardless of queue state).
  2750. if not ambient_drying_enabled and not printers_with_scheduled and not print_drying_enabled:
  2751. for pid in list(self._drying_in_progress):
  2752. logger.info("Auto-drying: printer %d — stopping, no scheduled prints in queue", pid)
  2753. await self._stop_drying(pid)
  2754. return
  2755. # Get humidity threshold (global fallback)
  2756. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  2757. setting = result.scalar_one_or_none()
  2758. global_humidity_threshold = int(setting.value) if setting else 60
  2759. # Per-filament humidity threshold overrides (#1605). Empty → fall back
  2760. # to the global threshold for every AMS unit.
  2761. per_type_thresholds = await self._get_humidity_thresholds(db)
  2762. # Get drying presets
  2763. presets = await self._get_drying_presets(db)
  2764. # Determine if drying should be skipped for printers with pending items
  2765. block_for_drying = await self._get_bool_setting(db, "queue_drying_block")
  2766. # Get all active printers
  2767. all_printers = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  2768. for printer in all_printers.scalars():
  2769. pid = printer.id
  2770. # Resolve model+firmware up front — needed to decide whether this printer
  2771. # qualifies for mid-print drying (busy printer on capable hardware).
  2772. state = printer_manager.get_status(pid)
  2773. if not state:
  2774. logger.debug("Auto-drying: printer %d skipped — no state", pid)
  2775. continue
  2776. model = printer_manager.get_model(pid)
  2777. firmware = state.firmware_version
  2778. mid_print = (
  2779. pid in busy_printers and print_drying_enabled and supports_drying_while_printing(model, firmware)
  2780. )
  2781. if pid in busy_printers and not mid_print:
  2782. logger.debug("Auto-drying: printer %d skipped — busy", pid)
  2783. continue
  2784. if not mid_print:
  2785. # In queue-only mode, only dry printers that have scheduled prints
  2786. if not ambient_drying_enabled and pid not in printers_with_scheduled:
  2787. if self._drying_in_progress.get(pid):
  2788. logger.info("Auto-drying: printer %d — stopping, no scheduled prints for this printer", pid)
  2789. await self._stop_drying(pid)
  2790. logger.debug("Auto-drying: printer %d skipped — no scheduled prints", pid)
  2791. continue
  2792. # When block mode is on, don't START new drying on printers with pending items.
  2793. # But allow already-drying printers through so humidity auto-stop logic still runs.
  2794. if block_for_drying and pid in printers_with_items and not self._drying_in_progress.get(pid):
  2795. logger.debug("Auto-drying: printer %d skipped — has pending items (block mode)", pid)
  2796. continue
  2797. if not printer_manager.is_connected(pid):
  2798. logger.debug("Auto-drying: printer %d skipped — not connected", pid)
  2799. continue
  2800. if not mid_print and not self._is_printer_idle(pid, require_plate_clear):
  2801. logger.debug("Auto-drying: printer %d skipped — not idle", pid)
  2802. continue
  2803. # Check drying capability. For mid-print path, supports_drying_while_printing
  2804. # was already verified when computing mid_print above.
  2805. if not mid_print and not supports_drying(model, firmware):
  2806. logger.debug("Auto-drying: printer %d skipped — model %s does not support drying", pid, model)
  2807. continue
  2808. # Check each AMS unit from raw_data
  2809. ams_list = state.raw_data.get("ams", [])
  2810. logger.debug("Auto-drying: printer %d — checking %d AMS units", pid, len(ams_list))
  2811. for ams_data in ams_list:
  2812. module_type = str(ams_data.get("module_type") or "")
  2813. ams_id = int(ams_data.get("id", 0))
  2814. # Only n3f/n3s support drying
  2815. if module_type not in ("n3f", "n3s"):
  2816. logger.debug("Auto-drying: printer %d AMS %d skipped — module_type=%s", pid, ams_id, module_type)
  2817. continue
  2818. # Resolve per-filament humidity threshold for this AMS unit (#1605).
  2819. # Most-restrictive of all loaded tray types; falls back to the
  2820. # global threshold when no overrides are configured.
  2821. trays = ams_data.get("tray", []) or []
  2822. humidity_threshold = self.resolve_humidity_threshold(
  2823. trays, per_type_thresholds, global_humidity_threshold
  2824. )
  2825. dry_time = int(ams_data.get("dry_time") or 0)
  2826. # Read humidity — prefer humidity_raw (actual %) over humidity (index 1-5)
  2827. humidity = None
  2828. h_raw = ams_data.get("humidity_raw")
  2829. if h_raw is not None:
  2830. try:
  2831. humidity = int(h_raw)
  2832. except (ValueError, TypeError):
  2833. pass
  2834. if humidity is None:
  2835. h_idx = ams_data.get("humidity")
  2836. if h_idx is not None:
  2837. try:
  2838. humidity = int(h_idx)
  2839. except (ValueError, TypeError):
  2840. pass
  2841. unit_key = (pid, ams_id)
  2842. unit_state = self._auto_dry_units.get(unit_key)
  2843. # Already drying — let it run to its configured duration (#1892).
  2844. #
  2845. # We deliberately do NOT stop drying from a humidity re-check here.
  2846. # Relative humidity drops steeply in heated air, so the AMS sensor
  2847. # reads ~15-20% within minutes of the dryer starting even while the
  2848. # filament is still saturated. A humidity-based early-stop therefore
  2849. # always fires at the minimum-time floor, truncating both user-started
  2850. # manual cycles and Bambuddy's own preset-duration dries to ~30 min.
  2851. # The firmware stops when the configured duration elapses; scheduling
  2852. # stops (print takes priority, queue no longer needs drying) are
  2853. # handled separately via _stop_drying().
  2854. if dry_time > 0:
  2855. if pid not in self._drying_in_progress:
  2856. # Drying we didn't start (manual or from before restart) —
  2857. # track it so scheduling stops still apply; never auto-stop it.
  2858. self._drying_in_progress[pid] = time.monotonic()
  2859. if unit_state is not None:
  2860. unit_state["running"] = True
  2861. logger.debug(
  2862. "Auto-drying: printer %d AMS %d — drying (%dm left, humidity %s%%), letting it run",
  2863. pid,
  2864. ams_id,
  2865. dry_time,
  2866. humidity,
  2867. )
  2868. continue
  2869. # Nothing is drying. Close out a cycle we armed ourselves and
  2870. # judge whether it achieved anything (#2770).
  2871. #
  2872. # "Achieved anything" is measured against the LOWEST reading any
  2873. # cycle on this unit has ended at, not against the threshold and
  2874. # not against the previous cycle. A spool that is genuinely wet
  2875. # in a humid room comes down slowly — 40, 37, 35 — and must be
  2876. # allowed to keep going for as long as it is still coming down,
  2877. # however far it still is from the threshold. What must not
  2878. # continue is a cycle that ends exactly where the last one did,
  2879. # which is the reporter's signature: 15, 15, 16, 15, forever.
  2880. # Comparing against the running minimum rather than the previous
  2881. # end is what stops a sensor oscillating by one point between two
  2882. # values from reading as progress every other cycle.
  2883. if unit_state is not None and unit_state.pop("running", False):
  2884. unit_state["ended_at"] = time.monotonic()
  2885. if humidity is not None and humidity > humidity_threshold:
  2886. best = unit_state.get("best_end_humidity")
  2887. if isinstance(best, int) and humidity < best:
  2888. # Still coming down. Keep going, however far the
  2889. # threshold still is.
  2890. unproductive = 0
  2891. else:
  2892. unproductive = int(unit_state.get("unproductive", 0)) + 1
  2893. if not isinstance(best, int) or humidity < best:
  2894. unit_state["best_end_humidity"] = humidity
  2895. unit_state["unproductive"] = unproductive
  2896. logger.info(
  2897. "Auto-drying: printer %d AMS %d — cycle ended with humidity still %d%% > "
  2898. "threshold %d%% (best so far %s%%, %d unproductive in a row)",
  2899. pid,
  2900. ams_id,
  2901. humidity,
  2902. humidity_threshold,
  2903. unit_state.get("best_end_humidity"),
  2904. unproductive,
  2905. )
  2906. # A cycle that ended at or below the threshold needs no
  2907. # counter reset here: the branch below drops the whole entry.
  2908. # Humidity below threshold — no need to start drying. This is
  2909. # also the only thing that lifts a suspension: the reading we
  2910. # gave up on has come down, so auto-drying works again and the
  2911. # unit goes back to having no history at all.
  2912. if humidity is None or humidity <= humidity_threshold:
  2913. if unit_state is not None and unit_state.get("suspended"):
  2914. logger.info(
  2915. "Auto-drying: printer %d AMS %d — humidity %s%% is back at or below the %d%% "
  2916. "threshold, resuming automatic drying",
  2917. pid,
  2918. ams_id,
  2919. humidity,
  2920. humidity_threshold,
  2921. )
  2922. self._auto_dry_units.pop(unit_key, None)
  2923. logger.debug(
  2924. "Auto-drying: printer %d AMS %d skipped — humidity %s <= threshold %d",
  2925. pid,
  2926. ams_id,
  2927. humidity,
  2928. humidity_threshold,
  2929. )
  2930. continue
  2931. if unit_state is not None:
  2932. if unit_state.get("suspended"):
  2933. logger.debug(
  2934. "Auto-drying: printer %d AMS %d skipped — suspended, %d cycles left humidity "
  2935. "above the %d%% threshold",
  2936. pid,
  2937. ams_id,
  2938. int(unit_state.get("unproductive", 0)),
  2939. humidity_threshold,
  2940. )
  2941. continue
  2942. if int(unit_state.get("unproductive", 0)) >= AUTO_DRY_MAX_UNPRODUCTIVE_CYCLES:
  2943. unit_state["suspended"] = True
  2944. logger.warning(
  2945. "Auto-drying: printer %d AMS %d — suspending automatic drying. %d cycles in a "
  2946. "row ended with humidity at %d%%, still above the %d%% threshold. The AMS reads "
  2947. "higher while it is warm, so a threshold in that range can never be reached and "
  2948. "re-arming would loop. Raise the threshold or dry the spools off the printer.",
  2949. pid,
  2950. ams_id,
  2951. int(unit_state.get("unproductive", 0)),
  2952. humidity,
  2953. humidity_threshold,
  2954. )
  2955. await self._notify_auto_drying_suspended(
  2956. db, printer, ams_id, humidity, humidity_threshold, int(unit_state.get("unproductive", 0))
  2957. )
  2958. continue
  2959. ended_at = unit_state.get("ended_at")
  2960. if isinstance(ended_at, float) and time.monotonic() - ended_at < AUTO_DRY_REARM_COOLDOWN_SECONDS:
  2961. logger.debug(
  2962. "Auto-drying: printer %d AMS %d skipped — cooling off for %ds after the last "
  2963. "cycle before the humidity reading is worth acting on",
  2964. pid,
  2965. ams_id,
  2966. AUTO_DRY_REARM_COOLDOWN_SECONDS,
  2967. )
  2968. continue
  2969. # Check cannot-dry reasons (power constraints etc.)
  2970. sf_reasons = ams_data.get("dry_sf_reason", [])
  2971. if sf_reasons:
  2972. logger.debug(
  2973. "Auto-drying: printer %d AMS %d skipped — cannot dry reasons: %s",
  2974. pid,
  2975. ams_id,
  2976. sf_reasons,
  2977. )
  2978. continue
  2979. # Get conservative drying params for mixed filaments
  2980. params = self._get_conservative_drying_params(trays, module_type, presets)
  2981. if not params:
  2982. logger.debug(
  2983. "Auto-drying: printer %d AMS %d skipped — no drying-eligible filaments in trays", pid, ams_id
  2984. )
  2985. continue
  2986. temp, duration_hours, filament_type = params
  2987. # Mid-print drying: cap drying temperature to protect spools (Bambu warns
  2988. # "drying temperature must not exceed the filament's softening temperature"
  2989. # for Print While Drying). Floor at 40 degC — below that the dryer is
  2990. # ineffective and firmware will reject anyway.
  2991. if mid_print:
  2992. temp = max(40, temp - 5)
  2993. # Start drying
  2994. logger.info(
  2995. "Auto-drying: printer %d AMS %d — humidity %d%% > threshold %d%%, "
  2996. "starting %s drying at %d°C for %dh%s",
  2997. pid,
  2998. ams_id,
  2999. humidity,
  3000. humidity_threshold,
  3001. filament_type,
  3002. temp,
  3003. duration_hours,
  3004. " (mid-print)" if mid_print else "",
  3005. )
  3006. success = printer_manager.send_drying_command(
  3007. pid, ams_id, temp, duration_hours, mode=1, filament=filament_type
  3008. )
  3009. if success:
  3010. self._drying_in_progress[pid] = time.monotonic()
  3011. armed = self._auto_dry_units.setdefault(
  3012. unit_key, {"unproductive": 0, "suspended": False, "ended_at": None}
  3013. )
  3014. armed["running"] = True
  3015. async def _notify_auto_drying_suspended(
  3016. self,
  3017. db: AsyncSession,
  3018. printer: Printer,
  3019. ams_id: int,
  3020. humidity: int,
  3021. threshold: int,
  3022. cycles: int,
  3023. ) -> None:
  3024. """Tell the user auto-drying has given up on one AMS unit (#2770).
  3025. Fires once per suspension — the caller sets ``suspended`` before calling
  3026. and every later pass short-circuits on it — because the whole point is
  3027. that Bambuddy has stopped acting. Somebody whose printer sits in another
  3028. building needs that to reach them, and the hourly humidity alarm they
  3029. are already getting says the opposite of what happened here.
  3030. Never raises: a notification provider being down must not stop the
  3031. suspension itself from taking effect.
  3032. """
  3033. ams_label = f"HT-{chr(65 + (ams_id - 128))}" if ams_id >= 128 else f"AMS-{chr(65 + ams_id)}"
  3034. try:
  3035. await notification_service.on_ams_drying_suspended(
  3036. printer.id,
  3037. printer.name,
  3038. ams_label,
  3039. float(humidity),
  3040. float(threshold),
  3041. cycles,
  3042. db,
  3043. )
  3044. except Exception as e:
  3045. logger.warning("Failed to send auto-drying suspended notification: %s", e)
  3046. def forget_auto_dry_cycle(self, printer_id: int, ams_id: int) -> None:
  3047. """Stop judging the drying cycle currently on this AMS unit (#2770).
  3048. The unproductive-cycle counter exists to notice that *drying* is not
  3049. moving the humidity reading. A cycle that ended because somebody sent a
  3050. stop says nothing about that — it was cut short before it had a chance —
  3051. so counting it would suspend auto-drying for a reason that has nothing to
  3052. do with the loop the counter is there to break.
  3053. Two callers, both of them a stop Bambuddy is responsible for: the
  3054. print-takes-priority stop below, and the manual Stop button. Left
  3055. uncalled, an install that dries between queue jobs would suspend its own
  3056. auto-drying after two prints interrupted a dry — exactly the install
  3057. queue-drying exists for.
  3058. The rest of the unit's history is kept: the cooldown before re-arming
  3059. still applies, and an earlier count still stands.
  3060. """
  3061. state = self._auto_dry_units.get((printer_id, ams_id))
  3062. if state is not None:
  3063. state.pop("running", None)
  3064. state["ended_at"] = time.monotonic()
  3065. def _sync_drying_state(self):
  3066. """Drop printers from ``_drying_in_progress`` that are no longer drying.
  3067. One direction only: it prunes, it never adds. A printer drying without an
  3068. entry here — because the user started the cycle from Studio, the printer's
  3069. screen or Bambuddy's own manual Dry button, or because Bambuddy restarted
  3070. mid-cycle — stays unknown to the scheduler, so the "print takes priority"
  3071. stop at ``check_queue`` only ever applies to cycles Bambuddy itself began.
  3072. That is deliberate for now rather than an oversight: populating this from
  3073. telemetry would hand the scheduler authority to stop drying a user started
  3074. by hand. It also means the backend-restart case this used to claim to
  3075. handle is not handled.
  3076. """
  3077. to_remove = []
  3078. for pid in self._drying_in_progress:
  3079. state = printer_manager.get_status(pid)
  3080. if not state:
  3081. to_remove.append(pid)
  3082. continue
  3083. # Check if any AMS unit is still drying
  3084. ams_list = state.raw_data.get("ams", [])
  3085. any_drying = any(int(a.get("dry_time") or 0) > 0 for a in ams_list)
  3086. if not any_drying:
  3087. to_remove.append(pid)
  3088. for pid in to_remove:
  3089. self._drying_in_progress.pop(pid, None)
  3090. # A printer that has gone away entirely takes its per-AMS auto-drying
  3091. # history with it (#2770), so a printer deleted and re-added does not
  3092. # inherit a suspension it never earned.
  3093. for key in [k for k in self._auto_dry_units if printer_manager.get_status(k[0]) is None]:
  3094. self._auto_dry_units.pop(key, None)
  3095. async def _stop_drying(self, printer_id: int):
  3096. """Stop all active drying on a printer (print takes priority)."""
  3097. state = printer_manager.get_status(printer_id)
  3098. if not state:
  3099. self._drying_in_progress.pop(printer_id, None)
  3100. return
  3101. ams_list = state.raw_data.get("ams", [])
  3102. for ams_data in ams_list:
  3103. dry_time = int(ams_data.get("dry_time") or 0)
  3104. if dry_time > 0:
  3105. ams_id = int(ams_data.get("id", 0))
  3106. logger.info(
  3107. "Auto-drying: stopping drying on printer %d AMS %d — print takes priority",
  3108. printer_id,
  3109. ams_id,
  3110. )
  3111. printer_manager.send_drying_command(printer_id, ams_id, 0, 0, mode=0)
  3112. self.forget_auto_dry_cycle(printer_id, ams_id)
  3113. self._drying_in_progress.pop(printer_id, None)
  3114. async def _get_smart_plugs(self, db: AsyncSession, printer_id: int) -> list[SmartPlug]:
  3115. """Get all smart plugs associated with a printer."""
  3116. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  3117. return list(result.scalars().all())
  3118. @staticmethod
  3119. def _pick_power_plug(auto_on_plugs: list[SmartPlug]) -> SmartPlug:
  3120. """Pick the plug to power-cycle a printer back online with (#2629).
  3121. Only a plug flagged ``controls_printer_power`` can actually bring the
  3122. printer back; waiting for a boot on an accessory (filter fan, lights)
  3123. just burns the power-on timeout and fails the dispatch. Falls back to
  3124. the first plug when none is flagged, which is the pre-#2629 behaviour.
  3125. Callers must pass a non-empty list.
  3126. """
  3127. for plug in auto_on_plugs:
  3128. if plug.controls_printer_power:
  3129. return plug
  3130. return auto_on_plugs[0]
  3131. # Bundled defaults for preheat_filament_targets (#1468). Values are the
  3132. # chamber-temperature recommendations BambuStudio ships for the matching
  3133. # filament profile; users can override via Settings → Workflow → Preheat
  3134. # card. "default" applies when a loaded tray's normalised type isn't in
  3135. # the map (rare — Bambu RFID-tagged spools always carry a known type).
  3136. DEFAULT_PREHEAT_FILAMENT_TARGETS: dict[str, int] = {
  3137. "PLA": 0,
  3138. "PETG": 0,
  3139. "PETG-CF": 40,
  3140. "ABS": 45,
  3141. "ASA": 45,
  3142. "PA": 50,
  3143. "PA-CF": 55,
  3144. "PC": 50,
  3145. "PC-FR": 50,
  3146. "TPU": 0,
  3147. "PVA": 0,
  3148. "default": 0,
  3149. }
  3150. async def _get_preheat_filament_targets(self, db: AsyncSession) -> dict[str, int]:
  3151. """Parse the user-configured filament→chamber-target map, falling back
  3152. to DEFAULT_PREHEAT_FILAMENT_TARGETS on missing / malformed JSON. Keys
  3153. are uppercased and the 'default' fallback is always present in the
  3154. returned dict so the resolution loop can index it unconditionally."""
  3155. raw = await self._get_setting(db, "preheat_filament_targets")
  3156. if not raw:
  3157. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  3158. try:
  3159. parsed = json.loads(raw)
  3160. if not isinstance(parsed, dict):
  3161. raise ValueError("not an object")
  3162. except (json.JSONDecodeError, ValueError) as exc:
  3163. logger.warning("preheat_filament_targets unparseable, using defaults: %s", exc)
  3164. return dict(self.DEFAULT_PREHEAT_FILAMENT_TARGETS)
  3165. # Coerce values to int; drop unparseable rows so a stray string
  3166. # doesn't crash the loop.
  3167. out: dict[str, int] = {}
  3168. for key, value in parsed.items():
  3169. try:
  3170. out[str(key).upper()] = int(value)
  3171. except (TypeError, ValueError):
  3172. continue
  3173. if "DEFAULT" not in out:
  3174. out["DEFAULT"] = self.DEFAULT_PREHEAT_FILAMENT_TARGETS["default"]
  3175. return out
  3176. @staticmethod
  3177. def _normalize_filament_type(tray_type: str) -> str:
  3178. """Reduce the printer's tray_type to a preset-lookup key. Mirrors the
  3179. existing drying-preset normalisation (split-at-space, upper-case) so
  3180. the two maps share vocabulary — "PLA Basic" → "PLA", "PA-CF" stays
  3181. "PA-CF" (no space to split on)."""
  3182. return tray_type.split()[0].upper() if tray_type else ""
  3183. def _derive_chamber_target(
  3184. self,
  3185. printer: Printer,
  3186. targets: dict[str, int],
  3187. ) -> int:
  3188. """Look up the chamber target for each loaded AMS tray and return the
  3189. max. Returns 0 when no AMS data is available (e.g. external-spool
  3190. prints) or when every loaded slot maps to 0 — the chamber phase then
  3191. short-circuits in the main loop.
  3192. Reads from `printer_manager.get_status(...).raw_data['ams']`, which is
  3193. the same source the dispatcher uses for AMS slot mapping. Empty / RFID-
  3194. less slots have empty `tray_type` and contribute nothing."""
  3195. state = printer_manager.get_status(printer.id)
  3196. if state is None:
  3197. return 0
  3198. ams_list = (state.raw_data or {}).get("ams") if state.raw_data else None
  3199. # Older Bambu firmware nests AMS as {"ams": {"ams": [...]}} — try both.
  3200. if isinstance(ams_list, dict):
  3201. ams_list = ams_list.get("ams") or []
  3202. if not isinstance(ams_list, list):
  3203. return 0
  3204. best = 0
  3205. for ams in ams_list:
  3206. for tray in (ams.get("tray") or []) if isinstance(ams, dict) else []:
  3207. normalised = self._normalize_filament_type(tray.get("tray_type") or "")
  3208. if not normalised:
  3209. continue
  3210. target = targets.get(normalised, targets.get("DEFAULT", 0))
  3211. if target > best:
  3212. best = target
  3213. return best
  3214. async def _preheat_and_soak(
  3215. self,
  3216. db: AsyncSession,
  3217. item: PrintQueueItem,
  3218. printer: Printer,
  3219. archive: PrintArchive | None,
  3220. ) -> None:
  3221. """Run the per-printer preheat + heat-soak stage before FTP upload (#1468).
  3222. Resolution order:
  3223. 1. `item.preheat_override` — 'off' skips entirely; 'inherit' falls back
  3224. to the global `preheat_enabled` setting; 'on' forces the stage on
  3225. even if the global is off.
  3226. 2. Chamber target — `item.preheat_chamber_target_override` if non-null;
  3227. else max of `preheat_filament_targets[normalize(t.tray_type)]`
  3228. across loaded AMS slots; else 0 (skips chamber phase, keeps bed
  3229. phase + soak timer).
  3230. 3. Three hardware tiers branch the wait loop:
  3231. - Chamber heater (H2C/H2D/H2DPro/H2S/X2D/X1E via supports_chamber_heater):
  3232. send M141 to the resolved target, then wait for the chamber sensor
  3233. to reach it (or the max-wait timeout to elapse).
  3234. - Chamber sensor only (X1C/P2S via supports_chamber_temp ∧ ¬supports_chamber_heater):
  3235. no M141; the bed is the only heat source, so we wait for the chamber
  3236. sensor to rise via bed radiation OR fall through on timeout.
  3237. - No chamber sensor (P1S/P1P/A1/A1 Mini): no way to verify chamber
  3238. temperature; the function just heats the bed and holds for the
  3239. configured soak duration.
  3240. The bed target comes from the archive's parsed metadata
  3241. (`bed_temperature`); if missing the preheat stage logs and returns
  3242. without dispatching anything, rather than guessing at a default that
  3243. might wreck filament setup.
  3244. Failures are logged but never re-raised — preheat is best-effort. A
  3245. printer that goes offline mid-soak, a refused gcode command, or a
  3246. missing temperature reading must not turn into a failed queue item; the
  3247. normal upload + start path runs immediately after this method returns.
  3248. """
  3249. override = (getattr(item, "preheat_override", None) or "inherit").lower()
  3250. if override == "off":
  3251. return
  3252. if override == "inherit":
  3253. enabled = await self._get_bool_setting(db, "preheat_enabled", default=False)
  3254. if not enabled:
  3255. return
  3256. # override == "on" forces the stage on regardless of the global setting.
  3257. max_wait = await self._get_int_setting(db, "preheat_max_wait_seconds", default=900)
  3258. soak_seconds = await self._get_int_setting(db, "preheat_soak_seconds", default=300)
  3259. # Chamber target resolution:
  3260. # 1. Explicit per-item override beats everything (user knows best).
  3261. # 2. Otherwise derive from loaded AMS filament types via the per-
  3262. # filament target map. PLA-only print derives 0 → chamber phase
  3263. # auto-skips without the user touching anything.
  3264. explicit_target = getattr(item, "preheat_chamber_target_override", None)
  3265. if explicit_target is not None and explicit_target > 0:
  3266. chamber_target = int(explicit_target)
  3267. chamber_source = "item-override"
  3268. elif explicit_target == 0:
  3269. chamber_target = 0 # explicit 0 means "no chamber, even if filament wants it"
  3270. chamber_source = "item-override-zero"
  3271. else:
  3272. targets = await self._get_preheat_filament_targets(db)
  3273. chamber_target = self._derive_chamber_target(printer, targets)
  3274. chamber_source = "filament-map"
  3275. bed_target = int(archive.bed_temperature) if archive and archive.bed_temperature else 0
  3276. if bed_target <= 0:
  3277. logger.info(
  3278. "Queue item %s: preheat skipped — archive has no bed_temperature metadata",
  3279. item.id,
  3280. )
  3281. return
  3282. client = printer_manager.get_client(printer.id)
  3283. if client is None:
  3284. logger.warning("Queue item %s: preheat skipped — printer client unavailable", item.id)
  3285. return
  3286. model = printer.model or ""
  3287. has_heater = supports_chamber_heater(model)
  3288. has_sensor = supports_chamber_temp(model)
  3289. do_chamber = chamber_target > 0 and (has_heater or has_sensor)
  3290. logger.info(
  3291. "Queue item %s: preheat starting — bed=%d°C chamber_target=%d°C (source=%s override=%s "
  3292. "model=%s has_heater=%s has_sensor=%s) max_wait=%ds soak=%ds",
  3293. item.id,
  3294. bed_target,
  3295. chamber_target if do_chamber else 0,
  3296. chamber_source,
  3297. override,
  3298. model,
  3299. has_heater,
  3300. has_sensor,
  3301. max_wait,
  3302. soak_seconds,
  3303. )
  3304. # Dispatch heaters. set_bed_temperature / set_chamber_temperature already
  3305. # cache the target locally so the polling reads below see consistent
  3306. # state (firmware MQTT echoes lag by ~1s).
  3307. try:
  3308. client.set_bed_temperature(bed_target)
  3309. except Exception as exc:
  3310. logger.warning("Queue item %s: preheat bed M140 failed: %s", item.id, exc)
  3311. return
  3312. # Airduct mode (#1468 follow-up). Models with the cooling/heating flap
  3313. # (H2C/H2D/H2D Pro/H2S/X2D/P2S) keep the flap whatever the user last
  3314. # left it on, regardless of M141. Default cooling actively vents the
  3315. # chamber, so a `chamber_target > 0` print with the flap stuck in
  3316. # cooling never converges — the heater fights the open exhaust. We
  3317. # flip the flap BEFORE M141 to "heating" when the preheat wants
  3318. # chamber heat, and back to "cooling" when it doesn't (PLA-only print
  3319. # on an H2D that was previously running ABS would otherwise stay in
  3320. # heating mode and overheat PLA). The current-state read keeps the
  3321. # command idempotent — no MQTT chatter when the flap is already where
  3322. # we want it.
  3323. if supports_airduct(model):
  3324. desired_airduct = "heating" if chamber_target > 0 else "cooling"
  3325. desired_id = 1 if desired_airduct == "heating" else 0
  3326. current_state = printer_manager.get_status(printer.id)
  3327. current_airduct = getattr(current_state, "airduct_mode", None) if current_state else None
  3328. if current_airduct != desired_id:
  3329. try:
  3330. client.set_airduct_mode(desired_airduct)
  3331. except Exception as exc:
  3332. logger.warning(
  3333. "Queue item %s: preheat airduct %s mode failed: %s",
  3334. item.id,
  3335. desired_airduct,
  3336. exc,
  3337. )
  3338. if do_chamber and has_heater:
  3339. try:
  3340. client.set_chamber_temperature(chamber_target)
  3341. except Exception as exc:
  3342. logger.warning("Queue item %s: preheat chamber M141 failed: %s", item.id, exc)
  3343. # Release the pooled DB connection before the (potentially many-minute)
  3344. # heat-soak wait below (#2572). Every setting this method needs is read
  3345. # above; the wait/soak loop only polls printer_manager state and sleeps —
  3346. # it never touches the DB. Without this the caller's transaction sat
  3347. # "idle in transaction" for the whole soak, pinning one pooled connection
  3348. # per preheating printer. expire_on_commit=False keeps item/printer
  3349. # readable afterwards; there are no pending writes to lose here.
  3350. await db.commit()
  3351. # Wait for convergence. Bed warm-up is fast (~5 min from cold); chamber
  3352. # via M141 takes a few minutes; chamber via bed radiation can take 20+.
  3353. # Poll every 3s — frequent enough for responsive logging without
  3354. # spamming the MQTT state stream. The "converged" predicate is:
  3355. # bed reached target (within 2°C tolerance for floating-point + heater hysteresis),
  3356. # AND
  3357. # chamber phase satisfied (no chamber phase, no sensor, or sensor reached target).
  3358. BED_TOLERANCE = 2.0
  3359. CHAMBER_TOLERANCE = 2.0
  3360. POLL_INTERVAL = 3.0
  3361. deadline = asyncio.get_event_loop().time() + max_wait
  3362. while True:
  3363. state = printer_manager.get_status(printer.id)
  3364. if state is None:
  3365. logger.warning("Queue item %s: preheat lost state during wait", item.id)
  3366. break
  3367. temps = state.temperatures or {}
  3368. bed_now = float(temps.get("bed", 0) or 0)
  3369. chamber_now = float(temps.get("chamber", 0) or 0)
  3370. bed_ok = bed_now >= bed_target - BED_TOLERANCE
  3371. if not do_chamber:
  3372. chamber_ok = True # phase disabled or model has neither sensor nor heater
  3373. elif not has_sensor:
  3374. chamber_ok = True # P1S etc — can't read, rely on soak timer only
  3375. else:
  3376. chamber_ok = chamber_now >= chamber_target - CHAMBER_TOLERANCE
  3377. if bed_ok and chamber_ok:
  3378. logger.info(
  3379. "Queue item %s: preheat target reached (bed=%.1f chamber=%.1f) — entering soak",
  3380. item.id,
  3381. bed_now,
  3382. chamber_now,
  3383. )
  3384. break
  3385. if asyncio.get_event_loop().time() >= deadline:
  3386. logger.info(
  3387. "Queue item %s: preheat max_wait reached (bed=%.1f/%d chamber=%.1f/%d) — falling through to soak",
  3388. item.id,
  3389. bed_now,
  3390. bed_target,
  3391. chamber_now,
  3392. chamber_target if do_chamber else 0,
  3393. )
  3394. break
  3395. await asyncio.sleep(POLL_INTERVAL)
  3396. if soak_seconds > 0:
  3397. logger.info("Queue item %s: preheat soak — holding for %ds", item.id, soak_seconds)
  3398. await asyncio.sleep(soak_seconds)
  3399. logger.info("Queue item %s: preheat complete — proceeding to upload", item.id)
  3400. async def _power_on_and_wait(self, plug: SmartPlug, printer_id: int, db: AsyncSession) -> bool:
  3401. """Turn on smart plug and wait for printer to connect.
  3402. Returns True if printer connected successfully within timeout.
  3403. """
  3404. # Get the appropriate service for the plug type (Tasmota or Home Assistant)
  3405. service = await smart_plug_manager.get_service_for_plug(plug, db)
  3406. # Check current plug state
  3407. status = await service.get_status(plug)
  3408. if not status.get("reachable"):
  3409. logger.warning("Smart plug '%s' is not reachable", plug.name)
  3410. return False
  3411. # Turn on if not already on
  3412. if status.get("state") != "ON":
  3413. success = await service.turn_on(plug)
  3414. if not success:
  3415. logger.warning("Failed to turn on smart plug '%s'", plug.name)
  3416. return False
  3417. logger.info("Powered on smart plug '%s' for printer %s", plug.name, printer_id)
  3418. # Get printer from database for connection
  3419. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3420. printer = result.scalar_one_or_none()
  3421. if not printer:
  3422. logger.error("Printer %s not found in database", printer_id)
  3423. return False
  3424. # Wait for printer to boot (give it some time before trying to connect)
  3425. logger.info("Waiting 30s for printer %s to boot...", printer_id)
  3426. await asyncio.sleep(30)
  3427. # Try to connect to the printer periodically
  3428. elapsed = 30 # Already waited 30s
  3429. while elapsed < self._power_on_wait_time:
  3430. # Try to connect
  3431. logger.info("Attempting to connect to printer %s...", printer_id)
  3432. try:
  3433. connected = await printer_manager.connect_printer(printer)
  3434. if connected:
  3435. logger.info("Printer %s connected after %ss", printer_id, elapsed)
  3436. # Give it a moment to stabilize and get status
  3437. await asyncio.sleep(5)
  3438. return True
  3439. except Exception as e:
  3440. logger.debug("Connection attempt failed: %s", e)
  3441. await asyncio.sleep(self._power_on_check_interval)
  3442. elapsed += self._power_on_check_interval
  3443. logger.debug("Waiting for printer %s to connect... (%ss)", printer_id, elapsed)
  3444. logger.warning("Printer %s did not connect within %ss after power on", printer_id, self._power_on_wait_time)
  3445. return False
  3446. async def _check_previous_success(self, db: AsyncSession, item: PrintQueueItem) -> bool:
  3447. """Check if the previous print on this printer succeeded.
  3448. A user-cancelled predecessor is treated as neutral — `cancelled` is a
  3449. deliberate action, not a failure, so subsequent items should still
  3450. dispatch (#1667). `skipped` is excluded from the lookback entirely:
  3451. a skip isn't an actual print attempt, so it must not gate downstream
  3452. items — counting it as a failed predecessor was the cascade bug that
  3453. let a single cancellation block 18 items over 3 days for the reporter.
  3454. Only `failed` and `aborted` — real print-attempt failures — block.
  3455. Failures with `gate_acknowledged=True` (set by the per-printer Resume
  3456. action — #1818) are also excluded from the lookback so the user can
  3457. clear the gate after fixing the physical issue without having to
  3458. re-queue every downstream job.
  3459. """
  3460. result = await db.execute(
  3461. select(PrintQueueItem)
  3462. .where(PrintQueueItem.printer_id == item.printer_id)
  3463. .where(PrintQueueItem.id != item.id)
  3464. .where(PrintQueueItem.status.in_(["completed", "failed", "cancelled", "aborted"]))
  3465. .where(PrintQueueItem.gate_acknowledged == False) # noqa: E712
  3466. .order_by(PrintQueueItem.completed_at.desc())
  3467. .limit(1)
  3468. )
  3469. prev_item = result.scalar_one_or_none()
  3470. # If no previous item, assume success (first in queue)
  3471. if not prev_item:
  3472. return True
  3473. return prev_item.status in ("completed", "cancelled")
  3474. async def _power_off_if_needed(self, db: AsyncSession, item: PrintQueueItem):
  3475. """Schedule power-off if the queue item enabled auto_off_after.
  3476. Delegates to the smart-plug manager so the off honours each plug's
  3477. configured strategy (time delay or temperature threshold), is cancelled
  3478. if the printer starts printing again, and never cuts power on a loaded
  3479. print (#1890). Previously this hardcoded a 50°C / 600s cooldown wait and
  3480. powered off on the timeout regardless of print state.
  3481. """
  3482. if not item.auto_off_after:
  3483. return
  3484. try:
  3485. await smart_plug_manager.schedule_off_after_queue_job(item.printer_id, db)
  3486. except Exception as e:
  3487. logger.warning("Auto-off: Failed to schedule power-off for printer %s: %s", item.printer_id, e)
  3488. async def _get_job_name(self, db: AsyncSession, item: PrintQueueItem) -> str:
  3489. """Get a human-readable name for a queue item."""
  3490. if item.archive_id:
  3491. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3492. archive = result.scalar_one_or_none()
  3493. if archive:
  3494. return archive.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  3495. if item.library_file_id:
  3496. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3497. library_file = result.scalar_one_or_none()
  3498. if library_file:
  3499. return library_file.filename.replace(".gcode.3mf", "").replace(".3mf", "")
  3500. # A cross-model item (#671) holds no file of its own until a printer is
  3501. # picked, so name it after its first candidate — otherwise every waiting
  3502. # notification for one reads "Job #12". Queried rather than read off
  3503. # item.variants because callers outside the selection loop have not
  3504. # eager-loaded them, and a lazy load raises in async.
  3505. first_variant_name = (
  3506. await db.execute(
  3507. select(LibraryFile.filename)
  3508. .join(PrintQueueVariant, PrintQueueVariant.library_file_id == LibraryFile.id)
  3509. .where(PrintQueueVariant.queue_item_id == item.id)
  3510. .order_by(PrintQueueVariant.position, PrintQueueVariant.id)
  3511. .limit(1)
  3512. )
  3513. ).scalar_one_or_none()
  3514. if first_variant_name:
  3515. return first_variant_name.replace(".gcode.3mf", "").replace(".3mf", "")
  3516. return f"Job #{item.id}"
  3517. async def _get_printer(self, db: AsyncSession, printer_id: int) -> Printer | None:
  3518. """Get printer by ID."""
  3519. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3520. return result.scalar_one_or_none()
  3521. async def _notify_dispatch_gave_up(
  3522. self,
  3523. queue_item_id: int,
  3524. printer_id: int,
  3525. created_by_id: int | None,
  3526. reason: str = "Printer accepted the file but never started printing",
  3527. ) -> None:
  3528. """Tell the user the queue item was failed after exhausting its dispatch retries.
  3529. Called from the watchdog, which is a background task with no session of
  3530. its own — hence the fresh one here. Best-effort throughout: the row is
  3531. already marked failed and that is the load-bearing part; a notification
  3532. provider being down must not resurrect the retry loop we just stopped.
  3533. ``reason`` defaults to the exhausted-retries wording. The command-rejected
  3534. path passes its own, because "accepted the file but never started" is the
  3535. opposite of what happened there — the printer refused it outright (#2732).
  3536. """
  3537. try:
  3538. async with async_session() as db:
  3539. item = await db.get(PrintQueueItem, queue_item_id)
  3540. if not item:
  3541. return
  3542. job_name = await self._get_job_name(db, item)
  3543. printer = await self._get_printer(db, printer_id)
  3544. await notification_service.on_queue_job_failed(
  3545. job_name=job_name,
  3546. printer_id=printer_id,
  3547. printer_name=printer.name if printer else "Unknown",
  3548. reason=reason,
  3549. db=db,
  3550. )
  3551. except Exception as e:
  3552. logger.warning("Queue item %s: give-up notification failed: %s", queue_item_id, e)
  3553. try:
  3554. await ws_manager.send_queue_item_failed(
  3555. user_id=created_by_id,
  3556. queue_item_id=queue_item_id,
  3557. printer_id=printer_id,
  3558. reason="never_started",
  3559. )
  3560. except Exception:
  3561. pass # toast is best-effort
  3562. async def _block_on_filament_deficit(
  3563. self,
  3564. db: AsyncSession,
  3565. item: PrintQueueItem,
  3566. ) -> bool:
  3567. """Promote the item to manual_start when the assigned spool is short (#1496).
  3568. Returns True when this dispatch attempt was blocked, False when the
  3569. item is clear to start. A previously-flagged item whose spool has
  3570. since been swapped to one with enough material clears the flag here
  3571. so the next scheduler tick dispatches it.
  3572. """
  3573. # User has explicitly acknowledged the deficit ("Print Anyway") —
  3574. # don't re-flag, don't even compute. Without this short-circuit the
  3575. # scheduler bounces between "user said anyway" (route clears
  3576. # manual_start) and "scheduler re-blocked" (this method re-flags it
  3577. # on identical spool state) (#1698-followup).
  3578. if item.skip_filament_check:
  3579. # #1762 diagnostic: surface the short-circuit at INFO so a
  3580. # future "Print Anyway didn't work" report (e.g. issue #1762
  3581. # comment 3) has actionable evidence in the support bundle
  3582. # without needing DEBUG enabled.
  3583. logger.info(
  3584. "Queue item %s honouring user's Print Anyway acknowledgement — skipping deficit check",
  3585. item.id,
  3586. )
  3587. return False
  3588. try:
  3589. deficit = await compute_deficit_for_queue_item(db, item)
  3590. except Exception as e:
  3591. # Never let a flaky deficit check wedge the queue — log and let
  3592. # dispatch proceed. The PrintModal-side check still runs on the
  3593. # manual paths.
  3594. logger.warning("Filament deficit check failed for item %s: %s", item.id, e)
  3595. return False
  3596. if deficit:
  3597. item.filament_short = True
  3598. item.manual_start = True
  3599. await db.commit()
  3600. job_name = await self._get_job_name(db, item)
  3601. printer = await self._get_printer(db, item.printer_id) if item.printer_id else None
  3602. logger.info(
  3603. "Queue item %s blocked on filament deficit (%d slot(s)) — promoted to manual_start",
  3604. item.id,
  3605. len(deficit),
  3606. )
  3607. try:
  3608. await notification_service.on_queue_job_waiting(
  3609. job_name=job_name,
  3610. target_model=(printer.model if printer else "") or "",
  3611. waiting_reason="filament_short",
  3612. db=db,
  3613. )
  3614. except Exception as e:
  3615. logger.debug("filament_short notification failed for item %s: %s", item.id, e)
  3616. return True
  3617. # No deficit — clear any stale flag from a previous tick.
  3618. if item.filament_short:
  3619. item.filament_short = False
  3620. await db.commit()
  3621. return False
  3622. async def _propagate_owner_to_printer_manager(self, db: AsyncSession, item: PrintQueueItem) -> None:
  3623. """Hand the queue item's owner to printer_manager so the
  3624. print-complete callback can credit the user in PrintLogEntry (#1670).
  3625. No-ops when the item has no `created_by_id` or the referenced user
  3626. row is missing (e.g. user deleted between queue-add and dispatch —
  3627. in that case the print log row falls back to the existing un-credited
  3628. behaviour rather than crashing the dispatch).
  3629. """
  3630. if not item.created_by_id:
  3631. return
  3632. from backend.app.models.user import User
  3633. owner = await db.get(User, item.created_by_id)
  3634. if owner:
  3635. printer_manager.set_current_print_user(item.printer_id, owner.id, owner.username)
  3636. async def _start_print(self, db: AsyncSession, item: PrintQueueItem):
  3637. """Upload file and start print for a queue item.
  3638. Supports two sources:
  3639. - archive_id: Print from an existing archive
  3640. - library_file_id: Print from a library file (file manager)
  3641. """
  3642. logger.info("Starting queue item %s", item.id)
  3643. # Also covers a reservation left active by a process interruption
  3644. # during an earlier attempt. `_dispatch_one` releases this marker on
  3645. # every exit unless start_print() confirms that the command was sent.
  3646. self._unconfirmed_budget_reservations.add(item.id)
  3647. try:
  3648. from backend.app.models.user import User
  3649. queue_user = await db.get(User, item.created_by_id) if item.created_by_id is not None else None
  3650. # Recompute at the final authorization boundary as well as enqueue
  3651. # time. This covers rows created before the server-side estimate
  3652. # migration and prevents any alternate write path from weakening
  3653. # the budget reservation.
  3654. archive = await db.get(PrintArchive, item.archive_id) if item.archive_id is not None else None
  3655. library_file = await db.get(LibraryFile, item.library_file_id) if item.library_file_id is not None else None
  3656. item.estimated_cost = await estimate_queue_source_cost(
  3657. db,
  3658. archive=archive,
  3659. library_file=library_file,
  3660. plate_id=item.plate_id,
  3661. ams_mapping=item.ams_mapping,
  3662. printer_id=item.printer_id,
  3663. )
  3664. await validate_print_budget(
  3665. db,
  3666. cost_center_id=item.cost_center_id,
  3667. estimated_cost=item.estimated_cost,
  3668. current_user=queue_user,
  3669. exclude_queue_item_id=item.id,
  3670. exclude_reservation_source_type="print_queue",
  3671. exclude_reservation_source_id=item.id,
  3672. )
  3673. budget_reservation = await create_budget_reservation(
  3674. db,
  3675. cost_center_id=item.cost_center_id,
  3676. estimated_cost=item.estimated_cost,
  3677. current_user=queue_user,
  3678. source_type="print_queue",
  3679. source_id=item.id,
  3680. print_archive_id=item.archive_id,
  3681. exclude_queue_item_id=item.id,
  3682. )
  3683. await db.commit()
  3684. except HTTPException as exc:
  3685. item.status = "failed"
  3686. item.error_message = str(exc.detail)
  3687. item.completed_at = datetime.now(timezone.utc)
  3688. await db.commit()
  3689. logger.error("Queue item %s: Budget check failed: %s", item.id, item.error_message)
  3690. await self._power_off_if_needed(db, item)
  3691. return
  3692. # Get printer first (needed for both paths)
  3693. result = await db.execute(select(Printer).where(Printer.id == item.printer_id))
  3694. printer = result.scalar_one_or_none()
  3695. if not printer:
  3696. item.status = "failed"
  3697. item.error_message = "Printer not found"
  3698. item.completed_at = datetime.now(timezone.utc)
  3699. await db.commit()
  3700. logger.error("Queue item %s: Printer %s not found", item.id, item.printer_id)
  3701. await self._power_off_if_needed(db, item)
  3702. return
  3703. # Check printer is connected
  3704. if not printer_manager.is_connected(item.printer_id):
  3705. item.status = "failed"
  3706. item.error_message = "Printer not connected"
  3707. item.completed_at = datetime.now(timezone.utc)
  3708. await db.commit()
  3709. logger.error("Queue item %s: Printer %s not connected", item.id, item.printer_id)
  3710. await self._power_off_if_needed(db, item)
  3711. return
  3712. # Cancel-while-dispatching race (#1853): the scheduler's snapshot of
  3713. # `items` was taken at the top of check_queue, but the user can /cancel
  3714. # any pending row in the gap before we reach this point. Re-read the
  3715. # row and bail out cleanly instead of starting an FTP upload for a row
  3716. # that's already cancelled. The atomic CAS at the pending→printing
  3717. # transition (below, before start_print) is the load-bearing guard;
  3718. # this is the early-exit optimisation that avoids wasted FTP I/O.
  3719. await db.refresh(item)
  3720. if item.status != "pending":
  3721. logger.info(
  3722. "Queue item %s no longer pending (status=%s) — aborting dispatch",
  3723. item.id,
  3724. item.status,
  3725. )
  3726. return
  3727. # Busy-printer guard (#2598). check_queue gates dispatch on
  3728. # _is_printer_idle(), but that treats FINISH as idle and a printer can
  3729. # keep reporting FINISH for tens of seconds *after* it accepted a
  3730. # project_file (see the watchdog's phase-B note). A watchdog revert
  3731. # (#2555) also releases the dispatch hold, so a re-selected item can
  3732. # reach here while its printer has actually started printing. Uploading
  3733. # and dispatching then collides with the live job — the firmware answers
  3734. # 0500_4004 and, on an A1 mini, cancels the running print. Re-check the
  3735. # live state right before the expensive FTP upload: if the printer is
  3736. # busy, leave the item pending and let a later tick dispatch it once the
  3737. # printer is genuinely idle. No wasted upload, no collision.
  3738. pre_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  3739. if pre_dispatch_state in _ACTIVE_PRINT_STATES:
  3740. logger.info(
  3741. "Queue item %s: printer %s is busy (state=%s) — deferring dispatch, "
  3742. "leaving item pending for a later tick (#2598)",
  3743. item.id,
  3744. item.printer_id,
  3745. pre_dispatch_state,
  3746. )
  3747. return
  3748. # Determine source: archive or library file
  3749. archive = None
  3750. library_file = None
  3751. file_path = None
  3752. filename = None
  3753. cleanup_disk_paths: list[Path] = []
  3754. if item.archive_id:
  3755. # Print from archive
  3756. result = await db.execute(select(PrintArchive).where(PrintArchive.id == item.archive_id))
  3757. archive = result.scalar_one_or_none()
  3758. if not archive:
  3759. item.status = "failed"
  3760. item.error_message = "Archive not found"
  3761. item.completed_at = datetime.now(timezone.utc)
  3762. await db.commit()
  3763. logger.error("Queue item %s: Archive %s not found", item.id, item.archive_id)
  3764. await self._power_off_if_needed(db, item)
  3765. return
  3766. # Persist the queue item's selected plate onto the archive so Print
  3767. # History can show the actual plate after cancel/fail/complete (#2603).
  3768. # Only when the archive doesn't already carry one, so a reprint of a
  3769. # plate-specific archive isn't relabelled by a differently-plated
  3770. # queue row.
  3771. if archive.plate_id is None and item.plate_id is not None:
  3772. archive.plate_id = item.plate_id
  3773. file_path = settings.base_dir / archive.file_path
  3774. filename = archive.filename
  3775. elif item.library_file_id:
  3776. # Print from library file (file manager)
  3777. result = await db.execute(LibraryFile.active().where(LibraryFile.id == item.library_file_id))
  3778. library_file = result.scalar_one_or_none()
  3779. if not library_file:
  3780. item.status = "failed"
  3781. item.error_message = "Library file not found"
  3782. item.completed_at = datetime.now(timezone.utc)
  3783. await db.commit()
  3784. logger.error("Queue item %s: Library file %s not found", item.id, item.library_file_id)
  3785. await self._power_off_if_needed(db, item)
  3786. return
  3787. # Library files store absolute paths
  3788. lib_path = Path(library_file.file_path)
  3789. file_path = lib_path if lib_path.is_absolute() else settings.base_dir / library_file.file_path
  3790. filename = library_file.filename
  3791. # Create archive from library file so usage tracking has access to the 3MF
  3792. queue_item_id = item.id
  3793. try:
  3794. from backend.app.services.archive import ArchiveService
  3795. archive_service = ArchiveService(db)
  3796. archive = await archive_service.archive_print(
  3797. printer_id=item.printer_id,
  3798. source_file=file_path,
  3799. original_filename=filename,
  3800. created_by_id=item.created_by_id,
  3801. project_id=item.project_id,
  3802. cost_center_id=item.cost_center_id,
  3803. library_file_id=item.library_file_id, # per-file project progress (#1897)
  3804. plate_id=item.plate_id, # selected plate → Print History (#2603)
  3805. )
  3806. if archive:
  3807. item.archive_id = archive.id
  3808. if budget_reservation is not None:
  3809. budget_reservation.print_archive_id = archive.id
  3810. if item.cleanup_library_after_dispatch and not library_file.is_external:
  3811. item.library_file_id = None
  3812. cleanup_disk_paths.append(file_path)
  3813. if library_file.thumbnail_path:
  3814. thumb_path = Path(library_file.thumbnail_path)
  3815. if not thumb_path.is_absolute():
  3816. thumb_path = settings.base_dir / library_file.thumbnail_path
  3817. cleanup_disk_paths.append(thumb_path)
  3818. await db.delete(library_file)
  3819. file_path = settings.base_dir / archive.file_path
  3820. filename = archive.filename
  3821. # Commit, not flush — flush opens the SQLite write
  3822. # transaction (item.archive_id update + library_file
  3823. # delete) and would hold the WAL writer lock through the
  3824. # FTP upload below, causing "database is locked" cascades
  3825. # for sensor history + concurrent cancels (#1853).
  3826. await db.commit()
  3827. logger.info(
  3828. "Queue item %s: Created archive %s from library file %s",
  3829. item.id,
  3830. archive.id,
  3831. item.library_file_id,
  3832. )
  3833. except Exception as e:
  3834. logger.warning(
  3835. "Queue item %s: Failed to create archive from library file: %s",
  3836. queue_item_id,
  3837. e,
  3838. exc_info=True,
  3839. )
  3840. await db.rollback()
  3841. item = await db.get(PrintQueueItem, queue_item_id)
  3842. if item:
  3843. item.status = "failed"
  3844. item.error_message = "Failed to create archive from library file"
  3845. item.completed_at = datetime.now(timezone.utc)
  3846. await db.commit()
  3847. await self._power_off_if_needed(db, item)
  3848. return
  3849. if not archive:
  3850. item.status = "failed"
  3851. item.error_message = "Failed to create archive from library file"
  3852. item.completed_at = datetime.now(timezone.utc)
  3853. await db.commit()
  3854. logger.error("Queue item %s: Archive creation from library file returned no archive", item.id)
  3855. await self._power_off_if_needed(db, item)
  3856. return
  3857. else:
  3858. # Neither archive nor library file specified
  3859. item.status = "failed"
  3860. item.error_message = "No source file specified"
  3861. item.completed_at = datetime.now(timezone.utc)
  3862. await db.commit()
  3863. logger.error("Queue item %s: No archive_id or library_file_id specified", item.id)
  3864. await self._power_off_if_needed(db, item)
  3865. return
  3866. # Check file exists on disk
  3867. if not file_path.exists():
  3868. item.status = "failed"
  3869. item.error_message = "Source file not found on disk"
  3870. item.completed_at = datetime.now(timezone.utc)
  3871. await db.commit()
  3872. logger.error("Queue item %s: File not found: %s", item.id, file_path)
  3873. await self._power_off_if_needed(db, item)
  3874. return
  3875. # Nozzle-diameter mismatch guard (#1899). A file sliced for one nozzle
  3876. # size dispatched to a printer with a different nozzle installed is
  3877. # rejected by the firmware with a cryptic HMS ("Failed to get AMS mapping
  3878. # table" 0700_8012, or "nozzle diameter … not consistent" 0500_4038) that
  3879. # gives the user no idea what went wrong. Catch it here, before we spend
  3880. # time preheating and uploading, and fail with an actionable message.
  3881. # Fail-safe by construction: only a POSITIVE mismatch blocks — when the
  3882. # slice carries no nozzle diameter (archive.nozzle_diameter is None) or
  3883. # the printer hasn't reported its nozzles yet, we fall through and let the
  3884. # print proceed exactly as before. On dual-nozzle printers (H2D) a match
  3885. # against EITHER installed nozzle passes, so a 0.6 slice is fine as long
  3886. # as one of the two hotends is a 0.6.
  3887. sliced_nozzle = archive.nozzle_diameter if archive else None
  3888. if sliced_nozzle:
  3889. installed = _installed_nozzle_diameters(printer_manager.get_status(item.printer_id))
  3890. mismatch_msg = _nozzle_mismatch_message(sliced_nozzle, installed)
  3891. if mismatch_msg:
  3892. item.status = "failed"
  3893. item.error_message = mismatch_msg
  3894. item.completed_at = datetime.now(timezone.utc)
  3895. await db.commit()
  3896. logger.warning("Queue item %s: nozzle mismatch — %s", item.id, mismatch_msg)
  3897. await notification_service.on_queue_job_failed(
  3898. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  3899. printer_id=printer.id,
  3900. printer_name=printer.name,
  3901. reason=mismatch_msg,
  3902. db=db,
  3903. )
  3904. try:
  3905. await ws_manager.send_queue_item_failed(
  3906. user_id=item.created_by_id,
  3907. queue_item_id=item.id,
  3908. printer_id=item.printer_id,
  3909. reason="nozzle_mismatch",
  3910. )
  3911. except Exception:
  3912. pass
  3913. await self._power_off_if_needed(db, item)
  3914. return
  3915. # Preheat / heat-soak (#1468) — fires before upload so the printer's
  3916. # bed (and chamber, if applicable) is at temperature when the firmware
  3917. # starts the actual print routine. Best-effort: any failure logs and
  3918. # falls through to the normal upload+start path rather than turning a
  3919. # configuration issue into a failed queue item.
  3920. await self._preheat_and_soak(db, item, printer, archive)
  3921. # G-code injection for auto-print systems (#422)
  3922. injected_path = None
  3923. # #2547: tracked separately from `injected_path`, which is also set when
  3924. # only a START snippet was injected. Only an END snippet changes what the
  3925. # camera sees at print completion.
  3926. end_gcode_injected = False
  3927. if item.gcode_injection:
  3928. try:
  3929. snippets_raw = await self._get_setting(db, "gcode_snippets")
  3930. if snippets_raw:
  3931. snippets = json.loads(snippets_raw)
  3932. model_snippets = snippets.get(printer.model, {})
  3933. start_gc = (model_snippets.get("start_gcode") or "").strip()
  3934. end_gc = (model_snippets.get("end_gcode") or "").strip()
  3935. if start_gc or end_gc:
  3936. from backend.app.utils.threemf_tools import inject_gcode_into_3mf
  3937. injected_path = inject_gcode_into_3mf(
  3938. file_path, item.plate_id or 1, start_gc or None, end_gc or None
  3939. )
  3940. if injected_path:
  3941. file_path = injected_path
  3942. end_gcode_injected = bool(end_gc)
  3943. logger.info("Queue item %s: G-code injected for model %s", item.id, printer.model)
  3944. else:
  3945. logger.warning(
  3946. "Queue item %s: G-code injection returned no result, using original", item.id
  3947. )
  3948. except Exception as e:
  3949. logger.warning("Queue item %s: G-code injection failed, using original: %s", item.id, e)
  3950. # #2547: the finish-photo path can't learn from telemetry that this print
  3951. # ends with user End G-code — which means the plate may be gone by the
  3952. # time FINISH arrives (#1867). Flag it here; `on_print_start` binds it to
  3953. # the print once the printer confirms it running.
  3954. if end_gcode_injected:
  3955. print_dispatch_context.mark_pending(printer.id)
  3956. # Upload to root directory (not /cache/) - the start_print command references
  3957. # files by name only (ftp://{filename}), so they must be in the root
  3958. remote_filename = derive_remote_filename(filename)
  3959. remote_path = f"/{remote_filename}"
  3960. # Get FTP retry settings
  3961. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  3962. logger.info(
  3963. f"Queue item {item.id}: FTP upload starting - printer={printer.name} ({printer.model}), "
  3964. f"ip={printer.ip_address}, file={remote_filename}, local_path={file_path}, "
  3965. f"retry_enabled={ftp_retry_enabled}, retry_count={ftp_retry_count}, timeout={ftp_timeout}"
  3966. )
  3967. # Release the pooled DB connection before the FTP delete/upload (#2572).
  3968. # Every read this method needs (printer, archive/library, preheat) is
  3969. # done, and the library-file branch already committed its archive
  3970. # creation. Without this the transaction opened by the first SELECT above
  3971. # stays "idle in transaction" for the entire upload — multiple seconds
  3972. # for a large 3MF — pinning one pooled connection per in-flight dispatch;
  3973. # a farm dispatching many jobs at once then exhausts the pool. This was
  3974. # correlated to an exact idle-in-transaction session on a 93-printer farm
  3975. # (reporter @Jostxxl). expire_on_commit=False keeps item/printer/archive
  3976. # readable; the status writes below (upload-failure path and the
  3977. # pending->printing CAS) transparently open a fresh transaction.
  3978. await db.commit()
  3979. # Delete existing file if present (avoids 553 error on overwrite)
  3980. try:
  3981. logger.debug("Queue item %s: Deleting existing file %s if present...", item.id, remote_path)
  3982. delete_result = await delete_file_async(
  3983. printer.ip_address,
  3984. printer.access_code,
  3985. remote_path,
  3986. socket_timeout=ftp_timeout,
  3987. printer_model=printer.model,
  3988. )
  3989. logger.debug("Queue item %s: Delete result: %s", item.id, delete_result)
  3990. except Exception as e:
  3991. logger.debug("Queue item %s: Delete failed (may not exist): %s", item.id, e)
  3992. # Dispatch toast — announce the upload start with the total byte
  3993. # count so the frontend can render an honest progress bar.
  3994. toast_uid = item.created_by_id
  3995. toast_file_name = filename.replace(".gcode.3mf", "").replace(".3mf", "")
  3996. try:
  3997. total_bytes = file_path.stat().st_size
  3998. except OSError:
  3999. total_bytes = 0
  4000. try:
  4001. await ws_manager.send_queue_item_uploading(
  4002. user_id=toast_uid,
  4003. queue_item_id=item.id,
  4004. printer_id=item.printer_id,
  4005. printer_name=printer.name,
  4006. file_name=toast_file_name,
  4007. total_bytes=total_bytes,
  4008. )
  4009. except Exception:
  4010. pass # toast is best-effort
  4011. progress_bridge = _UploadProgressBridge(toast_uid, item.id)
  4012. # A deadline expiry gets its own message: "check your SD card" is the
  4013. # wrong advice for a link that was simply too slow to finish (#2529).
  4014. upload_error: str | None = None
  4015. try:
  4016. if ftp_retry_enabled:
  4017. uploaded = await with_ftp_retry(
  4018. upload_file_async,
  4019. printer.ip_address,
  4020. printer.access_code,
  4021. file_path,
  4022. remote_path,
  4023. socket_timeout=ftp_timeout,
  4024. printer_model=printer.model,
  4025. progress_callback=progress_bridge,
  4026. max_retries=ftp_retry_count,
  4027. retry_delay=ftp_retry_delay,
  4028. operation_name=f"Upload print to {printer.name}",
  4029. )
  4030. else:
  4031. uploaded = await upload_file_async(
  4032. printer.ip_address,
  4033. printer.access_code,
  4034. file_path,
  4035. remote_path,
  4036. socket_timeout=ftp_timeout,
  4037. printer_model=printer.model,
  4038. progress_callback=progress_bridge,
  4039. )
  4040. except UploadCancelled as e:
  4041. uploaded = False
  4042. upload_error = (
  4043. "Upload was too slow to finish and was cancelled. The printer's connection could not sustain "
  4044. "the transfer — check its Wi-Fi signal, or move it closer to the access point."
  4045. )
  4046. logger.error("Queue item %s: upload deadline exceeded: %s", item.id, e)
  4047. except Exception as e:
  4048. uploaded = False
  4049. logger.error("Queue item %s: FTP error: %s (type: %s)", item.id, e, type(e).__name__)
  4050. # Clean up injected temp file after upload attempt
  4051. if injected_path and injected_path.exists():
  4052. injected_path.unlink(missing_ok=True)
  4053. if not uploaded:
  4054. error_msg = upload_error or (
  4055. "Failed to upload file to printer. Check if SD card is inserted and properly formatted (FAT32/exFAT). "
  4056. "See server logs for detailed diagnostics."
  4057. )
  4058. item.status = "failed"
  4059. item.error_message = error_msg
  4060. item.completed_at = datetime.now(timezone.utc)
  4061. await db.commit()
  4062. logger.error(
  4063. f"Queue item {item.id}: FTP upload failed - printer={printer.name}, model={printer.model}, "
  4064. f"ip={printer.ip_address}. Check logs above for storage diagnostics and specific error codes."
  4065. )
  4066. # Send failure notification
  4067. await notification_service.on_queue_job_failed(
  4068. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  4069. printer_id=printer.id,
  4070. printer_name=printer.name,
  4071. reason="Failed to upload file to printer",
  4072. db=db,
  4073. )
  4074. try:
  4075. await ws_manager.send_queue_item_failed(
  4076. user_id=toast_uid,
  4077. queue_item_id=item.id,
  4078. printer_id=item.printer_id,
  4079. reason="upload_failed",
  4080. )
  4081. except Exception:
  4082. pass
  4083. await self._power_off_if_needed(db, item)
  4084. return
  4085. # Parse AMS mapping if stored
  4086. ams_mapping = None
  4087. if item.ams_mapping:
  4088. try:
  4089. ams_mapping = json.loads(item.ams_mapping)
  4090. except json.JSONDecodeError:
  4091. logger.warning("Queue item %s: Invalid AMS mapping JSON, ignoring", item.id)
  4092. # Register as expected print so we don't create a duplicate archive
  4093. # Only applicable for archive-based prints
  4094. if archive:
  4095. from backend.app.main import register_expected_print
  4096. register_expected_print(
  4097. item.printer_id,
  4098. remote_filename,
  4099. archive.id,
  4100. ams_mapping=ams_mapping,
  4101. created_by_id=item.created_by_id,
  4102. cost_center_id=item.cost_center_id,
  4103. plate_id=item.plate_id,
  4104. )
  4105. # Registration happens before the print command by necessity (the
  4106. # printer can report the print before the send returns), so record
  4107. # what to undo if we never get as far as sending. `_dispatch_one`
  4108. # rolls back anything still pending here on every exit — exception,
  4109. # early return, or cancel winning the CAS below.
  4110. self._unconfirmed_expected_print[item.id] = (item.printer_id, remote_filename, archive.id)
  4111. # Propagate the queue item's owner into printer_manager so the
  4112. # print-complete callback can credit the user in the PrintLogEntry
  4113. # (#1670). `created_by_id` is set either at queue-add time (UI-added
  4114. # items) or when the user clicks the manual-start button.
  4115. await self._propagate_owner_to_printer_manager(db, item)
  4116. # IMPORTANT: Set status to "printing" BEFORE sending the print command.
  4117. # This prevents phantom reprints if the backend crashes/restarts after the
  4118. # print command is sent but before the status update is committed.
  4119. # If we crash after this commit but before start_print(), the item will be
  4120. # in "printing" status without actually printing - but that's safer than
  4121. # accidentally reprinting the same file hours later.
  4122. #
  4123. # Atomic CAS (#1853): a user pressing /cancel mid-dispatch (between the
  4124. # initial pending read at the top of check_queue and this point) flips
  4125. # the row to "cancelled" in a separate session. Without the WHERE
  4126. # status='pending' clause, the unconditional update here would silently
  4127. # overwrite that cancellation and we'd ship the MQTT start_print below
  4128. # — printer obeys, user sees "I pressed cancel and the print started".
  4129. # rowcount==0 means the user won the race; bail out, best-effort delete
  4130. # the file we just uploaded, do NOT send start_print.
  4131. now_utc = datetime.now(timezone.utc)
  4132. billing_run_id = str(uuid.uuid4())
  4133. cas = await db.execute(
  4134. update(PrintQueueItem)
  4135. .where(PrintQueueItem.id == item.id)
  4136. .where(PrintQueueItem.status == "pending")
  4137. .values(status="printing", started_at=now_utc, billing_run_id=billing_run_id)
  4138. )
  4139. await db.commit()
  4140. if cas.rowcount == 0:
  4141. logger.info(
  4142. "Queue item %s no longer pending at print-command time "
  4143. "(cancelled or removed mid-dispatch) — aborting before MQTT send (#1853)",
  4144. item.id,
  4145. )
  4146. try:
  4147. await delete_file_async(
  4148. printer.ip_address,
  4149. printer.access_code,
  4150. remote_path,
  4151. socket_timeout=ftp_timeout,
  4152. printer_model=printer.model,
  4153. )
  4154. except Exception as cleanup_err:
  4155. logger.debug(
  4156. "Queue item %s: best-effort cleanup of uploaded file failed: %s",
  4157. item.id,
  4158. cleanup_err,
  4159. )
  4160. try:
  4161. await ws_manager.send_queue_item_failed(
  4162. user_id=toast_uid,
  4163. queue_item_id=item.id,
  4164. printer_id=item.printer_id,
  4165. reason="cancelled_mid_dispatch",
  4166. )
  4167. except Exception:
  4168. pass
  4169. return
  4170. # Sync the in-memory item so subsequent code that reads item.status /
  4171. # item.started_at sees the values we just persisted.
  4172. item.status = "printing"
  4173. item.started_at = now_utc
  4174. item.billing_run_id = billing_run_id
  4175. if archive is not None:
  4176. archive.billing_run_id = billing_run_id
  4177. # Legacy transaction deletion used an archive-wide skip flag.
  4178. # A newly dispatched run has its own UUID/tombstone, so it must be
  4179. # billable independently of any older deleted run on this archive.
  4180. archive.wallet_charge_skipped = False
  4181. # Persist before MQTT send so completion and restart recovery can
  4182. # always recover the internal billing identity.
  4183. await db.commit()
  4184. for cleanup_path in cleanup_disk_paths:
  4185. try:
  4186. if cleanup_path.exists():
  4187. cleanup_path.unlink()
  4188. except OSError as cleanup_err:
  4189. logger.warning(
  4190. "TRANSIENT_LIBRARY_FILE_ORPHAN %s",
  4191. json.dumps(
  4192. {
  4193. "queue_item_id": item.id,
  4194. "path": str(cleanup_path),
  4195. "error": str(cleanup_err),
  4196. },
  4197. sort_keys=True,
  4198. ),
  4199. )
  4200. # Clear the awaiting-plate-clear flag now that we're starting a new print
  4201. printer_manager.set_awaiting_plate_clear(item.printer_id, False)
  4202. logger.info("Queue item %s: Status set to 'printing', sending print command...", item.id)
  4203. # Capture state before dispatch so the watchdog can detect whether the
  4204. # printer actually transitioned (#967). Also capture subtask_id so the
  4205. # watchdog can recognise "command landed but state hasn't flipped yet"
  4206. # on slow H2D transitions (#1078).
  4207. pre_status = printer_manager.get_status(item.printer_id)
  4208. pre_state = getattr(pre_status, "state", None) if pre_status else None
  4209. pre_subtask_id = getattr(pre_status, "subtask_id", None) if pre_status else None
  4210. pre_gcode_file = getattr(pre_status, "gcode_file", None) if pre_status else None
  4211. # #1721: respect the user's explicit timelapse choice. The #1397
  4212. # force-on at dispatch was removed because it caused per-layer nozzle
  4213. # parking on slicer profiles with Timelapse Type = Smooth. Finish-photo
  4214. # capture is now driven by the stg_cur=22 transition in bambu_mqtt.py
  4215. # ("Filament unloading", toolhead parked, bed not yet dropped) with a
  4216. # FINISH-state fallback — no need to force a video.
  4217. effective_timelapse = bool(item.timelapse)
  4218. # Start the print with AMS mapping, plate_id and print options.
  4219. # nozzle_mapping rides through verbatim — JSON string captured from
  4220. # Bambu Studio's project_file on VP intake (#1780); the MQTT layer
  4221. # parses + injects it only for dual-nozzle models so a null on every
  4222. # other model is a transparent pass-through.
  4223. started = printer_manager.start_print(
  4224. item.printer_id,
  4225. remote_filename,
  4226. plate_id=item.plate_id or 1,
  4227. ams_mapping=ams_mapping,
  4228. bed_levelling=item.bed_levelling,
  4229. flow_cali=item.flow_cali,
  4230. vibration_cali=item.vibration_cali,
  4231. layer_inspect=item.layer_inspect,
  4232. timelapse=effective_timelapse,
  4233. use_ams=item.use_ams,
  4234. nozzle_offset_cali=item.nozzle_offset_cali,
  4235. nozzle_mapping=item.nozzle_mapping,
  4236. )
  4237. if started:
  4238. # The command is away, so the expectation is now legitimate and must
  4239. # survive. Anything still in this dict when _dispatch_one exits gets
  4240. # rolled back.
  4241. self._unconfirmed_expected_print.pop(item.id, None)
  4242. self._unconfirmed_budget_reservations.discard(item.id)
  4243. logger.info("Queue item %s: Print started successfully - %s", item.id, filename)
  4244. # No dispatch-toast event here: the legacy bg-dispatch path kept
  4245. # status='processing' from upload start until the printer acked
  4246. # (or timed out). The frontend derives "Awaiting printer…" purely
  4247. # from upload_progress_pct >= 99.9; an explicit 'dispatched' WS
  4248. # event would push the status chip out of 'PROCESSING' prematurely
  4249. # — which is exactly what the screenshot at #1625-followup
  4250. # complained about.
  4251. # Register the local 3MF in the cover-cache so /cover skips FTP
  4252. # (#1166 follow-up). file_path was resolved earlier from either the
  4253. # archive or the library file row.
  4254. if file_path is not None:
  4255. cache_3mf_download(item.printer_id, remote_filename, file_path)
  4256. # Hold the printer against further dispatches until the watchdog
  4257. # confirms the printer transitioned (or until the hard timeout).
  4258. # Prevents multi-plate batches from triple-dispatching onto the
  4259. # same H2D Pro while it digests the first project_file (#1157).
  4260. self._mark_printer_dispatched(item.printer_id, pre_state, pre_subtask_id)
  4261. # Watchdog: if the printer never transitions out of pre_state AND
  4262. # never advances subtask_id, the MQTT publish was accepted locally but
  4263. # didn't reach the printer (half-broken session — same shape as
  4264. # #887/#936). Revert the queue item so the next dispatch can pick it
  4265. # up instead of leaving it stuck in "printing" (#967). subtask_id
  4266. # check avoids false reverts on slow H2D FINISH→PREPARE transitions
  4267. # that would otherwise cause the item to re-dispatch as a reprint
  4268. # of the just-finished job (#1078).
  4269. if pre_state:
  4270. spawn_background_task(
  4271. self._watchdog_print_start(
  4272. item.id,
  4273. item.printer_id,
  4274. pre_state,
  4275. pre_subtask_id,
  4276. pre_gcode_file,
  4277. created_by_id=toast_uid,
  4278. ),
  4279. name=f"watchdog-print-start-{item.id}",
  4280. )
  4281. # Get estimated time for notification.
  4282. #
  4283. # This used to fall back to `library_file.print_time_seconds`, a column
  4284. # LibraryFile does not have — the print time it knows about lives in
  4285. # `file_metadata`. So a library print whose archive carried no parseable
  4286. # print time (a plain .gcode, or a 3MF the parser could not read) raised
  4287. # AttributeError right here, *after* the printer had already been sent
  4288. # the job: the started-notification never fired, and the exception
  4289. # unwound the whole queue pass, so every other printer still waiting to
  4290. # be dispatched on that tick silently missed its turn.
  4291. #
  4292. # The queue item caches the print time at creation ("Cached from
  4293. # archive/library"), which is the value this was reaching for.
  4294. estimated_time = None
  4295. if archive and archive.print_time_seconds:
  4296. estimated_time = archive.print_time_seconds
  4297. elif item.print_time_seconds:
  4298. estimated_time = item.print_time_seconds
  4299. # Send job started notification
  4300. await notification_service.on_queue_job_started(
  4301. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  4302. printer_id=printer.id,
  4303. printer_name=printer.name,
  4304. db=db,
  4305. estimated_time=estimated_time,
  4306. )
  4307. # MQTT relay - publish queue job started
  4308. try:
  4309. from backend.app.services.mqtt_relay import mqtt_relay
  4310. await mqtt_relay.on_queue_job_started(
  4311. job_id=item.id,
  4312. filename=filename,
  4313. printer_id=printer.id,
  4314. printer_name=printer.name,
  4315. printer_serial=printer.serial_number,
  4316. )
  4317. except Exception:
  4318. pass # Don't fail if MQTT fails
  4319. else:
  4320. # Clean up uploaded file from SD card to prevent phantom prints
  4321. try:
  4322. await delete_file_async(
  4323. printer.ip_address,
  4324. printer.access_code,
  4325. remote_path,
  4326. printer_model=printer.model,
  4327. )
  4328. except Exception:
  4329. pass # Best-effort — don't fail the error handler
  4330. # Busy-refusal is a deferral, not a failure (#2598). The printer's
  4331. # state can flip from idle to active in the window between the
  4332. # pre-dispatch check above and this publish (the FTP upload takes
  4333. # seconds); start_print() then refuses to send project_file to the
  4334. # now-busy printer and returns False. Failing the item here would be
  4335. # wrong — the printer is fine, it is simply busy — so revert to
  4336. # pending and let a later tick dispatch it once the printer is idle,
  4337. # exactly like the pre-dispatch guard. Only a start_print() False on
  4338. # an idle/unknown printer is a genuine command failure.
  4339. post_dispatch_state = getattr(printer_manager.get_status(item.printer_id), "state", None)
  4340. if post_dispatch_state in _ACTIVE_PRINT_STATES:
  4341. logger.info(
  4342. "Queue item %s: printer %s became busy (state=%s) before the start "
  4343. "command was sent — deferring, reverting item to pending (#2598)",
  4344. item.id,
  4345. item.printer_id,
  4346. post_dispatch_state,
  4347. )
  4348. item.status = "pending"
  4349. item.started_at = None
  4350. await db.commit()
  4351. return
  4352. # Print command failed - revert status
  4353. item.status = "failed"
  4354. item.error_message = "Failed to send print command to printer"
  4355. item.completed_at = datetime.now(timezone.utc)
  4356. await db.commit()
  4357. logger.error(
  4358. f"Queue item {item.id}: Failed to start print on {printer.name} ({printer.model}) - "
  4359. f"printer_manager.start_print() returned False. "
  4360. f"This may indicate: printer not connected, MQTT error, unsupported model configuration, or firmware issue. "
  4361. f"Check printer status and backend logs for details."
  4362. )
  4363. # Send failure notification
  4364. await notification_service.on_queue_job_failed(
  4365. job_name=filename.replace(".gcode.3mf", "").replace(".3mf", ""),
  4366. printer_id=printer.id,
  4367. printer_name=printer.name,
  4368. reason="Failed to send print command to printer - check printer connection and status",
  4369. db=db,
  4370. )
  4371. try:
  4372. await ws_manager.send_queue_item_failed(
  4373. user_id=toast_uid,
  4374. queue_item_id=item.id,
  4375. printer_id=item.printer_id,
  4376. reason="start_command_failed",
  4377. )
  4378. except Exception:
  4379. pass
  4380. await self._power_off_if_needed(db, item)
  4381. @staticmethod
  4382. async def _watchdog_print_start(
  4383. queue_item_id: int,
  4384. printer_id: int,
  4385. pre_state: str,
  4386. pre_subtask_id: str | None = None,
  4387. pre_gcode_file: str | None = None,
  4388. timeout: float = 90.0,
  4389. phase_b_timeout: float = 180.0,
  4390. poll_interval: float = 3.0,
  4391. created_by_id: int | None = None,
  4392. ) -> None:
  4393. """Revert a queue item if the printer never acknowledges the start command.
  4394. Bambuddy optimistically marks the queue item as "printing" right after the
  4395. MQTT project_file publish succeeds locally. The watchdog runs in two phases:
  4396. Phase A (up to ``timeout``): wait for either an active-state transition
  4397. or a ``subtask_id`` advance past ``pre_subtask_id``. State alone is the
  4398. primary signal; subtask_id advance handles the H2D case where state can
  4399. sit at FINISH for ~50 s after the printer accepted ``project_file``
  4400. before flipping to PREPARE (#1078). If neither happens, the MQTT publish
  4401. was lost on a half-broken session (#887/#936) — revert and force
  4402. reconnect (the #967 recovery path).
  4403. Phase B (up to ``phase_b_timeout``, only if Phase A exited on subtask_id
  4404. alone): keep watching for the active-state transition. subtask_id alone
  4405. proves the file landed but not that the printer started — and a printer
  4406. that accepts the command but stays at IDLE/FINISH indefinitely (e.g.
  4407. cloud+LAN re-auth dance after a power cycle on old firmware, #1678)
  4408. used to leave the queue item stuck in 'printing' forever because the
  4409. old watchdog returned success as soon as subtask_id advanced. If Phase
  4410. B times out, revert the queue item so the user can retry without
  4411. restarting Bambuddy. Skip ``force_reconnect`` here: the file landed and
  4412. a forced reconnect mid-parse triggers 0500_4003 (#1150).
  4413. Phase A timeout raised from 45 s → 90 s as belt-and-braces for slow
  4414. transitions that also don't emit an early subtask_id tick.
  4415. Both phases also watch for ``HMS_MQTT_VERIFY_FAILED``. A printer that
  4416. refuses to verify our commands will never start this job or any other,
  4417. so waiting out the full 270 s and re-uploading the 3MF twice more only
  4418. burns an upload slot the rest of the farm is queued behind — that path
  4419. is for a printer that might still come good, which this one cannot
  4420. (#2732). It fails the item on the spot with the actual reason instead.
  4421. """
  4422. last_status = None
  4423. landed_on_subtask = False
  4424. # Latched, not level-tested: state.hms_errors is rebuilt from scratch on
  4425. # every push carrying an `hms` key, so the fault can come and go between
  4426. # 3-second polls. Seeing it once inside the dispatch window is enough.
  4427. command_rejected = False
  4428. # Latched for the same reason as command_rejected: drying can finish, or
  4429. # be stopped by the user, part-way through the dispatch window. Seeing it
  4430. # once is what matters — it is the state the printer was in when it
  4431. # declined to start (#2758).
  4432. drying_ams_ids: list[int] = []
  4433. deadline = time.monotonic() + timeout
  4434. while time.monotonic() < deadline:
  4435. await asyncio.sleep(poll_interval)
  4436. status = printer_manager.get_status(printer_id)
  4437. if not status:
  4438. # Printer disconnected — don't mess with the DB. Drop the
  4439. # in-memory dispatch hold too so a fresh dispatch can retry
  4440. # once the printer comes back; the hard timeout would
  4441. # otherwise hold the printer unnecessarily.
  4442. scheduler._release_dispatch_hold(printer_id)
  4443. return
  4444. last_status = status
  4445. if status.state in _ACTIVE_PRINT_STATES:
  4446. # Printer is actively processing the job — release the
  4447. # post-dispatch hold so the next pending item for this printer
  4448. # can be evaluated normally. We do NOT accept arbitrary state
  4449. # transitions: a printer going FINISH -> IDLE (user dismissed
  4450. # the post-print prompt without accepting our project_file)
  4451. # would otherwise look like "command landed" and leave the
  4452. # queue item stuck in 'printing' forever (#1370).
  4453. scheduler._release_dispatch_hold(printer_id)
  4454. try:
  4455. await ws_manager.send_queue_item_acked(
  4456. user_id=created_by_id,
  4457. queue_item_id=queue_item_id,
  4458. printer_id=printer_id,
  4459. )
  4460. except Exception:
  4461. pass
  4462. return
  4463. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  4464. # Checked only after the active-state exit above: a stale HMS left
  4465. # over from an earlier job must never abort a print that is visibly
  4466. # running. An actually-refused command leaves the printer idle, so
  4467. # this ordering costs the detection nothing.
  4468. if _mqtt_commands_rejected(status):
  4469. command_rejected = True
  4470. break
  4471. if pre_subtask_id is not None and status.subtask_id is not None and status.subtask_id != pre_subtask_id:
  4472. # Phase A exit — printer accepted the file (subtask_id flipped
  4473. # to our submission id). Don't return yet: the printer may
  4474. # have accepted the command but never actually start (e.g.
  4475. # cloud+LAN re-auth dance after a power cycle, #1678). Phase
  4476. # B watches for the active-state transition.
  4477. landed_on_subtask = True
  4478. break
  4479. if landed_on_subtask and not command_rejected:
  4480. phase_b_deadline = time.monotonic() + phase_b_timeout
  4481. while time.monotonic() < phase_b_deadline:
  4482. await asyncio.sleep(poll_interval)
  4483. status = printer_manager.get_status(printer_id)
  4484. if not status:
  4485. scheduler._release_dispatch_hold(printer_id)
  4486. return
  4487. last_status = status
  4488. if status.state in _ACTIVE_PRINT_STATES:
  4489. scheduler._release_dispatch_hold(printer_id)
  4490. try:
  4491. await ws_manager.send_queue_item_acked(
  4492. user_id=created_by_id,
  4493. queue_item_id=queue_item_id,
  4494. printer_id=printer_id,
  4495. )
  4496. except Exception:
  4497. pass
  4498. return
  4499. drying_ams_ids = drying_ams_ids or _drying_ams_ids(status)
  4500. # Same ordering rule as Phase A: a running print wins over a
  4501. # lingering HMS.
  4502. if _mqtt_commands_rejected(status):
  4503. command_rejected = True
  4504. break
  4505. # No active-state transition. Revert the item so the scheduler can retry.
  4506. # Drop the in-memory hold so the retry isn't blocked by it.
  4507. scheduler._release_dispatch_hold(printer_id)
  4508. # Logged on every failed dispatch window, not just the last one, so a
  4509. # support bundle shows the correlation from the first attempt rather than
  4510. # only after the retry budget is spent (#2758).
  4511. if drying_ams_ids:
  4512. logger.info(
  4513. "Queue item %s: printer %d never started while AMS %s drying — this may be why, see #2758",
  4514. queue_item_id,
  4515. printer_id,
  4516. ", ".join(str(i) for i in drying_ams_ids),
  4517. )
  4518. # Four outcomes from the revert attempt, each routed differently:
  4519. # "reverted": row flipped from printing -> pending, run recovery
  4520. # "gave_up": same, but the retry budget is spent — row failed
  4521. # rather than pending, so it stops going round again
  4522. # "already_moved_on": item.status != 'printing' (completed/cancelled by
  4523. # on_print_complete or user). Skip recovery entirely
  4524. # — the print clearly landed somewhere even if the
  4525. # watchdog didn't see the active-state transition.
  4526. # "revert_failed": SQLite contention exhausted retries. Still run
  4527. # recovery so the MQTT session gets a fresh client_id
  4528. # on the half-broken-session path.
  4529. #
  4530. # The retry budget (#2555): reverting to 'pending' hands the item straight
  4531. # back to the next queue pass, which re-uploads the whole 3MF and waits out
  4532. # the watchdog again. For a printer that is genuinely wedged that loop never
  4533. # ends — the reporter had one printer "since this morning still not launch"
  4534. # — and each lap also consumes an upload slot that the other printers in the
  4535. # farm are waiting on. Retrying is right; retrying forever is not.
  4536. async def _do_revert(db):
  4537. item = await db.get(PrintQueueItem, queue_item_id)
  4538. if not item or item.status != "printing":
  4539. return "already_moved_on"
  4540. item.dispatch_attempts = (item.dispatch_attempts or 0) + 1
  4541. item.started_at = None
  4542. # Charge the attempt to the candidate that was actually dispatched, so
  4543. # a cross-model item (#671) reaches for its other file next lap instead
  4544. # of retrying the printer that just failed to start. Matched by file
  4545. # because that is what the resolver copied onto the row.
  4546. if item.library_file_id is not None:
  4547. await db.execute(
  4548. update(PrintQueueVariant)
  4549. .where(PrintQueueVariant.queue_item_id == item.id)
  4550. .where(PrintQueueVariant.library_file_id == item.library_file_id)
  4551. .values(attempt_count=PrintQueueVariant.attempt_count + 1)
  4552. )
  4553. if command_rejected:
  4554. # No retry budget for this one: the printer refused to verify the
  4555. # command, and re-uploading the same 3MF to the same printer will
  4556. # be refused the same way. Fail now with the fix rather than after
  4557. # three laps of a message about SD cards (#2732).
  4558. item.status = "failed"
  4559. item.error_message = (
  4560. "The printer rejected the print command: MQTT command verification failed "
  4561. "(HMS 0500-0500-0001-0007). Enable Developer Mode on the printer, restart it, "
  4562. "then start the job again."
  4563. )
  4564. item.completed_at = datetime.now(timezone.utc)
  4565. await db.commit()
  4566. return "command_rejected"
  4567. if item.dispatch_attempts >= DISPATCH_MAX_ATTEMPTS:
  4568. item.status = "failed"
  4569. if drying_ams_ids:
  4570. # #2758: the generic message below sent the reporter looking
  4571. # at the SD card while the actual obstacle — AMS units in a
  4572. # drying cycle — was on screen the whole time. Name what we
  4573. # observed and let the user judge it; Bambuddy does not stop
  4574. # the cycle itself, because on this hardware drying can run
  4575. # alongside a print and stopping it may not be the fix.
  4576. units = ", ".join(f"AMS {i}" for i in drying_ams_ids)
  4577. item.error_message = (
  4578. f"The printer accepted the file but never started printing, after "
  4579. f"{item.dispatch_attempts} attempts. {units} "
  4580. f"{'was' if len(drying_ams_ids) == 1 else 'were'} drying throughout — "
  4581. f"some printers refuse to begin a print while an AMS is in a drying "
  4582. f"cycle, and an AMS drying without its external power supply can also "
  4583. f"leave too little power for the start-of-print calibration. Stop the "
  4584. f"drying, or connect the AMS power supply, and start the job again."
  4585. )
  4586. else:
  4587. item.error_message = (
  4588. f"The printer accepted the file but never started printing, after "
  4589. f"{item.dispatch_attempts} attempts. Check the printer's screen for a "
  4590. f"prompt or error, confirm its SD card is readable, and start the job again."
  4591. )
  4592. item.completed_at = datetime.now(timezone.utc)
  4593. await release_budget_reservation(
  4594. db,
  4595. source_type="print_queue",
  4596. source_id=item.id,
  4597. status="released",
  4598. )
  4599. await db.commit()
  4600. return "gave_up"
  4601. item.status = "pending"
  4602. await db.commit()
  4603. return "reverted"
  4604. try:
  4605. revert_outcome = await run_with_retry(_do_revert, label=f"watchdog revert item={queue_item_id}")
  4606. except Exception as e:
  4607. logger.warning(
  4608. "Queue item %s: failed to revert to 'pending' (printer %d): %s — "
  4609. "scheduler may keep treating this item as in-flight",
  4610. queue_item_id,
  4611. printer_id,
  4612. e,
  4613. )
  4614. revert_outcome = "revert_failed"
  4615. if revert_outcome == "already_moved_on":
  4616. # Preserves the pre-#1370 early-return: if on_print_complete (or any
  4617. # other path) already moved the item past 'printing', don't run the
  4618. # MQTT session-recovery logic below — a forced reconnect on a healthy
  4619. # session breaks ongoing prints on the same printer.
  4620. return
  4621. total_timeout = timeout + (phase_b_timeout if landed_on_subtask else 0.0)
  4622. if revert_outcome == "command_rejected":
  4623. logger.error(
  4624. "Queue item %s: printer %d reported HMS %s (MQTT command verification "
  4625. "failed) — the print command was rejected, not lost. Failing the item "
  4626. "without retrying; enable Developer Mode on the printer and restart it (#2732)",
  4627. queue_item_id,
  4628. printer_id,
  4629. HMS_MQTT_VERIFY_FAILED,
  4630. )
  4631. await scheduler._notify_dispatch_gave_up(
  4632. queue_item_id,
  4633. printer_id,
  4634. created_by_id,
  4635. reason="Printer rejected the print command (MQTT command verification failed)",
  4636. )
  4637. # Same reasoning as the landed_on_subtask path below: the file is on
  4638. # the printer and a forced reconnect would only add 0500_4003 to a
  4639. # problem that has nothing to do with the MQTT session (#1150).
  4640. return
  4641. if revert_outcome == "gave_up":
  4642. logger.error(
  4643. "Queue item %s: printer %d never started the print after %d dispatch "
  4644. "attempts (last one waited %.0fs) — marking the item failed instead of "
  4645. "re-uploading it again (#2555)",
  4646. queue_item_id,
  4647. printer_id,
  4648. DISPATCH_MAX_ATTEMPTS,
  4649. total_timeout,
  4650. )
  4651. await scheduler._notify_dispatch_gave_up(queue_item_id, printer_id, created_by_id)
  4652. elif revert_outcome == "reverted":
  4653. if landed_on_subtask:
  4654. logger.warning(
  4655. "Queue item %s: printer %d accepted project_file (subtask_id "
  4656. "advanced) but never transitioned to an active state within "
  4657. "%.0fs — printer wedged post-acceptance; reverted to 'pending' "
  4658. "for retry (#1678)",
  4659. queue_item_id,
  4660. printer_id,
  4661. total_timeout,
  4662. )
  4663. else:
  4664. logger.warning(
  4665. "Queue item %s: printer %d did not respond to print command within "
  4666. "%.0fs (state still %s, subtask_id still %s) — reverted to 'pending' "
  4667. "for retry (#967)",
  4668. queue_item_id,
  4669. printer_id,
  4670. timeout,
  4671. pre_state,
  4672. pre_subtask_id,
  4673. )
  4674. # Phase B was entered iff subtask_id advanced, which means the
  4675. # project_file landed on the printer. A forced reconnect at this point
  4676. # would interrupt the printer's parse and trigger 0500_4003 (#1150) —
  4677. # skip the recovery entirely.
  4678. if landed_on_subtask:
  4679. return
  4680. # Phase A timeout path: if the printer's gcode_file changed since
  4681. # pre-dispatch, the project_file command landed and the printer is
  4682. # parsing — a forced reconnect mid-parse triggers 0500_4003 (#1150).
  4683. # If gcode_file is unchanged, the publish was silently swallowed
  4684. # (#887/#936) and force_reconnect recovery is what we want.
  4685. client = printer_manager.get_client(printer_id)
  4686. current_gcode_file = getattr(last_status, "gcode_file", None) if last_status else None
  4687. publish_landed = current_gcode_file is not None and current_gcode_file != pre_gcode_file
  4688. if publish_landed:
  4689. logger.warning(
  4690. "Queue item %s: gcode_file changed to %r (was %r) — printer "
  4691. "received the command and is parsing slowly. Skipping forced "
  4692. "MQTT reconnect to avoid 0500_4003 mid-parse (#1150).",
  4693. queue_item_id,
  4694. current_gcode_file,
  4695. pre_gcode_file,
  4696. )
  4697. elif client and hasattr(client, "force_reconnect_stale_session"):
  4698. client.force_reconnect_stale_session(
  4699. f"queue print command unacknowledged after {timeout:.0f}s "
  4700. f"(state still {pre_state}, gcode_file {current_gcode_file!r})"
  4701. )
  4702. # Global scheduler instance
  4703. scheduler = PrintScheduler()