print_scheduler.py 294 KB

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