bambu_mqtt.py 264 KB

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