print_scheduler.py 267 KB

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