print_scheduler.py 301 KB

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