bambu_mqtt.py 265 KB

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