bambu_mqtt.py 274 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607
  1. """Bambu Lab MQTT communication service.
  2. IMPORTANT: Always use qos=1 for all MQTT publish calls!
  3. The printer ignores qos=0 messages when busy broadcasting status updates.
  4. Using qos=1 ensures the printer acknowledges and processes our commands immediately.
  5. This was discovered when K-profile requests with qos=0 took 20-30 seconds,
  6. but with qos=1 they respond instantly.
  7. """
  8. import asyncio
  9. import json
  10. import logging
  11. import os
  12. import ssl
  13. import threading
  14. import time
  15. from collections import deque
  16. from collections.abc import Callable
  17. from dataclasses import dataclass, field
  18. from datetime import datetime, timezone
  19. import paho.mqtt.client as mqtt
  20. from backend.app.services.hms_actions import HMSAction, get_actions_for_error_code
  21. logger = logging.getLogger(__name__)
  22. # AMS module name prefixes used in get_version responses.
  23. # The numeric suffix after '/' is the AMS unit ID as reported in push_status.
  24. # "ams/<id>" – original AMS (X1C, X1E, P1S, …)
  25. # "n3f/<id>" – AMS 2 Pro (H2D Pro and similar)
  26. # "n3s/<id>" – AMS HT (H2D Pro and similar; IDs typically start at 128)
  27. _AMS_MODULE_PREFIXES = ("ams/", "n3f/", "n3s/")
  28. def parse_ams_filament_backup_from_cfg(cfg_raw: object) -> bool | None:
  29. """Extract AMS Filament Backup state from a Bambu push_status ``print.cfg`` value.
  30. OrcaSlicer reads bit 18 of the hex string via
  31. ``get_flag_bits(cfg, 18)`` (DeviceManager.cpp:4961). Old-protocol families
  32. (A1 / A1 Mini) omit ``cfg`` entirely; this returns ``None`` for any input
  33. that doesn't yield a clean integer so downstream consumers preserve today's
  34. behaviour rather than treating "absent" as "OFF".
  35. """
  36. if not isinstance(cfg_raw, str) or not cfg_raw:
  37. return None
  38. try:
  39. return bool((int(cfg_raw, 16) >> 18) & 1)
  40. except ValueError:
  41. return None
  42. def apply_tray_exist_bits(
  43. units: list,
  44. tray_exist_bits_str: str | int | None,
  45. *,
  46. power_on_flag: bool = True,
  47. log_label: str | None = None,
  48. ) -> int:
  49. """Wipe stale per-tray filament fields on slots whose `tray_exist_bits` bit is 0.
  50. `tray_exist_bits` is firmware's canonical "which slots have a spool" bitmask
  51. (BambuStudio uses it too). For every slot whose bit is 0, promote the tray
  52. `state` to 9 (firmware's "no spool" code) and clear `tray_type` / `tray_color`
  53. / `tray_info_idx` / `tag_uid` / `tray_uuid` / `remain` etc so downstream
  54. readers (Bambuddy's AMS card, the VP slicer-facing cache, inventory short-
  55. circuits keyed on `state in {9, 10}`) all see one canonical empty-slot signal
  56. instead of guessing from payload shape (#1322, #147).
  57. Two callers share this helper to keep their views consistent:
  58. 1. ``_handle_ams_data`` for Bambuddy's internal AMS state (printer card).
  59. 2. ``virtual_printer.mqtt_bridge._on_printer_raw`` for the cached slicer-
  60. facing push_status (#1726 — without this the VP would forward stale
  61. per-tray fields for empty slots, and BambuStudio's Sync would render
  62. phantom loaded slots).
  63. Skipped only on the printer-shutdown pattern: all-zero bits paired with
  64. ``power_on_flag=False`` (#765). Non-zero bits with ``power_on_flag=False``
  65. is valid idle-printer state (#1365 — X1C between prints) and MUST be applied
  66. so spool removal is detected without requiring a manual reconnect.
  67. AMS-HT units (``id >= 128``) use a separate addressing scheme and are
  68. skipped here.
  69. `tray_exist_bits_str` is expected as a hex string (firmware sends it that
  70. way). Ints are tolerated for defensive symmetry but typically not seen
  71. on the wire. ``None`` / empty / unparseable → no-op.
  72. Mutates ``units`` in place. Returns the number of slots cleared.
  73. """
  74. if not tray_exist_bits_str:
  75. return 0
  76. try:
  77. if isinstance(tray_exist_bits_str, int):
  78. tray_exist_bits = tray_exist_bits_str
  79. else:
  80. tray_exist_bits = int(tray_exist_bits_str, 16)
  81. except (ValueError, TypeError):
  82. return 0
  83. if tray_exist_bits == 0 and not power_on_flag:
  84. return 0
  85. if not isinstance(units, list):
  86. return 0
  87. cleared = 0
  88. for ams_unit in units:
  89. if not isinstance(ams_unit, dict):
  90. continue
  91. ams_id_raw = ams_unit.get("id")
  92. if ams_id_raw is None:
  93. continue
  94. try:
  95. ams_id = int(ams_id_raw) if isinstance(ams_id_raw, str) else ams_id_raw
  96. except (ValueError, TypeError):
  97. continue
  98. if not isinstance(ams_id, int) or ams_id >= 128:
  99. # Skip AMS-HT (id >= 128) — separate addressing scheme.
  100. continue
  101. for tray in ams_unit.get("tray", []):
  102. if not isinstance(tray, dict):
  103. continue
  104. tray_id_raw = tray.get("id")
  105. if tray_id_raw is None:
  106. continue
  107. try:
  108. tray_id = int(tray_id_raw) if isinstance(tray_id_raw, str) else tray_id_raw
  109. except (ValueError, TypeError):
  110. continue
  111. if not isinstance(tray_id, int):
  112. continue
  113. global_bit = ams_id * 4 + tray_id
  114. slot_exists = (tray_exist_bits >> global_bit) & 1
  115. if slot_exists:
  116. continue
  117. tray["state"] = 9
  118. if tray.get("tray_type"):
  119. if log_label:
  120. logger.debug(
  121. f"[{log_label}] Clearing empty slot: AMS {ams_id} slot {tray_id} "
  122. f"(tray_exist_bits bit {global_bit} = 0)"
  123. )
  124. tray["tray_type"] = ""
  125. tray["tray_sub_brands"] = ""
  126. tray["tray_color"] = ""
  127. tray["tray_id_name"] = ""
  128. tray["tag_uid"] = "0000000000000000"
  129. tray["tray_uuid"] = "00000000000000000000000000000000"
  130. tray["tray_info_idx"] = ""
  131. tray["remain"] = 0
  132. cleared += 1
  133. return cleared
  134. @dataclass
  135. class MQTTLogEntry:
  136. """Log entry for MQTT message debugging."""
  137. timestamp: str
  138. topic: str
  139. direction: str # "in" or "out"
  140. payload: dict
  141. @dataclass
  142. class HMSError:
  143. """Health Management System error from printer."""
  144. code: str
  145. attr: int # Attribute value for constructing wiki URL
  146. module: int
  147. severity: int # 1=fatal, 2=serious, 3=common, 4=info
  148. message: str = ""
  149. # User-facing remediation actions from the bundled HMS catalog (e.g. "RESUME_PRINTING",
  150. # "CHECK_ASSISTANT"). Defaults to an empty list rather than None so the field always
  151. # satisfies HMSErrorResponse.actions: list[str] — a future code path that builds an
  152. # HMSError without explicitly passing actions can't silently land None on the schema
  153. # boundary and raise ValidationError at routes/printers.py response time.
  154. actions: list[str] = field(default_factory=list)
  155. # The `subtask_id` snapshotted from PrinterState when this error surfaced; Bambu's
  156. # HMS-aware commands echo it back as `job_id`. None for idle errors with no job.
  157. job_id: str | None = None
  158. # HMS short codes the firmware emits during normal user-cancel sequences.
  159. # These aren't faults — they're status echoes that confirm the cancel happened.
  160. # Filtering them at parse-time keeps them out of state.hms_errors entirely,
  161. # so they don't drive the printer card's "X problem" badge, the red pip, or
  162. # any other consumer that treats hms_errors as the active-fault list.
  163. _HMS_USER_ACTION_CODES: frozenset[str] = frozenset(
  164. {
  165. "0300_400C", # "The task was canceled."
  166. "0500_400E", # "Printing was cancelled."
  167. }
  168. )
  169. @dataclass
  170. class KProfile:
  171. """Pressure advance (K) calibration profile from printer."""
  172. slot_id: int
  173. extruder_id: int
  174. nozzle_id: str
  175. nozzle_diameter: str
  176. filament_id: str
  177. name: str
  178. k_value: str
  179. n_coef: str = "0.000000"
  180. ams_id: int = 0
  181. tray_id: int = -1
  182. setting_id: str | None = None
  183. @dataclass
  184. class NozzleInfo:
  185. """Nozzle hardware configuration."""
  186. nozzle_type: str = "" # "stainless_steel" or "hardened_steel"
  187. nozzle_diameter: str = "" # e.g., "0.4"
  188. @dataclass
  189. class FilaSwitchState:
  190. """Filament Track Switch (FTS) accessory state.
  191. The FTS is an external accessory that mediates filament routing between an
  192. AMS and the printer's extruders. When installed, the AMS no longer has a
  193. fixed extruder assignment — any slot can be routed to any extruder via the
  194. track switch. Detected from print.device.fila_switch in MQTT.
  195. """
  196. installed: bool = False
  197. # in[track] = currently loaded slot for that track (-1 = empty). The slot
  198. # value is reported as observed in MQTT (treated as a global tray ID).
  199. in_slots: list[int] = field(default_factory=list)
  200. # out[track] = extruder this track terminates at (0 = right/main, 1 = left)
  201. out_extruders: list[int] = field(default_factory=list)
  202. stat: int = 0 # status flags (0 = idle)
  203. info: int = 0 # info flags
  204. @dataclass
  205. class PrintOptions:
  206. """AI detection and print options from xcam data."""
  207. # Core AI detectors
  208. spaghetti_detector: bool = False
  209. print_halt: bool = False
  210. halt_print_sensitivity: str = "medium" # Spaghetti sensitivity
  211. first_layer_inspector: bool = False
  212. printing_monitor: bool = False # AI print quality monitoring
  213. buildplate_marker_detector: bool = False
  214. allow_skip_parts: bool = False
  215. # Additional AI detectors - decoded from cfg bitmask
  216. nozzle_clumping_detector: bool = True
  217. nozzle_clumping_sensitivity: str = "medium"
  218. pileup_detector: bool = True
  219. pileup_sensitivity: str = "medium"
  220. airprint_detector: bool = True
  221. airprint_sensitivity: str = "medium"
  222. auto_recovery_step_loss: bool = True # Uses print.print_option command
  223. filament_tangle_detect: bool = False
  224. @dataclass
  225. class PrinterState:
  226. connected: bool = False
  227. state: str = "unknown"
  228. current_print: str | None = None
  229. subtask_name: str | None = None
  230. progress: float = 0.0
  231. remaining_time: int = 0
  232. layer_num: int = 0
  233. total_layers: int = 0
  234. temperatures: dict = field(default_factory=dict)
  235. raw_data: dict = field(default_factory=dict)
  236. gcode_file: str | None = None
  237. subtask_id: str | None = None
  238. hms_errors: list = field(default_factory=list) # List of HMSError
  239. kprofiles: list = field(default_factory=list) # List of KProfile
  240. sdcard: bool = False # SD card inserted
  241. store_to_sdcard: bool = False # Store sent files on SD card (home_flag bit 11)
  242. timelapse: bool = False # Timelapse recording active
  243. ipcam: bool = False # Live view / camera streaming enabled
  244. wifi_signal: int | None = None # WiFi signal strength in dBm
  245. wired_network: bool = False # Ethernet connection detected (home_flag bit 18)
  246. door_open: bool = False # Enclosure door open (home_flag bit 23, X1/P1S/P2S/H2*)
  247. # Nozzle hardware info (for dual nozzle printers, index 0 = left, 1 = right)
  248. nozzles: list = field(default_factory=lambda: [NozzleInfo(), NozzleInfo()])
  249. # AI detection and print options
  250. print_options: PrintOptions = field(default_factory=PrintOptions)
  251. # Calibration stage tracking (from stg_cur and stg fields)
  252. stg_cur: int = -1 # Current stage index (-1 = not calibrating)
  253. stg: list = field(default_factory=list) # List of stages to execute
  254. # Air conditioning mode (0=cooling, 1=heating)
  255. airduct_mode: int = 0
  256. # Print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  257. speed_level: int = 2
  258. # Chamber light on/off
  259. chamber_light: bool = False
  260. # Active extruder for dual nozzle (0=right, 1=left) - from device.extruder.info[X].hnow
  261. active_extruder: int = 0
  262. # Currently loaded tray (global ID): 254/255 = external spools, 255 = no filament on legacy printers
  263. tray_now: int = 255
  264. # Last valid tray_now (0-253) — survives unload (255) for usage tracking after print completes
  265. last_loaded_tray: int = -1
  266. # Pending load target - used to track what tray we're loading for H2D disambiguation
  267. pending_tray_target: int | None = None
  268. # AMS status for filament change tracking (from print.ams.ams_status field)
  269. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  270. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration, etc.
  271. ams_status: int = 0
  272. ams_status_main: int = 0 # (ams_status >> 8) & 0xFF
  273. ams_status_sub: int = 0 # ams_status & 0xFF
  274. # mc_print_sub_stage - filament change step indicator from print.mc_print_sub_stage
  275. # Used by OrcaSlicer/BambuStudio to track progress during filament load/unload
  276. mc_print_sub_stage: int = 0
  277. # AMS mapping for dual nozzle: which slot is active (from ams.ams_exist_bits/tray_exist_bits)
  278. ams_mapping: list = field(default_factory=list)
  279. # Per-AMS extruder map: {ams_id: extruder_id} where 0=right/main, 1=left/deputy
  280. ams_extruder_map: dict = field(default_factory=dict)
  281. # Filament Track Switch (FTS) accessory — when installed, AMS info reports
  282. # bits 8-11 = 0xE (uninitialized) because routing is dynamic. See #1162.
  283. fila_switch: "FilaSwitchState" = field(default_factory=lambda: FilaSwitchState())
  284. # Plate dispatched by Bambuddy for the current print. Some firmware versions
  285. # (P1S 01.10.00.00) only put the .3mf filename in print.gcode_file, so the
  286. # regex used to derive the plate number from the path always falls back to
  287. # plate 1 — and the printer card shows the wrong thumbnail (#1166). When
  288. # Bambuddy dispatches the print itself we know the plate authoritatively;
  289. # we record it here and prefer it over the gcode_file regex. The subtask
  290. # field guards against staleness: if the printer is currently running a
  291. # different subtask (e.g. a Studio-direct dispatch), these values are
  292. # ignored. Cleared on disconnect.
  293. dispatched_plate_id: int | None = None
  294. dispatched_subtask: str | None = None
  295. # H2D per-extruder tray_now from snow field: {extruder_id: normalized_global_tray_id}
  296. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  297. h2d_extruder_snow: dict = field(default_factory=dict)
  298. # H2C nozzle rack: full device.nozzle.info array for tool-changer printers (>2 nozzles)
  299. nozzle_rack: list = field(default_factory=list)
  300. # Timestamp of last AMS data update (for RFID refresh detection)
  301. last_ams_update: float = 0.0
  302. # Printable objects for skip object functionality: {identify_id: object_name}
  303. printable_objects: dict = field(default_factory=dict)
  304. # Objects that have been skipped during the current print
  305. skipped_objects: list = field(default_factory=list)
  306. # Fan speeds (0-100 percentage, None if not available for this model)
  307. cooling_fan_speed: int | None = None # Part cooling fan
  308. big_fan1_speed: int | None = None # Auxiliary fan
  309. big_fan2_speed: int | None = None # Chamber/exhaust fan
  310. heatbreak_fan_speed: int | None = None # Hotend heatbreak fan
  311. # Tray change history during current print: [(global_tray_id, layer_num), ...]
  312. # Used by usage tracker to split filament weight on mid-print tray switch
  313. tray_change_log: list = field(default_factory=list)
  314. # Firmware version info (from info.module[name="ota"].sw_ver)
  315. firmware_version: str | None = None
  316. # Developer LAN mode: parsed from MQTT "fun" field bit 0x20000000
  317. # True = dev mode ON (no encryption), False = dev mode OFF (encryption required), None = unknown
  318. developer_mode: bool | None = None
  319. # AMS Filament Backup: bit 18 of top-level print.cfg hex on new-protocol Bambu
  320. # printers (H/X/P/H2 families). True=ON, False=OFF, None=unknown (e.g. A1 family
  321. # which uses the old protocol path; field not yet found). Consumers must treat
  322. # None as "no opinion" — preserving today's behaviour, NOT as "disabled".
  323. ams_filament_backup: bool | None = None
  324. # Stage name mapping from BambuStudio DeviceManager.cpp
  325. STAGE_NAMES = {
  326. 0: "Printing",
  327. 1: "Auto bed leveling",
  328. 2: "Heatbed preheating",
  329. 3: "Vibration compensation",
  330. 4: "Changing filament",
  331. 5: "M400 pause",
  332. 6: "Paused (filament ran out)",
  333. 7: "Heating nozzle",
  334. 8: "Calibrating dynamic flow",
  335. 9: "Scanning bed surface",
  336. 10: "Inspecting first layer",
  337. 11: "Identifying build plate type",
  338. 12: "Calibrating Micro Lidar",
  339. 13: "Homing toolhead",
  340. 14: "Cleaning nozzle tip",
  341. 15: "Checking extruder temperature",
  342. 16: "Paused by the user",
  343. 17: "Pause (front cover fall off)",
  344. 18: "Calibrating the micro lidar",
  345. 19: "Calibrating flow ratio",
  346. 20: "Pause (nozzle temperature malfunction)",
  347. 21: "Pause (heatbed temperature malfunction)",
  348. 22: "Filament unloading",
  349. 23: "Pause (step loss)",
  350. 24: "Filament loading",
  351. 25: "Motor noise cancellation",
  352. 26: "Pause (AMS offline)",
  353. 27: "Pause (low speed of the heatbreak fan)",
  354. 28: "Pause (chamber temperature control problem)",
  355. 29: "Cooling chamber",
  356. 30: "Pause (Gcode inserted by user)",
  357. 31: "Motor noise showoff",
  358. 32: "Pause (nozzle clumping)",
  359. 33: "Pause (cutter error)",
  360. 34: "Pause (first layer error)",
  361. 35: "Pause (nozzle clog)",
  362. 36: "Measuring motion precision",
  363. 37: "Enhancing motion precision",
  364. 38: "Measure motion accuracy",
  365. 39: "Nozzle offset calibration",
  366. 40: "High temperature auto bed leveling",
  367. 41: "Auto Check: Quick Release Lever",
  368. 42: "Auto Check: Door and Upper Cover",
  369. 43: "Laser Calibration",
  370. 44: "Auto Check: Platform",
  371. 45: "Confirming BirdsEye Camera location",
  372. 46: "Calibrating BirdsEye Camera",
  373. 47: "Auto bed leveling - phase 1",
  374. 48: "Auto bed leveling - phase 2",
  375. 49: "Heating chamber",
  376. 50: "Cooling heatbed",
  377. 51: "Printing calibration lines",
  378. 52: "Auto Check: Material",
  379. 53: "Live View Camera Calibration",
  380. 54: "Waiting for heatbed temperature",
  381. 55: "Auto Check: Material Position",
  382. 56: "Cutting Module Offset Calibration",
  383. 57: "Measuring Surface",
  384. 58: "Thermal Preconditioning",
  385. 59: "Homing Blade Holder",
  386. 60: "Calibrating Camera Offset",
  387. 61: "Calibrating Blade Holder Position",
  388. 62: "Hotend Pick and Place Test",
  389. 63: "Waiting for Chamber temperature",
  390. 64: "Preparing Hotend",
  391. 65: "Calibrating nozzle clumping detection",
  392. 66: "Purifying the chamber air",
  393. 74: "Preparing", # Seen on H2D during print preparation
  394. 77: "Preparing AMS",
  395. }
  396. def get_stage_name(stage: int) -> str:
  397. """Get human-readable stage name from stage number."""
  398. return STAGE_NAMES.get(stage, f"Unknown stage ({stage})")
  399. class BambuMQTTClient:
  400. """MQTT client for Bambu Lab printer communication."""
  401. MQTT_PORT = 8883
  402. # Class-level cache: serial_number -> False when request topic is known unsupported.
  403. # Persists across client instances so reconnects don't re-trigger failed subscriptions.
  404. _request_topic_cache: dict[str, bool] = {}
  405. # Counter for generating unique MQTT client IDs across instances.
  406. _client_instance_counter: int = 0
  407. def __init__(
  408. self,
  409. ip_address: str,
  410. serial_number: str,
  411. access_code: str,
  412. model: str | None = None,
  413. on_state_change: Callable[[PrinterState], None] | None = None,
  414. on_print_start: Callable[[dict], None] | None = None,
  415. on_print_complete: Callable[[dict], None] | None = None,
  416. on_ams_change: Callable[[list], None] | None = None,
  417. on_layer_change: Callable[[int], None] | None = None,
  418. on_bed_temp_update: Callable[[float], None] | None = None,
  419. on_drying_complete: Callable[[int], None] | None = None,
  420. on_print_running_observed: Callable[[dict], None] | None = None,
  421. on_finish_photo_moment: Callable[[dict], None] | None = None,
  422. ):
  423. self.ip_address = ip_address
  424. self.serial_number = serial_number
  425. self.access_code = access_code
  426. self.model = model
  427. self.on_state_change = on_state_change
  428. self.on_print_start = on_print_start
  429. self.on_print_complete = on_print_complete
  430. self.on_ams_change = on_ams_change
  431. self.on_layer_change = on_layer_change
  432. self.on_bed_temp_update = on_bed_temp_update
  433. # #1349: fired when an AMS unit's dry_time falls from >0 to 0 — i.e.
  434. # the drying cycle just finished (auto- or manually-triggered).
  435. # Receives the AMS id of the unit that finished drying.
  436. self.on_drying_complete = on_drying_complete
  437. # #1485 follow-up: fired the first time we see RUNNING state in a
  438. # session WHEN on_print_start was suppressed (Bambuddy started mid-
  439. # print, the #1304 first-push guard skipped the start event). Lets
  440. # main.py capture a fresh timelapse baseline at restart-recovery
  441. # time so the completion-time snapshot-diff still works. Receives
  442. # the same shape as on_print_start (filename / subtask_name /
  443. # remaining_time / raw_data / ams_mapping).
  444. self.on_print_running_observed = on_print_running_observed
  445. # #1721: fired the moment the printer enters the end-of-print
  446. # "Filament unloading" phase (stg_cur=22 while progress>=99 or
  447. # we've hit the last layer / remaining_time<=0). This is the
  448. # framing #1397 was after — toolhead parked, bed not yet
  449. # dropped — but reached via a clean state signal instead of
  450. # the per-layer M622 J1 macros which caused per-layer nozzle
  451. # parks on slicer profiles with Timelapse Type = Smooth.
  452. # A FINISH-state fallback below fires this same callback if
  453. # stage 22 never arrives (cancel mid-print, external-spool-
  454. # only prints, HMS halt before unload, firmware variants).
  455. self.on_finish_photo_moment = on_finish_photo_moment
  456. # Per-AMS previous dry_time, used to detect the falling edge above.
  457. # Seeded lazily as we observe each AMS unit.
  458. self._previous_dry_times: dict[int, int] = {}
  459. # Per-AMS active-cycle target params (filament + temp) we sent on the
  460. # last start. Bambu does not echo these back in the per-tick AMS push
  461. # — only the dry_time countdown — so we cache what we sent to drive
  462. # the UI badge. Cleared on stop or on the dry_time falling edge to 0.
  463. self._drying_targets: dict[int, dict[str, object]] = {}
  464. self.state = PrinterState()
  465. self._client: mqtt.Client | None = None
  466. self._loop: asyncio.AbstractEventLoop | None = None
  467. self._previous_gcode_state: str | None = None
  468. self._previous_gcode_file: str | None = None
  469. self._was_running: bool = False # Track if we've seen RUNNING state for current print
  470. self._completion_triggered: bool = False # Prevent duplicate completion triggers
  471. self._timelapse_during_print: bool = False # Track if timelapse was active during this print
  472. # #1721: one-shot guard so the end-of-print stage-22 detector
  473. # and the FINISH-state fallback don't both fire on the same
  474. # print. Reset to False on every print start.
  475. self._finish_photo_captured: bool = False
  476. self._last_valid_progress: float = 0.0 # Last non-zero progress (firmware resets on cancel)
  477. self._last_valid_layer_num: int = 0 # Last non-zero layer (firmware resets on cancel)
  478. # The subtask_id minted for the most recent start_print() command. The
  479. # printer echoes it back in status, but often not within the first few
  480. # seconds — so on_print_start uses this as the id source when the
  481. # printer hasn't reported it yet, letting queue/scheduled archives
  482. # persist a restart-stable id from the moment they dispatch (#1485).
  483. self.last_dispatch_subtask_id: str | None = None
  484. self._is_dual_nozzle: bool = False # Set when device.extruder.info has >= 2 entries
  485. self._message_log: deque[MQTTLogEntry] = deque(maxlen=100)
  486. self._logging_enabled: bool = False
  487. self._last_message_time: float = 0.0 # Track when we last received a message
  488. # Count of report-topic messages received since the last (re)connect.
  489. # Lets check_staleness() distinguish "printer never sent a status
  490. # report" (typically a wrong / mis-cased serial) from a normal quiet
  491. # gap mid-session. _zero_report_hint_logged keeps the actionable hint
  492. # to once per client lifetime so the stale loop doesn't spam it (#1465).
  493. self._report_messages_since_connect: int = 0
  494. self._zero_report_hint_logged: bool = False
  495. # Raw-message fan-out for VP MQTT bridge (non-proxy modes republish the
  496. # printer's pushes verbatim to slicers connected to a virtual printer).
  497. # Handlers receive (topic, payload_bytes) before JSON parsing.
  498. self._raw_message_handlers: list[Callable[[str, bytes], None]] = []
  499. self._disconnection_event: threading.Event | None = None
  500. self._previous_ams_hash: str | None = None # Track AMS changes
  501. # Cache AMS firmware/SN from get_version in case it arrives before AMS status
  502. # Key: ams_id (int). Value: {'sw_ver': str, 'sn': str}
  503. self._ams_version_cache: dict[int, dict[str, str]] = {}
  504. # Track which (ams_id, field) warnings have already been emitted this connection
  505. # so that missing-serial / missing-firmware warnings fire only once per connection.
  506. self._ams_version_warned: set[tuple[int | str, str]] = set()
  507. # K-profile command tracking
  508. self._sequence_id: int = 0
  509. self._pending_kprofile_response: asyncio.Event | None = None
  510. self._kprofile_response_data: list | None = None
  511. # Xcam hold timers - OrcaSlicer pattern: ignore incoming data for 3 seconds after command
  512. # Key: module_name, Value: timestamp when command was sent
  513. self._xcam_hold_start: dict[str, float] = {}
  514. self._xcam_hold_time: float = 3.0 # Ignore incoming data for 3 seconds after command
  515. # Track last requested tray ID for H2D dual-nozzle printers
  516. # H2D only reports slot number (0-3) in tray_now, not global tray ID
  517. # We use our tracked value to resolve the correct global ID
  518. self._last_load_tray_id: int | None = None
  519. # Captured ams_mapping from print commands on the request topic
  520. # Intercepts slicer/Bambuddy print commands to get the slot-to-tray mapping
  521. self._captured_ams_mapping: list[int] | None = None
  522. # Request topic subscription tracking
  523. # Some printer MQTT brokers (e.g. P1S, A1) reject subscriptions to the request
  524. # topic by killing the TCP connection. We detect this and gracefully degrade.
  525. # Check class-level cache first so new client instances don't retry known-bad subscriptions.
  526. self._request_topic_supported: bool = BambuMQTTClient._request_topic_cache.get(self.serial_number, True)
  527. self._request_topic_sub_mid: int | None = None
  528. self._request_topic_sub_time: float = 0.0
  529. self._request_topic_confirmed: bool = False
  530. # Developer mode probe: when the "fun" field is absent (A1/P1 printers),
  531. # we probe by sending an ams_filament_setting and checking the response.
  532. # "mqtt message verify failed" → dev mode OFF, success → dev mode ON.
  533. self._dev_mode_probed: bool = False
  534. self._dev_mode_needs_probe: bool = False # True after seeing a pushall without "fun"
  535. self._dev_mode_probe_seq: str | None = None
  536. self._dev_mode_probe_time: float = 0.0 # monotonic timestamp when probe was sent
  537. self._dev_mode_probe_failures: int = 0 # consecutive unanswered probes
  538. self._connect_time: float = 0.0 # monotonic timestamp of last _on_connect
  539. # Set when check_staleness() force-closes the socket to trigger reconnect.
  540. # Prevents _on_disconnect from redundantly broadcasting state (already done).
  541. self._stale_reconnecting: bool = False
  542. # Timestamp of last stale reconnect — prevents rapid-fire socket closes
  543. # when the frontend polls status faster than paho can reconnect.
  544. self._last_stale_reconnect: float = 0.0
  545. # Zombie session detection via ams_filament_setting response tracking (#887).
  546. # The dev-mode probe only runs on first connect; this catches zombie sessions
  547. # that develop later (telemetry flows but publishes silently fail).
  548. self._last_ams_cmd_time: float = 0.0 # monotonic time of last published command
  549. self._ams_cmd_unanswered: int = 0 # consecutive commands with no response
  550. @property
  551. def topic_subscribe(self) -> str:
  552. return f"device/{self.serial_number}/report"
  553. @property
  554. def topic_publish(self) -> str:
  555. return f"device/{self.serial_number}/request"
  556. @property
  557. def report_messages_since_connect(self) -> int:
  558. """Count of report-topic messages received since the latest (re)connect.
  559. Exposed for the connection diagnostic so it can distinguish "MQTT
  560. broker accepted us but the printer never published" (typically a
  561. wrong / mis-cased serial — #1622 follow-up to #1602) from a healthy
  562. bridge that happens to be idle right now. Zero immediately after a
  563. fresh connect is normal; zero after a full status push cycle is the
  564. wrong-serial failure mode.
  565. """
  566. return self._report_messages_since_connect
  567. # Maximum time (seconds) without a message before considering connection stale
  568. STALE_TIMEOUT = 60.0
  569. def is_stale(self) -> bool:
  570. """Check if the connection is stale (no messages for too long)."""
  571. if self._last_message_time == 0:
  572. return False # Never received a message yet
  573. time_since_last = time.time() - self._last_message_time
  574. return time_since_last > self.STALE_TIMEOUT
  575. # Minimum seconds between stale reconnect attempts. Frontend polls
  576. # status every few seconds — without a cooldown, each poll would
  577. # force-close the socket before paho has time to reconnect.
  578. STALE_RECONNECT_COOLDOWN = 30.0
  579. def check_staleness(self) -> bool:
  580. """Check staleness and update connected state if stale. Returns True if connected."""
  581. if self.state.connected and self.is_stale():
  582. # Don't force-close again if we already did recently — give paho
  583. # time to reconnect and the printer time to send its first message.
  584. now = time.time()
  585. if now - self._last_stale_reconnect < self.STALE_RECONNECT_COOLDOWN:
  586. return self.state.connected
  587. logger.warning(
  588. f"[{self.serial_number}] Connection stale - no message for {now - self._last_message_time:.1f}s, forcing reconnect"
  589. )
  590. # A connection that keeps going stale without ever receiving a
  591. # status report is almost always a wrong or mis-cased serial
  592. # number — the broker accepts the connection and the subscription
  593. # regardless, but the printer publishes to device/<real-serial>/
  594. # report, which is case-sensitive. Surface that once so the user
  595. # has something actionable instead of an endless reconnect loop.
  596. if self._report_messages_since_connect == 0 and not self._zero_report_hint_logged:
  597. self._zero_report_hint_logged = True
  598. logger.warning(
  599. "[%s] Connected and subscribed, but the printer has sent zero "
  600. "status reports. The most common cause is a wrong or mis-cased "
  601. "serial number — the device/<serial>/report MQTT topic is "
  602. "case-sensitive. Verify the serial number configured in Bambuddy "
  603. "exactly matches the printer.",
  604. self.serial_number,
  605. )
  606. self._last_stale_reconnect = now
  607. self.state.connected = False
  608. if self.on_state_change:
  609. self.on_state_change(self.state)
  610. # Route based on caller thread — see force_reconnect_stale_session.
  611. # check_staleness is normally called from FastAPI handlers (async,
  612. # gets the hard-reset path) but the dispatcher exists for safety.
  613. self._stale_reconnecting = True
  614. self._reset_client_for_reconnect()
  615. return self.state.connected
  616. def force_reconnect_stale_session(self, reason: str) -> None:
  617. # Heals the #887/#936/#1136 half-broken session: telemetry keeps
  618. # arriving but our publishes don't reach the printer.
  619. #
  620. # Two routing paths:
  621. #
  622. # Async-context callers (queue dispatch deadline)
  623. # → full client teardown + fresh client_id. Wipes paho's client-side
  624. # QoS 1 queue, which is exactly the #1136 reproducer: an unacked
  625. # `project_file` from the broken session would otherwise replay on
  626. # reconnect, mixing stale commands into the next dispatch and
  627. # triggering 0500_4003 SD R/W on the printer.
  628. #
  629. # Paho-network-thread callers (line ~2604/~2623 — dev-mode probe and
  630. # ams_filament_setting zombie detection inside `_update_state`)
  631. # → socket-close fallback. Calling `loop_stop()` from inside the
  632. # network thread would self-join and deadlock; the safe pattern is
  633. # to close the socket and let paho's own loop detect the broken
  634. # connection and auto-reconnect (same instance, same client_id —
  635. # queue replay is theoretically possible here but those paths have
  636. # always done socket-close and #1136 was specifically triggered
  637. # from the dispatch path).
  638. logger.warning("[%s] Forcing MQTT reconnect: %s", self.serial_number, reason)
  639. self._stale_reconnecting = True
  640. self.state.connected = False
  641. if self.on_state_change:
  642. self.on_state_change(self.state)
  643. self._reset_client_for_reconnect()
  644. def _reset_client_for_reconnect(self) -> None:
  645. """Route between hard-reset and socket-close based on caller thread.
  646. Hard-reset (preferred) requires we're not running on paho's network
  647. thread, since `loop_stop()` on the same thread deadlocks. Detect via
  648. ``asyncio.get_running_loop()`` — paho's callback thread has no loop;
  649. every legitimate hard-reset caller (FastAPI handlers, background
  650. async tasks) does."""
  651. try:
  652. loop = asyncio.get_running_loop()
  653. except RuntimeError:
  654. loop = None
  655. if loop is not None:
  656. self._loop = loop
  657. self._hard_reset_client()
  658. else:
  659. self._socket_close_for_reconnect()
  660. def _hard_reset_client(self) -> None:
  661. """Tear down the paho client entirely and rebuild it with a fresh
  662. client_id, so the broker drops the old session and paho's local
  663. QoS 1 queue is gone. Must NOT be called from paho's network thread.
  664. Caller is responsible for setting ``_stale_reconnecting`` and
  665. broadcasting the disconnected state."""
  666. old_client = self._client
  667. self._client = None
  668. if old_client is not None:
  669. try:
  670. old_client.disconnect() # MQTT DISCONNECT — broker drops session
  671. except Exception:
  672. pass
  673. try:
  674. old_client.loop_stop() # blocks briefly until the network thread exits
  675. except Exception:
  676. pass
  677. # Skip reconnect if no asyncio loop is available (test environment or
  678. # pre-init). The next initial connect() call from PrinterManager will
  679. # set up the client fresh.
  680. if self._loop is None:
  681. return
  682. try:
  683. self.connect(loop=self._loop)
  684. except Exception as e:
  685. logger.error("[%s] Hard reset reconnect failed: %s", self.serial_number, e)
  686. def _socket_close_for_reconnect(self) -> None:
  687. """Close the underlying socket so paho's loop thread detects the
  688. broken connection and triggers auto-reconnect on the SAME client
  689. instance. Safe to call from paho's own network thread (the loop
  690. polls the socket on every iteration and handles a closed socket
  691. gracefully). Used as a fallback when hard-reset isn't safe; queue
  692. replay remains theoretically possible here but #1136 specifically
  693. traced through the dispatch-deadline path which now hard-resets."""
  694. if self._client:
  695. try:
  696. sock = self._client.socket()
  697. if sock:
  698. sock.close()
  699. except Exception:
  700. pass
  701. def _on_connect(self, client, userdata, flags, rc, properties=None):
  702. if rc == 0:
  703. self.state.connected = True
  704. self._stale_reconnecting = False # Clear stale-reconnect flag on successful connect
  705. # Reset per-connection warning state so warnings fire once per (re)connection
  706. self._ams_version_warned = set()
  707. # Preserve cached developer_mode across auto-reconnects to avoid
  708. # re-probing on every reconnect. The probe (ams_filament_setting to
  709. # ext slot) can destabilize some firmware MQTT brokers, causing a
  710. # reconnect → probe → disconnect feedback loop (#887). Only probe
  711. # once when developer_mode is truly unknown (first connect).
  712. # Reset probe tracking so stale timeout state doesn't carry over.
  713. self._dev_mode_probed = False
  714. self._dev_mode_needs_probe = False
  715. self._dev_mode_probe_seq = None
  716. self._dev_mode_probe_time = 0.0
  717. self._dev_mode_probe_failures = 0
  718. self._connect_time = time.monotonic()
  719. self._report_messages_since_connect = 0
  720. self._last_ams_cmd_time = 0.0
  721. self._ams_cmd_unanswered = 0
  722. client.subscribe(self.topic_subscribe)
  723. # Subscribe to request topic for ams_mapping capture (if supported by broker)
  724. if self._request_topic_supported:
  725. result, mid = client.subscribe(self.topic_publish)
  726. if result == mqtt.MQTT_ERR_SUCCESS:
  727. self._request_topic_sub_mid = mid
  728. self._request_topic_sub_time = time.time()
  729. self._request_topic_confirmed = False
  730. else:
  731. logger.warning(
  732. "[%s] Failed to send request topic subscription",
  733. self.serial_number,
  734. )
  735. self._request_topic_supported = False
  736. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  737. # Request full status update (includes nozzle info in push_status response)
  738. self._request_push_all()
  739. # Request firmware version info
  740. self._request_version()
  741. # Note: get_accessories returns stale nozzle data on H2D, so we don't use it.
  742. # The correct nozzle data comes from push_status.
  743. # Prime K-profile request (Bambu printers often ignore first request)
  744. self._prime_kprofile_request()
  745. # Immediately broadcast connection state change
  746. if self.on_state_change:
  747. self.on_state_change(self.state)
  748. else:
  749. self.state.connected = False
  750. def _on_subscribe(self, client, userdata, mid, reason_code_list, properties=None):
  751. """Handle SUBACK responses to detect request topic subscription rejection."""
  752. if mid == self._request_topic_sub_mid:
  753. for rc in reason_code_list:
  754. if rc.is_failure:
  755. logger.warning(
  756. "[%s] Request topic subscription rejected (code=%d: %s). "
  757. "ams_mapping capture from slicer-initiated prints unavailable.",
  758. self.serial_number,
  759. rc.value,
  760. rc.getName(),
  761. )
  762. self._request_topic_supported = False
  763. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  764. else:
  765. logger.info(
  766. "[%s] Request topic subscription accepted. "
  767. "ams_mapping capture enabled for slicer-initiated prints.",
  768. self.serial_number,
  769. )
  770. self._request_topic_confirmed = True
  771. BambuMQTTClient._request_topic_cache[self.serial_number] = True
  772. self._request_topic_sub_mid = None
  773. self._request_topic_sub_time = 0.0
  774. def _on_disconnect(self, client, userdata, disconnect_flags=None, rc=None, properties=None):
  775. # Always unblock disconnect() callers, regardless of whether we suppress
  776. # the state broadcast below. disconnect() sets _disconnection_event and
  777. # waits on it — every callback path must fire it.
  778. if self._disconnection_event:
  779. self._disconnection_event.set()
  780. # If we intentionally closed the socket for stale reconnect, don't broadcast
  781. # another state change — check_staleness() already set connected=False and
  782. # notified the UI. Just log and let paho auto-reconnect.
  783. if self._stale_reconnecting:
  784. logger.info(
  785. "[%s] Disconnect callback after stale reconnect (expected), rc=%s",
  786. self.serial_number,
  787. rc,
  788. )
  789. return
  790. # Ignore spurious disconnect callbacks if we've received a message recently
  791. # Paho-mqtt sometimes fires disconnect callbacks while the connection is still active.
  792. # BUT: never suppress error disconnects (keepalive timeout, connection lost, etc.)
  793. # — only suppress when rc indicates a clean/normal disconnect.
  794. is_error_disconnect = rc is not None and hasattr(rc, "is_failure") and rc.is_failure
  795. time_since_last_message = time.time() - self._last_message_time
  796. if not is_error_disconnect and time_since_last_message < 10.0 and self._last_message_time > 0:
  797. logger.debug(
  798. f"[{self.serial_number}] Ignoring spurious disconnect (last message {time_since_last_message:.1f}s ago)"
  799. )
  800. return
  801. logger.warning("[%s] MQTT disconnected: rc=%s, flags=%s", self.serial_number, rc, disconnect_flags)
  802. # Detect if request topic subscription caused the disconnect.
  803. # If we just subscribed and got disconnected before any SUBACK confirmation,
  804. # the broker likely killed the connection due to the unauthorized subscription.
  805. if (
  806. self._request_topic_sub_time > 0
  807. and not self._request_topic_confirmed
  808. and time.time() - self._request_topic_sub_time < 10.0
  809. ):
  810. logger.warning(
  811. "[%s] Disconnected shortly after request topic subscription. Disabling request topic for this printer.",
  812. self.serial_number,
  813. )
  814. self._request_topic_supported = False
  815. BambuMQTTClient._request_topic_cache[self.serial_number] = False
  816. self._request_topic_sub_mid = None
  817. self._request_topic_sub_time = 0.0
  818. self.state.connected = False
  819. if self.on_state_change:
  820. self.on_state_change(self.state)
  821. def _on_message(self, client, userdata, msg):
  822. for handler in self._raw_message_handlers:
  823. try:
  824. handler(msg.topic, msg.payload)
  825. except Exception:
  826. logger.exception(
  827. "[%s] raw-message handler crashed for topic=%s",
  828. self.serial_number,
  829. msg.topic,
  830. )
  831. try:
  832. try:
  833. raw = msg.payload.decode()
  834. except UnicodeDecodeError:
  835. # Some firmware versions (e.g. A1 Mini 01.07.02.00) send payloads
  836. # with non-UTF-8 bytes. Replace invalid bytes to keep JSON parseable.
  837. raw = msg.payload.decode(errors="replace")
  838. logger.warning(
  839. "[%s] MQTT payload contained non-UTF-8 bytes (topic=%s, len=%d)",
  840. self.serial_number,
  841. msg.topic,
  842. len(msg.payload),
  843. )
  844. payload = json.loads(raw)
  845. # Track last message time - receiving a message proves we're connected
  846. self._last_message_time = time.time()
  847. self.state.connected = True
  848. # Intercept request-topic messages (print commands from slicer/Bambuddy)
  849. if msg.topic == self.topic_publish:
  850. self._handle_request_message(payload)
  851. return
  852. # Count status reports per connection so check_staleness() can tell
  853. # "printer never sent a report" apart from a mid-session quiet gap.
  854. if msg.topic == self.topic_subscribe:
  855. self._report_messages_since_connect += 1
  856. # Log message if logging is enabled
  857. if self._logging_enabled:
  858. self._message_log.append(
  859. MQTTLogEntry(
  860. timestamp=datetime.now(timezone.utc).isoformat(),
  861. topic=msg.topic,
  862. direction="in",
  863. payload=payload,
  864. )
  865. )
  866. self._process_message(payload)
  867. except json.JSONDecodeError:
  868. pass # Ignore non-JSON MQTT messages (e.g. binary or malformed payloads)
  869. def _handle_request_message(self, data: dict) -> None:
  870. """Intercept print commands on the request topic to capture ams_mapping."""
  871. print_data = data.get("print", {})
  872. if not isinstance(print_data, dict):
  873. return
  874. command = print_data.get("command", "")
  875. if command == "project_file":
  876. if "ams_mapping" in print_data:
  877. self._captured_ams_mapping = print_data["ams_mapping"]
  878. logger.info(
  879. "[%s] Captured ams_mapping from print command: %s",
  880. self.serial_number,
  881. self._captured_ams_mapping,
  882. )
  883. # Diagnostic for #1162 follow-up (X2D + FTS routing): when a
  884. # slicer-launched project_file passes through the request topic,
  885. # log the full payload so we can diff Studio's field set against
  886. # ours. We pin our own sequence_id to "20000" (line ~3195), so
  887. # any other value means the command came from Studio/Orca, not
  888. # from us.
  889. if print_data.get("sequence_id") != "20000":
  890. logger.info(
  891. "[%s] External project_file payload: %s",
  892. self.serial_number,
  893. json.dumps(print_data),
  894. )
  895. def _process_message(self, payload: dict):
  896. """Process incoming MQTT message from printer."""
  897. # Handle top-level AMS data (comes outside of "print" key)
  898. # Wrap in try/except to prevent breaking the MQTT connection
  899. if "ams" in payload:
  900. try:
  901. self._handle_ams_data(payload["ams"])
  902. except Exception as e:
  903. logger.error("[%s] Error handling AMS data: %s", self.serial_number, e)
  904. # Handle xcam data (camera settings and AI detection) at top level
  905. if "xcam" in payload:
  906. xcam_data = payload["xcam"]
  907. logger.debug("[%s] Received xcam data at top level: %s", self.serial_number, xcam_data)
  908. self._parse_xcam_data(xcam_data)
  909. # Fire state change callback for top-level xcam (not nested in "print")
  910. if "print" not in payload and self.on_state_change:
  911. self.on_state_change(self.state)
  912. # Handle system responses (accessories info, etc.)
  913. if "system" in payload:
  914. system_data = payload["system"]
  915. logger.debug("[%s] Received system data: %s", self.serial_number, system_data)
  916. self._handle_system_response(system_data)
  917. # Handle info responses (firmware version info from get_version command)
  918. if "info" in payload:
  919. info_data = payload["info"]
  920. if isinstance(info_data, dict) and info_data.get("command") == "get_version":
  921. self._handle_version_info(info_data)
  922. # Parse WiFi signal at top level (some printers send it here)
  923. if "wifi_signal" in payload:
  924. wifi_signal = payload["wifi_signal"]
  925. if isinstance(wifi_signal, (int, float)):
  926. self.state.wifi_signal = int(wifi_signal)
  927. elif isinstance(wifi_signal, str):
  928. try:
  929. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  930. except ValueError:
  931. pass # Ignore unparseable wifi_signal strings; field is non-critical
  932. # Detect ethernet: wifi_signal == -90 is a sentinel for "WiFi disabled/ethernet"
  933. from backend.app.utils.printer_models import has_ethernet
  934. if has_ethernet(self.model):
  935. self.state.wired_network = self.state.wifi_signal == -90
  936. # Parse developer LAN mode from top-level "fun" field
  937. # Some firmware versions send "fun" at the top level, others inside "print"
  938. if "fun" in payload:
  939. try:
  940. fun_val = payload["fun"]
  941. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  942. self.state.developer_mode = (fun_int & 0x20000000) == 0
  943. except (ValueError, TypeError):
  944. pass
  945. if "print" in payload:
  946. print_data = payload["print"]
  947. # Check if xcam is nested inside print data
  948. if "xcam" in print_data:
  949. logger.debug("[%s] Found xcam inside print data: %s", self.serial_number, print_data["xcam"])
  950. self._parse_xcam_data(print_data["xcam"])
  951. # Log when we see gcode_state changes
  952. if "gcode_state" in print_data:
  953. logger.debug(
  954. f"[{self.serial_number}] Received gcode_state: {print_data.get('gcode_state')}, "
  955. f"gcode_file: {print_data.get('gcode_file')}, subtask_name: {print_data.get('subtask_name')}"
  956. )
  957. # AMS Filament Backup state lives in bit 18 of top-level print.cfg on
  958. # new-protocol printers. Verified against OrcaSlicer's
  959. # DeviceManager.cpp:4961 SetAutoRefillEnabled(get_flag_bits(cfg, 18))
  960. # and live H2D ON/OFF capture 2026-06-20.
  961. #
  962. # Hold-timer guard: when the user just toggled via the badge, the
  963. # next 1-2 push_status frames may still carry the printer's OLD cfg
  964. # for ~3 s before the firmware reflects the change. Without this
  965. # gate the UI would flicker ON→OFF→ON. Same pattern xcam uses.
  966. new_backup = parse_ams_filament_backup_from_cfg(print_data.get("cfg"))
  967. if new_backup is not None and new_backup != self.state.ams_filament_backup:
  968. hold_start = self._xcam_hold_start.get("print_option_auto_switch_filament")
  969. if hold_start is not None and (time.time() - hold_start) <= self._xcam_hold_time:
  970. logger.debug(
  971. "[%s] AMS Filament Backup push ignored (hold active for %.1fs)",
  972. self.serial_number,
  973. time.time() - hold_start,
  974. )
  975. else:
  976. logger.info(
  977. "[%s] AMS Filament Backup: %s",
  978. self.serial_number,
  979. "ON" if new_backup else "OFF",
  980. )
  981. self.state.ams_filament_backup = new_backup
  982. self._xcam_hold_start.pop("print_option_auto_switch_filament", None)
  983. # Detect dual-nozzle BEFORE processing AMS data (tray_now disambiguation needs it)
  984. # device.extruder.info with >= 2 entries only exists on dual-nozzle printers (H2D, H2D Pro)
  985. if not self._is_dual_nozzle and "device" in print_data:
  986. dev = print_data.get("device")
  987. if isinstance(dev, dict):
  988. ext_info = dev.get("extruder", {}).get("info", [])
  989. if isinstance(ext_info, list) and len(ext_info) >= 2:
  990. self._is_dual_nozzle = True
  991. logger.info("[%s] Detected dual-nozzle printer from device.extruder.info", self.serial_number)
  992. # Handle AMS data that comes inside print key
  993. if "ams" in print_data:
  994. try:
  995. self._handle_ams_data(print_data["ams"])
  996. except Exception as e:
  997. logger.error("[%s] Error handling AMS data from print: %s", self.serial_number, e)
  998. # Handle vir_slot (H2-series external spool data) — list of external trays
  999. # Process vir_slot FIRST so it takes priority over vt_tray
  1000. if "vir_slot" in print_data:
  1001. vir_slot = print_data["vir_slot"]
  1002. if isinstance(vir_slot, list) and vir_slot:
  1003. # Fix: single-nozzle printers (X1C, P1S, A1) report their single
  1004. # external slot with id=255 in vir_slot, but tray_now=254 when active.
  1005. # Remap id=255→254 for single-slot printers so active detection works.
  1006. # Dual-nozzle (H2D) has 2 slots: id=254 (Ext-L) and id=255 (Ext-R).
  1007. if len(vir_slot) == 1 and str(vir_slot[0].get("id", "")) == "255":
  1008. vir_slot[0]["id"] = "254"
  1009. self.state.raw_data["vt_tray"] = vir_slot
  1010. # Handle vt_tray (virtual tray / external spool) data
  1011. # Only use vt_tray if vir_slot is NOT in this message AND we don't already
  1012. # have vir_slot data (H2-series sends vt_tray as a single active spool dict
  1013. # which would overwrite the correct multi-slot vir_slot data)
  1014. if "vt_tray" in print_data and "vir_slot" not in print_data:
  1015. vt_tray = print_data["vt_tray"]
  1016. existing = self.state.raw_data.get("vt_tray")
  1017. # Don't let a single-spool vt_tray dict overwrite multi-slot vir_slot data
  1018. if isinstance(vt_tray, dict) and isinstance(existing, list) and len(existing) > 1:
  1019. pass # Keep the vir_slot data
  1020. else:
  1021. if isinstance(vt_tray, dict):
  1022. vt_tray = [vt_tray]
  1023. self.state.raw_data["vt_tray"] = vt_tray
  1024. # Parse ams_status directly from print data (NOT from print.ams)
  1025. # ams_status is a combined value: lower 8 bits = sub status, bits 8-15 = main status
  1026. # Main status: 0=idle, 1=filament_change, 2=rfid_identifying, 3=assist, 4=calibration
  1027. # Sub status (when main=1): 2=heating, 3=AMS feeding, 4=retract, 6=push, 7=purge
  1028. if "ams_status" in print_data:
  1029. raw_ams_status = print_data["ams_status"]
  1030. if isinstance(raw_ams_status, str):
  1031. try:
  1032. self.state.ams_status = int(raw_ams_status)
  1033. except ValueError:
  1034. self.state.ams_status = 0
  1035. else:
  1036. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  1037. # Compute main and sub status
  1038. self.state.ams_status_sub = self.state.ams_status & 0xFF
  1039. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  1040. # Log when ams_status changes (for filament change tracking debug)
  1041. logger.debug(
  1042. f"[{self.serial_number}] ams_status: {self.state.ams_status} "
  1043. f"(main={self.state.ams_status_main}, sub={self.state.ams_status_sub})"
  1044. )
  1045. # Check for command responses
  1046. if "command" in print_data:
  1047. cmd = print_data.get("command")
  1048. logger.debug("[%s] Received command response: %s", self.serial_number, cmd)
  1049. if cmd in ("extrusion_cali_sel", "extrusion_cali_set", "extrusion_cali_del", "ams_filament_setting"):
  1050. logger.debug("[%s] %s response: %s", self.serial_number, cmd, print_data)
  1051. # AMS drying responses are rare (user-initiated only) and the
  1052. # full payload — including `result` and any `reason` code —
  1053. # is the only way to diagnose silent rejections like #1447.
  1054. # INFO level so the body lands in support bundles by default.
  1055. elif cmd == "ams_filament_drying":
  1056. logger.info("[%s] ams_filament_drying response: %s", self.serial_number, print_data)
  1057. # Check for developer mode probe response
  1058. if (
  1059. cmd == "ams_filament_setting"
  1060. and self._dev_mode_probe_seq is not None
  1061. and print_data.get("sequence_id") == self._dev_mode_probe_seq
  1062. ):
  1063. self._handle_dev_mode_probe_response(print_data)
  1064. # Track user-initiated ams_filament_setting responses (#887
  1065. # zombie detection). Reset both the timer AND the unanswered
  1066. # counter on ANY response — the response proves the channel is
  1067. # alive, so the counter must not stay armed even when the
  1068. # watchdog already zeroed `_last_ams_cmd_time` on a previous
  1069. # tick. The original `and self._last_ams_cmd_time > 0` guard
  1070. # caused #1164: one sluggish response (>10s) would set the
  1071. # counter to 1 and zero the timer; the late response arrived
  1072. # but was ignored by this branch (timer is 0); the counter
  1073. # stayed at 1 indefinitely; the very next slow response —
  1074. # possibly hours later, on a totally unrelated command — would
  1075. # take it to 2 and force-reconnect, surfacing as "filament
  1076. # config doesn't reach the printer ~6 changes in".
  1077. elif cmd == "ams_filament_setting":
  1078. self._last_ams_cmd_time = 0.0
  1079. self._ams_cmd_unanswered = 0
  1080. if "command" in print_data and print_data.get("command") == "extrusion_cali_get":
  1081. self._handle_kprofile_response(print_data)
  1082. self._update_state(print_data)
  1083. def _handle_system_response(self, data: dict):
  1084. """Handle system responses including accessories info.
  1085. Note: get_accessories returns stale/incorrect nozzle_type data on H2D.
  1086. The correct nozzle data comes from push_status, so we don't update
  1087. nozzle type/diameter from get_accessories. We just log the response
  1088. for debugging purposes.
  1089. """
  1090. command = data.get("command")
  1091. if command == "get_accessories":
  1092. # Log response for debugging - but DON'T use it to update nozzle data
  1093. # because it returns stale values (e.g., 'stainless_steel' when the
  1094. # actual nozzle is 'HH01' hardened steel high-flow)
  1095. logger.debug("[%s] Accessories response (not used for nozzle data): %s", self.serial_number, data)
  1096. def _handle_version_info(self, data: dict):
  1097. """Handle version info response from get_version command.
  1098. Parses firmware version from the 'ota' module in the module list.
  1099. Also extracts AMS unit firmware versions from AMS modules and stores
  1100. them on the corresponding AMS unit in raw_data so the status route can
  1101. expose them to the frontend.
  1102. AMS module naming conventions (numeric suffix is the AMS unit ID):
  1103. - ``ams/<id>`` – original AMS
  1104. - ``n3f/<id>`` – AMS 2 Pro (H2D Pro and similar)
  1105. - ``n3s/<id>`` – AMS HT (H2D Pro and similar)
  1106. Message format:
  1107. {
  1108. "command": "get_version",
  1109. "module": [
  1110. {"name": "ota", "sw_ver": "01.08.05.00"},
  1111. {"name": "rv1126", "sw_ver": "00.00.14.74"},
  1112. {"name": "ams/0", "sw_ver": "00.00.06.96", "sn": "ABC123"},
  1113. {"name": "n3f/0", "sw_ver": "03.00.21.29", "sn": "19C06A552504488"},
  1114. {"name": "n3s/128", "sw_ver": "03.00.21.29", "sn": "19F06A561801096"},
  1115. ...
  1116. ]
  1117. }
  1118. """
  1119. modules = data.get("module", [])
  1120. if not isinstance(modules, list):
  1121. return
  1122. state_changed = False
  1123. for module in modules:
  1124. if not isinstance(module, dict):
  1125. continue
  1126. if module.get("name") == "ota":
  1127. version = module.get("sw_ver")
  1128. if version:
  1129. old_version = self.state.firmware_version
  1130. self.state.firmware_version = version
  1131. if old_version != version:
  1132. logger.info("[%s] Firmware version: %s", self.serial_number, version)
  1133. state_changed = True
  1134. break
  1135. # Extract AMS unit firmware versions from AMS modules.
  1136. # See module-level _AMS_MODULE_PREFIXES for supported naming conventions.
  1137. # Always cache regardless of whether AMS data has arrived yet — get_version
  1138. # often arrives before the first push_status, so caching must be unconditional.
  1139. ams_raw = self.state.raw_data.get("ams")
  1140. for module in modules:
  1141. if not isinstance(module, dict):
  1142. continue
  1143. name = module.get("name", "")
  1144. if not any(name.startswith(prefix) for prefix in _AMS_MODULE_PREFIXES):
  1145. continue
  1146. try:
  1147. ams_id = int(name.split("/", 1)[1])
  1148. except (ValueError, IndexError):
  1149. continue
  1150. sw_ver = module.get("sw_ver", "")
  1151. sn = module.get("sn", "")
  1152. # Extract module type from prefix (e.g. "ams/0" → "ams", "n3f/0" → "n3f")
  1153. module_type = name.split("/", 1)[0]
  1154. # Always cache so _apply_ams_version_cache can apply it when AMS data arrives
  1155. if sw_ver or sn or module_type:
  1156. self._ams_version_cache[ams_id] = {"sw_ver": sw_ver, "sn": sn, "module_type": module_type}
  1157. state_changed = True
  1158. # Also directly update any AMS unit already present in raw_data
  1159. if ams_raw and isinstance(ams_raw, list):
  1160. for ams_unit in ams_raw:
  1161. if not isinstance(ams_unit, dict):
  1162. continue
  1163. try:
  1164. unit_id = int(ams_unit.get("id")) if ams_unit.get("id") is not None else None
  1165. except (ValueError, TypeError):
  1166. unit_id = None
  1167. if unit_id == ams_id:
  1168. if sw_ver:
  1169. ams_unit["sw_ver"] = sw_ver
  1170. logger.debug("[%s] AMS %s firmware: %s", self.serial_number, ams_id, sw_ver)
  1171. # Only set sn from version info if not already present in AMS data
  1172. if sn and not ams_unit.get("sn"):
  1173. ams_unit["sn"] = sn
  1174. if module_type:
  1175. ams_unit["module_type"] = module_type
  1176. break
  1177. # Trigger state change callback AFTER both loops so AMS sn/sw_ver are
  1178. # included in the broadcast (not just the printer firmware version).
  1179. if state_changed and self.on_state_change:
  1180. self.on_state_change(self.state)
  1181. # Warn if any AMS unit is still missing serial number or firmware version
  1182. # after processing the version info response. Warn only once per connection
  1183. # to avoid repeated noise on older firmware that doesn't report these fields.
  1184. if ams_raw and isinstance(ams_raw, list):
  1185. for ams_unit in ams_raw:
  1186. if not isinstance(ams_unit, dict):
  1187. continue
  1188. ams_id = ams_unit.get("id", "?")
  1189. if not ams_unit.get("sn") and not ams_unit.get("serial_number"):
  1190. key = (ams_id, "sn")
  1191. if key not in self._ams_version_warned:
  1192. self._ams_version_warned.add(key)
  1193. logger.warning(
  1194. "[%s] AMS unit %s: serial number not available in version info",
  1195. self.serial_number,
  1196. ams_id,
  1197. )
  1198. if not ams_unit.get("sw_ver"):
  1199. key = (ams_id, "sw_ver")
  1200. if key not in self._ams_version_warned:
  1201. self._ams_version_warned.add(key)
  1202. logger.warning(
  1203. "[%s] AMS unit %s: firmware version not available in version info",
  1204. self.serial_number,
  1205. ams_id,
  1206. )
  1207. def _apply_ams_version_cache(self, ams_list: list) -> None:
  1208. """Apply cached AMS firmware/SN (from get_version) onto an AMS list in-place.
  1209. get_version may arrive before pushall/AMS status, and AMS unit IDs may be
  1210. strings in MQTT payloads. This helper normalizes IDs and fills missing
  1211. sw_ver/sn fields without overwriting values already present.
  1212. """
  1213. if not ams_list or not isinstance(ams_list, list):
  1214. return
  1215. cache = self._ams_version_cache
  1216. if not cache:
  1217. return
  1218. for unit in ams_list:
  1219. if not isinstance(unit, dict):
  1220. continue
  1221. raw_id = unit.get("id")
  1222. try:
  1223. unit_id = int(raw_id) if raw_id is not None else None
  1224. except (ValueError, TypeError):
  1225. unit_id = None
  1226. if unit_id is None:
  1227. continue
  1228. cached = cache.get(unit_id)
  1229. if not cached:
  1230. continue
  1231. sw_ver = cached.get("sw_ver") or ""
  1232. sn = cached.get("sn") or ""
  1233. if sw_ver and not unit.get("sw_ver"):
  1234. unit["sw_ver"] = sw_ver
  1235. # Only set sn if not already present in AMS data
  1236. if sn and not unit.get("sn") and not unit.get("serial_number"):
  1237. unit["sn"] = sn
  1238. module_type = cached.get("module_type") or ""
  1239. if module_type and not unit.get("module_type"):
  1240. unit["module_type"] = module_type
  1241. def _parse_xcam_data(self, xcam_data):
  1242. """Parse xcam data for camera settings and AI detection options."""
  1243. if not isinstance(xcam_data, dict):
  1244. return
  1245. current_time = time.time()
  1246. # Helper to check if we should accept incoming value for a module
  1247. # OrcaSlicer pattern: simple hold timer, ignore ALL data for 3 seconds after command
  1248. def should_accept_value(module_name: str, incoming_value: bool) -> bool:
  1249. """Check if we should accept an incoming xcam value.
  1250. OrcaSlicer pattern: After sending a command, ignore incoming data
  1251. for 3 seconds. After that, accept whatever the printer sends.
  1252. """
  1253. if module_name not in self._xcam_hold_start:
  1254. return True # No hold timer, accept incoming
  1255. hold_start = self._xcam_hold_start[module_name]
  1256. elapsed = current_time - hold_start
  1257. if elapsed > self._xcam_hold_time:
  1258. # Hold timer expired - accept incoming and clear hold
  1259. del self._xcam_hold_start[module_name]
  1260. logger.debug("[%s] Hold expired for %s, accepting %s", self.serial_number, module_name, incoming_value)
  1261. return True
  1262. # Within hold period - ignore incoming data
  1263. logger.debug(
  1264. f"[{self.serial_number}] Ignoring {module_name}={incoming_value} "
  1265. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  1266. )
  1267. return False
  1268. # Log all xcam fields for debugging
  1269. logger.debug("[%s] Parsing xcam data - all fields: %s", self.serial_number, list(xcam_data.keys()))
  1270. # The cfg bitmask contains the ACTUAL detector states - the individual boolean
  1271. # fields (spaghetti_detector, etc.) are often stale/cached.
  1272. # CFG bitmask structure (each detector uses 3 bits: [sens_low, sens_high, enabled]):
  1273. # - Bits 5-7: spaghetti_detector (sens in 5-6, enabled in 7)
  1274. # - Bits 8-10: pileup_detector (sens in 8-9, enabled in 10)
  1275. # - Bits 11-13: clump_detector/nozzle_clumping (sens in 11-12, enabled in 13)
  1276. # - Bits 14-16: airprint_detector (sens in 14-15, enabled in 16)
  1277. # Sensitivity values: 0=low, 1=medium, 2=high
  1278. if "cfg" in xcam_data:
  1279. cfg = xcam_data["cfg"]
  1280. logger.debug("[%s] xcam cfg bitmask: %s (binary: %s)", self.serial_number, cfg, bin(cfg))
  1281. def decode_detector(start_bit):
  1282. """Decode a detector from cfg: returns (enabled, sensitivity_str)"""
  1283. sens_bits = (cfg >> start_bit) & 0x3
  1284. enabled = bool((cfg >> (start_bit + 2)) & 1)
  1285. sensitivity = {0: "low", 1: "medium", 2: "high"}.get(sens_bits, "medium")
  1286. return enabled, sensitivity
  1287. # Spaghetti detector (bits 5-7)
  1288. cfg_spaghetti, cfg_sensitivity = decode_detector(5)
  1289. if should_accept_value("spaghetti_detector", cfg_spaghetti):
  1290. old_value = self.state.print_options.spaghetti_detector
  1291. if cfg_spaghetti != old_value:
  1292. logger.debug(
  1293. f"[{self.serial_number}] spaghetti_detector changed (from cfg): {old_value} -> {cfg_spaghetti}"
  1294. )
  1295. self.state.print_options.spaghetti_detector = cfg_spaghetti
  1296. # Check hold timer for sensitivity before accepting
  1297. if "halt_print_sensitivity" not in self._xcam_hold_start:
  1298. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  1299. logger.debug(
  1300. f"[{self.serial_number}] Sensitivity changed (from cfg): "
  1301. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  1302. )
  1303. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  1304. else:
  1305. hold_start = self._xcam_hold_start["halt_print_sensitivity"]
  1306. elapsed = current_time - hold_start
  1307. if elapsed <= self._xcam_hold_time:
  1308. logger.debug(
  1309. f"[{self.serial_number}] Ignoring cfg sensitivity={cfg_sensitivity} "
  1310. f"(hold active, {elapsed:.1f}s < {self._xcam_hold_time}s)"
  1311. )
  1312. else:
  1313. # Hold expired - accept from cfg
  1314. if cfg_sensitivity != self.state.print_options.halt_print_sensitivity:
  1315. logger.debug(
  1316. f"[{self.serial_number}] Sensitivity synced (from cfg after hold): "
  1317. f"{self.state.print_options.halt_print_sensitivity} -> {cfg_sensitivity}"
  1318. )
  1319. self.state.print_options.halt_print_sensitivity = cfg_sensitivity
  1320. del self._xcam_hold_start["halt_print_sensitivity"]
  1321. # Pileup detector (bits 8-10)
  1322. cfg_pileup, cfg_pileup_sens = decode_detector(8)
  1323. if should_accept_value("pileup_detector", cfg_pileup):
  1324. if cfg_pileup != self.state.print_options.pileup_detector:
  1325. logger.debug(
  1326. f"[{self.serial_number}] pileup_detector changed (from cfg): {self.state.print_options.pileup_detector} -> {cfg_pileup}"
  1327. )
  1328. self.state.print_options.pileup_detector = cfg_pileup
  1329. # Pileup sensitivity with hold timer
  1330. if "pileup_sensitivity" not in self._xcam_hold_start:
  1331. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  1332. logger.debug(
  1333. f"[{self.serial_number}] pileup_sensitivity changed (from cfg): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  1334. )
  1335. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  1336. else:
  1337. hold_start = self._xcam_hold_start["pileup_sensitivity"]
  1338. elapsed = current_time - hold_start
  1339. if elapsed > self._xcam_hold_time:
  1340. if cfg_pileup_sens != self.state.print_options.pileup_sensitivity:
  1341. logger.debug(
  1342. f"[{self.serial_number}] pileup_sensitivity synced (from cfg after hold): {self.state.print_options.pileup_sensitivity} -> {cfg_pileup_sens}"
  1343. )
  1344. self.state.print_options.pileup_sensitivity = cfg_pileup_sens
  1345. del self._xcam_hold_start["pileup_sensitivity"]
  1346. # Clump/nozzle clumping detector (bits 11-13)
  1347. cfg_clump, cfg_clump_sens = decode_detector(11)
  1348. if should_accept_value("clump_detector", cfg_clump):
  1349. if cfg_clump != self.state.print_options.nozzle_clumping_detector:
  1350. logger.debug(
  1351. f"[{self.serial_number}] nozzle_clumping_detector changed (from cfg): {self.state.print_options.nozzle_clumping_detector} -> {cfg_clump}"
  1352. )
  1353. self.state.print_options.nozzle_clumping_detector = cfg_clump
  1354. # Clump sensitivity with hold timer
  1355. if "nozzle_clumping_sensitivity" not in self._xcam_hold_start:
  1356. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  1357. logger.debug(
  1358. f"[{self.serial_number}] nozzle_clumping_sensitivity changed (from cfg): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  1359. )
  1360. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  1361. else:
  1362. hold_start = self._xcam_hold_start["nozzle_clumping_sensitivity"]
  1363. elapsed = current_time - hold_start
  1364. if elapsed > self._xcam_hold_time:
  1365. if cfg_clump_sens != self.state.print_options.nozzle_clumping_sensitivity:
  1366. logger.debug(
  1367. f"[{self.serial_number}] nozzle_clumping_sensitivity synced (from cfg after hold): {self.state.print_options.nozzle_clumping_sensitivity} -> {cfg_clump_sens}"
  1368. )
  1369. self.state.print_options.nozzle_clumping_sensitivity = cfg_clump_sens
  1370. del self._xcam_hold_start["nozzle_clumping_sensitivity"]
  1371. # Airprint detector (bits 14-16)
  1372. cfg_airprint, cfg_airprint_sens = decode_detector(14)
  1373. if should_accept_value("airprint_detector", cfg_airprint):
  1374. if cfg_airprint != self.state.print_options.airprint_detector:
  1375. logger.debug(
  1376. f"[{self.serial_number}] airprint_detector changed (from cfg): {self.state.print_options.airprint_detector} -> {cfg_airprint}"
  1377. )
  1378. self.state.print_options.airprint_detector = cfg_airprint
  1379. # Airprint sensitivity with hold timer
  1380. if "airprint_sensitivity" not in self._xcam_hold_start:
  1381. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  1382. logger.debug(
  1383. f"[{self.serial_number}] airprint_sensitivity changed (from cfg): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  1384. )
  1385. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  1386. else:
  1387. hold_start = self._xcam_hold_start["airprint_sensitivity"]
  1388. elapsed = current_time - hold_start
  1389. if elapsed > self._xcam_hold_time:
  1390. if cfg_airprint_sens != self.state.print_options.airprint_sensitivity:
  1391. logger.debug(
  1392. f"[{self.serial_number}] airprint_sensitivity synced (from cfg after hold): {self.state.print_options.airprint_sensitivity} -> {cfg_airprint_sens}"
  1393. )
  1394. self.state.print_options.airprint_sensitivity = cfg_airprint_sens
  1395. del self._xcam_hold_start["airprint_sensitivity"]
  1396. # Camera settings
  1397. if "ipcam_record" in xcam_data:
  1398. self.state.ipcam = xcam_data.get("ipcam_record") == "enable"
  1399. if "timelapse" in xcam_data:
  1400. self.state.timelapse = xcam_data.get("timelapse") == "enable"
  1401. # Track if timelapse was ever active during this print
  1402. if self.state.timelapse and self._was_running:
  1403. self._timelapse_during_print = True
  1404. # Skip spaghetti_detector boolean field - we read from cfg bitmask above
  1405. if "print_halt" in xcam_data:
  1406. self.state.print_options.print_halt = bool(xcam_data.get("print_halt"))
  1407. # Skip halt_print_sensitivity field - it's always stale ("medium")
  1408. # We read the actual sensitivity from cfg bits 5-6 above
  1409. if "first_layer_inspector" in xcam_data:
  1410. new_value = bool(xcam_data.get("first_layer_inspector"))
  1411. if should_accept_value("first_layer_inspector", new_value):
  1412. self.state.print_options.first_layer_inspector = new_value
  1413. if "printing_monitor" in xcam_data:
  1414. new_value = bool(xcam_data.get("printing_monitor"))
  1415. if should_accept_value("printing_monitor", new_value):
  1416. self.state.print_options.printing_monitor = new_value
  1417. if "buildplate_marker_detector" in xcam_data:
  1418. new_value = bool(xcam_data.get("buildplate_marker_detector"))
  1419. if should_accept_value("buildplate_marker_detector", new_value):
  1420. self.state.print_options.buildplate_marker_detector = new_value
  1421. if "allow_skip_parts" in xcam_data:
  1422. new_value = bool(xcam_data.get("allow_skip_parts"))
  1423. if should_accept_value("allow_skip_parts", new_value):
  1424. self.state.print_options.allow_skip_parts = new_value
  1425. # Additional AI detectors - these are decoded from cfg bitmask above, not from
  1426. # individual boolean fields (which are not sent by the printer)
  1427. # pileup_detector, nozzle_clumping_detector, airprint_detector - from cfg
  1428. # auto_recovery_step_loss and filament_tangle_detect - tracked locally only
  1429. if "auto_recovery_step_loss" in xcam_data:
  1430. self.state.print_options.auto_recovery_step_loss = bool(xcam_data.get("auto_recovery_step_loss"))
  1431. if "filament_tangle_detect" in xcam_data:
  1432. self.state.print_options.filament_tangle_detect = bool(xcam_data.get("filament_tangle_detect"))
  1433. @staticmethod
  1434. def _resolve_local_slot_from_mapping(local_slot: int, mapping_raw: list | None) -> int | None:
  1435. """Resolve a local AMS slot ID to a global tray ID using the MQTT mapping field.
  1436. The MQTT mapping field is an array of snow-encoded values:
  1437. each entry = ams_hw_id * 256 + slot_id (65535 = unmapped).
  1438. Finds entries where the local slot matches, then computes the global tray ID.
  1439. Returns the global ID if exactly one AMS matches, or None if ambiguous/unavailable.
  1440. """
  1441. if not isinstance(mapping_raw, list) or not mapping_raw:
  1442. return None
  1443. candidates: set[int] = set()
  1444. for value in mapping_raw:
  1445. if not isinstance(value, int) or value >= 65535:
  1446. continue
  1447. ams_hw_id = value >> 8
  1448. slot = value & 0xFF
  1449. if 0 <= ams_hw_id <= 3 and (slot & 0x03) == local_slot:
  1450. candidates.add(ams_hw_id * 4 + local_slot)
  1451. elif 128 <= ams_hw_id <= 135 and local_slot == 0:
  1452. candidates.add(ams_hw_id)
  1453. if len(candidates) == 1:
  1454. return candidates.pop()
  1455. return None
  1456. def _handle_ams_data(self, ams_data):
  1457. """Handle AMS data changes for Spoolman integration.
  1458. This is called when we receive top-level AMS data in MQTT messages.
  1459. It detects changes and triggers the callback for Spoolman sync.
  1460. """
  1461. import hashlib
  1462. # Handle nested ams structure: {"ams": {"ams": [...]}} or {"ams": [...]}
  1463. # Also handle P1S partial updates: {"tray_now": ..., "tray_tar": ...} without "ams" key
  1464. ams_list = None
  1465. if isinstance(ams_data, dict):
  1466. if "ams" in ams_data:
  1467. ams_list = ams_data["ams"]
  1468. # Log all AMS dict fields to debug tray_now for H2D dual-nozzle
  1469. non_list_fields = {k: v for k, v in ams_data.items() if k != "ams"}
  1470. if non_list_fields:
  1471. logger.debug("[%s] AMS dict fields: %s", self.serial_number, non_list_fields)
  1472. # IMPORTANT: Parse ams_status FIRST before tray_now, so we have fresh status
  1473. # when checking if we're in filament change mode for tray_now disambiguation
  1474. if "ams_status" in ams_data:
  1475. raw_ams_status = ams_data["ams_status"]
  1476. if isinstance(raw_ams_status, str):
  1477. try:
  1478. self.state.ams_status = int(raw_ams_status)
  1479. except ValueError:
  1480. self.state.ams_status = 0
  1481. else:
  1482. self.state.ams_status = raw_ams_status if raw_ams_status is not None else 0
  1483. # Compute main and sub status
  1484. self.state.ams_status_sub = self.state.ams_status & 0xFF
  1485. self.state.ams_status_main = (self.state.ams_status >> 8) & 0xFF
  1486. logger.debug(
  1487. f"[{self.serial_number}] ams_status: {self.state.ams_status} "
  1488. f"(main={self.state.ams_status_main}, sub={self.state.ams_status_sub})"
  1489. )
  1490. # Parse tray_now from AMS dict - this is the currently loaded tray global ID
  1491. # Note: tray_tar is also available but on H2D it's just slot number (0-3), not global ID
  1492. if "tray_now" in ams_data:
  1493. raw_tray_now = ams_data["tray_now"]
  1494. # Convert string to int if needed
  1495. if isinstance(raw_tray_now, str):
  1496. try:
  1497. parsed_tray_now = int(raw_tray_now)
  1498. except ValueError:
  1499. parsed_tray_now = 255
  1500. else:
  1501. parsed_tray_now = raw_tray_now if raw_tray_now is not None else 255
  1502. # H2D dual-nozzle printers report only slot number (0-3), not global tray ID
  1503. # Use active_extruder + ams_extruder_map to determine which AMS the slot belongs to
  1504. # Single-nozzle printers with multiple AMS (e.g. P2S) also report local slot IDs (#420)
  1505. # — disambiguated below using MQTT mapping field
  1506. ams_map = self.state.ams_extruder_map
  1507. if self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  1508. # First, check if we have a pending target that matches this slot
  1509. pending_target = self.state.pending_tray_target
  1510. if pending_target is not None:
  1511. pending_slot = pending_target % 4
  1512. if pending_slot == parsed_tray_now:
  1513. # Slot matches our pending target - use the full global ID
  1514. logger.debug(
  1515. f"[{self.serial_number}] H2D tray_now disambiguation: "
  1516. f"slot {parsed_tray_now} matches pending_tray_target {pending_target} -> using global ID {pending_target}"
  1517. )
  1518. self.state.tray_now = pending_target
  1519. # Clear pending target now that load is confirmed
  1520. self.state.pending_tray_target = None
  1521. else:
  1522. # Slot doesn't match our pending target - something changed, use slot as-is
  1523. logger.warning(
  1524. f"[{self.serial_number}] H2D tray_now: slot {parsed_tray_now} doesn't match "
  1525. f"pending_tray_target {pending_target} (slot {pending_slot}) - using slot as global ID"
  1526. )
  1527. self.state.tray_now = parsed_tray_now
  1528. # Clear pending target since it's stale
  1529. self.state.pending_tray_target = None
  1530. else:
  1531. # No pending target - use h2d_extruder_snow for accurate disambiguation
  1532. # H2D sends snow field in device.extruder.info with AMS ID in high byte
  1533. active_ext = self.state.active_extruder # 0=right, 1=left
  1534. # Best source: use snow value from device.extruder.info if available
  1535. snow_tray = self.state.h2d_extruder_snow.get(active_ext)
  1536. if snow_tray is not None and snow_tray != 255:
  1537. # snow_tray is already normalized to global ID
  1538. # Verify the slot matches what we see in tray_now
  1539. # Regular AMS: slot = global_id % 4; AMS HT (128-135): single slot = 0
  1540. snow_slot = snow_tray % 4 if snow_tray < 128 else (0 if snow_tray <= 135 else -1)
  1541. if snow_slot == parsed_tray_now:
  1542. if self.state.tray_now != snow_tray:
  1543. logger.debug(
  1544. f"[{self.serial_number}] H2D tray_now from snow: "
  1545. f"extruder[{active_ext}] snow={snow_tray} (slot {snow_slot})"
  1546. )
  1547. self.state.tray_now = snow_tray
  1548. else:
  1549. # Slot mismatch - snow field may not have updated yet, trust snow
  1550. logger.debug(
  1551. f"[{self.serial_number}] H2D tray_now: ams.tray_now slot {parsed_tray_now} "
  1552. f"!= snow slot {snow_slot}, using snow value {snow_tray}"
  1553. )
  1554. self.state.tray_now = snow_tray
  1555. else:
  1556. # Fallback: snow not available, use ams_extruder_map (less reliable)
  1557. # Find ALL AMS units on the active extruder
  1558. ams_on_extruder = []
  1559. for ams_id_str, ext_id in ams_map.items():
  1560. if ext_id == active_ext:
  1561. try:
  1562. ams_on_extruder.append(int(ams_id_str))
  1563. except ValueError:
  1564. pass # Skip AMS IDs that aren't valid integers
  1565. if len(ams_on_extruder) == 1:
  1566. # Single AMS on this extruder - unambiguous
  1567. active_ams_id = ams_on_extruder[0]
  1568. if 128 <= active_ams_id <= 135:
  1569. # AMS-HT: single slot per unit, global ID = unit ID
  1570. global_tray_id = active_ams_id
  1571. else:
  1572. global_tray_id = active_ams_id * 4 + parsed_tray_now
  1573. logger.debug(
  1574. f"[{self.serial_number}] H2D tray_now fallback: "
  1575. f"slot {parsed_tray_now} + single AMS {active_ams_id} -> global ID {global_tray_id}"
  1576. )
  1577. self.state.tray_now = global_tray_id
  1578. elif len(ams_on_extruder) > 1:
  1579. # Multiple AMS on this extruder - keep current if valid, else try to narrow down
  1580. current_tray = self.state.tray_now
  1581. # Determine which AMS unit and slot the current tray belongs to
  1582. if 0 <= current_tray <= 15:
  1583. current_ams = current_tray // 4
  1584. current_slot = current_tray % 4
  1585. elif 128 <= current_tray <= 135:
  1586. current_ams = current_tray # AMS-HT: ID = tray ID
  1587. current_slot = 0
  1588. else:
  1589. current_ams = -1
  1590. current_slot = -1
  1591. if current_ams in ams_on_extruder and current_slot == parsed_tray_now:
  1592. # Current is valid and matches slot - keep it
  1593. logger.debug(
  1594. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  1595. f"keeping current {current_tray} (matches slot {parsed_tray_now})"
  1596. )
  1597. else:
  1598. # Filter candidates: AMS-HT (128-135) only valid for slot 0
  1599. if parsed_tray_now > 0:
  1600. candidates = [a for a in ams_on_extruder if a <= 3]
  1601. else:
  1602. candidates = ams_on_extruder
  1603. if len(candidates) == 1:
  1604. cand = candidates[0]
  1605. resolved = cand if 128 <= cand <= 135 else cand * 4 + parsed_tray_now
  1606. logger.debug(
  1607. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder}, "
  1608. f"narrowed to AMS {cand} -> global ID {resolved}"
  1609. )
  1610. self.state.tray_now = resolved
  1611. else:
  1612. # Genuinely ambiguous - use slot as-is (will be wrong for non-first AMS)
  1613. logger.warning(
  1614. f"[{self.serial_number}] H2D tray_now: multiple AMS {ams_on_extruder} on extruder {active_ext}, "
  1615. f"no snow field, using slot {parsed_tray_now} (may be incorrect)"
  1616. )
  1617. self.state.tray_now = parsed_tray_now
  1618. else:
  1619. # No AMS on this extruder - use slot as-is
  1620. logger.warning(
  1621. f"[{self.serial_number}] H2D tray_now: no AMS on extruder {active_ext}, "
  1622. f"using slot {parsed_tray_now}"
  1623. )
  1624. self.state.tray_now = parsed_tray_now
  1625. elif not self._is_dual_nozzle and 0 <= parsed_tray_now <= 3:
  1626. # Single-nozzle printer with tray_now in 0-3 range.
  1627. # #1822: H2S firmware reports tray_now as the AMS's idle
  1628. # slot (typically 0) when the active feed is actually the
  1629. # external spool. X1C / P1S / A1 correctly report 254 in
  1630. # that case; H2S does not. When the slicer-captured
  1631. # ams_mapping is all-external (every entry == -1), the
  1632. # print can only be feeding from the external spool, so
  1633. # promote tray_now to 254. Mixed (e.g. [5, -1]) and
  1634. # AMS-only mappings are NOT overridden — there's no
  1635. # evidence the firmware misreports in those cases. Prints
  1636. # started without a captured mapping (printer-screen start,
  1637. # or before Bambuddy connected) fall through unchanged.
  1638. captured = self._captured_ams_mapping
  1639. if captured and all(s == -1 for s in captured):
  1640. if self.state.tray_now != 254:
  1641. logger.debug(
  1642. f"[{self.serial_number}] tray_now external-spool override (#1822): "
  1643. f"slot {parsed_tray_now} -> 254 (ams_mapping={captured})"
  1644. )
  1645. self.state.tray_now = 254
  1646. else:
  1647. # P2S (and possibly other models) with multiple AMS units sends LOCAL slot IDs
  1648. # in tray_now, not global tray IDs (#420). Use the MQTT mapping field
  1649. # (snow-encoded) to resolve the correct AMS unit.
  1650. ams_exist_raw = ams_data.get("ams_exist_bits", "0")
  1651. try:
  1652. ams_exist = int(ams_exist_raw, 16) if isinstance(ams_exist_raw, str) else int(ams_exist_raw)
  1653. except (ValueError, TypeError):
  1654. ams_exist = 0
  1655. num_ams = bin(ams_exist).count("1")
  1656. if num_ams > 1:
  1657. # Multiple AMS on single-nozzle — tray_now is likely a local slot ID.
  1658. # Cross-reference with MQTT mapping field to find the correct AMS unit.
  1659. mapping_raw = self.state.raw_data.get("mapping")
  1660. resolved = self._resolve_local_slot_from_mapping(parsed_tray_now, mapping_raw)
  1661. if resolved is not None:
  1662. if resolved != parsed_tray_now:
  1663. logger.debug(
  1664. f"[{self.serial_number}] Multi-AMS tray_now: "
  1665. f"local slot {parsed_tray_now} -> global ID {resolved} (from mapping)"
  1666. )
  1667. self.state.tray_now = resolved
  1668. else:
  1669. # No mapping available (not printing, or ambiguous) — use as-is.
  1670. # This matches the old behavior and is correct for AMS 0.
  1671. self.state.tray_now = parsed_tray_now
  1672. else:
  1673. # Single AMS — local slot 0-3 equals global ID
  1674. self.state.tray_now = parsed_tray_now
  1675. else:
  1676. # tray_now > 3 means it's already a global ID, or 255 means unloaded
  1677. # Note: Do NOT clear pending_tray_target on tray_now=255 here.
  1678. # During filament change, the printer sends 255 first (unload), then the slot.
  1679. # We only clear pending_tray_target explicitly in ams_unload_filament().
  1680. # Trust the printer's reported value.
  1681. self.state.tray_now = parsed_tray_now
  1682. # Track last valid tray for usage tracking (survives retract → 255 at print end)
  1683. # Valid physical trays: 0-15 (regular AMS), 128-135 (AMS-HT), 254 (external spool)
  1684. tn = self.state.tray_now
  1685. if (0 <= tn <= 15) or (128 <= tn <= 135) or tn == 254:
  1686. # Log tray change for mid-print usage splitting. Gate on the
  1687. # print-lifecycle flags (`_was_running` set on first RUNNING /
  1688. # new print, `_completion_triggered` set when on_print_complete
  1689. # fires) instead of `state in ("RUNNING", "PAUSE")` — P2S
  1690. # firmware briefly transitions out of RUNNING during AMS
  1691. # auto-fallback (#957), so a literal-string gate misses the
  1692. # switch and the usage tracker double-credits at completion.
  1693. if tn != self.state.last_loaded_tray and self._was_running and not self._completion_triggered:
  1694. self.state.tray_change_log.append((tn, self.state.layer_num))
  1695. logger.info(
  1696. "[%s] Tray change during print: tray=%d at layer=%d",
  1697. self.serial_number,
  1698. tn,
  1699. self.state.layer_num,
  1700. )
  1701. self.state.last_loaded_tray = self.state.tray_now
  1702. logger.debug("[%s] tray_now updated: %s", self.serial_number, self.state.tray_now)
  1703. # NOTE: ams_status is parsed BEFORE tray_now (see above) to ensure correct
  1704. # state when checking filament change mode for H2D disambiguation
  1705. # P1S/P1P send partial updates without "ams" key - this is valid, not an error
  1706. # We've already processed the status fields above, so just return if no ams list
  1707. if ams_list is None:
  1708. logger.debug("[%s] AMS partial update (no tray data)", self.serial_number)
  1709. return
  1710. elif isinstance(ams_data, list):
  1711. ams_list = ams_data
  1712. else:
  1713. logger.warning("[%s] Unexpected AMS data format: %s", self.serial_number, type(ams_data))
  1714. return
  1715. # Merge AMS data instead of replacing, to handle partial updates
  1716. # During prints, the printer may only send updates for active AMS units
  1717. # We need deep merging at the tray level to preserve fields like tray_sub_brands
  1718. existing_ams = self.state.raw_data.get("ams", [])
  1719. existing_by_id = {ams.get("id"): ams for ams in existing_ams if ams.get("id") is not None}
  1720. # Update existing units with new data, add new units
  1721. for ams_unit in ams_list:
  1722. ams_id = ams_unit.get("id")
  1723. if ams_id is not None:
  1724. existing_unit = existing_by_id.get(ams_id)
  1725. if existing_unit and "tray" in ams_unit:
  1726. # Deep merge trays to preserve fields from previous updates
  1727. existing_trays = {t.get("id"): t for t in existing_unit.get("tray", []) if t.get("id") is not None}
  1728. merged_trays = []
  1729. for new_tray in ams_unit.get("tray", []):
  1730. tray_id = new_tray.get("id")
  1731. if tray_id is not None and tray_id in existing_trays:
  1732. # Merge: start with existing, update with new non-empty values
  1733. merged_tray = existing_trays[tray_id].copy()
  1734. # Detect slot-clearing updates (spool removal):
  1735. # When tray_type is explicitly empty, clear everything
  1736. # including RFID data (tag_uid/tray_uuid).
  1737. slot_clearing = new_tray.get("tray_type") == ""
  1738. # Some printers (e.g. H2D) only send {id, state} in
  1739. # incremental updates when a tray is not fully loaded.
  1740. # state=11 means loaded; other values (9=empty,
  1741. # 10=spool present but filament not in feeder) indicate
  1742. # the slot should be cleared. Without this, old
  1743. # tray_type/tray_color persist indefinitely (#784).
  1744. tray_state = new_tray.get("state")
  1745. if (
  1746. tray_state is not None
  1747. and tray_state != 11
  1748. and "tray_type" not in new_tray
  1749. and merged_tray.get("tray_type")
  1750. ):
  1751. logger.info(
  1752. "[%s] AMS %s tray %s: state=%s (not loaded) — clearing stale tray data",
  1753. self.serial_number,
  1754. ams_id,
  1755. tray_id,
  1756. tray_state,
  1757. )
  1758. slot_clearing = True
  1759. # The incremental update only has {id, state} — inject
  1760. # empty values for all content fields so the merge loop
  1761. # below clears the stale data from merged_tray.
  1762. new_tray.update(
  1763. {
  1764. "tray_type": "",
  1765. "tray_sub_brands": "",
  1766. "tray_color": "",
  1767. "tray_id_name": "",
  1768. "tray_info_idx": "",
  1769. "tag_uid": "0000000000000000",
  1770. "tray_uuid": "00000000000000000000000000000000",
  1771. "remain": 0,
  1772. "k": None,
  1773. "cali_idx": None,
  1774. }
  1775. )
  1776. for key, value in new_tray.items():
  1777. # Fields that should always be updated (even with empty/zero values):
  1778. # - remain, k, id, cali_idx: status indicators where 0 is valid
  1779. # - tray_type, tray_sub_brands, tray_info_idx, tray_color,
  1780. # tray_id_name: slot content indicators that must be cleared
  1781. # when a spool is removed (fixes #147 - old AMS empty slot)
  1782. # NOTE: tag_uid and tray_uuid are NOT in always_update_fields.
  1783. # They are only cleared during spool removal (slot_clearing=True).
  1784. # Periodic AMS updates often include empty RFID fields which
  1785. # would overwrite valid data from the initial pushall.
  1786. always_update_fields = (
  1787. "remain",
  1788. "k",
  1789. "id",
  1790. "cali_idx",
  1791. "tray_type",
  1792. "tray_sub_brands",
  1793. "tray_info_idx",
  1794. "tray_color",
  1795. "tray_id_name",
  1796. )
  1797. if (
  1798. key in always_update_fields
  1799. or slot_clearing
  1800. or value
  1801. not in (
  1802. None,
  1803. "",
  1804. "0000000000000000",
  1805. "00000000000000000000000000000000",
  1806. )
  1807. ):
  1808. merged_tray[key] = value
  1809. merged_trays.append(merged_tray)
  1810. else:
  1811. merged_trays.append(new_tray)
  1812. # Update ams_unit with merged trays. Spread existing_unit
  1813. # FIRST so top-level fields the partial update omits —
  1814. # dry_time, info (which drives dry_status / dry_sub_status),
  1815. # humidity, temp — are preserved instead of dropped. The
  1816. # printer sends tray-bearing partials that carry no drying
  1817. # fields; without this, dry_time reads as absent → 0 and the
  1818. # falling-edge detector below fires a false "drying complete"
  1819. # (#1462). Mirrors the no-tray branch's merge semantics.
  1820. ams_unit = {**existing_unit, **ams_unit, "tray": merged_trays}
  1821. elif existing_unit:
  1822. # Partial update without tray data: merge new fields into existing
  1823. # unit to preserve tray, sn, sw_ver, and other accumulated data.
  1824. ams_unit = {**existing_unit, **ams_unit}
  1825. existing_by_id[ams_id] = ams_unit
  1826. # Convert back to list, sorted by ID for consistent ordering
  1827. merged_ams = sorted(existing_by_id.values(), key=lambda x: x.get("id", 0))
  1828. # Empty-slot cleanup via tray_exist_bits (#147, #1322, #765, #1365).
  1829. # Shared with the VP bridge cache so the slicer-facing view stays in
  1830. # sync with Bambuddy's AMS card (#1726). See the helper's docstring
  1831. # for the full rationale and the printer-shutdown guard.
  1832. if isinstance(ams_data, dict):
  1833. apply_tray_exist_bits(
  1834. merged_ams,
  1835. ams_data.get("tray_exist_bits"),
  1836. power_on_flag=ams_data.get("power_on_flag", True),
  1837. log_label=self.serial_number,
  1838. )
  1839. self.state.raw_data["ams"] = merged_ams
  1840. # Apply cached AMS firmware/SN from get_version (handles ordering and id type mismatches)
  1841. self._apply_ams_version_cache(merged_ams)
  1842. # Update timestamp for RFID refresh detection (frontend can detect "new data arrived")
  1843. self.state.last_ams_update = time.time()
  1844. logger.debug("[%s] Merged AMS data: %s new units, %s total", self.serial_number, len(ams_list), len(merged_ams))
  1845. # Extract ams_extruder_map from each AMS unit's info field
  1846. # BambuStudio DevFilaSystem.cpp parses info as hex string:
  1847. # type_id = get_flag_bits(info, 0, 4) // bits 0-3: AMS type
  1848. # extruder_id = get_flag_bits(info, 8, 4) // bits 8-11: extruder assignment
  1849. # where get_flag_bits uses std::stoull(str, nullptr, 16) — hex parsing.
  1850. # extruder_id: 0=right/main, 1=left/deputy, 0xE=uninitialized (skip)
  1851. #
  1852. # Use merged_ams (not ams_list) to avoid partial MQTT updates overwriting
  1853. # the full map. Merge into existing map to preserve entries from prior updates.
  1854. ams_extruder_map = dict(self.state.ams_extruder_map) if self.state.ams_extruder_map else {}
  1855. for ams_unit in merged_ams:
  1856. ams_id = ams_unit.get("id")
  1857. info = ams_unit.get("info")
  1858. if ams_id is not None and info is not None:
  1859. try:
  1860. # info is a hex-encoded string in MQTT JSON (e.g. "10001003")
  1861. info_val = int(str(info), 16)
  1862. # Extract 4 bits starting at bit 8 for extruder assignment
  1863. extruder_id = (info_val >> 8) & 0xF
  1864. if extruder_id == 0xE:
  1865. # 0xE = uninitialized AMS, skip
  1866. continue
  1867. ams_extruder_map[str(ams_id)] = extruder_id
  1868. logger.debug(f"[{self.serial_number}] AMS {ams_id} info=0x{info} -> extruder {extruder_id}")
  1869. except (ValueError, TypeError):
  1870. pass # Skip AMS units with unparseable info bitmask values
  1871. if ams_extruder_map:
  1872. self.state.raw_data["ams_extruder_map"] = ams_extruder_map
  1873. self.state.ams_extruder_map = ams_extruder_map
  1874. logger.debug("[%s] ams_extruder_map: %s", self.serial_number, ams_extruder_map)
  1875. # Extract drying status from info hex string and dry_sf_reason per AMS unit
  1876. # BambuStudio DevFilaSystem.cpp parses info bits:
  1877. # dry_status = get_flag_bits(info, 4, 4) // bits 4-7
  1878. # dry_sub_status = get_flag_bits(info, 22, 4) // bits 22-25
  1879. for ams_unit in merged_ams:
  1880. info = ams_unit.get("info")
  1881. if info is not None:
  1882. try:
  1883. info_val = int(str(info), 16)
  1884. ams_unit["dry_status"] = (info_val >> 4) & 0xF
  1885. ams_unit["dry_sub_status"] = (info_val >> 22) & 0xF
  1886. except (ValueError, TypeError):
  1887. pass # Skip unparseable info values
  1888. # dry_sf_reason is a per-unit array of cannot-dry reason codes
  1889. if "dry_sf_reason" in ams_unit:
  1890. sf_reason = ams_unit["dry_sf_reason"]
  1891. if isinstance(sf_reason, list):
  1892. ams_unit["dry_sf_reason"] = [
  1893. int(r) for r in sf_reason if isinstance(r, int) or (isinstance(r, str) and r.isdigit())
  1894. ]
  1895. else:
  1896. ams_unit["dry_sf_reason"] = []
  1897. # Persist updated drying fields back to raw_data
  1898. self.state.raw_data["ams"] = merged_ams
  1899. # Detect AMS drying-complete falling edge per-unit (#1349). When an
  1900. # AMS's `dry_time` transitions from >0 to 0 the cycle just finished
  1901. # — fire the callback so smart-plug auto-off-after-drying can run,
  1902. # and drop our cached target-cycle params so the badge stops claiming
  1903. # an active cycle. Works identically for queue-triggered, ambient,
  1904. # and manual drying because we observe the firmware-reported state.
  1905. for ams_unit in merged_ams:
  1906. try:
  1907. ams_id = int(ams_unit.get("id", -1))
  1908. except (TypeError, ValueError):
  1909. continue
  1910. if ams_id < 0:
  1911. continue
  1912. # Only evaluate the edge when this update carries an explicit
  1913. # dry_time. An absent / unparseable value is NOT zero — treating
  1914. # it as 0 lets a tray-only partial fake a drying-complete edge
  1915. # (#1462). Skip without touching the remembered value so the
  1916. # next update that DOES carry dry_time sees the true previous.
  1917. raw_dry_time = ams_unit.get("dry_time")
  1918. if raw_dry_time is None:
  1919. continue
  1920. try:
  1921. current = int(raw_dry_time)
  1922. except (TypeError, ValueError):
  1923. continue
  1924. previous = self._previous_dry_times.get(ams_id, 0)
  1925. self._previous_dry_times[ams_id] = current
  1926. if previous > 0 and current == 0:
  1927. logger.info(
  1928. "[%s] AMS %d drying complete (dry_time %d → 0)",
  1929. self.serial_number,
  1930. ams_id,
  1931. previous,
  1932. )
  1933. self._drying_targets.pop(ams_id, None)
  1934. if self.on_drying_complete:
  1935. self.on_drying_complete(ams_id)
  1936. # Create a hash of relevant AMS data to detect changes
  1937. ams_hash_data = []
  1938. for ams_unit in ams_list:
  1939. for tray in ams_unit.get("tray", []):
  1940. # Include fields that matter for filament tracking
  1941. ams_hash_data.append(
  1942. f"{ams_unit.get('id')}:{tray.get('id')}:"
  1943. f"{tray.get('tray_type')}:{tray.get('tag_uid')}:{tray.get('remain')}"
  1944. )
  1945. ams_hash = hashlib.md5(":".join(ams_hash_data).encode(), usedforsecurity=False).hexdigest()
  1946. # Only trigger callback if AMS data actually changed
  1947. if ams_hash != self._previous_ams_hash:
  1948. self._previous_ams_hash = ams_hash
  1949. if self.on_ams_change:
  1950. logger.debug("[%s] AMS data changed, triggering sync callback", self.serial_number)
  1951. # Pass merged AMS data (not raw ams_list) — partial MQTT updates
  1952. # may lack fields like 'remain' that the merged state preserves
  1953. self.on_ams_change(merged_ams)
  1954. def _update_state(self, data: dict):
  1955. """Update printer state from message data."""
  1956. _previous_state = self.state.state
  1957. # Update state fields
  1958. if "gcode_state" in data:
  1959. self.state.state = data["gcode_state"]
  1960. if "gcode_file" in data:
  1961. self.state.gcode_file = data["gcode_file"]
  1962. self.state.current_print = data["gcode_file"]
  1963. if "subtask_name" in data:
  1964. self.state.subtask_name = data["subtask_name"]
  1965. # Prefer subtask_name as current_print if available
  1966. if data["subtask_name"]:
  1967. self.state.current_print = data["subtask_name"]
  1968. if "subtask_id" in data:
  1969. self.state.subtask_id = data["subtask_id"]
  1970. if "mc_percent" in data:
  1971. # Save last non-zero progress for usage tracking (firmware resets to 0 on cancel)
  1972. if self.state.progress > 0:
  1973. self._last_valid_progress = self.state.progress
  1974. self.state.progress = float(data["mc_percent"])
  1975. if "mc_remaining_time" in data:
  1976. self.state.remaining_time = int(data["mc_remaining_time"])
  1977. if "mc_print_sub_stage" in data:
  1978. new_sub_stage = int(data["mc_print_sub_stage"])
  1979. if new_sub_stage != self.state.mc_print_sub_stage:
  1980. logger.debug(
  1981. f"[{self.serial_number}] mc_print_sub_stage changed: "
  1982. f"{self.state.mc_print_sub_stage} -> {new_sub_stage}"
  1983. )
  1984. self.state.mc_print_sub_stage = new_sub_stage
  1985. if "layer_num" in data:
  1986. new_layer = int(data["layer_num"])
  1987. old_layer = self.state.layer_num
  1988. # Save last non-zero layer for usage tracking (firmware resets to 0 on cancel)
  1989. if old_layer > 0:
  1990. self._last_valid_layer_num = old_layer
  1991. self.state.layer_num = new_layer
  1992. # Trigger layer change callback if layer increased
  1993. if new_layer > old_layer and self.on_layer_change:
  1994. self.on_layer_change(new_layer)
  1995. if "total_layer_num" in data:
  1996. # Some firmware (P1S observed) resets `total_layer_num` to 0 at
  1997. # print end — same shape as the `layer_num` reset guarded above.
  1998. # Preserve the last known good value so the usage-tracker split
  1999. # path (#1771) has a denominator that survives the reset frame.
  2000. # Explicit reset to 0 happens on print start (`_handle_print_start`).
  2001. new_total = int(data["total_layer_num"])
  2002. if new_total > 0:
  2003. self.state.total_layers = new_total
  2004. # Fan speeds (MQTT sends as string "0"-"15" representing speed levels, or percentage)
  2005. # Convert to 0-100 percentage for display
  2006. def parse_fan_speed(value: str | int | None) -> int | None:
  2007. if value is None:
  2008. return None
  2009. try:
  2010. speed = int(value)
  2011. # MQTT reports 0-15 speed levels, convert to percentage (0-100)
  2012. # 15 = 100%, so multiply by 100/15 ≈ 6.67
  2013. if speed <= 15:
  2014. return round(speed * 100 / 15)
  2015. # If already a percentage (0-255 scale from some printers), convert
  2016. elif speed <= 255:
  2017. return round(speed * 100 / 255)
  2018. return speed
  2019. except (ValueError, TypeError):
  2020. return None
  2021. # Log fan fields once for debugging
  2022. if not hasattr(self, "_fan_fields_logged"):
  2023. fan_fields = {k: v for k, v in data.items() if "fan" in k.lower()}
  2024. if fan_fields:
  2025. logger.debug("[%s] Fan fields in MQTT data: %s", self.serial_number, fan_fields)
  2026. self._fan_fields_logged = True
  2027. if "cooling_fan_speed" in data:
  2028. self.state.cooling_fan_speed = parse_fan_speed(data["cooling_fan_speed"])
  2029. if "big_fan1_speed" in data:
  2030. self.state.big_fan1_speed = parse_fan_speed(data["big_fan1_speed"])
  2031. if "big_fan2_speed" in data:
  2032. self.state.big_fan2_speed = parse_fan_speed(data["big_fan2_speed"])
  2033. if "heatbreak_fan_speed" in data:
  2034. self.state.heatbreak_fan_speed = parse_fan_speed(data["heatbreak_fan_speed"])
  2035. # Calibration stage tracking
  2036. if "stg_cur" in data:
  2037. new_stg = data["stg_cur"]
  2038. prev_stg = self.state.stg_cur
  2039. # Always log ANY stg_cur change for debugging filament operations
  2040. if new_stg != prev_stg:
  2041. logger.debug(
  2042. f"[{self.serial_number}] stg_cur changed: {prev_stg} -> {new_stg} ({get_stage_name(new_stg)})"
  2043. )
  2044. self.state.stg_cur = new_stg
  2045. # #1721 end-of-print finish photo trigger.
  2046. # Stage 22 = "Filament unloading" fires at end-of-print AND
  2047. # during mid-print color swaps. The end-of-print gate
  2048. # (progress>=99 / layer>=total / remaining<=0) disambiguates
  2049. # — those signals only line up at the real end. Edge-only
  2050. # (prev != 22) so the trigger fires once per stage entry.
  2051. if (
  2052. new_stg == 22
  2053. and prev_stg != 22
  2054. and self._was_running
  2055. and not self._finish_photo_captured
  2056. and self.on_finish_photo_moment
  2057. ):
  2058. progress = self.state.progress or 0.0
  2059. layer_num = self.state.layer_num or 0
  2060. total_layers = self.state.total_layers or 0
  2061. remaining = self.state.remaining_time or 0
  2062. is_end_of_print = progress >= 99 or (total_layers > 0 and layer_num >= total_layers) or remaining <= 0
  2063. if is_end_of_print:
  2064. self._finish_photo_captured = True
  2065. logger.info(
  2066. f"[{self.serial_number}] FINISH PHOTO MOMENT (stage-22) — "
  2067. f"progress={progress}, layer={layer_num}/{total_layers}, "
  2068. f"remaining={remaining}min, timelapse_active={self._timelapse_during_print}"
  2069. )
  2070. self.on_finish_photo_moment(
  2071. {
  2072. "trigger": "stage_22",
  2073. "filename": self._previous_gcode_file or self.state.gcode_file,
  2074. "subtask_name": self.state.subtask_name,
  2075. "timelapse_was_active": self._timelapse_during_print,
  2076. }
  2077. )
  2078. if "stg" in data:
  2079. self.state.stg = data["stg"] if isinstance(data["stg"], list) else []
  2080. # Temperature data
  2081. temps = {}
  2082. # Log all fields for debugging dual-nozzle temperature discovery (only once)
  2083. if "bed_temper" in data and not hasattr(self, "_temp_fields_logged"):
  2084. temp_fields = {k: v for k, v in data.items() if "temp" in k.lower() or "chamber" in k.lower()}
  2085. logger.debug("[%s] Temperature-related fields: %s", self.serial_number, temp_fields)
  2086. # Log ALL keys in print data for H2D temperature discovery
  2087. all_keys = sorted(data.keys())
  2088. logger.debug("[%s] ALL print data keys (%s): %s", self.serial_number, len(all_keys), all_keys)
  2089. self._temp_fields_logged = True
  2090. # Log vir_slot data (once) - this may contain per-extruder slot mapping for H2D
  2091. if "vir_slot" in data and not hasattr(self, "_vir_slot_logged"):
  2092. logger.debug("[%s] vir_slot data: %s", self.serial_number, data["vir_slot"])
  2093. self._vir_slot_logged = True
  2094. # Log nozzle hardware info fields (once)
  2095. nozzle_fields = {
  2096. k: v
  2097. for k, v in data.items()
  2098. if "nozzle" in k.lower() or "hw" in k.lower() or "extruder" in k.lower() or "upgrade" in k.lower()
  2099. }
  2100. if nozzle_fields and not hasattr(self, "_nozzle_fields_logged"):
  2101. logger.debug("[%s] Nozzle/hardware fields in MQTT data: %s", self.serial_number, nozzle_fields)
  2102. self._nozzle_fields_logged = True
  2103. # Parse active extruder from device.extruder.state bit 8
  2104. # bit 8 = 0 → RIGHT extruder (active_extruder=0)
  2105. # bit 8 = 1 → LEFT extruder (active_extruder=1)
  2106. if "device" in data and isinstance(data.get("device"), dict):
  2107. device = data["device"]
  2108. # One-shot identification probe: surface whatever the firmware uses to
  2109. # name itself so an unknown model in a support bundle becomes self-
  2110. # diagnosing. INFO level so it shows up without debug logging. Falls
  2111. # back to dumping device.keys() if none of the known fields are present
  2112. # (so a future Bambu rename like `model_name` is still observable).
  2113. if not getattr(self, "_device_id_logged", False):
  2114. id_fields = {
  2115. k: device.get(k)
  2116. for k in ("dev_model_name", "dev_product_name", "dev_id", "project_name")
  2117. if k in device
  2118. }
  2119. if id_fields:
  2120. logger.info("[%s] Device identification: %s", self.serial_number, id_fields)
  2121. else:
  2122. logger.info(
  2123. "[%s] Device identification: no known id fields; device.keys=%s",
  2124. self.serial_number,
  2125. sorted(device.keys()),
  2126. )
  2127. self._device_id_logged = True
  2128. if "extruder" in device and "state" in device["extruder"]:
  2129. state_val = device["extruder"]["state"]
  2130. # Extract bit 8 for extruder position
  2131. new_extruder = (state_val >> 8) & 0x1
  2132. if new_extruder != self.state.active_extruder:
  2133. logger.debug(
  2134. f"[{self.serial_number}] ACTIVE EXTRUDER CHANGED (state bit 8): {self.state.active_extruder} -> {new_extruder} (0=right, 1=left) [state={state_val}]"
  2135. )
  2136. self.state.active_extruder = new_extruder
  2137. # Log device.extruder structure for active extruder
  2138. if "device" in data and isinstance(data.get("device"), dict):
  2139. device = data["device"]
  2140. if "extruder" in device:
  2141. ext_data = device["extruder"]
  2142. # Log 'state' field - OrcaSlicer uses bits 12-14 for switch state
  2143. if "state" in ext_data:
  2144. state_val = ext_data["state"]
  2145. # Extract bits 12-14 (3 bits) for switch state
  2146. switch_state = (state_val >> 12) & 0x7
  2147. logger.debug(
  2148. f"[{self.serial_number}] device.extruder.state={state_val} (switch_state bits 12-14: {switch_state})"
  2149. )
  2150. # Log 'cur' field if present (might indicate current/active extruder)
  2151. if "cur" in ext_data:
  2152. logger.debug("[%s] device.extruder.cur: %s", self.serial_number, ext_data["cur"])
  2153. # Filament Track Switch (FTS) detection — #1162. Presence of
  2154. # device.fila_switch in MQTT means the FTS accessory is installed.
  2155. if "device" in data and isinstance(data.get("device"), dict):
  2156. fs_data = data["device"].get("fila_switch")
  2157. if isinstance(fs_data, dict):
  2158. in_raw = fs_data.get("in")
  2159. out_raw = fs_data.get("out")
  2160. self.state.fila_switch = FilaSwitchState(
  2161. installed=True,
  2162. in_slots=list(in_raw) if isinstance(in_raw, list) else [],
  2163. out_extruders=list(out_raw) if isinstance(out_raw, list) else [],
  2164. stat=int(fs_data.get("stat", 0) or 0),
  2165. info=int(fs_data.get("info", 0) or 0),
  2166. )
  2167. if "bed_temper" in data:
  2168. temps["bed"] = float(data["bed_temper"])
  2169. if "bed_target_temper" in data:
  2170. temps["bed_target"] = float(data["bed_target_temper"])
  2171. # Check if this is H2D (has device.extruder.info with 2 extruders)
  2172. has_h2d_extruder_info = (
  2173. "device" in data
  2174. and isinstance(data.get("device"), dict)
  2175. and "extruder" in data["device"]
  2176. and isinstance(data["device"]["extruder"].get("info"), list)
  2177. and len(data["device"]["extruder"]["info"]) >= 2
  2178. )
  2179. # Standard nozzle fields: these are for the RIGHT/default nozzle on H2D
  2180. # For H2D, we use these for nozzle_2 (RIGHT), for others use as nozzle (primary)
  2181. # NOTE: On H2D, nozzle_temper seems to mirror left nozzle - we override with extruder_info[0] later
  2182. if "nozzle_temper" in data:
  2183. if has_h2d_extruder_info:
  2184. temps["nozzle_2"] = float(data["nozzle_temper"]) # Will be overridden by extruder_info[0]
  2185. else:
  2186. temps["nozzle"] = float(data["nozzle_temper"])
  2187. if "nozzle_target_temper" in data:
  2188. if has_h2d_extruder_info:
  2189. temps["nozzle_2_target"] = float(data["nozzle_target_temper"]) # RIGHT target on H2D
  2190. else:
  2191. temps["nozzle_target"] = float(data["nozzle_target_temper"])
  2192. # Second nozzle for dual-extruder printers - skip for H2D (uses device.extruder.info instead)
  2193. if not has_h2d_extruder_info:
  2194. # Try multiple possible field names used by different firmware versions
  2195. if "nozzle_temper_2" in data:
  2196. val = float(data["nozzle_temper_2"])
  2197. if -50 < val < 500: # Valid temp range
  2198. temps["nozzle_2"] = val
  2199. else:
  2200. logger.debug("[%s] nozzle_temper_2=%s out of range", self.serial_number, val)
  2201. elif "right_nozzle_temper" in data:
  2202. val = float(data["right_nozzle_temper"])
  2203. if -50 < val < 500: # Valid temp range
  2204. temps["nozzle_2"] = val
  2205. else:
  2206. logger.debug("[%s] right_nozzle_temper=%s out of range", self.serial_number, val)
  2207. if "nozzle_target_temper_2" in data:
  2208. val = float(data["nozzle_target_temper_2"])
  2209. if 0 <= val < 500: # Valid temp range
  2210. temps["nozzle_2_target"] = val
  2211. else:
  2212. logger.debug("[%s] nozzle_target_temper_2=%s out of range", self.serial_number, val)
  2213. elif "right_nozzle_target_temper" in data:
  2214. val = float(data["right_nozzle_target_temper"])
  2215. if 0 <= val < 500: # Valid temp range
  2216. temps["nozzle_2_target"] = val
  2217. else:
  2218. logger.debug("[%s] right_nozzle_target_temper=%s out of range", self.serial_number, val)
  2219. # Also check for left nozzle as primary (some H2 models)
  2220. if "left_nozzle_temper" in data and "nozzle" not in temps:
  2221. temps["nozzle"] = float(data["left_nozzle_temper"])
  2222. if "left_nozzle_target_temper" in data and "nozzle_target" not in temps:
  2223. temps["nozzle_target"] = float(data["left_nozzle_target_temper"])
  2224. if "chamber_temper" in data:
  2225. chamber_val = float(data["chamber_temper"])
  2226. logger.debug("[%s] chamber_temper raw value: %s", self.serial_number, chamber_val)
  2227. # Check if we recently set the target locally (within 5 seconds)
  2228. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2229. respect_local = (time.time() - local_set_time) < 5.0
  2230. # H2D protocol: chamber_temper encoding indicates heater state
  2231. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  2232. # - When < 500: direct Celsius current temp only - heater is OFF
  2233. if -50 < chamber_val < 100:
  2234. # Direct value = heater is OFF
  2235. temps["chamber"] = chamber_val
  2236. if not respect_local:
  2237. temps["chamber_target"] = 0.0 # Heater off means target = 0
  2238. logger.debug("[%s] chamber_temper direct value: %s°C (heater OFF)", self.serial_number, chamber_val)
  2239. else:
  2240. logger.debug("[%s] chamber_temper %s out of direct range", self.serial_number, chamber_val)
  2241. # Try to decode if it looks like an encoded value
  2242. if chamber_val > 500:
  2243. mqtt_target = int(chamber_val) // 65536
  2244. current = int(chamber_val) % 65536
  2245. logger.debug(
  2246. f"[{self.serial_number}] chamber_temper decoded: mqtt_target={mqtt_target}, current={current}, respect_local={respect_local}"
  2247. )
  2248. if -50 < current < 100:
  2249. temps["chamber"] = float(current)
  2250. # Store decoded target for later use, but DON'T set chamber_heating here!
  2251. # Heating state will be calculated later after parsing ctc.info.target (explicit target)
  2252. # which is the authoritative source the slicer uses.
  2253. if not respect_local:
  2254. if 0 <= mqtt_target <= 60:
  2255. # Store as "decoded" target - may be overridden by explicit target fields
  2256. temps["_chamber_decoded_target"] = float(mqtt_target)
  2257. # Chamber target temperature (set by print file or display)
  2258. if "mc_target_cham" in data:
  2259. mc_target = float(data["mc_target_cham"])
  2260. logger.debug("[%s] mc_target_cham raw value: %s", self.serial_number, mc_target)
  2261. # Filter out encoded/invalid values - valid chamber target is 0-60°C
  2262. if 0 <= mc_target <= 60:
  2263. temps["chamber_target"] = mc_target
  2264. # H2D series: Chamber temp is in info.temp (may be encoded or direct °C)
  2265. # NOTE: Don't set chamber_heating here - let ctc.info.target or fallback logic handle it
  2266. # The encoded target in info.temp may be stale (slicer uses ctc.info.target as source of truth)
  2267. try:
  2268. if "info" in data and isinstance(data["info"], dict):
  2269. info_temp = data["info"].get("temp")
  2270. if info_temp is not None and "chamber" not in temps:
  2271. # Check for encoded value (target * 65536 + current)
  2272. if info_temp > 500:
  2273. # Decode: extract current temperature and target
  2274. target = info_temp // 65536
  2275. current = info_temp % 65536
  2276. temps["chamber"] = float(current)
  2277. # Store decoded target as fallback (may be overridden by ctc.info.target)
  2278. if "_chamber_decoded_target" not in temps:
  2279. temps["_chamber_decoded_target"] = float(target)
  2280. logger.debug(
  2281. f"[{self.serial_number}] info.temp encoded: {info_temp} -> current={current}, decoded_target={target}"
  2282. )
  2283. elif -50 < info_temp < 100:
  2284. # Valid direct temperature - heater is OFF
  2285. temps["chamber"] = float(info_temp)
  2286. temps["chamber_target"] = 0.0 # Direct value means heater off
  2287. logger.debug("[%s] info.temp direct: %s°C (heater OFF)", self.serial_number, info_temp)
  2288. # H2D series: Dual extruder temps are in device.extruder.info array
  2289. # Temperature values are encoded as fixed-point (value / 65536 = °C)
  2290. if "device" in data and isinstance(data["device"], dict):
  2291. device = data["device"]
  2292. # Parse dual extruder temperatures
  2293. extruder_data = device.get("extruder", {})
  2294. extruder_info = extruder_data.get("info", [])
  2295. if isinstance(extruder_info, list) and len(extruder_info) >= 1:
  2296. # H2D nozzle mapping: id=0 is RIGHT nozzle (default), id=1 is LEFT nozzle
  2297. # Only parse dual nozzle temps if this is actually a dual nozzle printer (H2D)
  2298. # has_h2d_extruder_info requires len(extruder_info) >= 2
  2299. if has_h2d_extruder_info:
  2300. # Right nozzle (extruder 0) - use extruder_info for actual temp, not nozzle_temper
  2301. # nozzle_temper field seems to mirror left nozzle on H2D, so use extruder_info[0]
  2302. if "temp" in extruder_info[0]:
  2303. temp_val = extruder_info[0]["temp"]
  2304. if temp_val > 500:
  2305. # Encoded format: temp = target * 65536 + current
  2306. target = temp_val // 65536
  2307. current = temp_val % 65536
  2308. if -50 < current < 500:
  2309. temps["nozzle_2"] = float(current)
  2310. if 0 < target < 500:
  2311. temps["nozzle_2_target"] = float(target)
  2312. temps["nozzle_2_heating"] = target > 0 and current < target
  2313. elif -50 < temp_val < 500:
  2314. # Direct Celsius value = heater is OFF
  2315. temps["nozzle_2"] = float(temp_val)
  2316. temps["nozzle_2_target"] = 0.0
  2317. temps["nozzle_2_heating"] = False
  2318. # Left nozzle (extruder 1) - only for dual nozzle printers
  2319. # H2D protocol: temp field encoding depends on value
  2320. # - When > 500: encoded as (target * 65536 + current) - heater is ON
  2321. # - When < 500: direct Celsius current temp only - heater is OFF
  2322. if len(extruder_info) >= 2 and "temp" in extruder_info[1]:
  2323. ext1 = extruder_info[1]
  2324. temp_val = ext1["temp"]
  2325. # Check if we recently set the target locally (within 5 seconds)
  2326. # If so, don't let MQTT data overwrite it
  2327. local_set_time = self.state.temperatures.get("_nozzle_target_set_time", 0)
  2328. respect_local_target = (time.time() - local_set_time) < 5.0
  2329. if temp_val > 500:
  2330. # Encoded format: temp = target * 65536 + current
  2331. target = temp_val // 65536
  2332. current = temp_val % 65536
  2333. if 0 < target < 500 and not respect_local_target:
  2334. temps["nozzle_target"] = float(target)
  2335. if -50 < current < 500:
  2336. temps["nozzle"] = float(current)
  2337. # Heating = encoded AND we're using the MQTT target (not local override)
  2338. # If local target is being respected, use local target to determine heating
  2339. if respect_local_target:
  2340. local_target = self.state.temperatures.get("nozzle_target", 0)
  2341. temps["nozzle_heating"] = local_target > 0 and current < local_target
  2342. else:
  2343. temps["nozzle_heating"] = target > 0 and current < target
  2344. elif -50 < temp_val < 500:
  2345. # Direct Celsius = heater is OFF (or at target with heater off)
  2346. temps["nozzle"] = float(temp_val)
  2347. if not respect_local_target:
  2348. temps["nozzle_target"] = 0.0
  2349. temps["nozzle_heating"] = False # Direct = not heating
  2350. # Parse H2D snow field (slot now) for accurate tray_now disambiguation
  2351. # snow encodes AMS ID in high byte: ams_id = snow >> 8, slot = snow & 0xFF
  2352. if has_h2d_extruder_info:
  2353. for ext_info in extruder_info:
  2354. ext_id = ext_info.get("id")
  2355. snow = ext_info.get("snow")
  2356. if ext_id is not None and snow is not None and ext_id <= 1:
  2357. # Normalize H2D snow value to global tray ID
  2358. ams_id = snow >> 8
  2359. slot = snow & 0xFF
  2360. if 0 <= ams_id <= 3:
  2361. # Regular AMS slot
  2362. global_tray = ams_id * 4 + (slot & 0x03)
  2363. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2364. if old_val != global_tray:
  2365. logger.debug(
  2366. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2367. f"raw={snow} (AMS {ams_id} slot {slot}) -> global tray {global_tray}"
  2368. )
  2369. self.state.h2d_extruder_snow[ext_id] = global_tray
  2370. elif ams_id == 254 or ams_id == 255:
  2371. # External spool or unloaded
  2372. normalized = 254 if slot != 255 else 255
  2373. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2374. if old_val != normalized:
  2375. logger.debug(
  2376. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2377. f"raw={snow} -> {'external' if normalized == 254 else 'unloaded'}"
  2378. )
  2379. self.state.h2d_extruder_snow[ext_id] = normalized
  2380. elif 128 <= ams_id <= 135:
  2381. # External spool with hub mapping
  2382. old_val = self.state.h2d_extruder_snow.get(ext_id)
  2383. if old_val != ams_id:
  2384. logger.debug(
  2385. f"[{self.serial_number}] H2D extruder[{ext_id}] snow: "
  2386. f"raw={snow} -> external hub {ams_id}"
  2387. )
  2388. self.state.h2d_extruder_snow[ext_id] = ams_id
  2389. # Parse bed heating state from device.bed.info.temp encoding
  2390. # temp > 500 means encoded (target*65536+current), heating = target > 0 AND current < target
  2391. bed_data = device.get("bed", {})
  2392. bed_info = bed_data.get("info", {})
  2393. if "temp" in bed_info:
  2394. temp_val = bed_info["temp"]
  2395. if temp_val > 500:
  2396. target = temp_val // 65536
  2397. current = temp_val % 65536
  2398. temps["bed_heating"] = target > 0 and current < target
  2399. else:
  2400. temps["bed_heating"] = False
  2401. # Parse chamber temp from device.ctc.info.temp if not already set
  2402. ctc_data = device.get("ctc", {})
  2403. ctc_info = ctc_data.get("info", {})
  2404. # Parse airduct mode (0=cooling, 1=heating)
  2405. airduct_data = device.get("airduct", {})
  2406. if "modeCur" in airduct_data:
  2407. new_mode = airduct_data["modeCur"]
  2408. if new_mode != self.state.airduct_mode:
  2409. logger.debug(
  2410. f"[{self.serial_number}] airduct_mode changed: {self.state.airduct_mode} -> {new_mode}"
  2411. )
  2412. self.state.airduct_mode = new_mode
  2413. # Parse chamber temp - may be encoded as (target*65536+current) when > 500
  2414. # Check if we recently set the target locally (within 5 seconds)
  2415. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2416. respect_local_target = (time.time() - local_set_time) < 5.0
  2417. # Log ctc_info contents for debugging
  2418. if ctc_info:
  2419. logger.debug("[%s] ctc_info keys: %s", self.serial_number, list(ctc_info.keys()))
  2420. # FIRST: Parse explicit ctc.info.target if available - this is the authoritative target
  2421. # (what the slicer shows). This OVERRIDES any previously decoded target.
  2422. explicit_target = None
  2423. if "target" in ctc_info:
  2424. target_val = ctc_info["target"]
  2425. logger.debug(
  2426. f"[{self.serial_number}] ctc_info.target explicit value: {target_val}, respect_local={respect_local_target}"
  2427. )
  2428. # Filter out invalid values (valid chamber target is 0-60°C)
  2429. if 0 <= target_val <= 60 and not respect_local_target:
  2430. explicit_target = float(target_val)
  2431. temps["chamber_target"] = explicit_target # Override any previous value
  2432. logger.debug(
  2433. f"[{self.serial_number}] Setting chamber_target from ctc_info.target: {explicit_target}"
  2434. )
  2435. # Parse chamber temp from ctc.info.temp - may be encoded
  2436. if "temp" in ctc_info and "chamber" not in temps:
  2437. temp_val = ctc_info["temp"]
  2438. logger.debug("[%s] ctc_info.temp raw value: %s", self.serial_number, temp_val)
  2439. if temp_val > 500:
  2440. # Encoded value: decode target and current
  2441. decoded_target = temp_val // 65536
  2442. current = temp_val % 65536
  2443. temps["chamber"] = float(current)
  2444. logger.debug(
  2445. f"[{self.serial_number}] ctc_info.temp decoded: target={decoded_target}, current={current}, explicit_target={explicit_target}"
  2446. )
  2447. # Determine which target to use for heating state:
  2448. # Priority: local target > explicit target > decoded target
  2449. if respect_local_target:
  2450. local_target = self.state.temperatures.get("chamber_target", 0)
  2451. temps["chamber_heating"] = local_target > 0 and current < local_target
  2452. elif explicit_target is not None:
  2453. # Use explicit ctc.info.target - this is what slicer sees
  2454. temps["chamber_heating"] = explicit_target > 0 and current < explicit_target
  2455. else:
  2456. # Fallback to decoded target only if no explicit target available
  2457. if not respect_local_target and "chamber_target" not in temps:
  2458. temps["chamber_target"] = float(decoded_target)
  2459. temps["chamber_heating"] = decoded_target > 0 and current < decoded_target
  2460. else:
  2461. # Direct value (not encoded) - heater is OFF
  2462. temps["chamber"] = float(temp_val)
  2463. temps["chamber_heating"] = False
  2464. except Exception as e:
  2465. logger.warning("[%s] Error parsing H2D temperatures: %s", self.serial_number, e)
  2466. if temps:
  2467. # Handle chamber_target: prefer explicit over decoded
  2468. if "_chamber_decoded_target" in temps and "chamber_target" not in temps:
  2469. # No explicit target available, use decoded target from chamber_temper
  2470. temps["chamber_target"] = temps["_chamber_decoded_target"]
  2471. # Remove internal temp key before merging
  2472. temps.pop("_chamber_decoded_target", None)
  2473. # Merge new temps into existing, preserving valid values when new ones are filtered out
  2474. for key, value in temps.items():
  2475. self.state.temperatures[key] = value
  2476. # Notify bed temperature updates (used by event-driven bed cooldown monitor)
  2477. if "bed" in temps and self.on_bed_temp_update:
  2478. self.on_bed_temp_update(temps["bed"])
  2479. # Calculate chamber_heating after all targets are known
  2480. # Priority: local target (if recent) > explicit target (chamber_target) > 0
  2481. if "chamber" in temps and "chamber_heating" not in temps:
  2482. current = self.state.temperatures.get("chamber", 0)
  2483. local_set_time = self.state.temperatures.get("_chamber_target_set_time", 0)
  2484. respect_local = (time.time() - local_set_time) < 5.0
  2485. if respect_local:
  2486. # Use locally-set target
  2487. target = self.state.temperatures.get("chamber_target", 0)
  2488. else:
  2489. # Use explicit/decoded target from MQTT
  2490. target = self.state.temperatures.get("chamber_target", 0)
  2491. self.state.temperatures["chamber_heating"] = target > 0 and current < target
  2492. logger.debug(
  2493. f"[{self.serial_number}] Chamber heating calculated: target={target}, current={current}, heating={self.state.temperatures['chamber_heating']}, respect_local={respect_local}"
  2494. )
  2495. # Debug: log chamber value if it was updated
  2496. if "chamber" in temps:
  2497. logger.debug(
  2498. f"[{self.serial_number}] Chamber temp updated to: {self.state.temperatures.get('chamber')}, target: {self.state.temperatures.get('chamber_target')}, heating: {self.state.temperatures.get('chamber_heating')}"
  2499. )
  2500. # Calculate nozzle_heating for single nozzle printers (not set by H2D parsing)
  2501. # For H2D, nozzle_heating is set in temps dict; for single nozzle, calculate here
  2502. if "nozzle" in temps and "nozzle_heating" not in temps:
  2503. current = self.state.temperatures.get("nozzle", 0)
  2504. target = self.state.temperatures.get("nozzle_target", 0)
  2505. self.state.temperatures["nozzle_heating"] = target > 0 and current < target
  2506. # Parse HMS (Health Management System) errors
  2507. if "hms" in data:
  2508. hms_list = data["hms"]
  2509. logger.debug("[%s] HMS data received: %s", self.serial_number, hms_list)
  2510. self.state.hms_errors = []
  2511. if isinstance(hms_list, list):
  2512. for hms in hms_list:
  2513. if isinstance(hms, dict):
  2514. # HMS format: {"attr": attribute_code, "code": error_code}
  2515. # attr contains module/severity info, code contains error number
  2516. # Both are needed to construct the wiki URL
  2517. attr = hms.get("attr", 0)
  2518. code = hms.get("code", 0)
  2519. if isinstance(attr, str):
  2520. attr = int(attr.replace("0x", ""), 16) if attr else 0
  2521. if isinstance(code, str):
  2522. code = int(code.replace("0x", ""), 16) if code else 0
  2523. # Severity is in attr byte 1 (bits 8-15)
  2524. severity = (attr >> 8) & 0xF
  2525. # Module is in attr byte 3 (bits 24-31)
  2526. module = (attr >> 24) & 0xFF
  2527. # Skip non-error status codes — all real HMS errors
  2528. # have code >= 0x4000. Lower values are status/phase
  2529. # indicators that some firmware sends during normal printing.
  2530. if code < 0x4000:
  2531. continue
  2532. # Skip user-action echoes — the printer firmware emits these
  2533. # as part of normal user-cancel sequences. They're not faults
  2534. # and shouldn't count toward "X problem" badges or surface as
  2535. # red pips on the printer card. Backend's notification path
  2536. # already suppresses 0500_400E for the same reason.
  2537. short_code = f"{(attr >> 16) & 0xFFFF:04X}_{code & 0xFFFF:04X}"
  2538. if short_code in _HMS_USER_ACTION_CODES:
  2539. continue
  2540. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  2541. self.state.hms_errors.append(
  2542. HMSError(
  2543. code=f"0x{code:x}" if code else "0x0",
  2544. attr=attr,
  2545. module=module,
  2546. severity=severity if severity > 0 else 2,
  2547. actions=actions,
  2548. job_id=self.state.subtask_id,
  2549. )
  2550. )
  2551. # Parse print_error - this is a different error format than HMS
  2552. # print_error is a 32-bit integer where:
  2553. # - High 16 bits contain module info (e.g., 0x0500)
  2554. # - Low 16 bits contain error code (e.g., 0x8061)
  2555. # Format on printer screen: [0500-8061] -> short code: 0500_8061
  2556. if "print_error" in data:
  2557. print_error = data["print_error"]
  2558. if print_error and print_error != 0:
  2559. # Extract components: MMMMEEEE -> MMMM_EEEE
  2560. module = (print_error >> 16) & 0xFFFF # High 16 bits (e.g., 0x0500)
  2561. error = print_error & 0xFFFF # Low 16 bits (e.g., 0x8061)
  2562. # Values below 0x4000 are status/phase indicators, not real errors.
  2563. # All known HMS errors use 0x4xxx (fatal), 0x8xxx (warning), 0xCxxx (prompt).
  2564. # Some firmware sends low values like 0x0002 during normal printing.
  2565. if error < 0x4000:
  2566. pass # Skip — not a real error
  2567. else:
  2568. # Store in a format that matches the community error database
  2569. # attr stores the full 32-bit value for reconstruction
  2570. # code stores the short format string for lookup
  2571. short_code = f"{module:04X}_{error:04X}"
  2572. logger.debug(
  2573. f"[{self.serial_number}] print_error: {print_error} (0x{print_error:08x}) -> short_code={short_code}"
  2574. )
  2575. # Same user-action filter as the hms[] branch above — print_error
  2576. # carries the same cancel echoes (e.g. 0500_400E) and they must
  2577. # not surface as faults on the printer card.
  2578. if short_code in _HMS_USER_ACTION_CODES:
  2579. pass # cancel echo — silently drop
  2580. else:
  2581. # Only add if not already in HMS errors (avoid duplicates)
  2582. existing_short_codes = set()
  2583. for e in self.state.hms_errors:
  2584. # Extract short code from existing errors
  2585. e_module = (e.attr >> 16) & 0xFFFF
  2586. e_error = int(e.code.replace("0x", ""), 16) if e.code else 0
  2587. existing_short_codes.add(f"{e_module:04X}_{e_error:04X}")
  2588. if short_code not in existing_short_codes:
  2589. # Bambu's HMS catalog keys by 3-letter device code (the SN
  2590. # prefix) and a 16-char short error code without the
  2591. # underscore separator we store internally.
  2592. actions = get_actions_for_error_code(self.serial_number[:3], short_code.replace("_", ""))
  2593. # Bambu pushes the current job as `subtask_id` on the
  2594. # state stream; the HMS-action commands echo it back as
  2595. # `job_id`. The error payload itself doesn't carry the
  2596. # id, so snapshot it from the live state at parse time
  2597. # and freeze it on the HMSError so subsequent
  2598. # job changes don't invalidate the action.
  2599. job_id = self.state.subtask_id
  2600. logger.debug(
  2601. "[%s, %s] HMS available actions: %s (job_id=%s)",
  2602. self.serial_number[:3],
  2603. short_code.replace("_", ""),
  2604. actions,
  2605. job_id,
  2606. )
  2607. self.state.hms_errors.append(
  2608. HMSError(
  2609. code=f"0x{error:x}",
  2610. attr=print_error, # Store full value for display
  2611. module=module >> 8, # High byte of module (e.g., 0x05)
  2612. severity=3, # Warning level for print_error
  2613. actions=actions,
  2614. job_id=job_id,
  2615. )
  2616. )
  2617. # Parse home_flag first so SD-card detection below can prefer it.
  2618. # Bit 8 = HAS_SDCARD_NORMAL, bit 9 = HAS_SDCARD_ABNORMAL, bit 11 = store-to-SD,
  2619. # bit 23 = door-open (X1 family only).
  2620. home_flag = None
  2621. if "home_flag" in data:
  2622. home_flag = data["home_flag"]
  2623. if home_flag < 0:
  2624. home_flag = home_flag & 0xFFFFFFFF
  2625. # SD card presence: the only remaining consumer is the firmware-update
  2626. # precondition check (firmware_update.py). Use the top-level `sdcard`
  2627. # field when present with a permissive truthy check covering the
  2628. # bool/int/"HAS_SDCARD_NORMAL" variants real firmware emits. We do NOT
  2629. # derive this from home_flag — heartbeat pushes clear bits 8-9 even
  2630. # when a card is inserted, which caused the badge to flap before the
  2631. # badge was removed entirely.
  2632. if "sdcard" in data:
  2633. raw_sdcard = data["sdcard"]
  2634. if isinstance(raw_sdcard, str):
  2635. self.state.sdcard = "HAS_SDCARD" in raw_sdcard.upper() or raw_sdcard.lower() in ("true", "normal", "1")
  2636. else:
  2637. self.state.sdcard = bool(raw_sdcard)
  2638. if home_flag is not None:
  2639. store_to_sdcard = bool((home_flag >> 11) & 1)
  2640. if store_to_sdcard != self.state.store_to_sdcard:
  2641. logger.debug(
  2642. f"[{self.serial_number}] store_to_sdcard changed: {self.state.store_to_sdcard} -> {store_to_sdcard}"
  2643. )
  2644. self.state.store_to_sdcard = store_to_sdcard
  2645. # Door open detection — source depends on printer family:
  2646. # X1 series (X1, X1C, X1E): home_flag bit 23
  2647. # All others (P1/P2/H2/A1/N-series): top-level `stat` field (hex string), bit 23
  2648. # Both share the same bitmask (0x00800000) but live in different fields.
  2649. model_upper = (self.model or "").upper().strip()
  2650. is_x1_family = model_upper in ("X1", "X1C", "X1E")
  2651. if is_x1_family and home_flag is not None:
  2652. door_open = (home_flag & 0x00800000) != 0
  2653. if door_open != self.state.door_open:
  2654. logger.debug(
  2655. "[%s] door_open changed: %s -> %s (home_flag=0x%08X)",
  2656. self.serial_number,
  2657. self.state.door_open,
  2658. door_open,
  2659. home_flag,
  2660. )
  2661. self.state.door_open = door_open
  2662. elif not is_x1_family and "stat" in data:
  2663. try:
  2664. stat_value = int(data["stat"], 16) if isinstance(data["stat"], str) else int(data["stat"])
  2665. door_open = (stat_value & 0x00800000) != 0
  2666. if door_open != self.state.door_open:
  2667. logger.debug(
  2668. "[%s] door_open changed: %s -> %s (stat=0x%08X)",
  2669. self.serial_number,
  2670. self.state.door_open,
  2671. door_open,
  2672. stat_value,
  2673. )
  2674. self.state.door_open = door_open
  2675. except (ValueError, TypeError):
  2676. logger.debug("[%s] could not parse stat field: %r", self.serial_number, data["stat"])
  2677. # Parse timelapse status (recording active during print)
  2678. if "timelapse" in data:
  2679. logger.debug("[%s] timelapse field: %s", self.serial_number, data["timelapse"])
  2680. self.state.timelapse = data["timelapse"] is True
  2681. # Track if timelapse was ever active during this print
  2682. if self.state.timelapse and self._was_running:
  2683. self._timelapse_during_print = True
  2684. # Parse ipcam/live view status
  2685. if "ipcam" in data:
  2686. ipcam_data = data["ipcam"]
  2687. logger.debug("[%s] ipcam field: %s", self.serial_number, ipcam_data)
  2688. if isinstance(ipcam_data, dict):
  2689. # Check ipcam_record field for live view status
  2690. self.state.ipcam = ipcam_data.get("ipcam_record") == "enable"
  2691. # Check timelapse field (H2D sends it here, not in xcam)
  2692. if "timelapse" in ipcam_data:
  2693. timelapse_enabled = ipcam_data.get("timelapse") == "enable"
  2694. if timelapse_enabled != self.state.timelapse:
  2695. logger.debug(
  2696. f"[{self.serial_number}] timelapse changed (from ipcam): {self.state.timelapse} -> {timelapse_enabled}"
  2697. )
  2698. self.state.timelapse = timelapse_enabled
  2699. # Track if timelapse was ever active during this print
  2700. if self.state.timelapse and self._was_running:
  2701. self._timelapse_during_print = True
  2702. logger.debug("[%s] Timelapse detected during print (from ipcam)", self.serial_number)
  2703. else:
  2704. self.state.ipcam = ipcam_data is True
  2705. # Parse WiFi signal strength (dBm)
  2706. if "wifi_signal" in data:
  2707. wifi_signal = data["wifi_signal"]
  2708. logger.debug("[%s] wifi_signal received: %s", self.serial_number, wifi_signal)
  2709. if isinstance(wifi_signal, (int, float)):
  2710. self.state.wifi_signal = int(wifi_signal)
  2711. elif isinstance(wifi_signal, str):
  2712. # Handle string format like "-52dBm"
  2713. try:
  2714. self.state.wifi_signal = int(wifi_signal.replace("dBm", "").strip())
  2715. except ValueError:
  2716. pass # Ignore unparseable wifi_signal strings; field is non-critical
  2717. # Detect ethernet connection: printers on ethernet with WiFi disabled
  2718. # report a hardcoded wifi_signal of -90 dBm. Real WiFi signals vary
  2719. # (typically -30 to -80 dBm). Only check models with an ethernet port.
  2720. from backend.app.utils.printer_models import has_ethernet
  2721. if has_ethernet(self.model):
  2722. self.state.wired_network = self.state.wifi_signal == -90
  2723. # Parse print speed level (1=silent, 2=standard, 3=sport, 4=ludicrous)
  2724. if "spd_lvl" in data:
  2725. new_speed = data["spd_lvl"]
  2726. if new_speed != self.state.speed_level:
  2727. logger.debug(
  2728. "[%s] speed_level changed: %s -> %s", self.serial_number, self.state.speed_level, new_speed
  2729. )
  2730. self.state.speed_level = new_speed
  2731. # Parse skipped objects from printer status (s_obj field)
  2732. # This allows us to restore skipped objects state after reconnection
  2733. if "s_obj" in data:
  2734. s_obj = data["s_obj"]
  2735. if isinstance(s_obj, list):
  2736. # Update skipped objects from printer's list
  2737. new_skipped = [int(oid) for oid in s_obj if isinstance(oid, (int, str))]
  2738. if new_skipped != self.state.skipped_objects:
  2739. logger.debug("[%s] skipped_objects updated from printer: %s", self.serial_number, new_skipped)
  2740. self.state.skipped_objects = new_skipped
  2741. # Parse chamber light status from lights_report
  2742. if "lights_report" in data:
  2743. lights = data["lights_report"]
  2744. logger.debug("[%s] lights_report: %s", self.serial_number, lights)
  2745. if isinstance(lights, list):
  2746. for light in lights:
  2747. if isinstance(light, dict) and light.get("node") == "chamber_light":
  2748. new_light_state = light.get("mode") == "on"
  2749. if new_light_state != self.state.chamber_light:
  2750. logger.debug(
  2751. f"[{self.serial_number}] chamber_light changed: {self.state.chamber_light} -> {new_light_state}"
  2752. )
  2753. self.state.chamber_light = new_light_state
  2754. break
  2755. # Parse nozzle hardware info (single nozzle printers)
  2756. if "nozzle_type" in data:
  2757. self.state.nozzles[0].nozzle_type = str(data["nozzle_type"])
  2758. if "nozzle_diameter" in data:
  2759. self.state.nozzles[0].nozzle_diameter = str(data["nozzle_diameter"])
  2760. # Parse nozzle hardware info (dual nozzle printers - H2D series)
  2761. # Left nozzle
  2762. if "left_nozzle_type" in data:
  2763. self.state.nozzles[0].nozzle_type = str(data["left_nozzle_type"])
  2764. if "left_nozzle_diameter" in data:
  2765. self.state.nozzles[0].nozzle_diameter = str(data["left_nozzle_diameter"])
  2766. # Right nozzle
  2767. if "right_nozzle_type" in data:
  2768. self.state.nozzles[1].nozzle_type = str(data["right_nozzle_type"])
  2769. if "right_nozzle_diameter" in data:
  2770. self.state.nozzles[1].nozzle_diameter = str(data["right_nozzle_diameter"])
  2771. # Alternative format for dual nozzle (nozzle_type_2, etc.)
  2772. if "nozzle_type_2" in data:
  2773. self.state.nozzles[1].nozzle_type = str(data["nozzle_type_2"])
  2774. if "nozzle_diameter_2" in data:
  2775. self.state.nozzles[1].nozzle_diameter = str(data["nozzle_diameter_2"])
  2776. # H2D/H2C series: Nozzle hardware info is in device.nozzle.info array
  2777. if "device" in data and isinstance(data["device"], dict):
  2778. device = data["device"]
  2779. nozzle_data = device.get("nozzle", {})
  2780. nozzle_info = nozzle_data.get("info", [])
  2781. if isinstance(nozzle_info, list):
  2782. # H2 series: nozzle_info contains extended nozzle data (wear, serial,
  2783. # max_temp, etc.) for all nozzles: L/R hotend (IDs 0,1) and rack slots
  2784. # (IDs 16-21 on H2C). Store ALL entries so the frontend can use them
  2785. # for hover cards on both the L/R indicator and the nozzle rack card.
  2786. if nozzle_info:
  2787. self.state.nozzle_rack = sorted(
  2788. [
  2789. {
  2790. "id": n.get("id", i),
  2791. "type": str(n.get("type", "")),
  2792. "diameter": str(n.get("diameter", "")),
  2793. "wear": n.get("wear"),
  2794. "stat": n.get("stat"),
  2795. # H2C uses "tm", H2D uses "max_temp"
  2796. "max_temp": n.get("max_temp") or n.get("tm", 0),
  2797. # H2C uses "sn", H2D uses "serial_number"
  2798. "serial_number": str(n.get("serial_number") or n.get("sn", "")),
  2799. # H2C uses "color_m", H2D uses "filament_colour"
  2800. "filament_color": str(n.get("filament_colour") or n.get("color_m", "")),
  2801. # H2C uses "fila_id", H2D uses "filament_id"
  2802. "filament_id": str(n.get("filament_id") or n.get("fila_id", "")),
  2803. "filament_type": str(n.get("tray_type", "") or n.get("filament_type", "")),
  2804. }
  2805. for i, n in enumerate(nozzle_info)
  2806. ],
  2807. key=lambda x: x["id"],
  2808. )
  2809. if not hasattr(self, "_nozzle_rack_logged") and nozzle_info:
  2810. self._nozzle_rack_logged = True
  2811. logger.debug(
  2812. "[%s] Nozzle info: %d entries, IDs: %s",
  2813. self.serial_number,
  2814. len(nozzle_info),
  2815. [n.get("id") for n in nozzle_info],
  2816. )
  2817. for nozzle in nozzle_info:
  2818. idx = nozzle.get("id", 0)
  2819. if idx < len(self.state.nozzles):
  2820. if "type" in nozzle and nozzle["type"]:
  2821. self.state.nozzles[idx].nozzle_type = str(nozzle["type"])
  2822. if "diameter" in nozzle:
  2823. self.state.nozzles[idx].nozzle_diameter = str(nozzle["diameter"])
  2824. # Preserve AMS, vt_tray, ams_extruder_map, and mapping data when updating raw_data
  2825. # (these fields aren't sent in every MQTT push, only when changed)
  2826. ams_data = self.state.raw_data.get("ams")
  2827. vt_tray_data = self.state.raw_data.get("vt_tray")
  2828. ams_extruder_map_data = self.state.raw_data.get("ams_extruder_map")
  2829. mapping_data = self.state.raw_data.get("mapping")
  2830. # Normalize vt_tray in data before assigning to raw_data: MQTT sends it
  2831. # as a dict but consumers expect a list. Without this, the dev mode probe
  2832. # below can release the GIL (via publish), letting the event-loop thread
  2833. # read raw_data["vt_tray"] as a dict and crash iterating over string keys.
  2834. if "vt_tray" in data and isinstance(data["vt_tray"], dict):
  2835. data["vt_tray"] = [data["vt_tray"]]
  2836. self.state.raw_data = data
  2837. # Restore preserved fields BEFORE any work that may release the GIL
  2838. # (e.g. _probe_developer_mode publishes an MQTT message).
  2839. if ams_data is not None:
  2840. self.state.raw_data["ams"] = ams_data
  2841. if vt_tray_data is not None:
  2842. self.state.raw_data["vt_tray"] = vt_tray_data
  2843. if ams_extruder_map_data is not None:
  2844. self.state.raw_data["ams_extruder_map"] = ams_extruder_map_data
  2845. if mapping_data is not None and "mapping" not in data:
  2846. self.state.raw_data["mapping"] = mapping_data
  2847. # Parse developer LAN mode from "fun" field
  2848. if "fun" in data:
  2849. try:
  2850. fun_val = data["fun"]
  2851. fun_int = fun_val if isinstance(fun_val, int) else int(fun_val, 16)
  2852. self.state.developer_mode = (fun_int & 0x20000000) == 0
  2853. except (ValueError, TypeError):
  2854. pass
  2855. elif self.state.developer_mode is None and not self._dev_mode_probed:
  2856. # No "fun" field — A1/P1 series never send it, so we need to probe.
  2857. # Two gates: (1) wait for a full pushall (30+ keys) so we don't probe
  2858. # before a pushall that might contain "fun" arrives, and (2) delay 5s
  2859. # after connect to let the MQTT session stabilize — probing too early
  2860. # can destabilize some firmware MQTT brokers (#887).
  2861. if not self._dev_mode_needs_probe and len(data) > 30:
  2862. # First full status without "fun" — mark that probe is needed
  2863. self._dev_mode_needs_probe = True
  2864. if self._dev_mode_needs_probe and time.monotonic() - self._connect_time >= 5.0:
  2865. self._probe_developer_mode()
  2866. elif self._dev_mode_needs_probe:
  2867. logger.debug(
  2868. "[%s] Deferring developer mode probe (%.1fs since connect, need 5s)",
  2869. self.serial_number,
  2870. time.monotonic() - self._connect_time,
  2871. )
  2872. elif self._dev_mode_probed and self._dev_mode_probe_seq is not None:
  2873. # Probe was sent but no response yet — check for timeout.
  2874. # A half-broken MQTT session (e.g. after keep-alive timeout reconnect)
  2875. # may deliver status pushes but silently drop commands (#887).
  2876. elapsed = time.monotonic() - self._dev_mode_probe_time
  2877. if elapsed > 10.0:
  2878. self._dev_mode_probe_failures += 1
  2879. logger.warning(
  2880. "[%s] Developer mode probe timed out after %.0fs (attempt %d)",
  2881. self.serial_number,
  2882. elapsed,
  2883. self._dev_mode_probe_failures,
  2884. )
  2885. self._dev_mode_probe_seq = None
  2886. if self._dev_mode_probe_failures >= 2:
  2887. self.force_reconnect_stale_session("developer mode probe unanswered 2×")
  2888. else:
  2889. # Allow retry on next full status message
  2890. self._dev_mode_probed = False
  2891. # Zombie session detection: if an ams_filament_setting command has been
  2892. # pending for >10s with no response, the publish path is likely dead (#887).
  2893. if self._last_ams_cmd_time > 0:
  2894. elapsed = time.monotonic() - self._last_ams_cmd_time
  2895. if elapsed > 10.0:
  2896. self._ams_cmd_unanswered += 1
  2897. logger.warning(
  2898. "[%s] ams_filament_setting unanswered for %.0fs (count=%d)",
  2899. self.serial_number,
  2900. elapsed,
  2901. self._ams_cmd_unanswered,
  2902. )
  2903. self._last_ams_cmd_time = 0.0 # don't re-trigger on next push_status
  2904. if self._ams_cmd_unanswered >= 2:
  2905. self.force_reconnect_stale_session("ams_filament_setting unanswered 2\u00d7")
  2906. self._ams_cmd_unanswered = 0
  2907. # Log mapping data when received (for usage tracking debugging)
  2908. if "mapping" in data:
  2909. logger.debug("[%s] MQTT mapping field: %s", self.serial_number, data["mapping"])
  2910. # Log state transitions for debugging
  2911. if "gcode_state" in data:
  2912. logger.debug(
  2913. f"[{self.serial_number}] gcode_state: {self._previous_gcode_state} -> {self.state.state}, "
  2914. f"file: {self.state.gcode_file}, subtask: {self.state.subtask_name}"
  2915. )
  2916. # Detect print start (state changes TO RUNNING with a file)
  2917. current_file = self.state.gcode_file or self.state.current_print
  2918. is_new_print = (
  2919. self.state.state == "RUNNING"
  2920. and self._previous_gcode_state is not None # #1304: skip on first push after Bambuddy startup
  2921. and self._previous_gcode_state != "RUNNING"
  2922. and current_file
  2923. and not self._was_running # Prevent duplicates when resuming from PAUSE
  2924. )
  2925. # Also detect if file changed while running (new print started)
  2926. is_file_change = (
  2927. self.state.state == "RUNNING"
  2928. and current_file
  2929. and current_file != self._previous_gcode_file
  2930. and self._previous_gcode_file is not None
  2931. )
  2932. # Track RUNNING state for more robust completion detection
  2933. running_first_observed = False
  2934. if self.state.state == "RUNNING" and current_file:
  2935. if not self._was_running:
  2936. logger.debug("[%s] Now tracking RUNNING state for %s", self.serial_number, current_file)
  2937. # Check if timelapse was enabled in the same message (xcam parsed before this)
  2938. if self.state.timelapse:
  2939. self._timelapse_during_print = True
  2940. logger.debug("[%s] Timelapse detected when entering RUNNING state", self.serial_number)
  2941. # Mark this as the first RUNNING observation of the session.
  2942. # If is_new_print also fires below, on_print_start handles
  2943. # baseline capture and we suppress on_print_running_observed
  2944. # to avoid double-capture. If is_new_print does NOT fire
  2945. # (Bambuddy started mid-print — the #1304 guard suppressed
  2946. # it), main.py needs this hook to catch the restart-recovery
  2947. # case (#1485 follow-up).
  2948. running_first_observed = True
  2949. self._was_running = True
  2950. self._completion_triggered = False
  2951. if is_new_print or is_file_change:
  2952. # Clear any old HMS errors when a new print starts
  2953. self.state.hms_errors = []
  2954. # Reset layer tracking for new print (needed for layer-based timelapse)
  2955. self.state.layer_num = 0
  2956. # Reset total_layers so the previous print's value can't bleed into
  2957. # this print's usage-tracker split before the new push_status arrives
  2958. # with the slicer's total (#1771 follow-on to the preservation guard
  2959. # above at line ~2135 — the guard now ignores firmware-reset 0s, so
  2960. # the explicit reset has to happen here instead).
  2961. self.state.total_layers = 0
  2962. # Reset completion tracking for new print
  2963. self._was_running = True
  2964. self._completion_triggered = False
  2965. # #1721: rearm the end-of-print finish-photo trigger for the new print
  2966. self._finish_photo_captured = False
  2967. # Reset last valid progress/layer for usage tracking
  2968. self._last_valid_progress = 0.0
  2969. self._last_valid_layer_num = 0
  2970. # Clear and seed tray change log for mid-print usage splitting
  2971. self.state.tray_change_log.clear()
  2972. tn = self.state.tray_now
  2973. if (0 <= tn <= 15) or (128 <= tn <= 135) or tn == 254:
  2974. self.state.tray_change_log.append((tn, 0))
  2975. # Initialize timelapse tracking based on current state
  2976. # NOTE: xcam data is parsed BEFORE this code runs in _process_message,
  2977. # so self.state.timelapse may already be set from this message.
  2978. # We preserve that value instead of blindly resetting to False.
  2979. if self.state.timelapse:
  2980. self._timelapse_during_print = True
  2981. logger.debug("[%s] Timelapse detected at print start", self.serial_number)
  2982. else:
  2983. self._timelapse_during_print = False
  2984. if (is_new_print or is_file_change) and self.on_print_start:
  2985. logger.info(
  2986. f"[{self.serial_number}] PRINT START detected - file: {current_file}, "
  2987. f"subtask: {self.state.subtask_name}, is_new: {is_new_print}, is_file_change: {is_file_change}"
  2988. )
  2989. self.on_print_start(
  2990. {
  2991. "filename": current_file,
  2992. "subtask_name": self.state.subtask_name,
  2993. "remaining_time": self.state.remaining_time * 60
  2994. if self.state.remaining_time > 0
  2995. else None, # Convert minutes to seconds
  2996. "raw_data": data,
  2997. "ams_mapping": self._captured_ams_mapping,
  2998. }
  2999. )
  3000. elif running_first_observed and self.on_print_running_observed:
  3001. # Restart-recovery hook (#1485 follow-up): Bambuddy started mid-
  3002. # print, so the #1304 first-push guard suppressed on_print_start,
  3003. # but we still need main.py to capture a fresh timelapse baseline
  3004. # before the printer uploads the in-flight MP4. Same payload
  3005. # shape as on_print_start so the consumer can reuse fields.
  3006. logger.info(
  3007. f"[{self.serial_number}] RUNNING observed without PRINT START "
  3008. f"(restart-recovery) - file: {current_file}, subtask: {self.state.subtask_name}"
  3009. )
  3010. self.on_print_running_observed(
  3011. {
  3012. "filename": current_file,
  3013. "subtask_name": self.state.subtask_name,
  3014. "remaining_time": self.state.remaining_time * 60 if self.state.remaining_time > 0 else None,
  3015. "raw_data": data,
  3016. "ams_mapping": self._captured_ams_mapping,
  3017. }
  3018. )
  3019. # Detect print completion (FINISH = success, FAILED = error, IDLE = aborted)
  3020. # Use _was_running flag in addition to _previous_gcode_state for more robust detection
  3021. # This handles cases where server restarts during a print
  3022. should_trigger_completion = (
  3023. self.state.state in ("FINISH", "FAILED")
  3024. and not self._completion_triggered
  3025. and self.on_print_complete
  3026. and (
  3027. self._previous_gcode_state == "RUNNING" # Normal transition
  3028. or (self._was_running and self._previous_gcode_state != self.state.state) # After server restart
  3029. # Pre-print failure (#1111): printer rejected the job during setup
  3030. # — wrong nozzle size, AMS error, etc. The print never reaches
  3031. # RUNNING, so without this branch neither the RUNNING check nor
  3032. # _was_running match and the queue item stays stuck at "printing".
  3033. # Restricted to FAILED from pre-print states so a stale FAILED on
  3034. # first connection (prev=None) still can't accidentally fire.
  3035. or (self.state.state == "FAILED" and self._previous_gcode_state in ("PREPARE", "SLICING"))
  3036. )
  3037. )
  3038. # For IDLE, only trigger if we just came from RUNNING (explicit abort/cancel)
  3039. if (
  3040. self.state.state == "IDLE"
  3041. and self._previous_gcode_state == "RUNNING"
  3042. and not self._completion_triggered
  3043. and self.on_print_complete
  3044. ):
  3045. should_trigger_completion = True
  3046. # Log when we FIRST see a terminal state but DON'T trigger completion (diagnostics)
  3047. # Only log on the transition (prev != current) to avoid flooding logs every MQTT update
  3048. if (
  3049. not should_trigger_completion
  3050. and self.state.state in ("FINISH", "FAILED")
  3051. and self._previous_gcode_state != self.state.state
  3052. ):
  3053. logger.info(
  3054. f"[{self.serial_number}] State is {self.state.state} but completion NOT triggered: "
  3055. f"prev={self._previous_gcode_state}, was_running={self._was_running}, "
  3056. f"already_triggered={self._completion_triggered}, has_callback={bool(self.on_print_complete)}"
  3057. )
  3058. # Mark as triggered so state is clean for the next print cycle
  3059. self._completion_triggered = True
  3060. if should_trigger_completion:
  3061. if self.state.state == "FINISH":
  3062. status = "completed"
  3063. elif self.state.state == "FAILED":
  3064. status = "failed"
  3065. else:
  3066. status = "aborted"
  3067. logger.info(
  3068. f"[{self.serial_number}] PRINT COMPLETE detected - state: {self.state.state}, "
  3069. f"status: {status}, file: {self._previous_gcode_file or current_file}, "
  3070. f"subtask: {self.state.subtask_name}, was_running: {self._was_running}, "
  3071. f"timelapse_during_print: {self._timelapse_during_print}"
  3072. )
  3073. timelapse_was_active = self._timelapse_during_print
  3074. # #1721 fallback: if the stage-22 trigger never fired (cancel,
  3075. # external-spool-only, HMS halt, or firmware variant that skips
  3076. # the unload phase) fire the finish-photo moment now. Bed has
  3077. # already dropped, framing is worse, but we still capture.
  3078. # Only on successful completion — aborted/failed prints don't
  3079. # produce a meaningful finish photo.
  3080. if status == "completed" and not self._finish_photo_captured and self.on_finish_photo_moment:
  3081. self._finish_photo_captured = True
  3082. logger.info(
  3083. f"[{self.serial_number}] FINISH PHOTO MOMENT (FINISH fallback) — "
  3084. f"stage-22 never fired; capturing at FINISH-state transition"
  3085. )
  3086. self.on_finish_photo_moment(
  3087. {
  3088. "trigger": "finish_state",
  3089. "filename": self._previous_gcode_file or current_file,
  3090. "subtask_name": self.state.subtask_name,
  3091. "timelapse_was_active": timelapse_was_active,
  3092. }
  3093. )
  3094. self._completion_triggered = True
  3095. self._was_running = False
  3096. self._timelapse_during_print = False # Reset for next print
  3097. # Include HMS errors for failure reason detection
  3098. hms_errors_data = (
  3099. [
  3100. {"code": e.code, "attr": e.attr, "module": e.module, "severity": e.severity}
  3101. for e in self.state.hms_errors
  3102. ]
  3103. if self.state.hms_errors
  3104. else []
  3105. )
  3106. self.on_print_complete(
  3107. {
  3108. "status": status,
  3109. "filename": self._previous_gcode_file or current_file,
  3110. "subtask_name": self.state.subtask_name,
  3111. "raw_data": data,
  3112. "timelapse_was_active": timelapse_was_active,
  3113. "hms_errors": hms_errors_data,
  3114. "ams_mapping": self._captured_ams_mapping,
  3115. # Last valid progress/layer before firmware reset (for partial usage tracking)
  3116. "last_progress": self._last_valid_progress,
  3117. "last_layer_num": self._last_valid_layer_num,
  3118. }
  3119. )
  3120. self._captured_ams_mapping = None
  3121. self._previous_gcode_state = self.state.state
  3122. if current_file:
  3123. self._previous_gcode_file = current_file
  3124. if self.on_state_change:
  3125. self.on_state_change(self.state)
  3126. def _request_push_all(self):
  3127. """Request full status update from printer."""
  3128. if self._client:
  3129. message = {"pushing": {"command": "pushall"}}
  3130. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3131. def _probe_developer_mode(self):
  3132. """Probe developer mode by sending an ams_filament_setting for the external slot.
  3133. Some printers (A1/P1 series) never send the "fun" field in MQTT status.
  3134. For these, we detect developer mode by sending a harmless command and
  3135. checking whether the printer accepts or rejects it:
  3136. - result="success" → developer mode ON (commands accepted)
  3137. - result="failed", reason="mqtt message verify failed" → developer mode OFF
  3138. The probe re-sends the current external slot configuration so it's a no-op
  3139. when the command succeeds. If there's no external slot data yet, we send a
  3140. reset (empty filament) which is also safe.
  3141. """
  3142. if not self._client or not self.state.connected:
  3143. return
  3144. self._dev_mode_probed = True
  3145. self._dev_mode_probe_time = time.monotonic()
  3146. self._sequence_id += 1
  3147. seq = str(self._sequence_id)
  3148. self._dev_mode_probe_seq = seq
  3149. # Build probe command: re-send current external slot config (no-op on success)
  3150. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  3151. current = vt_tray[0] if vt_tray else {}
  3152. command = {
  3153. "print": {
  3154. "command": "ams_filament_setting",
  3155. "ams_id": 255,
  3156. "tray_id": 0,
  3157. "slot_id": 0,
  3158. "tray_info_idx": current.get("tray_info_idx", ""),
  3159. "tray_type": current.get("tray_type", ""),
  3160. "tray_sub_brands": current.get("tray_sub_brands", ""),
  3161. "tray_color": current.get("tray_color", "00000000"),
  3162. "nozzle_temp_min": current.get("nozzle_temp_min", 0),
  3163. "nozzle_temp_max": current.get("nozzle_temp_max", 0),
  3164. "sequence_id": seq,
  3165. }
  3166. }
  3167. setting_id = current.get("setting_id")
  3168. if setting_id:
  3169. command["print"]["setting_id"] = setting_id
  3170. logger.info("[%s] Probing developer mode via ams_filament_setting (seq=%s)", self.serial_number, seq)
  3171. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3172. def _handle_dev_mode_probe_response(self, data: dict):
  3173. """Handle response to the developer mode probe command.
  3174. Sets developer_mode based on whether the printer accepted or rejected the command.
  3175. """
  3176. self._dev_mode_probe_seq = None # One-shot: don't match future responses
  3177. self._dev_mode_probe_failures = 0 # Reset on any response
  3178. result = data.get("result", "")
  3179. reason = data.get("reason", "")
  3180. if result == "failed" and "verify failed" in reason:
  3181. self.state.developer_mode = False
  3182. logger.info("[%s] Developer mode probe: DISABLED (reason=%r)", self.serial_number, reason)
  3183. else:
  3184. # Success or any other response — commands are accepted
  3185. self.state.developer_mode = True
  3186. logger.info("[%s] Developer mode probe: ENABLED (result=%r)", self.serial_number, result)
  3187. if self.on_state_change:
  3188. self.on_state_change(self.state)
  3189. def _request_version(self):
  3190. """Request firmware version info from printer."""
  3191. if self._client:
  3192. self._sequence_id += 1
  3193. message = {
  3194. "info": {
  3195. "sequence_id": str(self._sequence_id),
  3196. "command": "get_version",
  3197. }
  3198. }
  3199. logger.debug("[%s] Requesting firmware version info", self.serial_number)
  3200. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3201. def request_status_update(self) -> bool:
  3202. """Request a full status update from the printer (public API).
  3203. Sends both pushall and get_accessories commands to refresh all data
  3204. including nozzle hardware info.
  3205. Returns:
  3206. True if the request was sent, False if not connected.
  3207. """
  3208. if not self._client or not self.state.connected:
  3209. logger.warning("[%s] request_status_update: not connected", self.serial_number)
  3210. return False
  3211. logger.debug("[%s] Requesting status update (pushall)", self.serial_number)
  3212. self._request_push_all()
  3213. # Note: get_accessories returns stale nozzle data on H2D.
  3214. # The correct nozzle data comes from push_status response.
  3215. return True
  3216. def _request_accessories(self):
  3217. """Request accessories info (nozzle type, etc.) from printer."""
  3218. if self._client:
  3219. self._sequence_id += 1
  3220. message = {
  3221. "system": {
  3222. "sequence_id": str(self._sequence_id),
  3223. "command": "get_accessories",
  3224. "accessory_type": "none",
  3225. }
  3226. }
  3227. logger.debug("[%s] Requesting accessories info", self.serial_number)
  3228. self._client.publish(self.topic_publish, json.dumps(message), qos=1)
  3229. def _prime_kprofile_request(self):
  3230. """Send a priming K-profile request on connect.
  3231. Bambu printers often ignore the first K-profile request after connection,
  3232. so we send a dummy request on connect to 'prime' the system.
  3233. """
  3234. if self._client:
  3235. self._sequence_id += 1
  3236. command = {
  3237. "print": {
  3238. "command": "extrusion_cali_get",
  3239. "filament_id": "",
  3240. "nozzle_diameter": "0.4",
  3241. "sequence_id": str(self._sequence_id),
  3242. }
  3243. }
  3244. logger.debug("[%s] Sending K-profile priming request", self.serial_number)
  3245. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3246. def connect(self, loop: asyncio.AbstractEventLoop | None = None):
  3247. """Connect to the printer MQTT broker.
  3248. Args:
  3249. loop: The asyncio event loop to use for thread-safe callbacks.
  3250. If not provided, will try to get the running loop.
  3251. """
  3252. self._loop = loop
  3253. BambuMQTTClient._client_instance_counter += 1
  3254. client_id = f"bambuddy_{self.serial_number}_{os.getpid()}_{BambuMQTTClient._client_instance_counter}"
  3255. self._client = mqtt.Client(
  3256. callback_api_version=mqtt.CallbackAPIVersion.VERSION2,
  3257. client_id=client_id,
  3258. protocol=mqtt.MQTTv311,
  3259. )
  3260. # Bambu's broker has racy PUBACK matching with paho's QoS=1 inflight
  3261. # tracking (#1164). The default ceiling of 20 wedges sessions after
  3262. # ~16-20 cumulative commands; lifting it well above any realistic
  3263. # session count keeps QoS=1 working without changing wire-protocol
  3264. # behaviour across printer models.
  3265. self._client.max_inflight_messages_set(1000)
  3266. self._client.username_pw_set("bblp", self.access_code)
  3267. self._client.on_connect = self._on_connect
  3268. self._client.on_disconnect = self._on_disconnect
  3269. self._client.on_subscribe = self._on_subscribe
  3270. self._client.on_message = self._on_message
  3271. # TLS setup - Bambu uses self-signed certs
  3272. ssl_context = ssl.create_default_context()
  3273. ssl_context.check_hostname = False
  3274. ssl_context.verify_mode = ssl.CERT_NONE
  3275. self._client.tls_set_context(ssl_context)
  3276. # Backoff reconnects to avoid tight reconnect loops on unstable brokers.
  3277. self._client.reconnect_delay_set(min_delay=1, max_delay=30)
  3278. # Keepalive: paho sends PINGREQs at this interval, broker considers
  3279. # client dead at 1.5x. 30s is a good balance — fast enough to detect
  3280. # real network loss (45s), not so aggressive that transient hiccups
  3281. # trigger false disconnects. Stale detection (60s no messages) handles
  3282. # the P1S/P1P firmware bug where the broker stops publishing but the
  3283. # TCP connection stays alive.
  3284. self._client.connect_async(self.ip_address, self.MQTT_PORT, keepalive=30)
  3285. self._client.loop_start()
  3286. def start_print(
  3287. self,
  3288. filename: str,
  3289. plate_id: int = 1,
  3290. ams_mapping: list[int] | None = None,
  3291. bed_levelling: bool = True,
  3292. flow_cali: bool = False,
  3293. vibration_cali: bool = True,
  3294. layer_inspect: bool = False,
  3295. timelapse: bool = False,
  3296. use_ams: bool = True,
  3297. nozzle_offset_cali: bool = False,
  3298. nozzle_mapping: str | None = None,
  3299. ):
  3300. """Start a print job on the printer.
  3301. The file should already be uploaded to the printer's root directory via FTP.
  3302. Args:
  3303. filename: Name of the uploaded file
  3304. plate_id: Plate number to print (default 1)
  3305. ams_mapping: List of tray IDs for each filament slot in the 3MF.
  3306. Global tray ID = (ams_id * 4) + slot_id, external = 254
  3307. timelapse: Record timelapse video
  3308. bed_levelling: Auto bed levelling before print
  3309. flow_cali: Flow/pressure advance calibration
  3310. vibration_cali: Vibration compensation calibration
  3311. layer_inspect: First layer AI inspection
  3312. use_ams: Use AMS for automatic filament changes
  3313. nozzle_offset_cali: Run nozzle offset calibration before print
  3314. (dual-nozzle printers only — silently ignored on single-nozzle).
  3315. nozzle_mapping: Opaque JSON string captured from BambuStudio's
  3316. project_file for H2C rack-swap (O1C2) (#1780). When non-null
  3317. AND the printer is dual-nozzle, parsed and injected as the
  3318. `nozzle_mapping` array on the dispatched project_file so the
  3319. firmware honours the user's slicer pick instead of falling
  3320. back to "last matching nozzle" auto-pick. Silently ignored
  3321. on single-nozzle printers.
  3322. """
  3323. if self._client and self.state.connected:
  3324. # Bambu print command format — matches Bambu Studio's format.
  3325. # The calibration/leveling fields (timelapse, bed_leveling,
  3326. # flow_cali, vibration_cali, layer_inspect) are JSON booleans for
  3327. # every model. An earlier revision integer-encoded them for the H2
  3328. # family (H2D/H2S/H2C/X2D) on the belief that H2 firmware required
  3329. # 0/1 — but a BambuStudio request-topic capture from a real H2D
  3330. # sends plain booleans, and the integer encoding made the H2S
  3331. # silently skip flow-dynamics calibration (#1478). use_ams is the
  3332. # one field that genuinely must stay boolean: H2D Pro firmware
  3333. # reads an integer use_ams as a nozzle index (1 = deputy), which is
  3334. # what actually caused the wrong-extruder routing behind #1386.
  3335. # Dual-nozzle routing for external spool (254 = deputy/left,
  3336. # 255 = main/right) and the use_ams=False fallback. H2S is in the
  3337. # H2 firmware family but is single-nozzle, despite sharing serial
  3338. # prefix "094" with H2D. Prefer runtime detection from
  3339. # device.extruder.info (set in _handle_push_status); fall back to
  3340. # model name for the brief window after connect before push data
  3341. # arrives. _is_dual_nozzle only ever flips False→True, so it's safe
  3342. # as the primary signal.
  3343. from backend.app.utils.printer_models import is_dual_nozzle_model
  3344. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  3345. # Build ams_mapping2 from ams_mapping (detailed format with ams_id/slot_id)
  3346. ams_mapping2 = []
  3347. # BambuStudio converts virtual tray IDs (254/255) to -1 in the flat
  3348. # ams_mapping and relies on ams_mapping2 for external spool details.
  3349. # Passing raw 254/255 in the flat array causes H2D firmware to fail
  3350. # with 0700_8012 "Failed to get AMS mapping table".
  3351. flat_ams_mapping = []
  3352. if ams_mapping is not None:
  3353. for tray_id in ams_mapping:
  3354. # Ensure tray_id is an integer (may be string from JSON)
  3355. tray_id = int(tray_id) if tray_id is not None else -1
  3356. if tray_id == -1:
  3357. # Unmapped filament slot
  3358. flat_ams_mapping.append(-1)
  3359. ams_mapping2.append({"ams_id": 255, "slot_id": 255})
  3360. elif tray_id >= 254:
  3361. # External/virtual spool. BambuStudio convention:
  3362. # 255 = VIRTUAL_TRAY_MAIN_ID (main/right nozzle)
  3363. # 254 = VIRTUAL_TRAY_DEPUTY_ID (deputy/left nozzle)
  3364. # Flat mapping must use -1 (firmware doesn't accept raw 254/255).
  3365. # Single-nozzle printers (X1C, P1S, A1, etc.) report tray_now=254
  3366. # for external spool, but BambuStudio always sends ams_id=255
  3367. # (VIRTUAL_TRAY_MAIN_ID) in ams_mapping2. Sending 254 causes the
  3368. # firmware to target AMS tray 0 instead of external spool, leading
  3369. # to 07FF_8012 "Failed to get AMS mapping table" or stuck prints.
  3370. # Only H2D dual-nozzle printers use 254 (deputy/left nozzle).
  3371. flat_ams_mapping.append(-1)
  3372. ext_ams_id = tray_id if is_dual_nozzle else 255
  3373. ams_mapping2.append({"ams_id": ext_ams_id, "slot_id": 0})
  3374. elif tray_id >= 128:
  3375. # AMS-HT: global tray ID IS the ams_id (single tray per unit)
  3376. flat_ams_mapping.append(tray_id)
  3377. ams_mapping2.append({"ams_id": tray_id, "slot_id": 0})
  3378. else:
  3379. # Regular AMS tray: Global tray ID = (ams_id * 4) + slot_id
  3380. ams_id = tray_id // 4
  3381. slot_id = tray_id % 4
  3382. flat_ams_mapping.append(tray_id)
  3383. ams_mapping2.append({"ams_id": ams_id, "slot_id": slot_id})
  3384. # If all mapped slots are external spool (no real AMS trays), force use_ams=False.
  3385. # P1S/P1P with no AMS rejects use_ams=True with "Failed to get AMS mapping table".
  3386. # Skip for dual-nozzle printers — use_ams controls nozzle routing there.
  3387. # H2S falls through this gate now (#1386): it is single-nozzle and was
  3388. # hitting the dual-nozzle bypass, which caused 07FF_8012 when printing
  3389. # without an AMS attached.
  3390. if ams_mapping and use_ams and not is_dual_nozzle:
  3391. if all(t is None or int(t) < 0 or int(t) >= 254 for t in ams_mapping):
  3392. use_ams = False
  3393. logger.info(
  3394. "[%s] All filament slots use external spool — setting use_ams=False",
  3395. self.serial_number,
  3396. )
  3397. # Unique per-submission identity fields. Hardcoded "0" values caused
  3398. # third-party MQTT observers (OctoEverywhere, etc.) to see reprints as
  3399. # continuations of the same job: the printer reuses gcode_start_time
  3400. # from the prior print with task_id=0, so observers latch onto a stale
  3401. # timestamp and report compounding durations on repeat replays (#1011).
  3402. # BambuStudio mints fresh IDs per submission; matching that behavior
  3403. # makes the printer emit a clean state-transition for each job.
  3404. # md5 is left empty — firmware historically accepts "" as "skip
  3405. # validation" (unlike Studio, we don't have the file's real md5 here
  3406. # without re-reading the upload, and sending a synthetic wrong digest
  3407. # risks activation of md5 verification on some firmwares).
  3408. # Cap at signed int32 max: P1S firmware (01.10.00.00) clamps oversized
  3409. # task identity fields to 2**31-1, so raw epoch-ms (13 digits, ~1.7e12)
  3410. # overflows and every submission ends up with the same task_id from
  3411. # the printer's perspective — the printer then treats a fresh dispatch
  3412. # as a continuation of the last FAILED job and never leaves IDLE (#1042).
  3413. # Modulo keeps uniqueness within a ~24-day wrap window; `or 1` guards
  3414. # the (astronomically unlikely) zero case since task_id=0 is rejected.
  3415. submission_id = str(int(time.time() * 1000) % 2_147_483_647 or 1)
  3416. # Remember it so on_print_start can persist a restart-stable id on
  3417. # the archive even before the printer echoes subtask_id back (#1485).
  3418. self.last_dispatch_subtask_id = submission_id
  3419. command = {
  3420. "print": {
  3421. "sequence_id": "20000",
  3422. "command": "project_file",
  3423. "param": f"Metadata/plate_{plate_id}.gcode",
  3424. "url": f"ftp://{filename}",
  3425. "file": filename,
  3426. "md5": "",
  3427. "bed_type": "auto",
  3428. "timelapse": timelapse,
  3429. "bed_leveling": bed_levelling,
  3430. "auto_bed_leveling": 1 if bed_levelling else 0,
  3431. "flow_cali": flow_cali,
  3432. "vibration_cali": vibration_cali,
  3433. "layer_inspect": layer_inspect,
  3434. "use_ams": use_ams,
  3435. "cfg": "0",
  3436. # extrude_cali_flag gates flow-dynamics calibration:
  3437. # 1 = run it, 0 = printer skips entirely (#1478 evidence).
  3438. # 2 = "skip and reuse stored PA" was previously believed to
  3439. # suppress the stage too, but #1721 testing on H2D 01.x
  3440. # showed stage 8 ("Calibrating dynamic flow") still gets
  3441. # queued when we send 2. A real BambuStudio Send-dialog
  3442. # capture today also showed 0 when the user disables flow
  3443. # calibration. Going with 0 to actually suppress the
  3444. # pre-print calibration stage.
  3445. "extrude_cali_flag": 1 if flow_cali else 0,
  3446. "extrude_cali_manual_mode": 0,
  3447. # 1 = run, 0 = skip (matches BambuStudio's wire today). The
  3448. # earlier 2 = "skip" reading from #1682 didn't actually
  3449. # suppress stage 39 ("Nozzle offset calibration") on H2D
  3450. # 01.x — captured live in #1721. BambuStudio exposes the
  3451. # toggle only for dual-nozzle (H2D/H2D Pro/H2C/X2D); single-
  3452. # nozzle prints still resolve to 0 here so firmware never
  3453. # runs a calibration the head doesn't support.
  3454. "nozzle_offset_cali": 1 if (nozzle_offset_cali and is_dual_nozzle) else 0,
  3455. "subtask_name": filename.replace(".3mf", "").replace(".gcode", ""),
  3456. "profile_id": "0",
  3457. "project_id": submission_id,
  3458. "subtask_id": submission_id,
  3459. "task_id": submission_id,
  3460. }
  3461. }
  3462. # P2S-specific parameter adjustments
  3463. # P2S printer doesn't support vibration calibration like X1/P1 series
  3464. if self.model and self.model.upper().strip() in ("P2S", "N7"):
  3465. command["print"]["vibration_cali"] = False
  3466. logger.debug("[%s] P2S detected: disabling vibration_cali", self.serial_number)
  3467. # Add AMS mapping if provided
  3468. if ams_mapping is not None:
  3469. command["print"]["ams_mapping"] = flat_ams_mapping
  3470. command["print"]["ams_mapping2"] = ams_mapping2
  3471. # H2C dual-nozzle-rack slicer-pick preservation (#1780).
  3472. # `nozzle_mapping` carries per-filament physical nozzle position
  3473. # IDs (`list[int]`), JSON-string-encoded when it leaves the queue
  3474. # item; parse here so the wire ships an array, matching
  3475. # BambuStudio's project_file shape. Gate by `is_dual_nozzle`
  3476. # defensively — single-nozzle firmwares would ignore the field
  3477. # but we err on the side of not emitting unrecognised fields. A
  3478. # parse failure is logged but never blocks the dispatch — the
  3479. # firmware will fall back to its auto-pick path, which is the
  3480. # pre-fix behaviour.
  3481. if is_dual_nozzle and nozzle_mapping:
  3482. try:
  3483. command["print"]["nozzle_mapping"] = json.loads(nozzle_mapping)
  3484. except json.JSONDecodeError:
  3485. logger.warning(
  3486. "[%s] Invalid nozzle_mapping JSON on dispatch, omitting from "
  3487. "project_file (firmware will auto-pick): %r",
  3488. self.serial_number,
  3489. nozzle_mapping,
  3490. )
  3491. logger.info("[%s] Sending print command: %s", self.serial_number, json.dumps(command))
  3492. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3493. # Record what we dispatched so /cover can pick the right plate
  3494. # thumbnail even when the printer's gcode_file echo is just the
  3495. # 3MF filename without a plate path (#1166). Match the same
  3496. # subtask_name shape we send so the comparison in the cover route
  3497. # works against state.subtask_name reflected back via MQTT.
  3498. self.state.dispatched_plate_id = plate_id
  3499. self.state.dispatched_subtask = command["print"]["subtask_name"]
  3500. return True
  3501. else:
  3502. # Log why we couldn't send the command
  3503. if not self._client:
  3504. logger.error("[%s] Cannot start print: MQTT client not initialized", self.serial_number)
  3505. elif not self.state.connected:
  3506. logger.error(
  3507. f"[{self.serial_number}] Cannot start print: Printer not connected (client exists but disconnected). "
  3508. f"Connection state: {self.state.connected}, Last message: {self._last_message_time}"
  3509. )
  3510. return False
  3511. def stop_print(self) -> bool:
  3512. """Stop the current print job."""
  3513. if self._client and self.state.connected:
  3514. command = {"print": {"command": "stop", "sequence_id": "0"}}
  3515. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3516. logger.info("[%s] Sent stop print command", self.serial_number)
  3517. return True
  3518. return False
  3519. def set_xcam_option(
  3520. self, module_name: str, enabled: bool, print_halt: bool = True, sensitivity: str = "medium"
  3521. ) -> bool:
  3522. """Set an xcam (AI detection) option on the printer.
  3523. Args:
  3524. module_name: The xcam module to control (e.g., "spaghetti_detector",
  3525. "first_layer_inspector", "printing_monitor", "buildplate_marker_detector")
  3526. enabled: Whether to enable or disable the feature
  3527. print_halt: Whether to halt print on detection (only applies to some detectors)
  3528. sensitivity: Sensitivity level ("low", "medium", "high", or "never_halt")
  3529. Returns:
  3530. True if command was sent, False if not connected
  3531. """
  3532. if not self._client or not self.state.connected:
  3533. return False
  3534. # auto_recovery_step_loss uses a different command format (print.print_option)
  3535. if module_name == "auto_recovery_step_loss":
  3536. return self._set_print_option("auto_recovery", enabled)
  3537. self._sequence_id += 1
  3538. # Build the xcam control command (exact OrcaSlicer format)
  3539. # Key findings from OrcaSlicer source:
  3540. # - Uses "xcam" wrapper (not "print")
  3541. # - print_halt is ALWAYS true (legacy protocol requirement)
  3542. # - Both "control" and "enable" are set to the same value
  3543. # - halt_print_sensitivity controls actual halt behavior
  3544. command = {
  3545. "xcam": {
  3546. "command": "xcam_control_set",
  3547. "sequence_id": str(self._sequence_id),
  3548. "module_name": module_name,
  3549. "control": enabled,
  3550. "enable": enabled, # old protocol compatibility
  3551. "print_halt": True, # ALWAYS true per OrcaSlicer
  3552. }
  3553. }
  3554. # Only add sensitivity if not "never_halt"
  3555. # OrcaSlicer uses halt_print_sensitivity for ALL detectors
  3556. # The module_name field determines which detector's sensitivity is being set
  3557. if sensitivity and sensitivity != "never_halt":
  3558. command["xcam"]["halt_print_sensitivity"] = sensitivity
  3559. command_json = json.dumps(command)
  3560. self._client.publish(self.topic_publish, command_json, qos=1)
  3561. logger.debug(
  3562. "[%s] Set xcam option: %s=%s, sensitivity=%s", self.serial_number, module_name, enabled, sensitivity
  3563. )
  3564. logger.debug("[%s] MQTT command sent: %s", self.serial_number, command_json)
  3565. # OrcaSlicer pattern: Set hold timer to ignore incoming data for 3 seconds
  3566. # This prevents stale MQTT data from immediately overwriting our change
  3567. self._xcam_hold_start[module_name] = time.time()
  3568. # Update local state immediately for responsive UI
  3569. # NOTE: Spaghetti and Pileup sensitivities are linked in firmware
  3570. # When spaghetti_detector sensitivity is changed, pileup also changes
  3571. if module_name == "spaghetti_detector":
  3572. self.state.print_options.spaghetti_detector = enabled
  3573. self.state.print_options.print_halt = print_halt
  3574. if sensitivity and sensitivity != "never_halt":
  3575. # spaghetti_detector controls BOTH spaghetti and pileup sensitivities
  3576. self.state.print_options.halt_print_sensitivity = sensitivity
  3577. self.state.print_options.pileup_sensitivity = sensitivity
  3578. self._xcam_hold_start["halt_print_sensitivity"] = time.time()
  3579. self._xcam_hold_start["pileup_sensitivity"] = time.time()
  3580. elif module_name == "first_layer_inspector":
  3581. self.state.print_options.first_layer_inspector = enabled
  3582. elif module_name == "printing_monitor":
  3583. self.state.print_options.printing_monitor = enabled
  3584. elif module_name == "buildplate_marker_detector":
  3585. self.state.print_options.buildplate_marker_detector = enabled
  3586. elif module_name == "allow_skip_parts":
  3587. self.state.print_options.allow_skip_parts = enabled
  3588. elif module_name == "pileup_detector":
  3589. self.state.print_options.pileup_detector = enabled
  3590. # Pileup sensitivity is linked to spaghetti - both are set via spaghetti_detector
  3591. elif module_name == "clump_detector":
  3592. self.state.print_options.nozzle_clumping_detector = enabled
  3593. if sensitivity and sensitivity != "never_halt":
  3594. self.state.print_options.nozzle_clumping_sensitivity = sensitivity
  3595. self._xcam_hold_start["nozzle_clumping_sensitivity"] = time.time()
  3596. elif module_name == "airprint_detector":
  3597. self.state.print_options.airprint_detector = enabled
  3598. if sensitivity and sensitivity != "never_halt":
  3599. self.state.print_options.airprint_sensitivity = sensitivity
  3600. self._xcam_hold_start["airprint_sensitivity"] = time.time()
  3601. elif module_name == "auto_recovery_step_loss":
  3602. self.state.print_options.auto_recovery_step_loss = enabled
  3603. return True
  3604. def _set_print_option(self, option_name: str, enabled: bool) -> bool:
  3605. """Set a print option using the print.print_option command.
  3606. This is different from xcam_control_set and is used for options like:
  3607. - auto_recovery
  3608. - air_print_detect
  3609. - filament_tangle_detect
  3610. - nozzle_blob_detect
  3611. - sound_enable
  3612. Args:
  3613. option_name: The option to control (e.g., "auto_recovery")
  3614. enabled: Whether to enable or disable the option
  3615. Returns:
  3616. True if command was sent, False if not connected
  3617. """
  3618. if not self._client or not self.state.connected:
  3619. return False
  3620. self._sequence_id += 1
  3621. command = {
  3622. "print": {
  3623. "command": "print_option",
  3624. "sequence_id": str(self._sequence_id),
  3625. option_name: enabled,
  3626. }
  3627. }
  3628. command_json = json.dumps(command)
  3629. self._client.publish(self.topic_publish, command_json, qos=1)
  3630. logger.debug("[%s] Set print option: %s=%s", self.serial_number, option_name, enabled)
  3631. # Set hold timer
  3632. hold_key = f"print_option_{option_name}"
  3633. self._xcam_hold_start[hold_key] = time.time()
  3634. # Update local state immediately
  3635. if option_name == "auto_recovery":
  3636. self.state.print_options.auto_recovery_step_loss = enabled
  3637. elif option_name == "auto_switch_filament":
  3638. self.state.ams_filament_backup = enabled
  3639. return True
  3640. def set_ams_filament_backup(self, enabled: bool) -> bool:
  3641. """Toggle AMS Filament Backup (a.k.a. auto-switch / auto-refill).
  3642. Mirrors BambuStudio's "AMS Filament Backup" checkbox. Verified payload
  3643. shape from H2D capture 2026-06-20.
  3644. """
  3645. return self._set_print_option("auto_switch_filament", enabled)
  3646. def start_calibration(
  3647. self,
  3648. bed_leveling: bool = False,
  3649. vibration: bool = False,
  3650. motor_noise: bool = False,
  3651. nozzle_offset: bool = False,
  3652. high_temp_heatbed: bool = False,
  3653. ) -> bool:
  3654. """Start printer calibration with selected options.
  3655. Args:
  3656. bed_leveling: Run bed leveling calibration
  3657. vibration: Run vibration compensation calibration
  3658. motor_noise: Run motor noise cancellation calibration
  3659. nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  3660. high_temp_heatbed: Run high-temperature heatbed calibration
  3661. Returns:
  3662. True if command was sent, False if not connected
  3663. """
  3664. if not self._client or not self.state.connected:
  3665. return False
  3666. # Build calibration bitmask based on OrcaSlicer DeviceManager.cpp
  3667. # Bit 0: xcam_cali (not exposed in UI)
  3668. # Bit 1: bed_leveling
  3669. # Bit 2: vibration
  3670. # Bit 3: motor_noise
  3671. # Bit 4: nozzle_cali
  3672. # Bit 5: bed_cali (high-temp heatbed)
  3673. # Bit 6: clumppos_cali (not exposed in UI)
  3674. option = 0
  3675. if bed_leveling:
  3676. option |= 1 << 1
  3677. if vibration:
  3678. option |= 1 << 2
  3679. if motor_noise:
  3680. option |= 1 << 3
  3681. if nozzle_offset:
  3682. option |= 1 << 4
  3683. if high_temp_heatbed:
  3684. option |= 1 << 5
  3685. if option == 0:
  3686. logger.warning("[%s] No calibration options selected", self.serial_number)
  3687. return False
  3688. self._sequence_id += 1
  3689. command = {
  3690. "print": {
  3691. "command": "calibration",
  3692. "sequence_id": str(self._sequence_id),
  3693. "option": option,
  3694. }
  3695. }
  3696. command_json = json.dumps(command)
  3697. self._client.publish(self.topic_publish, command_json, qos=1)
  3698. logger.info(
  3699. f"[{self.serial_number}] Starting calibration: "
  3700. f"bed_leveling={bed_leveling}, vibration={vibration}, "
  3701. f"motor_noise={motor_noise}, nozzle_offset={nozzle_offset}, "
  3702. f"high_temp_heatbed={high_temp_heatbed} (option={option})"
  3703. )
  3704. return True
  3705. def disconnect(self, timeout: float = 0):
  3706. """Disconnect from the printer."""
  3707. if self._client:
  3708. self._disconnection_event = threading.Event()
  3709. self._client.disconnect()
  3710. self._disconnection_event.wait(timeout=timeout)
  3711. self._client.loop_stop()
  3712. self._client = None
  3713. self.state.connected = False
  3714. def send_command(self, command: dict):
  3715. """Send a command to the printer."""
  3716. if self._client and self.state.connected:
  3717. # Log outgoing message if logging is enabled
  3718. if self._logging_enabled:
  3719. self._message_log.append(
  3720. MQTTLogEntry(
  3721. timestamp=datetime.now(timezone.utc).isoformat(),
  3722. topic=self.topic_publish,
  3723. direction="out",
  3724. payload=command,
  3725. )
  3726. )
  3727. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3728. def enable_logging(self, enabled: bool = True):
  3729. """Enable or disable MQTT message logging."""
  3730. self._logging_enabled = enabled
  3731. # Don't clear logs when stopping - user can manually clear with clear_logs()
  3732. def get_logs(self) -> list[MQTTLogEntry]:
  3733. """Get all logged MQTT messages."""
  3734. return list(self._message_log)
  3735. def clear_logs(self):
  3736. """Clear the message log."""
  3737. self._message_log.clear()
  3738. @property
  3739. def logging_enabled(self) -> bool:
  3740. """Check if logging is enabled."""
  3741. return self._logging_enabled
  3742. def register_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  3743. """Register a handler invoked for every incoming MQTT message.
  3744. Used by the VP MQTT bridge to republish the printer's report pushes to
  3745. slicers connected to a virtual printer in non-proxy mode. Handlers run
  3746. on paho's network thread and must not block; exceptions are caught.
  3747. """
  3748. if handler not in self._raw_message_handlers:
  3749. self._raw_message_handlers.append(handler)
  3750. def unregister_raw_message_handler(self, handler: Callable[[str, bytes], None]) -> None:
  3751. """Unregister a previously-registered raw-message handler."""
  3752. try:
  3753. self._raw_message_handlers.remove(handler)
  3754. except ValueError:
  3755. pass
  3756. def publish_raw(self, topic: str, payload: bytes | str, qos: int = 1) -> bool:
  3757. """Publish a pre-formed payload directly to the printer's MQTT broker.
  3758. Used by the VP MQTT bridge to forward slicer-originated commands without
  3759. going through send_command's sequence-id mangling. Returns False if the
  3760. underlying paho client isn't ready.
  3761. """
  3762. if self._client is None:
  3763. return False
  3764. try:
  3765. info = self._client.publish(topic, payload, qos=qos)
  3766. return info.rc == mqtt.MQTT_ERR_SUCCESS
  3767. except Exception:
  3768. logger.exception("[%s] publish_raw failed for topic=%s", self.serial_number, topic)
  3769. return False
  3770. def send_drying_command(
  3771. self, ams_id: int, temp: int, duration: int, mode: int = 1, filament: str = "", rotate_tray: bool = False
  3772. ):
  3773. """Send AMS drying start/stop command.
  3774. Args:
  3775. ams_id: AMS unit ID (0-3 for AMS 2 Pro, 128-135 for AMS-HT)
  3776. temp: Target drying temperature (45-65 for AMS 2 Pro, 45-85 for AMS-HT)
  3777. duration: Drying duration in hours
  3778. mode: 1=start, 0=stop
  3779. filament: Filament type string (e.g. "PLA", "PETG")
  3780. rotate_tray: Whether to rotate the spool during drying for even heat
  3781. """
  3782. if not self._client:
  3783. return False
  3784. self._sequence_id += 1
  3785. command = {
  3786. "print": {
  3787. "sequence_id": str(self._sequence_id),
  3788. "command": "ams_filament_drying",
  3789. "ams_id": ams_id,
  3790. "temp": temp,
  3791. "cooling_temp": 20 if mode == 1 else 0,
  3792. "duration": duration,
  3793. "humidity": 0,
  3794. "mode": mode,
  3795. "rotate_tray": rotate_tray,
  3796. "filament": filament,
  3797. "close_power_conflict": False,
  3798. }
  3799. }
  3800. # Log the full wire JSON at INFO so support bundles capture exactly
  3801. # what we sent — needed to diagnose silent rejections (#1447) where
  3802. # the printer ACKs the command but never starts/stops drying.
  3803. # Paired with the ams_filament_drying response-payload INFO log so
  3804. # both halves of the conversation land in the bundle by default.
  3805. wire_json = json.dumps(command)
  3806. self._client.publish(self.topic_publish, wire_json, qos=1)
  3807. logger.info(
  3808. "[%s] Sent ams_filament_drying: %s",
  3809. self.serial_number,
  3810. wire_json,
  3811. )
  3812. # Track the active-cycle target so the badge can show "PETG @ 65°C"
  3813. # while drying. Bambu only echoes dry_time on subsequent pushes.
  3814. if mode == 1:
  3815. self._drying_targets[ams_id] = {
  3816. "filament": filament or "",
  3817. "temp": int(temp),
  3818. }
  3819. else:
  3820. self._drying_targets.pop(ams_id, None)
  3821. return True
  3822. def _handle_kprofile_response(self, data: dict):
  3823. """Handle K-profile response from printer."""
  3824. response_nozzle = data.get("nozzle_diameter")
  3825. response_seq_id = data.get("sequence_id", "?")
  3826. filaments = data.get("filaments", [])
  3827. expected_nozzle = getattr(self, "_expected_kprofile_nozzle", None)
  3828. has_pending_request = self._pending_kprofile_response is not None
  3829. # Log all incoming responses when we have a pending request (for debugging)
  3830. if has_pending_request:
  3831. logger.info(
  3832. f"[{self.serial_number}] K-profile response: nozzle={response_nozzle}, "
  3833. f"seq_id={response_seq_id}, {len(filaments)} profiles, expected={expected_nozzle}"
  3834. )
  3835. # If we have a pending request, only accept responses with matching nozzle_diameter
  3836. # The printer broadcasts 0.4mm profiles constantly - we need to wait for the actual response
  3837. if has_pending_request and expected_nozzle and response_nozzle != expected_nozzle:
  3838. # Ignore this broadcast, keep waiting for matching response
  3839. logger.debug(
  3840. f"[{self.serial_number}] Ignoring broadcast: got nozzle={response_nozzle}, waiting for {expected_nozzle}"
  3841. )
  3842. return
  3843. # If no pending request, this is just a broadcast - update state silently and return early
  3844. if not has_pending_request:
  3845. # Still parse profiles to keep state updated, but don't log
  3846. profiles = []
  3847. for f in filaments:
  3848. if isinstance(f, dict):
  3849. try:
  3850. cali_idx = f.get("cali_idx", 0)
  3851. profiles.append(
  3852. KProfile(
  3853. slot_id=cali_idx,
  3854. extruder_id=int(f.get("extruder_id", 0)),
  3855. nozzle_id=str(f.get("nozzle_id", "")),
  3856. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  3857. filament_id=str(f.get("filament_id", "")),
  3858. name=str(f.get("name", "")),
  3859. k_value=str(f.get("k_value", "0.000000")),
  3860. n_coef=str(f.get("n_coef", "0.000000")),
  3861. ams_id=int(f.get("ams_id", 0)),
  3862. tray_id=int(f.get("tray_id", -1)),
  3863. setting_id=f.get("setting_id"),
  3864. )
  3865. )
  3866. except (ValueError, TypeError):
  3867. pass # Skip malformed K-profile entries; remaining profiles still usable
  3868. self.state.kprofiles = profiles
  3869. return
  3870. profiles = []
  3871. for i, f in enumerate(filaments):
  3872. if isinstance(f, dict):
  3873. try:
  3874. # cali_idx is the actual slot/calibration index from the printer
  3875. cali_idx = f.get("cali_idx", i)
  3876. profiles.append(
  3877. KProfile(
  3878. slot_id=cali_idx,
  3879. extruder_id=int(f.get("extruder_id", 0)),
  3880. nozzle_id=str(f.get("nozzle_id", "")),
  3881. nozzle_diameter=str(f.get("nozzle_diameter", "0.4")),
  3882. filament_id=str(f.get("filament_id", "")),
  3883. name=str(f.get("name", "")),
  3884. k_value=str(f.get("k_value", "0.000000")),
  3885. n_coef=str(f.get("n_coef", "0.000000")),
  3886. ams_id=int(f.get("ams_id", 0)),
  3887. tray_id=int(f.get("tray_id", -1)),
  3888. setting_id=f.get("setting_id"),
  3889. )
  3890. )
  3891. except (ValueError, TypeError) as e:
  3892. logger.warning("Failed to parse K-profile: %s", e)
  3893. self.state.kprofiles = profiles
  3894. self._kprofile_response_data = profiles
  3895. # Signal that we received the response (only if we were waiting for one)
  3896. # Use thread-safe method since MQTT callbacks run in a different thread
  3897. # Capture in local var to avoid TOCTOU race: asyncio thread can clear
  3898. # self._pending_kprofile_response between the check and the .set() call
  3899. event = self._pending_kprofile_response
  3900. if event:
  3901. logger.info("[%s] Got %s K-profiles for nozzle=%s", self.serial_number, len(profiles), response_nozzle)
  3902. if self._loop and self._loop.is_running():
  3903. self._loop.call_soon_threadsafe(event.set)
  3904. else:
  3905. # Fallback for when loop is not available
  3906. event.set()
  3907. async def get_kprofiles(
  3908. self, nozzle_diameter: str = "0.4", timeout: float = 5.0, max_retries: int = 3
  3909. ) -> list[KProfile]:
  3910. """Request K-profiles from the printer with retry logic.
  3911. Bambu printers sometimes ignore the first K-profile request, so we
  3912. implement retry logic to ensure reliable retrieval.
  3913. Args:
  3914. nozzle_diameter: Filter by nozzle diameter (e.g., "0.4")
  3915. timeout: Timeout in seconds to wait for each response attempt
  3916. max_retries: Maximum number of retry attempts
  3917. Returns:
  3918. List of KProfile objects
  3919. """
  3920. if not self._client or not self.state.connected:
  3921. logger.warning("[%s] Cannot get K-profiles: not connected", self.serial_number)
  3922. return []
  3923. # Capture current event loop for thread-safe callback
  3924. try:
  3925. self._loop = asyncio.get_running_loop()
  3926. except RuntimeError:
  3927. logger.warning("[%s] No running event loop", self.serial_number)
  3928. return []
  3929. for attempt in range(max_retries):
  3930. # Set up response event for this attempt
  3931. self._sequence_id += 1
  3932. self._pending_kprofile_response = asyncio.Event()
  3933. self._kprofile_response_data = None
  3934. self._expected_kprofile_nozzle = nozzle_diameter # Track which nozzle response we expect
  3935. # Send the command with nozzle_diameter filter
  3936. command = {
  3937. "print": {
  3938. "command": "extrusion_cali_get",
  3939. "filament_id": "",
  3940. "nozzle_diameter": nozzle_diameter,
  3941. "sequence_id": str(self._sequence_id),
  3942. }
  3943. }
  3944. logger.info(
  3945. f"[{self.serial_number}] Requesting K-profiles for nozzle_diameter={nozzle_diameter} (attempt {attempt + 1}/{max_retries})"
  3946. )
  3947. logger.debug("[%s] K-profile request JSON: %s", self.serial_number, json.dumps(command))
  3948. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  3949. # Wait for response (response handler already filters by nozzle_diameter)
  3950. try:
  3951. await asyncio.wait_for(self._pending_kprofile_response.wait(), timeout=timeout)
  3952. profiles = self._kprofile_response_data or []
  3953. logger.info(
  3954. f"[{self.serial_number}] Got {len(profiles)} K-profiles for nozzle={nozzle_diameter} on attempt {attempt + 1}"
  3955. )
  3956. return profiles
  3957. except TimeoutError:
  3958. logger.warning(
  3959. f"[{self.serial_number}] Timeout on K-profiles request attempt {attempt + 1}/{max_retries}"
  3960. )
  3961. if attempt < max_retries - 1:
  3962. # Brief delay before retry
  3963. await asyncio.sleep(0.5)
  3964. finally:
  3965. self._pending_kprofile_response = None
  3966. self._expected_kprofile_nozzle = None
  3967. logger.error("[%s] Failed to get K-profiles after %s attempts", self.serial_number, max_retries)
  3968. return []
  3969. def set_kprofile(
  3970. self,
  3971. filament_id: str,
  3972. name: str,
  3973. k_value: str,
  3974. nozzle_diameter: str = "0.4",
  3975. nozzle_id: str = "HS00-0.4",
  3976. extruder_id: int = 0,
  3977. setting_id: str | None = None,
  3978. slot_id: int = 0,
  3979. cali_idx: int | None = None,
  3980. ) -> bool:
  3981. """Set/update a K-profile on the printer.
  3982. Args:
  3983. filament_id: Bambu filament identifier
  3984. name: Profile name
  3985. k_value: Pressure advance value (e.g., "0.020000")
  3986. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  3987. nozzle_id: Nozzle identifier (e.g., "HS00-0.4")
  3988. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  3989. setting_id: Existing setting ID for updates, None for new
  3990. slot_id: Calibration index (cali_idx) for the profile
  3991. cali_idx: For edits, the existing slot being edited (enables in-place edit)
  3992. Returns:
  3993. True if command was sent, False otherwise
  3994. """
  3995. if not self._client or not self.state.connected:
  3996. logger.warning("[%s] Cannot set K-profile: not connected", self.serial_number)
  3997. return False
  3998. self._sequence_id += 1
  3999. # Build the filament entry - printer uses cali_idx for profile identification
  4000. # For new profiles (slot_id=0), use cali_idx=-1 to tell printer to create new slot
  4001. # For edits, use the provided cali_idx or slot_id
  4002. if cali_idx is not None:
  4003. effective_cali_idx = cali_idx
  4004. else:
  4005. effective_cali_idx = -1 if slot_id == 0 else slot_id
  4006. # Generate a setting_id for new profiles (required by printer)
  4007. # Format: "PF" + 17 random digits
  4008. import random
  4009. if not setting_id and slot_id == 0:
  4010. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  4011. filament_entry = {
  4012. "ams_id": 0,
  4013. "cali_idx": effective_cali_idx,
  4014. "extruder_id": extruder_id,
  4015. "filament_id": filament_id,
  4016. "k_value": k_value,
  4017. "n_coef": "0.000000",
  4018. "name": name,
  4019. "nozzle_diameter": nozzle_diameter,
  4020. "nozzle_id": nozzle_id,
  4021. "setting_id": setting_id if setting_id else "",
  4022. "tray_id": -1,
  4023. }
  4024. command = {
  4025. "print": {
  4026. "command": "extrusion_cali_set",
  4027. "filaments": [filament_entry],
  4028. "nozzle_diameter": nozzle_diameter,
  4029. "sequence_id": str(self._sequence_id),
  4030. }
  4031. }
  4032. command_json = json.dumps(command)
  4033. logger.info(
  4034. f"[{self.serial_number}] Setting K-profile: {name} = {k_value} (cali_idx={effective_cali_idx}, new={slot_id == 0})"
  4035. )
  4036. logger.debug("[%s] K-profile SET command: %s", self.serial_number, command_json)
  4037. self._client.publish(self.topic_publish, command_json, qos=1)
  4038. return True
  4039. def set_kprofiles_batch(
  4040. self,
  4041. profiles: list[dict],
  4042. nozzle_diameter: str = "0.4",
  4043. ) -> bool:
  4044. """Set multiple K-profiles in a single command (for dual-nozzle).
  4045. Args:
  4046. profiles: List of profile dicts, each with:
  4047. - filament_id, name, k_value, nozzle_id, extruder_id, setting_id (optional), slot_id
  4048. nozzle_diameter: Common nozzle diameter for all profiles
  4049. Returns:
  4050. True if command was sent, False otherwise
  4051. """
  4052. if not self._client or not self.state.connected:
  4053. logger.warning("[%s] Cannot set K-profiles batch: not connected", self.serial_number)
  4054. return False
  4055. import random
  4056. self._sequence_id += 1
  4057. filament_entries = []
  4058. for p in profiles:
  4059. slot_id = p.get("slot_id", 0)
  4060. cali_idx = p.get("cali_idx")
  4061. if cali_idx is not None:
  4062. effective_cali_idx = cali_idx
  4063. else:
  4064. effective_cali_idx = -1 if slot_id == 0 else slot_id
  4065. setting_id = p.get("setting_id")
  4066. if not setting_id and slot_id == 0:
  4067. setting_id = f"PF{random.randint(10000000000000000, 99999999999999999)}"
  4068. filament_entries.append(
  4069. {
  4070. "ams_id": 0,
  4071. "cali_idx": effective_cali_idx,
  4072. "extruder_id": p.get("extruder_id", 0),
  4073. "filament_id": p.get("filament_id", ""),
  4074. "k_value": p.get("k_value", "0.020000"),
  4075. "n_coef": "0.000000",
  4076. "name": p.get("name", ""),
  4077. "nozzle_diameter": nozzle_diameter,
  4078. "nozzle_id": p.get("nozzle_id", f"HS00-{nozzle_diameter}"),
  4079. "setting_id": setting_id if setting_id else "",
  4080. "tray_id": -1,
  4081. }
  4082. )
  4083. command = {
  4084. "print": {
  4085. "command": "extrusion_cali_set",
  4086. "filaments": filament_entries,
  4087. "nozzle_diameter": nozzle_diameter,
  4088. "sequence_id": str(self._sequence_id),
  4089. }
  4090. }
  4091. command_json = json.dumps(command)
  4092. logger.info("[%s] Setting %s K-profiles in batch", self.serial_number, len(filament_entries))
  4093. logger.debug("[%s] K-profile SET batch command: %s", self.serial_number, command_json)
  4094. self._client.publish(self.topic_publish, command_json, qos=1)
  4095. return True
  4096. def delete_kprofile(
  4097. self,
  4098. cali_idx: int,
  4099. filament_id: str,
  4100. nozzle_id: str,
  4101. nozzle_diameter: str = "0.4",
  4102. extruder_id: int = 0,
  4103. setting_id: str | None = None,
  4104. ) -> bool:
  4105. """Delete a K-profile from the printer.
  4106. Args:
  4107. cali_idx: The calibration index (slot_id) of the profile to delete
  4108. filament_id: Bambu filament identifier
  4109. nozzle_id: Nozzle identifier (e.g., "HH00-0.4")
  4110. nozzle_diameter: Nozzle diameter (e.g., "0.4")
  4111. extruder_id: Extruder ID (0 or 1 for dual nozzle)
  4112. setting_id: Unique setting identifier (for X1C series)
  4113. Returns:
  4114. True if command was sent, False otherwise
  4115. """
  4116. if not self._client or not self.state.connected:
  4117. logger.warning("[%s] Cannot delete K-profile: not connected", self.serial_number)
  4118. return False
  4119. self._sequence_id += 1
  4120. # Dual-nozzle K-profile delete uses the extruder_id/nozzle_id format;
  4121. # single-nozzle printers (X1C/P1/A1/P2S/H2S) need the setting_id form.
  4122. # Prefer runtime detection from device.extruder.info; fall back to
  4123. # model name. H2S is single-nozzle but shares serial prefix "094" with
  4124. # H2D, so a prefix-only check misclassified it (#1386).
  4125. from backend.app.utils.printer_models import is_dual_nozzle_model
  4126. is_dual_nozzle = self._is_dual_nozzle or is_dual_nozzle_model(self.model)
  4127. if is_dual_nozzle:
  4128. # H2D format: uses extruder_id, nozzle_id, nozzle_diameter
  4129. command = {
  4130. "print": {
  4131. "command": "extrusion_cali_del",
  4132. "sequence_id": str(self._sequence_id),
  4133. "extruder_id": extruder_id,
  4134. "nozzle_id": nozzle_id,
  4135. "filament_id": filament_id,
  4136. "cali_idx": cali_idx,
  4137. "nozzle_diameter": nozzle_diameter,
  4138. }
  4139. }
  4140. else:
  4141. # X1C/P1/A1 format: include all fields like the set command
  4142. # The delete command structure should match what set uses
  4143. command = {
  4144. "print": {
  4145. "command": "extrusion_cali_del",
  4146. "sequence_id": str(self._sequence_id),
  4147. "filament_id": filament_id,
  4148. "cali_idx": cali_idx,
  4149. "setting_id": setting_id if setting_id else "",
  4150. "nozzle_diameter": nozzle_diameter,
  4151. "nozzle_id": nozzle_id,
  4152. "extruder_id": extruder_id,
  4153. }
  4154. }
  4155. command_json = json.dumps(command)
  4156. logger.info(
  4157. f"[{self.serial_number}] Deleting K-profile: cali_idx={cali_idx}, filament={filament_id}, setting_id={setting_id}, dual={is_dual_nozzle}"
  4158. )
  4159. logger.debug("[%s] K-profile DELETE command: %s", self.serial_number, command_json)
  4160. # Use QoS 1 for reliable delivery (at least once)
  4161. self._client.publish(self.topic_publish, command_json, qos=1)
  4162. return True
  4163. # =========================================================================
  4164. # Printer Control Commands
  4165. # =========================================================================
  4166. def pause_print(self) -> bool:
  4167. """Pause the current print job."""
  4168. if not self._client or not self.state.connected:
  4169. logger.warning("[%s] Cannot pause print: not connected", self.serial_number)
  4170. return False
  4171. command = {"print": {"command": "pause", "sequence_id": "0"}}
  4172. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4173. logger.info("[%s] Sent pause print command", self.serial_number)
  4174. return True
  4175. def resume_print(self) -> bool:
  4176. """Resume a paused print job."""
  4177. if not self._client or not self.state.connected:
  4178. logger.warning("[%s] Cannot resume print: not connected", self.serial_number)
  4179. return False
  4180. command = {"print": {"command": "resume", "sequence_id": "0"}}
  4181. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4182. logger.info("[%s] Sent resume print command", self.serial_number)
  4183. return True
  4184. def clear_hms_errors(self) -> bool:
  4185. """Clear HMS/print errors on the printer and locally."""
  4186. if not self._client or not self.state.connected:
  4187. logger.warning("[%s] Cannot clear HMS errors: not connected", self.serial_number)
  4188. return False
  4189. command = {"print": {"command": "clean_print_error", "sequence_id": "0"}}
  4190. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4191. self.state.hms_errors = []
  4192. logger.info("[%s] Sent clear HMS errors command", self.serial_number)
  4193. return True
  4194. def skip_objects(self, object_ids: list[int]) -> bool:
  4195. """Skip specific objects during a print.
  4196. This command tells the printer to skip printing the specified objects.
  4197. The object IDs come from the slice_info.config file in the 3MF.
  4198. Args:
  4199. object_ids: List of identify_id values from slice_info.config
  4200. Returns:
  4201. True if command was sent, False otherwise
  4202. """
  4203. if not self._client or not self.state.connected:
  4204. logger.warning("[%s] Cannot skip objects: not connected", self.serial_number)
  4205. return False
  4206. if self.state.state != "RUNNING" and self.state.state != "PAUSE":
  4207. logger.warning(
  4208. f"[{self.serial_number}] Cannot skip objects: printer not printing (state={self.state.state})"
  4209. )
  4210. return False
  4211. if not object_ids:
  4212. logger.warning("[%s] Cannot skip objects: no object IDs provided", self.serial_number)
  4213. return False
  4214. # Validate all IDs are integers
  4215. try:
  4216. obj_list = [int(oid) for oid in object_ids]
  4217. except (ValueError, TypeError) as e:
  4218. logger.warning("[%s] Invalid object IDs: %s", self.serial_number, e)
  4219. return False
  4220. self._sequence_id += 1
  4221. command = {"print": {"sequence_id": str(self._sequence_id), "command": "skip_objects", "obj_list": obj_list}}
  4222. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4223. logger.info("[%s] Sent skip_objects command: %s", self.serial_number, obj_list)
  4224. # Track skipped objects in state
  4225. for oid in obj_list:
  4226. if oid not in self.state.skipped_objects:
  4227. self.state.skipped_objects.append(oid)
  4228. return True
  4229. def send_gcode(self, gcode: str) -> bool:
  4230. """Send G-code command(s) to the printer.
  4231. Multiple commands can be separated by newlines.
  4232. Args:
  4233. gcode: G-code command(s) to send
  4234. Returns:
  4235. True if command was sent, False otherwise
  4236. """
  4237. if not self._client or not self.state.connected:
  4238. logger.warning("[%s] Cannot send G-code: not connected", self.serial_number)
  4239. return False
  4240. self._sequence_id += 1
  4241. command = {"print": {"command": "gcode_line", "param": gcode, "sequence_id": str(self._sequence_id)}}
  4242. # Use QoS 1 for reliable delivery (at least once)
  4243. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4244. logger.debug("[%s] Sent G-code: %s...", self.serial_number, gcode[:50])
  4245. return True
  4246. def set_bed_temperature(self, target: int) -> bool:
  4247. """Set the bed target temperature.
  4248. Args:
  4249. target: Target temperature in Celsius (0 to turn off)
  4250. Returns:
  4251. True if command was sent, False otherwise
  4252. """
  4253. return self.send_gcode(f"M140 S{target}")
  4254. def set_nozzle_temperature(self, target: int, nozzle: int = 0) -> bool:
  4255. """Set the nozzle target temperature.
  4256. Args:
  4257. target: Target temperature in Celsius (0 to turn off)
  4258. nozzle: Nozzle index (0 for right/default, 1 for left on H2D)
  4259. Returns:
  4260. True if command was sent, False otherwise
  4261. """
  4262. # Use M104 for non-blocking
  4263. # Always use T parameter for H2D compatibility
  4264. result = self.send_gcode(f"M104 T{nozzle} S{target}")
  4265. # H2D quirk: left nozzle (nozzle=1) target isn't reported in MQTT
  4266. # Track it locally so we can display it correctly
  4267. if result and nozzle == 1:
  4268. self.state.temperatures["nozzle_target"] = float(target)
  4269. self.state.temperatures["_nozzle_target_set_time"] = time.time()
  4270. logger.info("[%s] Tracking LEFT nozzle target locally: %s°C", self.serial_number, target)
  4271. return result
  4272. def set_chamber_temperature(self, target: int) -> bool:
  4273. """Set the chamber target temperature.
  4274. Args:
  4275. target: Target temperature in Celsius (0 to turn off heating)
  4276. Returns:
  4277. True if command was sent, False otherwise
  4278. """
  4279. # M141 sets chamber temperature
  4280. result = self.send_gcode(f"M141 S{target}")
  4281. # Track chamber target locally (MQTT reports encoded values that need filtering)
  4282. if result:
  4283. self.state.temperatures["chamber_target"] = float(target)
  4284. self.state.temperatures["_chamber_target_set_time"] = time.time()
  4285. # Update heating state immediately based on new target
  4286. current_temp = self.state.temperatures.get("chamber", 0)
  4287. self.state.temperatures["chamber_heating"] = target > 0 and current_temp < target
  4288. logger.info(
  4289. f"[{self.serial_number}] Tracking chamber target locally: {target}°C (heating={self.state.temperatures['chamber_heating']})"
  4290. )
  4291. return result
  4292. def set_print_speed(self, mode: int) -> bool:
  4293. """Set the print speed mode.
  4294. Args:
  4295. mode: Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)
  4296. Returns:
  4297. True if command was sent, False otherwise
  4298. """
  4299. if not self._client or not self.state.connected:
  4300. logger.warning("[%s] Cannot set print speed: not connected", self.serial_number)
  4301. return False
  4302. if mode not in (1, 2, 3, 4):
  4303. logger.warning("[%s] Invalid speed mode: %s", self.serial_number, mode)
  4304. return False
  4305. command = {"print": {"command": "print_speed", "param": str(mode), "sequence_id": "0"}}
  4306. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4307. logger.info("[%s] Set print speed mode to %s", self.serial_number, mode)
  4308. return True
  4309. def set_fan_speed(self, fan: int, speed: int) -> bool:
  4310. """Set fan speed.
  4311. Args:
  4312. fan: Fan index (1=part cooling, 2=auxiliary, 3=chamber)
  4313. speed: Speed 0-255 (0=off, 255=full)
  4314. Returns:
  4315. True if command was sent, False otherwise
  4316. """
  4317. if fan not in (1, 2, 3):
  4318. logger.warning("[%s] Invalid fan index: %s", self.serial_number, fan)
  4319. return False
  4320. speed = max(0, min(255, speed)) # Clamp to 0-255
  4321. return self.send_gcode(f"M106 P{fan} S{speed}")
  4322. def set_part_fan(self, speed: int) -> bool:
  4323. """Set part cooling fan speed (0-255)."""
  4324. return self.set_fan_speed(1, speed)
  4325. def set_aux_fan(self, speed: int) -> bool:
  4326. """Set auxiliary fan speed (0-255)."""
  4327. return self.set_fan_speed(2, speed)
  4328. def set_chamber_fan(self, speed: int) -> bool:
  4329. """Set chamber fan speed (0-255)."""
  4330. return self.set_fan_speed(3, speed)
  4331. def set_airduct_mode(self, mode: str) -> bool:
  4332. """Set air conditioning mode (cooling or heating).
  4333. Args:
  4334. mode: "cooling" (modeId=0) or "heating" (modeId=1)
  4335. - Cooling: Suitable for PLA/PETG/TPU, filters and cools chamber air
  4336. - Heating: Suitable for ABS/ASA/PC/PA, circulates and heats chamber air,
  4337. closes top exhaust flap
  4338. Returns:
  4339. True if command was sent, False otherwise
  4340. """
  4341. if not self._client or not self.state.connected:
  4342. logger.warning("[%s] Cannot set airduct mode: not connected", self.serial_number)
  4343. return False
  4344. self._sequence_id += 1
  4345. mode_id = 0 if mode == "cooling" else 1
  4346. command = {
  4347. "print": {"command": "set_airduct", "modeId": mode_id, "sequence_id": str(self._sequence_id), "submode": -1}
  4348. }
  4349. # Use QoS 1 for reliable delivery
  4350. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4351. logger.info(
  4352. "[%s] Set airduct mode to %s (modeId=%s, seq=%s)", self.serial_number, mode, mode_id, self._sequence_id
  4353. )
  4354. return True
  4355. def set_chamber_light(self, on: bool) -> bool:
  4356. """Turn chamber light on or off.
  4357. Args:
  4358. on: True to turn on, False to turn off
  4359. Returns:
  4360. True if command was sent, False otherwise
  4361. """
  4362. if not self._client or not self.state.connected:
  4363. logger.warning("[%s] Cannot set chamber light: not connected", self.serial_number)
  4364. return False
  4365. mode = "on" if on else "off"
  4366. # Control both chamber lights (some printers like H2D have two)
  4367. for led_node in ["chamber_light", "chamber_light2"]:
  4368. self._sequence_id += 1
  4369. command = {
  4370. "system": {
  4371. "command": "ledctrl",
  4372. "led_node": led_node,
  4373. "led_mode": mode,
  4374. "led_on_time": 500,
  4375. "led_off_time": 500,
  4376. "loop_times": 0,
  4377. "interval_time": 0,
  4378. "sequence_id": str(self._sequence_id),
  4379. }
  4380. }
  4381. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4382. logger.info("[%s] Set chamber lights %s (seq=%s)", self.serial_number, "on" if on else "off", self._sequence_id)
  4383. return True
  4384. def select_extruder(self, extruder: int) -> bool:
  4385. """Select the active extruder for dual-nozzle printers (H2D).
  4386. Args:
  4387. extruder: Extruder index (0=right, 1=left for H2D)
  4388. Returns:
  4389. True if command was sent, False otherwise
  4390. """
  4391. if extruder not in (0, 1):
  4392. logger.warning("[%s] Invalid extruder: %s", self.serial_number, extruder)
  4393. return False
  4394. if not self._client or not self.state.connected:
  4395. logger.warning("[%s] Cannot switch extruder: not connected", self.serial_number)
  4396. return False
  4397. # H2D extruder switching via select_extruder command
  4398. # Command format captured from OrcaSlicer:
  4399. # {"print": {"command": "select_extruder", "extruder_index": 0, "sequence_id": "..."}}
  4400. # extruder_index: 0 = RIGHT, 1 = LEFT
  4401. self._sequence_id += 1
  4402. command = {
  4403. "print": {"command": "select_extruder", "extruder_index": extruder, "sequence_id": str(self._sequence_id)}
  4404. }
  4405. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4406. logger.info(
  4407. "[%s] Sent select_extruder command: extruder_index=%s (0=right, 1=left)", self.serial_number, extruder
  4408. )
  4409. return True
  4410. def home_axes(self, axes: str = "XYZ") -> bool:
  4411. """Run the printer's full auto-home sequence.
  4412. The ``axes`` argument is ignored: a bare ``G28`` is always sent so
  4413. Bambu firmware runs its safe multi-step routine (park toolhead →
  4414. home XY → home Z). Partial-axis variants like ``G28 Z`` skip the
  4415. toolhead-park step and can crash the bed into the toolhead on H2C
  4416. / H2D / H2S / X1 where Z-home moves the bed UP — see #1052.
  4417. """
  4418. return self.send_gcode("G28")
  4419. def move_axis(self, axis: str, distance: float, speed: int = 3000) -> bool:
  4420. """Move an axis by a relative distance.
  4421. Args:
  4422. axis: Axis to move ("X", "Y", or "Z")
  4423. distance: Distance to move in mm (positive or negative)
  4424. speed: Movement speed in mm/min
  4425. Returns:
  4426. True if command was sent, False otherwise
  4427. """
  4428. axis = axis.upper()
  4429. if axis not in ("X", "Y", "Z"):
  4430. logger.warning("[%s] Invalid axis: %s", self.serial_number, axis)
  4431. return False
  4432. # G91 = relative mode, G0 = rapid move, G90 = back to absolute
  4433. gcode = f"G91\nG0 {axis}{distance:.2f} F{speed}\nG90"
  4434. return self.send_gcode(gcode)
  4435. def disable_motors(self) -> bool:
  4436. """Disable all stepper motors.
  4437. Warning: This will cause the printer to lose its position.
  4438. A homing operation will be required before printing.
  4439. Returns:
  4440. True if command was sent, False otherwise
  4441. """
  4442. return self.send_gcode("M18")
  4443. def enable_motors(self) -> bool:
  4444. """Enable all stepper motors.
  4445. Returns:
  4446. True if command was sent, False otherwise
  4447. """
  4448. return self.send_gcode("M17")
  4449. def ams_load_filament(self, tray_id: int, extruder_id: int | None = None) -> bool:
  4450. """Load filament from a specific AMS tray.
  4451. Args:
  4452. tray_id: Global tray ID — 0..15 for AMS slots, 254 for external spool
  4453. (single-external printers and Ext-L on dual-nozzle H2D),
  4454. 255 for Ext-R on dual-nozzle H2D.
  4455. extruder_id: Unused - kept for API compatibility
  4456. Returns:
  4457. True if command was sent, False otherwise
  4458. """
  4459. if not self._client or not self.state.connected:
  4460. logger.warning("[%s] Cannot load filament: not connected", self.serial_number)
  4461. return False
  4462. # Build the ams_change_filament command. Encoding differs by target type:
  4463. # - AMS slots (0..15): slot_id is the local slot, curr/tar_temp = -1.
  4464. # - External spool (tray_id=254): legacy capture from a single-extruder
  4465. # printer used slot_id=254, curr/tar_temp=-1; preserved here.
  4466. # - Ext-R on dual-nozzle H2D (tray_id=255): captured shape from
  4467. # BambuStudio uses slot_id=0 (extruder index, 0=right), and
  4468. # curr_temp/tar_temp = the actual right-nozzle temp. See #891.
  4469. self._sequence_id += 1
  4470. if tray_id == 255:
  4471. ams_id = 255
  4472. slot_id = 0 # extruder index for the right nozzle
  4473. right_temp = int(self.state.temperatures.get("nozzle_2", 0) or 0)
  4474. if right_temp < 180:
  4475. right_temp = 215 # Reasonable default if right nozzle is cold/unknown
  4476. curr_temp = right_temp
  4477. tar_temp = right_temp
  4478. elif tray_id == 254:
  4479. ams_id = 255
  4480. slot_id = 254
  4481. curr_temp = -1
  4482. tar_temp = -1
  4483. else:
  4484. ams_id = tray_id // 4
  4485. slot_id = tray_id % 4
  4486. curr_temp = -1
  4487. tar_temp = -1
  4488. command = {
  4489. "print": {
  4490. "command": "ams_change_filament",
  4491. "sequence_id": str(self._sequence_id),
  4492. "ams_id": ams_id,
  4493. "slot_id": slot_id,
  4494. "target": tray_id,
  4495. "curr_temp": curr_temp,
  4496. "tar_temp": tar_temp,
  4497. }
  4498. }
  4499. command_json = json.dumps(command)
  4500. logger.info("[%s] Publishing ams_change_filament command: %s", self.serial_number, command_json)
  4501. self._client.publish(self.topic_publish, command_json, qos=1)
  4502. logger.info("[%s] Loading filament from tray %s (AMS %s slot %s)", self.serial_number, tray_id, ams_id, slot_id)
  4503. # Track this load request for H2D dual-nozzle disambiguation
  4504. # H2D reports only slot number (0-3) in tray_now, so we use our tracked value
  4505. self._last_load_tray_id = tray_id
  4506. self.state.pending_tray_target = tray_id
  4507. logger.info("[%s] Set pending_tray_target=%s for H2D disambiguation", self.serial_number, tray_id)
  4508. return True
  4509. def ams_unload_filament(self) -> bool:
  4510. """Unload the currently loaded filament.
  4511. Returns:
  4512. True if command was sent, False otherwise
  4513. """
  4514. if not self._client or not self.state.connected:
  4515. logger.warning("[%s] Cannot unload filament: not connected", self.serial_number)
  4516. return False
  4517. # Get the currently loaded tray info
  4518. tray_now = self.state.tray_now
  4519. logger.info("[%s] Unload requested, tray_now=%s", self.serial_number, tray_now)
  4520. # Determine source ams_id for the unload command
  4521. if tray_now == 255 or tray_now == 254:
  4522. ams_id = 255 # No filament or external spool
  4523. else:
  4524. ams_id = tray_now // 4 # Source AMS
  4525. # Command format from BambuStudio traffic capture:
  4526. # - No extruder_id field
  4527. # - For UNLOAD: curr_temp and tar_temp are the actual nozzle temp (e.g., 210)
  4528. # - slot_id=255 and target=255 for unload
  4529. # Get current nozzle temperature for the unload command
  4530. nozzle_temp = int(self.state.temperatures.get("nozzle", 210))
  4531. if nozzle_temp < 180:
  4532. nozzle_temp = 210 # Default to PLA temp if nozzle is cold
  4533. self._sequence_id += 1
  4534. command = {
  4535. "print": {
  4536. "command": "ams_change_filament",
  4537. "sequence_id": str(self._sequence_id),
  4538. "ams_id": ams_id,
  4539. "slot_id": 255, # 255 = unload marker
  4540. "target": 255, # 255 = unload destination
  4541. "curr_temp": nozzle_temp,
  4542. "tar_temp": nozzle_temp,
  4543. }
  4544. }
  4545. command_json = json.dumps(command)
  4546. logger.info("[%s] Publishing ams_change_filament (unload) command: %s", self.serial_number, command_json)
  4547. self._client.publish(self.topic_publish, command_json, qos=1)
  4548. logger.info("[%s] Unloading filament (tray_now was %s)", self.serial_number, tray_now)
  4549. # Clear tracked load request since we're unloading
  4550. self._last_load_tray_id = None
  4551. self.state.pending_tray_target = None
  4552. logger.info("[%s] Cleared pending_tray_target (unload)", self.serial_number)
  4553. return True
  4554. def ams_control(self, action: str) -> bool:
  4555. """Control AMS operations.
  4556. Args:
  4557. action: "resume", "reset", or "pause"
  4558. Returns:
  4559. True if command was sent, False otherwise
  4560. """
  4561. if not self._client or not self.state.connected:
  4562. logger.warning("[%s] Cannot control AMS: not connected", self.serial_number)
  4563. return False
  4564. if action not in ("resume", "reset", "pause"):
  4565. logger.warning("[%s] Invalid AMS action: %s", self.serial_number, action)
  4566. return False
  4567. command = {"print": {"command": "ams_control", "param": action, "sequence_id": "0"}}
  4568. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4569. logger.info("[%s] AMS control: %s", self.serial_number, action)
  4570. return True
  4571. def ams_refresh_tray(self, ams_id: int, tray_id: int) -> tuple[bool, str]:
  4572. """Trigger RFID re-read for a specific AMS tray.
  4573. Args:
  4574. ams_id: AMS unit ID (0-3, or 128 for H2D external tray)
  4575. tray_id: Tray ID within the AMS (0-3)
  4576. Returns:
  4577. Tuple of (success, message)
  4578. """
  4579. if not self._client or not self.state.connected:
  4580. logger.warning("[%s] Cannot refresh AMS tray: not connected", self.serial_number)
  4581. return False, "Printer not connected"
  4582. # Check if filament is currently loaded (tray_now != 255)
  4583. # RFID refresh requires the AMS to move filament, which can't happen if one is loaded
  4584. tray_now = self.state.tray_now
  4585. if tray_now != 255:
  4586. # Decode which tray is loaded for the message
  4587. if tray_now == 254:
  4588. loaded_tray = "external spool"
  4589. elif tray_now >= 0 and tray_now < 128:
  4590. loaded_ams = tray_now // 4
  4591. loaded_slot = tray_now % 4
  4592. loaded_tray = f"AMS {loaded_ams + 1} slot {loaded_slot + 1}"
  4593. else:
  4594. loaded_tray = f"tray {tray_now}"
  4595. logger.warning("[%s] Cannot refresh AMS tray: filament loaded from %s", self.serial_number, loaded_tray)
  4596. return False, f"Please unload filament first. Currently loaded: {loaded_tray}"
  4597. # Use ams_get_rfid command to trigger RFID re-read
  4598. # This command is used by Bambu Studio to re-read the RFID tag
  4599. command = {"print": {"command": "ams_get_rfid", "ams_id": ams_id, "slot_id": tray_id, "sequence_id": "0"}}
  4600. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4601. logger.info("[%s] Triggering RFID re-read: AMS %s, slot %s", self.serial_number, ams_id, tray_id)
  4602. return True, f"Refreshing AMS {ams_id} tray {tray_id}"
  4603. def ams_set_filament_setting(
  4604. self,
  4605. ams_id: int,
  4606. tray_id: int,
  4607. tray_info_idx: str,
  4608. tray_type: str,
  4609. tray_sub_brands: str,
  4610. tray_color: str,
  4611. nozzle_temp_min: int,
  4612. nozzle_temp_max: int,
  4613. setting_id: str = "",
  4614. ) -> bool:
  4615. """Set AMS tray filament settings (type, color, temperature).
  4616. Note: K value is set separately via extrusion_cali_sel command.
  4617. Args:
  4618. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  4619. tray_id: Tray ID within the AMS (0-3)
  4620. tray_info_idx: Filament ID short format (e.g., "GFL05")
  4621. tray_type: Filament type (e.g., "PLA", "PETG")
  4622. tray_sub_brands: Sub-brand name (e.g., "PLA Basic", "PETG HF")
  4623. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  4624. nozzle_temp_min: Minimum nozzle temperature
  4625. nozzle_temp_max: Maximum nozzle temperature
  4626. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  4627. Returns:
  4628. True if command was sent, False otherwise
  4629. """
  4630. if not self._client or not self.state.connected:
  4631. logger.warning("[%s] Cannot set AMS filament setting: not connected", self.serial_number)
  4632. return False
  4633. # Calculate mqtt IDs based on AMS type.
  4634. # External-spool convention verified against a BambuStudio→X1C packet capture
  4635. # (issue #1279, May 2026): for `ams_filament_setting` Studio sends the
  4636. # *global* tray index in `tray_id`, not a local position within the virtual
  4637. # unit. The printer's response echoes `tray_id: 0` (slot position), which
  4638. # is what the original code was matching — but the request and response
  4639. # use different semantics for that field. Sending `tray_id: 0` is what
  4640. # the P1S in #1279 rejected with `result: "fail"`.
  4641. if ams_id == 255:
  4642. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  4643. if len(vt_tray) > 1:
  4644. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  4645. # (254=ext-L / slot 0, 255=ext-R / slot 1). The dual case is NOT
  4646. # covered by the X1C capture — left at `mqtt_tray_id = 0` until a
  4647. # captured Studio→H2D exchange confirms the correct value.
  4648. mqtt_ams_id = 254 + tray_id
  4649. mqtt_tray_id = 0
  4650. else:
  4651. # Single external slot (X1C, P1S, A1): global tray_id=254.
  4652. mqtt_ams_id = 255
  4653. mqtt_tray_id = 254
  4654. slot_id = 0
  4655. elif ams_id <= 3:
  4656. mqtt_ams_id = ams_id
  4657. mqtt_tray_id = tray_id
  4658. slot_id = tray_id
  4659. else:
  4660. # AMS-HT: single tray per unit
  4661. mqtt_ams_id = ams_id
  4662. mqtt_tray_id = tray_id
  4663. slot_id = 0
  4664. command = {
  4665. "print": {
  4666. "command": "ams_filament_setting",
  4667. "ams_id": mqtt_ams_id,
  4668. "tray_id": mqtt_tray_id,
  4669. "slot_id": slot_id,
  4670. "tray_info_idx": tray_info_idx,
  4671. "tray_type": tray_type,
  4672. "tray_sub_brands": tray_sub_brands,
  4673. "tray_color": tray_color,
  4674. "nozzle_temp_min": nozzle_temp_min,
  4675. "nozzle_temp_max": nozzle_temp_max,
  4676. "sequence_id": "0",
  4677. }
  4678. }
  4679. # Include setting_id if provided (helps slicer show correct profile)
  4680. if setting_id:
  4681. command["print"]["setting_id"] = setting_id
  4682. command_json = json.dumps(command)
  4683. logger.info(
  4684. f"[{self.serial_number}] Publishing ams_filament_setting: AMS {ams_id}, tray {tray_id}, tray_info_idx={tray_info_idx}, setting_id={setting_id}"
  4685. )
  4686. logger.debug("[%s] ams_filament_setting command: %s", self.serial_number, command_json)
  4687. self._client.publish(self.topic_publish, command_json, qos=1)
  4688. self._last_ams_cmd_time = time.monotonic()
  4689. return True
  4690. def reset_ams_slot(self, ams_id: int, tray_id: int) -> bool:
  4691. """Reset an AMS slot to empty/unconfigured state.
  4692. Args:
  4693. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  4694. tray_id: Tray ID within the AMS (0-3)
  4695. Returns:
  4696. True if command was sent, False otherwise
  4697. """
  4698. if not self._client or not self.state.connected:
  4699. logger.warning("[%s] Cannot reset AMS slot: not connected", self.serial_number)
  4700. return False
  4701. # Calculate mqtt IDs based on AMS type — same convention as
  4702. # ams_set_filament_setting above. See its comment for the #1279 capture rationale.
  4703. if ams_id == 255:
  4704. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  4705. if len(vt_tray) > 1:
  4706. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  4707. mqtt_ams_id = 254 + tray_id
  4708. mqtt_tray_id = 0
  4709. else:
  4710. # Single external slot (X1C, P1S, A1): global tray_id=254.
  4711. mqtt_ams_id = 255
  4712. mqtt_tray_id = 254
  4713. slot_id = 0
  4714. elif ams_id <= 3:
  4715. mqtt_ams_id = ams_id
  4716. mqtt_tray_id = tray_id
  4717. slot_id = tray_id
  4718. else:
  4719. # AMS-HT: single tray per unit
  4720. mqtt_ams_id = ams_id
  4721. mqtt_tray_id = tray_id
  4722. slot_id = 0
  4723. command = {
  4724. "print": {
  4725. "command": "ams_filament_setting",
  4726. "ams_id": mqtt_ams_id,
  4727. "tray_id": mqtt_tray_id,
  4728. "slot_id": slot_id,
  4729. "tray_info_idx": "",
  4730. "tray_type": "",
  4731. "tray_sub_brands": "",
  4732. "tray_color": "00000000",
  4733. "nozzle_temp_min": 0,
  4734. "nozzle_temp_max": 0,
  4735. "sequence_id": "0",
  4736. }
  4737. }
  4738. command_json = json.dumps(command)
  4739. logger.info("[%s] Resetting AMS slot: AMS %s, tray %s", self.serial_number, ams_id, tray_id)
  4740. logger.debug("[%s] reset_ams_slot command: %s", self.serial_number, command_json)
  4741. self._client.publish(self.topic_publish, command_json, qos=1)
  4742. self._last_ams_cmd_time = time.monotonic()
  4743. return True
  4744. def extrusion_cali_sel(
  4745. self,
  4746. ams_id: int,
  4747. tray_id: int,
  4748. cali_idx: int,
  4749. filament_id: str,
  4750. nozzle_diameter: str = "0.4",
  4751. ) -> bool:
  4752. """Set calibration profile (K value) for an AMS slot.
  4753. This command selects a K profile from the printer's calibration list.
  4754. Use cali_idx=-1 to use the default K value (0.020).
  4755. Note: Do NOT send setting_id in this command — BambuStudio never includes
  4756. it, and adding it causes the firmware to mislink the profile on X1C/P1S.
  4757. Args:
  4758. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  4759. tray_id: Tray ID within the AMS (0-3)
  4760. cali_idx: Calibration profile index (-1 for default)
  4761. filament_id: Filament preset ID (same as tray_info_idx)
  4762. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  4763. Returns:
  4764. True if command was sent, False otherwise
  4765. """
  4766. if not self._client or not self.state.connected:
  4767. logger.warning("[%s] Cannot set calibration: not connected", self.serial_number)
  4768. return False
  4769. # Calculate mqtt IDs based on AMS type.
  4770. # IMPORTANT: extrusion_cali_sel uses GLOBAL tray_id (unlike ams_filament_setting
  4771. # which uses LOCAL). BambuStudio confirms: tray_id = ams_id * 4 + slot.
  4772. if ams_id == 255:
  4773. # External spool: extrusion_cali_sel uses GLOBAL tray_id (unlike
  4774. # ams_filament_setting which uses LOCAL tray_id=0).
  4775. vt_tray = self.state.raw_data.get("vt_tray", []) if self.state.raw_data else []
  4776. if len(vt_tray) > 1:
  4777. # Dual external slots (H2D): each ext slot is its own virtual AMS unit
  4778. # Confirmed from BambuStudio logs: ext-R sends ams_id=255, tray_id=255
  4779. mqtt_ams_id = 254 + tray_id
  4780. mqtt_tray_id = 254 + tray_id
  4781. else:
  4782. # Single external slot (X1C, P1S, A1): global tray_id=254
  4783. mqtt_ams_id = 254
  4784. mqtt_tray_id = 254
  4785. slot_id = 0
  4786. elif ams_id <= 3:
  4787. mqtt_ams_id = ams_id
  4788. mqtt_tray_id = ams_id * 4 + tray_id
  4789. slot_id = tray_id
  4790. elif ams_id >= 128 and ams_id <= 135:
  4791. mqtt_ams_id = ams_id
  4792. mqtt_tray_id = tray_id
  4793. slot_id = 0
  4794. else:
  4795. mqtt_ams_id = ams_id
  4796. mqtt_tray_id = tray_id
  4797. slot_id = 0
  4798. command = {
  4799. "print": {
  4800. "command": "extrusion_cali_sel",
  4801. "cali_idx": cali_idx,
  4802. "filament_id": filament_id,
  4803. "nozzle_diameter": nozzle_diameter,
  4804. "ams_id": mqtt_ams_id,
  4805. "tray_id": mqtt_tray_id,
  4806. "slot_id": slot_id,
  4807. "sequence_id": "0",
  4808. }
  4809. }
  4810. command_json = json.dumps(command)
  4811. logger.info(
  4812. f"[{self.serial_number}] Publishing extrusion_cali_sel: AMS {ams_id}, tray {tray_id}, cali_idx={cali_idx}"
  4813. )
  4814. logger.debug("[%s] extrusion_cali_sel command: %s", self.serial_number, command_json)
  4815. self._client.publish(self.topic_publish, command_json, qos=1)
  4816. return True
  4817. def extrusion_cali_set(
  4818. self,
  4819. tray_id: int,
  4820. k_value: float,
  4821. nozzle_diameter: str = "0.4",
  4822. nozzle_temp: int = 220,
  4823. filament_id: str = "",
  4824. setting_id: str = "",
  4825. name: str = "",
  4826. cali_idx: int = -1,
  4827. ) -> bool:
  4828. """Directly set K value (pressure advance) for a tray.
  4829. Uses the filaments array format required by current firmware.
  4830. Args:
  4831. tray_id: Global tray ID (ams_id * 4 + slot)
  4832. k_value: Pressure advance K value (e.g., 0.020)
  4833. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  4834. nozzle_temp: Nozzle temperature for calibration reference
  4835. filament_id: Filament preset ID (e.g., "GFA02")
  4836. setting_id: Setting ID (e.g., "GFSA02_07")
  4837. name: Profile display name
  4838. cali_idx: Calibration index (-1 for new)
  4839. Returns:
  4840. True if command was sent, False otherwise
  4841. """
  4842. if not self._client or not self.state.connected:
  4843. logger.warning("[%s] Cannot set K value: not connected", self.serial_number)
  4844. return False
  4845. nozzle_id = f"HS00-{nozzle_diameter}"
  4846. filament_entry = {
  4847. "ams_id": 0,
  4848. "cali_idx": cali_idx,
  4849. "extruder_id": 0,
  4850. "filament_id": filament_id,
  4851. "k_value": f"{k_value:.6f}",
  4852. "n_coef": "1.400000",
  4853. "name": name,
  4854. "nozzle_diameter": nozzle_diameter,
  4855. "nozzle_id": nozzle_id,
  4856. "setting_id": setting_id,
  4857. "tray_id": tray_id,
  4858. }
  4859. command = {
  4860. "print": {
  4861. "command": "extrusion_cali_set",
  4862. "filaments": [filament_entry],
  4863. "nozzle_diameter": nozzle_diameter,
  4864. "sequence_id": str(self._sequence_id),
  4865. }
  4866. }
  4867. command_json = json.dumps(command)
  4868. logger.info("[%s] Publishing extrusion_cali_set: tray %s, k_value=%s", self.serial_number, tray_id, k_value)
  4869. logger.debug("[%s] extrusion_cali_set command: %s", self.serial_number, command_json)
  4870. self._client.publish(self.topic_publish, command_json, qos=1)
  4871. return True
  4872. def set_timelapse(self, enable: bool) -> bool:
  4873. """Enable or disable timelapse recording.
  4874. Args:
  4875. enable: True to enable, False to disable
  4876. Returns:
  4877. True if command was sent, False otherwise
  4878. """
  4879. if not self._client or not self.state.connected:
  4880. logger.warning("[%s] Cannot set timelapse: not connected", self.serial_number)
  4881. return False
  4882. command = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  4883. # First send the timelapse setting
  4884. timelapse_cmd = {
  4885. "print": {"command": "gcode_line", "param": f"M981 S{1 if enable else 0} P20000", "sequence_id": "0"}
  4886. }
  4887. self._client.publish(self.topic_publish, json.dumps(timelapse_cmd), qos=1)
  4888. # Request status update
  4889. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4890. logger.info("[%s] Set timelapse %s", self.serial_number, "enabled" if enable else "disabled")
  4891. return True
  4892. def set_liveview(self, enable: bool) -> bool:
  4893. """Enable or disable live view / camera streaming.
  4894. Args:
  4895. enable: True to enable, False to disable
  4896. Returns:
  4897. True if command was sent, False otherwise
  4898. """
  4899. if not self._client or not self.state.connected:
  4900. logger.warning("[%s] Cannot set liveview: not connected", self.serial_number)
  4901. return False
  4902. command = {
  4903. "xcam": {"command": "ipcam_record_set", "control": "enable" if enable else "disable", "sequence_id": "0"}
  4904. }
  4905. self._client.publish(self.topic_publish, json.dumps(command), qos=1)
  4906. # Request status update
  4907. pushall = {"pushing": {"command": "pushall", "sequence_id": "0"}}
  4908. self._client.publish(self.topic_publish, json.dumps(pushall), qos=1)
  4909. logger.info("[%s] Set liveview %s", self.serial_number, "enabled" if enable else "disabled")
  4910. return True
  4911. def execute_hms_action(self, print_error: str, action: str, job_id: str | None = None) -> bool:
  4912. """Dispatch the user's choice from the HMS-error modal as a printer command.
  4913. Args:
  4914. print_error: 8-char hex short code with no separator (e.g. "05000070").
  4915. The frontend strips the underscore from the displayed `MMMM_EEEE`
  4916. before sending.
  4917. action: One of HMSAction's string values.
  4918. job_id: The `subtask_id` snapshotted onto the HMSError at parse-time.
  4919. Bambu's HMS-aware commands echo it back as `job_id`. May be None
  4920. for idle errors that never had a job.
  4921. Returns False when the MQTT client is offline or when `action` is unknown
  4922. so the route surfaces it as a 4xx rather than a silent no-op.
  4923. """
  4924. if not self._client or not self.state.connected:
  4925. logger.warning("[%s] Cannot execute HMS action: not connected", self.serial_number)
  4926. return False
  4927. # Always re-push the full state after a command so the modal's underlying
  4928. # status query reflects the new error list (or absence) on the next tick.
  4929. def publish(payload: dict):
  4930. self._client.publish(self.topic_publish, json.dumps(payload), qos=1)
  4931. self._client.publish(
  4932. self.topic_publish, json.dumps({"pushing": {"command": "pushall", "sequence_id": "0"}}), qos=1
  4933. )
  4934. def hms_resume():
  4935. publish(
  4936. {
  4937. "print": {
  4938. "command": "resume",
  4939. "err": print_error,
  4940. "param": "reserve",
  4941. "job_id": job_id,
  4942. "sequence_id": "0",
  4943. }
  4944. }
  4945. )
  4946. def hms_stop():
  4947. publish(
  4948. {
  4949. "print": {
  4950. "command": "stop",
  4951. "err": print_error,
  4952. "param": "reserve",
  4953. "job_id": job_id,
  4954. "sequence_id": "0",
  4955. }
  4956. }
  4957. )
  4958. def hms_ignore(persistent: bool = False):
  4959. # `idle_ignore` is BambuStudio's "dismiss this warning" command.
  4960. # type=0 dismisses once, type=1 hides the same warning permanently.
  4961. publish(
  4962. {
  4963. "print": {
  4964. "command": "idle_ignore",
  4965. "err": print_error,
  4966. "type": 1 if persistent else 0,
  4967. "sequence_id": "0",
  4968. }
  4969. }
  4970. )
  4971. def ams_control(param: str):
  4972. publish(
  4973. {
  4974. "print": {
  4975. "command": "ams_control",
  4976. "param": param,
  4977. "sequence_id": "0",
  4978. }
  4979. }
  4980. )
  4981. def clean_print_error():
  4982. # Matches the existing `clear_hms_errors` shape — Bambu does not
  4983. # expect `print_error` in the body; the command clears whatever
  4984. # error dialog is currently active on the printer.
  4985. publish(
  4986. {
  4987. "print": {
  4988. "command": "clean_print_error",
  4989. "sequence_id": "0",
  4990. }
  4991. }
  4992. )
  4993. def uiop_close():
  4994. # `err` is the 8-char hex short code (already a string from the
  4995. # frontend), uppercased for consistency with how BambuStudio sends it.
  4996. publish(
  4997. {
  4998. "system": {
  4999. "command": "uiop",
  5000. "name": "print_error",
  5001. "action": "close",
  5002. "source": 1,
  5003. "type": "dialog",
  5004. "err": print_error.upper(),
  5005. "sequence_id": "0",
  5006. }
  5007. }
  5008. )
  5009. match action:
  5010. case (
  5011. HMSAction.RESUME_PRINTING
  5012. | HMSAction.RESUME_PRINTING_DEFECTS
  5013. | HMSAction.RESUME_PRINTING_PROBELM_SOLVED
  5014. | HMSAction.PROBLEM_SOLVED_RESUME
  5015. | HMSAction.FILAMENT_LOAD_RESUME
  5016. | HMSAction.PROCEED
  5017. ):
  5018. hms_resume()
  5019. case HMSAction.STOP_PRINTING:
  5020. hms_stop()
  5021. case HMSAction.IGNORE_RESUME | HMSAction.NO_REMINDER_NEXT_TIME:
  5022. hms_ignore(persistent=False)
  5023. case HMSAction.IGNORE_NO_REMINDER_NEXT_TIME | HMSAction.DONT_REMIND_NEXT_TIME:
  5024. hms_ignore(persistent=True)
  5025. case HMSAction.FILAMENT_EXTRUDED | HMSAction.DBL_CHECK_DONE:
  5026. ams_control("done")
  5027. case (
  5028. HMSAction.RETRY_FILAMENT_EXTRUDED
  5029. | HMSAction.CONTINUE
  5030. | HMSAction.RETRY_PROBLEM_SOLVED
  5031. | HMSAction.DBL_CHECK_RETRY
  5032. ):
  5033. ams_control("resume")
  5034. case HMSAction.ABORT:
  5035. ams_control("abort")
  5036. case HMSAction.OK_BUTTON:
  5037. clean_print_error()
  5038. case HMSAction.DBL_CHECK_OK:
  5039. clean_print_error()
  5040. uiop_close()
  5041. case HMSAction.DBL_CHECK_RESUME:
  5042. # Plain resume — not HMS-aware, no err/job_id.
  5043. publish(
  5044. {
  5045. "print": {
  5046. "command": "resume",
  5047. "param": "",
  5048. "sequence_id": "0",
  5049. }
  5050. }
  5051. )
  5052. case HMSAction.REFRESH_NOZZLE:
  5053. publish({"print": {"command": "refresh_nozzle", "sequence_id": "0"}})
  5054. case HMSAction.TURN_OFF_FIRE_ALARM:
  5055. publish({"print": {"command": "buzzer_ctrl", "mode": 0, "sequence_id": "0"}})
  5056. case HMSAction.STOP_DRYING:
  5057. publish({"print": {"command": "auto_stop_ams_dry", "sequence_id": "0"}})
  5058. case HMSAction.DISABLE_PURIFICATION:
  5059. publish({"print": {"command": "close_air_filt", "sequence_id": "0"}})
  5060. case (
  5061. HMSAction.CHECK_ASSISTANT
  5062. | HMSAction.JUMP_TO_LIVEVIEW
  5063. | HMSAction.OK_JUMP_RACK
  5064. | HMSAction.REMOVE_CLOSE_BTN
  5065. | HMSAction.LOAD_VIRTUAL_TRAY
  5066. | HMSAction.CANCLE
  5067. | HMSAction.DBL_CHECK_CANCEL
  5068. ):
  5069. # UI-only actions — the printer's own screen handles these; the
  5070. # modal still surfaces them so the user has parity with Studio.
  5071. pass
  5072. case _:
  5073. logger.warning("[%s] Unknown HMS action '%s'", self.serial_number, action)
  5074. return False
  5075. return True