| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449 |
- #!/usr/bin/env python3
- """Shared interface for the two Prod2U products with full SET/GET command generation,
- detailed field decoding, universal frame inspection, and optional serial communication.
- """
- from __future__ import annotations
- from pathlib import Path
- import base64, datetime, json, math, os, queue, re, struct, subprocess, sys, threading, time, zipfile, zlib
- from typing import Any
- ROOT = Path(__file__).resolve().parents[1]
- sys.path.insert(0, str(Path(__file__).resolve().parent / "_vendor"))
- from hth_protocol import (
- FrameType,
- NackReason,
- MotorAction,
- DoneReason,
- Type,
- Status,
- encode_frame,
- decode_frame,
- crc16_ccitt_false,
- PREAMBLE,
- )
- from prod2u_status import state_6400, mrdimm_state, decode_temperature, diagnostic_6400_v2, diagnostic_mrdimm
- try:
- from tools.stream_receiver import StreamReceiver, TransactionTracker, SessionDiskLogger
- except ImportError:
- from stream_receiver import StreamReceiver, TransactionTracker, SessionDiskLogger
- # Optional pyserial for hardware communication
- try:
- import serial
- import serial.tools.list_ports
- HAVE_SERIAL = True
- except ImportError:
- HAVE_SERIAL = False
- ENDPOINTS = {"nothing": 0, "push_down": 1, "push_up": 2, "stop_clear": 255}
- HOST_BAUDRATES = (921600, 460800, 230400, 115200)
- FAN_GROUP_NAMES = {"Front": "新风 / 进风 (Front)", "Rear": "排风 / 出风 (Rear)"}
- PWM_FREQUENCY_HZ = 20
- PWM_PERIOD_MS = 50.0
- SOFTWARE_VERSION = (
- (ROOT / "VERSION").read_text(encoding="utf-8").strip()
- if (ROOT / "VERSION").is_file()
- else "3.3.0"
- )
- FRAME_TYPE_NAMES = {
- 0x01: "SET_ALL (下发全量控制)",
- 0x02: "GET_ALL (查询当前状态)",
- 0x03: "HEARTBEAT (心跳测试 Ping)",
- 0x51: "BEACON (单板自发心跳信标)",
- 0x52: "DIAGNOSTIC (温度采集诊断)",
- 0x81: "SET_ACK (设置确认已应用)",
- 0x82: "GET_ACK (查询确认已受理)",
- 0x83: "HEARTBEAT_ACK (主动心跳应答 Pong)",
- 0x42: "GET_DATA (全量状态数据)",
- 0x50: "MOTOR_DONE (电机动作完成事件)",
- 0xC0: "NACK (请求被拒绝)",
- }
- NACK_REASON_NAMES = {
- 0x01: "UNSUPPORTED (不支持的请求类型)",
- 0x02: "BAD_LENGTH (报文长度不匹配)",
- 0x03: "BAD_VALUE (参数值越界或非法)",
- 0x04: "QUEUE_FULL (电机队列已满)",
- 0x05: "BUSY (单板正忙)",
- }
- DONE_REASON_NAMES = {
- 0x00: "STEPS_DONE (脉冲步数正常发射完成)",
- 0x01: "LOWER_LIMIT (运动触发下限位阻断)",
- 0x02: "UPPER_LIMIT (运动触发上限位阻断)",
- 0x03: "BOTH_LIMITS (双向限位同时异常触发)",
- }
- # The PCB proves Axis0..11 <-> M1..M12. Mechanical front/rear/top roles
- # need a verified harness map and must not be invented by the GUI.
- MRDIMM_AXIS_NAMES = [f"Axis {index} (M{index + 1})" for index in range(12)]
- def parse_hex(text: str) -> bytes:
- value = re.sub(r"[\s:_\-]+", "", text)
- if not value or len(value) % 2 or not re.fullmatch(r"[0-9a-fA-F]+", value):
- raise ValueError("HEX 必须是偶数个十六进制字符(支持空格、冒号、连字符分隔)")
- return bytes.fromhex(value)
- def frame_hex(data: bytes) -> str:
- return data.hex(" ").upper()
- def status_rows(state: dict[str, Any], groups: list[tuple[str, int, int]]) -> tuple[list, list]:
- outputs = []
- temperatures = []
- for group, count, _ in groups:
- name = group.lower()
- duties = state.get(name, [])
- for n in range(count):
- val = duties[n] if n < len(duties) else 0
- outputs.append((f"{group}{n}", val))
- for name in ("bmc", "ct"):
- sensor = state.get(name, {})
- temps = sensor.get("temperature_c", [])
- for n, temp in enumerate(temps):
- condition = "无效" if temp is None else "有效"
- temperatures.append((f"{name.upper()}{n}", "未知" if temp is None else f"{temp} °C", condition))
- return outputs, temperatures
- def integer(value: Any, low: int, high: int, name: str) -> int:
- if isinstance(value, bool) or not isinstance(value, (str, int)):
- raise ValueError(f"{name} 必须是整数")
- try:
- n = int(value, 16 if str(value).lower().startswith("0x") else 10) if isinstance(value, str) else value
- except ValueError:
- raise ValueError(f"{name} 必须是整数")
- if not low <= n <= high:
- raise ValueError(f"{name} 必须在 {low}..{high}")
- return n
- class ZipAsset:
- def __init__(self, data: bytes):
- self._data = data
- def read_text(self, encoding: str = "utf-8") -> str:
- return self._data.decode(encoding)
- def read_bytes(self) -> bytes:
- return self._data
- def is_file(self) -> bool:
- return True
- class Model:
- def __init__(self, product: str):
- if product not in ("6400-front-rear", "mrdimm-chamber", "6400-v2"):
- raise ValueError("未知产品: " + product)
- self.product = product
- self.motor = (product == "mrdimm-chamber")
- self.folder = "mrdimm" if self.motor else ("6400-v2" if product == "6400-v2" else "6400")
- filename = "snapshot-layout.json" if self.motor else "manual-uart-contract.json"
- self.contract = json.loads(self.asset(filename).read_text(encoding="utf-8"))
- self.wire = self.contract["control"]["wire"] if self.motor else self.contract["wire"]
- self.outputs = self.contract["control"]["outputs"] if self.motor else self.contract["outputs"]
- self.board = "FCB V1.2" if self.motor else ("6400V2.0" if product == "6400-v2" else "FCB V1.1")
- try:
- self.metadata = json.loads(self.asset("gui-build-metadata.json").read_text(encoding="utf-8"))
- except (FileNotFoundError, ValueError):
- self.metadata = {
- "product": product,
- "commit": "source preview",
- "bitstream_sha256": None,
- "contract_sha256": self.contract.get("contract_sha256"),
- }
- if self.metadata.get("product") not in (None, product):
- raise ValueError("GUI 产品入口与嵌入构建信息不匹配")
- try:
- source_version = self.asset("VERSION").read_text().strip()
- except FileNotFoundError:
- source_version = "未标记"
- self.release_version = self.metadata.get("release_version", source_version)
- # The receipt describes the flashed BIT's build rate; the combo changes
- # only the PC UART and must match the selected firmware variant.
- self.host_baud = int(self.metadata.get("host_baud", 921600))
- if self.host_baud not in HOST_BAUDRATES:
- raise ValueError("构建信息中的 Host 波特率不受支持")
- def output_label(self, group: str, index: int) -> str:
- if self.product == "6400-v2" and group == "SSR":
- return ("SSR1 腔体1", "SSR2 腔体2+3 共用", "SSR4 腔体4")[index]
- if self.product == "6400-v2" and group in FAN_GROUP_NAMES:
- role = "新风/进风" if group == "Front" else "排风/出风"
- return f"腔室{index + 1} {role} ({group}{index})"
- return f"{group}{index}"
- def group_label(self, group: str) -> str:
- if self.product == "6400-v2":
- if group == "SSR":
- return "加热布 SSR(20 Hz,50 ms 周期,0..100%,SSR2 由腔体2+3共用)"
- return FAN_GROUP_NAMES.get(group, group)
- return group
- def asset(self, name: str) -> Any:
- if hasattr(sys, "_MEIPASS"):
- for root in (Path(sys._MEIPASS), Path(sys._MEIPASS) / "generated" / self.folder):
- if (root / name).is_file():
- return root / name
- for parent in Path(__file__).resolve().parents:
- if parent.is_file() and zipfile.is_zipfile(parent):
- with zipfile.ZipFile(parent) as z:
- preferred = f"generated/{self.folder}/{name}"
- for member in (preferred, name):
- if member in z.namelist():
- return ZipAsset(z.read(member))
- roots = [ROOT / "generated" / self.folder, ROOT / "contracts", ROOT / "tools", ROOT]
- for root in roots:
- if (root / name).is_file():
- return root / name
- raise FileNotFoundError(f"GUI asset missing: {name}")
- def groups(self) -> list[tuple[str, int, int]]:
- if self.motor:
- return [("FAN", 4, 20), ("PTC", 4, 0)]
- return [
- ("PTC", self.outputs["ptc_count"], self.outputs["default_ptc_percent"]),
- ("Front", self.outputs["front_fan_count"], self.outputs["default_front_percent"]),
- ("Rear", self.outputs["rear_fan_count"], self.outputs["default_rear_percent"]),
- ] + ([("SSR", self.outputs["ssr_count"], self.outputs["default_ssr_percent"])]
- if self.product == "6400-v2" else [])
- def set_all(
- self,
- values: list[Any],
- motor_slots: list[dict[str, Any]] | None = None,
- buzzer: int | bool = 0,
- ) -> bytes:
- expected_duties = sum(n for _, n, _ in self.groups())
- if len(values) != expected_duties:
- raise ValueError(f"需要 {expected_duties} 个输出值")
- duty_bytes = bytes(integer(v, 0, 100, "占空比") for v in values)
- buzzer_val = 1 if buzzer is True else (0 if buzzer is False else integer(buzzer, 0, 1, "蜂鸣器控制"))
- if not self.motor:
- if self.product == "6400-v2":
- return encode_frame(FrameType.SET_ALL, duty_bytes + bytes((buzzer_val,)))
- return encode_frame(FrameType.SET_ALL, duty_bytes)
- # MRDIMM v3.1.0: 4 FAN + 4 PTC + 12 axis slots (5 bytes each) + 1 buzzer byte = 69 bytes
- slots_payload = bytearray(60)
- if motor_slots:
- if len(motor_slots) > 12:
- raise ValueError("最多 12 个电机轴")
- for i, slot in enumerate(motor_slots):
- action = integer(slot.get("action", 0), 0, 255, f"轴{i}动作")
- steps = integer(slot.get("steps", 0), 0, 65535, f"轴{i}步数")
- half = integer(slot.get("half_period_us", 0), 0, 65535, f"轴{i}半周期")
- if action in (1, 2) and (steps == 0 or half == 0):
- raise ValueError(f"轴{i} PUSH 步数与半周期不能为0")
- slots_payload[i * 5] = action
- slots_payload[i * 5 + 1 : i * 5 + 3] = steps.to_bytes(2, "little")
- slots_payload[i * 5 + 3 : i * 5 + 5] = half.to_bytes(2, "little")
- return encode_frame(FrameType.SET_ALL, duty_bytes + bytes(slots_payload) + bytes((buzzer_val,)))
- def heartbeat(self, nonce: bytes | None = None) -> bytes:
- """Generate HEARTBEAT request frame. If nonce provided, payload is 4-byte nonce."""
- if nonce is not None:
- return encode_frame(FrameType.HEARTBEAT, nonce)
- return encode_frame(FrameType.HEARTBEAT)
- def get_all(self) -> bytes:
- """Generate golden GET_ALL request frame (A5 5A 02 00 6D 7B)."""
- return encode_frame(FrameType.GET_ALL)
- def checked_request(self, frame: bytes) -> Any:
- parsed = decode_frame(frame)
- if not parsed.crc_ok:
- raise ValueError("CRC 校验失败")
- allowed = {FrameType.SET_ALL, FrameType.GET_ALL, FrameType.HEARTBEAT}
- if parsed.frame_type not in allowed:
- raise ValueError("此产品不支持该请求类型;响应请在状态页解析")
- if parsed.frame_type == FrameType.SET_ALL:
- if self.motor:
- valid_lens = (68, 69)
- elif self.product == "6400-v2":
- valid_lens = (35, 36)
- else:
- valid_lens = (sum(count for _, count, _ in self.groups()),)
- if len(parsed.payload) not in valid_lens:
- raise ValueError(f"此产品 SET_ALL 载荷必须为 {valid_lens} 字节;请使用匹配版本的 GUI 和固件")
- return parsed
- def state(self, payload: bytes) -> dict[str, Any]:
- if self.motor:
- return mrdimm_state(payload, self.contract)
- valid_lens = (86, 88, 90) if self.product == "6400-v2" else (83,)
- if len(payload) not in valid_lens:
- raise ValueError(f"{self.product} GET_DATA 载荷必须为 {valid_lens} 字节;请使用匹配版本的 GUI 和固件")
- return state_6400(payload, self.contract)
- def parse(self, data: bytes, raw_status: bool = False) -> list[dict[str, Any]]:
- if raw_status:
- return [{"kind": "status", "state": self.state(data)}]
- result = []
- offset = 0
- while offset < len(data):
- if data[offset : offset + 2] != PREAMBLE:
- raise ValueError("报文头不完整或未找到 A5 5A 同步头")
- if len(data) - offset < 6:
- raise ValueError("报文长度不足最小帧长 (6 字节)")
- frame_type = data[offset + 2]
- declared_len = data[offset + 3]
- frame_len = declared_len + 6
- if offset + frame_len > len(data):
- raise ValueError(f"报文数据不完整: 声明载荷 {declared_len} 字节,总长需 {frame_len} 字节,剩余 {len(data) - offset} 字节")
- frame_bytes = data[offset : offset + frame_len]
- frame = decode_frame(frame_bytes)
- offset += frame_len
- if not frame.crc_ok:
- raise ValueError("CRC 校验失败")
- kind = frame.frame_type
- p = frame.payload
- if kind == FrameType.GET_DATA:
- result.append({"kind": "status", "state": self.state(p)})
- elif kind == FrameType.DIAGNOSTIC and self.product == "6400-v2":
- result.append({"kind": "diagnostic", "diagnostic": diagnostic_6400_v2(p)})
- elif kind == FrameType.DIAGNOSTIC and self.motor:
- result.append({"kind": "diagnostic", "diagnostic": diagnostic_mrdimm(p)})
- elif kind == FrameType.SET_ACK:
- result.append({"kind": "ack", "type": "SET_ACK"})
- elif kind == FrameType.GET_ACK:
- result.append({"kind": "ack", "type": "GET_ACK"})
- elif kind == FrameType.HEARTBEAT_ACK:
- result.append({"kind": "ack", "type": "HEARTBEAT_ACK"})
- elif kind == FrameType.MOTOR_DONE:
- if len(p) != 4:
- raise ValueError("MOTOR_DONE 长度必须为 4 字节")
- axis = p[0]
- reason = p[1]
- steps = int.from_bytes(p[2:4], "little")
- reason_name = DoneReason(reason).name if reason in DoneReason._value2member_map_ else str(reason)
- result.append({"kind": "done", "axis": axis, "reason": reason_name, "steps_done": steps})
- elif kind == FrameType.NACK:
- if len(p) != 2:
- raise ValueError("NACK 长度必须为 2 字节")
- req = p[0]
- reason = p[1]
- reason_name = NackReason(reason).name if reason in NackReason._value2member_map_ else str(reason)
- result.append({"kind": "nack", "request_type": req, "reason": reason_name})
- else:
- result.append({"kind": "frame", "type": kind, "payload_hex": frame_hex(p)})
- if not result:
- raise ValueError("未提供报文")
- return result
- def explain(self, frame_bytes: bytes) -> dict[str, Any]:
- """Provide detailed, human-readable breakdown of any valid or partial frame."""
- if len(frame_bytes) < 6:
- raise ValueError("报文长度不足 6 字节最小帧长")
- if frame_bytes[:2] != PREAMBLE:
- raise ValueError("帧同步头必须为 A5 5A")
- ftype = frame_bytes[2]
- length = frame_bytes[3]
- if len(frame_bytes) < length + 6:
- raise ValueError(f"帧数据不完整: 声明载荷 {length} 字节,实际仅有 {len(frame_bytes) - 6} 字节")
- payload = frame_bytes[4 : 4 + length]
- crc_actual = int.from_bytes(frame_bytes[4 + length : 6 + length], "little")
- crc_calc = crc16_ccitt_false(frame_bytes[2 : 4 + length])
- crc_ok = (crc_actual == crc_calc)
- type_name = FRAME_TYPE_NAMES.get(ftype, f"未知类型 0x{ftype:02X}")
- explanation: dict[str, Any] = {
- "hex": frame_hex(frame_bytes[: 6 + length]),
- "preamble": "A5 5A (同步头)",
- "type": f"0x{ftype:02X} - {type_name}",
- "length": f"{length} 字节 (0x{length:02X})",
- "crc_hex": f"0x{frame_bytes[4+length]:02X} 0x{frame_bytes[5+length]:02X} (低字节在先)",
- "crc_ok": crc_ok,
- "crc_status": "PASS" if crc_ok else f"FAIL (计算值=0x{crc_calc:04X}, 报文值=0x{crc_actual:04X})",
- }
- # Detailed breakdown per frame type
- fields = []
- if ftype == 0x01: # SET_ALL
- explanation["summary"] = "上位机向单板下发全量输出/电机配置,成功后单板回复 SET_ACK (0x81) 并重载 30s 看门狗"
- if not self.motor:
- expected = sum(count for _, count, _ in self.groups())
- valid_lens = (expected, expected + 1) if self.product == "6400-v2" else (expected,)
- if length in valid_lens:
- offset = 0
- for group, count, _ in self.groups():
- for index in range(count):
- fields.append(f"{self.output_label(group, index)}: {payload[offset + index]} %")
- offset += count
- if self.product == "6400-v2":
- buz = payload[35] if length == 36 else 0
- fields.append(f"蜂鸣器 (CON146.1/H6): {'开启 (1)' if buz else '关闭 (0)'}")
- else:
- fields.append(f"警告: {self.product} SET_ALL 载荷长度应为 {valid_lens} 字节,当前为 {length} 字节")
- else:
- # MRDIMM: 69 bytes (or legacy 68): 4 FAN + 4 PTC + 12 axis slots [+ buzzer]
- if length in (68, 69):
- for i in range(4):
- fields.append(f"FAN{i}: {payload[i]} %")
- for i in range(4):
- fields.append(f"PTC{i}: {payload[4+i]} %")
- for i in range(12):
- act = payload[8 + i * 5]
- act_str = {0: "NOTHING", 1: "PUSH_DOWN", 2: "PUSH_UP", 255: "STOP_CLEAR"}.get(act, f"0x{act:02X}")
- st = int.from_bytes(payload[9 + i * 5 : 11 + i * 5], "little")
- hp = int.from_bytes(payload[11 + i * 5 : 13 + i * 5], "little")
- speed = f"{500000 / hp:.1f} Hz" if hp > 0 else "N/A"
- ax_name = MRDIMM_AXIS_NAMES[i] if i < len(MRDIMM_AXIS_NAMES) else f"Axis{i}"
- fields.append(f"{ax_name}: 动作={act_str}, 步数={st}, 半周期={hp} us (频率={speed})")
- buz = payload[68] if length == 69 else 0
- fields.append(f"蜂鸣器 (CON146.1/H6): {'开启 (1)' if buz else '关闭 (0)'}")
- else:
- fields.append(f"警告: MRDIMM SET_ALL 载荷长度应为 68 或 69 字节,当前为 {length} 字节")
- elif ftype == 0x02: # GET_ALL
- explanation["summary"] = "上位机向单板查询当前全量状态与温度;单板先回复 GET_ACK (0x82),紧接着回复 GET_DATA (0x42)"
- fields.append("无载荷 (0 字节)")
- elif ftype == 0x03: # HEARTBEAT
- explanation["summary"] = "上位机向单板发送独立心跳检测请求 (PING),单板立即应答 0x83 并重载看门狗"
- if len(payload) == 4:
- fields.append(f"Nonce 随机验证码: 0x{payload.hex().upper()} (4 字节)")
- else:
- fields.append("零载荷心跳探测帧 (0 字节)")
- elif ftype == 0x51: # BEACON
- explanation["summary"] = "MRDIMM 周期性自发信标 (BEACON 0x51);证明板端发送可达,不喂看门狗,不占用事务请求槽"
- fields.append("零载荷自发信标帧 (0 字节)")
- elif ftype == 0x52 and self.product == "6400-v2":
- diagnostic = diagnostic_6400_v2(payload)
- explanation["summary"] = diagnostic_summary(diagnostic)
- fields.extend(f"{key}: {value}" for key, value in diagnostic.items())
- elif ftype == 0x52 and self.motor:
- diagnostic = diagnostic_mrdimm(payload)
- explanation["summary"] = diagnostic_summary(diagnostic)
- fields.extend(f"{key}: {value}" for key, value in diagnostic.items())
- elif ftype == 0x81: # SET_ACK
- explanation["summary"] = "单板确认已应用 SET_ALL 配置;30 秒硬件看门狗已成功重载"
- fields.append("无载荷 (0 字节)")
- elif ftype == 0x82: # GET_ACK
- explanation["summary"] = "单板确认已受理 GET_ALL 查询请求,随后立即发送 GET_DATA"
- fields.append("无载荷 (0 字节)")
- elif ftype == 0x83: # HEARTBEAT_ACK
- explanation["summary"] = "单板回复主动心跳应答 (PONG 0x83),重载看门狗"
- if len(payload) == 4:
- fields.append(f"Nonce 验证码回显: 0x{payload.hex().upper()} (4 字节)")
- else:
- fields.append("零载荷心跳确认帧 (0 字节)")
- elif ftype == 0x42: # GET_DATA
- explanation["summary"] = "全量状态、温度与限位;0x42 可为自动遥测,仅 GET_ACK 后的数据完成当前查询"
- state = self.state(payload)
- if not self.motor:
- ptc_duties = state.get("ptc", [])
- fields.append(f"PTC 生效占空比 (共 24 路):")
- for chunk_idx in range(0, len(ptc_duties), 8):
- chunk = ptc_duties[chunk_idx : chunk_idx + 8]
- chunk_str = " | ".join(f"PTC{chunk_idx+j:02d}: {val}%" for j, val in enumerate(chunk))
- fields.append(f" {chunk_str}")
- for group in ("Front", "Rear", "SSR"):
- for index, value in enumerate(state.get(group.lower(), [])):
- fields.append(f"{self.output_label(group, index)}: {value}%")
- if self.product == "6400-v2":
- fields.append(f"急停按钮 EPB1 (CON165.10/F8): {'按下 (高电平=1)' if state.get('estop_btn') else '未按下/默认 (低电平=0)'}")
- fields.append(f"开罩按钮 SB1 (CON165.9/C11): {'按下 (高电平=1)' if state.get('hood_open_btn') else '未按下/默认 (低电平=0)'}")
- fields.append(f"合罩按钮 SB2 (CON165.8/A11): {'按下 (高电平=1)' if state.get('hood_close_btn') else '未按下/默认 (低电平=0)'}")
- fields.append(f"蜂鸣器状态 (CON146.1/H6, 4000Hz 80%): {'开启 (1)' if state.get('buzzer') else '关闭 (0)'}")
- else:
- fields.append(f"FAN 生效占空比 (4路): {state.get('fan', [])}")
- fields.append(f"PTC 生效占空比 (4路): {state.get('ptc', [])}")
- fields.append(f"下限位掩码 (Lower Limit): 0x{state.get('lower_limit_mask', 0):04X}")
- fields.append(f"上限位掩码 (Upper Limit): 0x{state.get('upper_limit_mask', 0):04X}")
- fields.append(f"高温罩开关 (CON140.3/L3): {'按下 (高电平=1)' if state.get('hood_switch') else '未按下/默认 (低电平=0)'}")
- fields.append(f"蜂鸣器状态 (CON146.1/H6, 4000Hz 80%): {'开启 (1)' if state.get('buzzer') else '关闭 (0)'}")
- bmc_temps = state.get("bmc", {}).get("temperature_c", [])
- ct_temps = state.get("ct", {}).get("temperature_c", [])
- fields.append(f"BMC 24通道温度 (°C): {[f'{t}°C' if t is not None else '--(无效/未采样)' for t in bmc_temps]}")
- fields.append(f"CT7428 27通道温度 (°C): {[f'{t}°C' if t is not None else '--(无效/未采样)' for t in ct_temps]}")
- elif ftype == 0x50: # MOTOR_DONE
- axis = payload[0] if len(payload) > 0 else 0
- reason = payload[1] if len(payload) > 1 else 0
- steps = int.from_bytes(payload[2:4], "little") if len(payload) >= 4 else 0
- r_name = DONE_REASON_NAMES.get(reason, f"未知 0x{reason:02X}")
- ax_label = MRDIMM_AXIS_NAMES[axis] if axis < len(MRDIMM_AXIS_NAMES) else f"Axis{axis}"
- explanation["summary"] = f"MRDIMM 电机 {ax_label} 运动段结束事件: {r_name},实际输出 {steps} 步"
- fields.append(f"轴号: {ax_label}")
- fields.append(f"完成原因: 0x{reason:02X} - {r_name}")
- fields.append(f"实际发射脉冲步数: {steps}")
- elif ftype == 0xC0: # NACK
- req = payload[0] if len(payload) > 0 else 0
- reason = payload[1] if len(payload) > 1 else 0
- req_name = FRAME_TYPE_NAMES.get(req, f"0x{req:02X}")
- r_name = NACK_REASON_NAMES.get(reason, f"0x{reason:02X}")
- explanation["summary"] = f"请求被单板拒绝 (NACK)!原请求: {req_name},拒绝原因: {r_name}"
- fields.append(f"原请求类型: 0x{req:02X} ({req_name})")
- fields.append(f"拒绝原因码: 0x{reason:02X} ({r_name})")
- explanation["fields"] = fields
- return explanation
- def diagnostic_summary(d: dict[str, Any]) -> str:
- if not d["supported"]:
- return f"未支持的诊断格式/板型: {d['format']}/{d['board_id']:02X};原始帧已保留"
- if d.get("format") == 2:
- axes = d.get("active_axes", [])
- axes_str = ",".join(f"M{i+1}" for i in axes) if axes else "全部空闲"
- flags = "/".join(name for name, active in (
- ("看门狗超时", d.get("watchdog_expired")),
- ("蜂鸣器开启", d.get("buzzer_on")),
- ) if active) or "无"
- return (f"MRDIMM 固件 {d['firmware_version']} | 输出有效={int(bool(d.get('duty_bank_valid')))} | "
- f"运行中电机: {axes_str} (0x{d.get('motor_active_mask', 0):03X}) | 标志: {flags}")
- seen = "已完成采样" if d["sample_seen"] else "尚无采样完成"
- valid = int(d["valid_temperature_mask"]).bit_count()
- flags = "/".join(name for name, active in (
- ("BMC失败", d["bmc_failed"]), ("BMC帧错", d["bmc_framing_error_seen"]),
- ("温度队列溢出", d["temperature_queue_overflow"]),
- ("看门狗超时", d["watchdog_expired"]),
- ("蜂鸣器开启", d.get("buzzer_on", False))) if active) or "无"
- sample = (f"温度 {d['temperature_c']} °C" if d["is_temperature"] else "状态寄存器(非温度)")
- return (f"固件 {d['firmware_version']} | CT {seen},读数可解码 {valid}/9,轮次 {d['scan_round']} | "
- f"SCL/SDA={int(d['scl_high'])}/{int(d['sda_high'])},忙={int(d['i2c_busy'])}\n"
- f"通道 {d['last_channel']},地址 0x{d['device_address']:02X},寄存器 0x{d['register']:02X},"
- f"结果 {d['error_name']},原始值 0x{d['raw_temperature']:04X},{sample}\n"
- f"BMC有效 {d['bmc_valid_count']}/24 | 历次结果掩码 0x{d['observed_result_mask']:02X} | 标志: {flags}")
- # ---------------------------------------------------------------------------
- # Configurable Chamber Mapping & Temperature Curve / Image Engine
- # ---------------------------------------------------------------------------
- CHAMBER_IDS = (1, 2, 3, 4)
- DEFAULT_CHAMBER_MAPPING: dict[int, dict[str, Any]] = {
- 1: {"name": "腔体 1", "bmc": [0, 1, 2, 3, 4, 5], "ct": [1, 2]},
- 2: {"name": "腔体 2", "bmc": [6, 7, 8, 9, 10, 11], "ct": [3, 4]},
- 3: {"name": "腔体 3", "bmc": [12, 13, 14, 15, 16, 17], "ct": [5, 6]},
- 4: {"name": "腔体 4", "bmc": [18, 19, 20, 21, 22, 23], "ct": [7, 8]},
- }
- CT_CHANNEL_HINTS: dict[int, str] = {
- 0: "U6本地",
- 1: "CON53/腔1进",
- 2: "CON55/腔1出",
- 3: "CON56/腔2进",
- 4: "CON57/腔2出",
- 5: "CON79/腔3进",
- 6: "CON80/腔3出",
- 7: "CON81/腔4进",
- 8: "CON82/腔4出",
- 9: "U24本地",
- 18: "U25本地",
- }
- BMC_CHANNEL_HINTS: dict[int, str] = {
- i: f"CPU{i // 12}_DIMM{i % 12}" for i in range(24)
- }
- # Distinct palettes for Memory (BMC) and Sensor (CT) curves
- BMC_CURVE_COLORS = (
- "#1976D2", "#0288D1", "#0097A7", "#5C6BC0", "#7B1FA2", "#3949AB",
- "#1E88E5", "#00ACC1", "#8E24AA", "#5E35B1", "#039BE5", "#303F9F",
- )
- BMC_AVG_COLOR = "#0D47A1"
- BMC_MAX_COLOR = "#6A1B9A"
- CT_CURVE_COLORS = (
- "#D32F2F", "#E65100", "#2E7D32", "#C2185B", "#F57C00", "#388E3C",
- "#B71C1C", "#BF360C", "#1B5E20",
- )
- CT_AVG_COLOR = "#B71C1C"
- def ct_channel_label(index: int, short: bool = False) -> str:
- hint = CT_CHANNEL_HINTS.get(index)
- if not hint:
- return f"CT{index}"
- if short:
- short_hint = hint.split("/")[-1]
- return f"CT{index}({short_hint})"
- return f"CT{index}({hint})"
- def bmc_channel_label(index: int, short: bool = True) -> str:
- if short:
- return f"BMC{index}"
- hint = BMC_CHANNEL_HINTS.get(index, "")
- return f"BMC{index}({hint})" if hint else f"BMC{index}"
- def parse_channel_spec(spec: Any, max_index: int, label: str = "通道") -> list[int]:
- """Parse flexible channel expressions like '0-5', '1,2', 'BMC0..BMC5', 'CT1,CT2' or list[int]."""
- if spec is None:
- return []
- if isinstance(spec, (list, tuple)):
- raw_items = list(spec)
- result: list[int] = []
- seen: set[int] = set()
- for item in raw_items:
- idx = integer(item, 0, max_index, label)
- if idx not in seen:
- seen.add(idx)
- result.append(idx)
- return result
- if not isinstance(spec, str):
- raise ValueError(f"{label} 配置格式无效")
- cleaned = spec.strip()
- if not cleaned or cleaned.lower() in ("none", "null", "无", "-"):
- return []
- # Normalize prefixes and separators
- cleaned = re.sub(r"(?i)\b(bmc|ct|ch|sensor|mem)", "", cleaned)
- cleaned = cleaned.replace("..", "-").replace("~", "-").replace("~", "-").replace("—", "-")
- tokens = [t.strip() for t in re.split(r"[,;,;\s/]+", cleaned) if t.strip()]
- result = []
- seen = set()
- for tok in tokens:
- if "-" in tok:
- parts = [p.strip() for p in tok.split("-") if p.strip()]
- if len(parts) != 2:
- raise ValueError(f"{label} 范围表达式无效: '{tok}'")
- start = integer(parts[0], 0, max_index, label)
- end = integer(parts[1], 0, max_index, label)
- step = 1 if end >= start else -1
- for idx in range(start, end + step, step):
- if idx not in seen:
- seen.add(idx)
- result.append(idx)
- else:
- idx = integer(tok, 0, max_index, label)
- if idx not in seen:
- seen.add(idx)
- result.append(idx)
- return result
- def format_channel_spec(channels: list[int]) -> str:
- """Format a channel list into compact string form (e.g., [0,1,2,3,4,5] -> '0-5', [1,2] -> '1,2')."""
- if not channels:
- return ""
- parts: list[str] = []
- i = 0
- n = len(channels)
- while i < n:
- j = i
- while j + 1 < n and channels[j + 1] == channels[j] + 1:
- j += 1
- if j - i >= 2:
- parts.append(f"{channels[i]}-{channels[j]}")
- elif j - i == 1:
- parts.append(f"{channels[i]},{channels[j]}")
- else:
- parts.append(str(channels[i]))
- i = j + 1
- return ",".join(parts)
- class ChamberMappingConfig:
- """Manages per-chamber Memory (BMC 0..23) and Sensor (CT 0..26) channel mapping with defaults and persistence."""
- def __init__(self, product: str = "6400-v2", chambers: dict[int, dict[str, Any]] | None = None):
- self.product = product
- self.chambers: dict[int, dict[str, Any]] = {}
- base = DEFAULT_CHAMBER_MAPPING
- for cid in CHAMBER_IDS:
- src = (chambers or {}).get(cid) or (chambers or {}).get(str(cid)) or base[cid]
- name = str(src.get("name", base[cid]["name"])).strip() or base[cid]["name"]
- bmc_list = parse_channel_spec(src.get("bmc", base[cid]["bmc"]), 23, f"腔体{cid} 内存(BMC)通道")
- ct_list = parse_channel_spec(src.get("ct", base[cid]["ct"]), 26, f"腔体{cid} Sensor(CT)通道")
- self.chambers[cid] = {"name": name, "bmc": bmc_list, "ct": ct_list}
- @classmethod
- def default(cls, product: str = "6400-v2") -> "ChamberMappingConfig":
- return cls(product=product)
- def reset_to_default(self) -> None:
- for cid in CHAMBER_IDS:
- base = DEFAULT_CHAMBER_MAPPING[cid]
- self.chambers[cid] = {
- "name": base["name"],
- "bmc": list(base["bmc"]),
- "ct": list(base["ct"]),
- }
- def set_chamber(self, chamber_id: int, bmc_spec: Any, ct_spec: Any, name: str | None = None) -> None:
- if chamber_id not in CHAMBER_IDS:
- raise ValueError(f"腔体编号必须为 1..4,当前为 {chamber_id}")
- bmc_list = parse_channel_spec(bmc_spec, 23, f"腔体{chamber_id} 内存(BMC)通道")
- ct_list = parse_channel_spec(ct_spec, 26, f"腔体{chamber_id} Sensor(CT)通道")
- cur_name = (name.strip() if isinstance(name, str) and name.strip() else self.chambers[chamber_id]["name"])
- self.chambers[chamber_id] = {"name": cur_name, "bmc": bmc_list, "ct": ct_list}
- def swap_pairs(self, *, swap_bmc: bool = False, swap_ct: bool = True) -> None:
- """Swap Chamber 1<->3 and Chamber 2<->4 channel mappings for field harness pair matching."""
- for a, b in ((1, 3), (2, 4)):
- if swap_bmc:
- self.chambers[a]["bmc"], self.chambers[b]["bmc"] = (
- list(self.chambers[b]["bmc"]),
- list(self.chambers[a]["bmc"]),
- )
- if swap_ct:
- self.chambers[a]["ct"], self.chambers[b]["ct"] = (
- list(self.chambers[b]["ct"]),
- list(self.chambers[a]["ct"]),
- )
- def to_dict(self) -> dict[str, Any]:
- return {
- "schema": "prod2u-chamber-mapping-v1",
- "product": self.product,
- "chambers": {
- str(cid): {
- "name": self.chambers[cid]["name"],
- "bmc": list(self.chambers[cid]["bmc"]),
- "bmc_spec": format_channel_spec(self.chambers[cid]["bmc"]),
- "ct": list(self.chambers[cid]["ct"]),
- "ct_spec": format_channel_spec(self.chambers[cid]["ct"]),
- }
- for cid in CHAMBER_IDS
- },
- }
- @classmethod
- def from_dict(cls, data: dict[str, Any], product: str | None = None) -> "ChamberMappingConfig":
- if not isinstance(data, dict):
- raise ValueError("映射配置必须为 JSON 对象")
- prod = product or data.get("product", "6400-v2")
- raw_chambers = data.get("chambers", data)
- if not isinstance(raw_chambers, dict):
- raise ValueError("映射配置缺少 chambers 字段")
- return cls(product=prod, chambers=raw_chambers)
- def save(self, path: Path) -> Path:
- target = Path(path)
- target.parent.mkdir(parents=True, exist_ok=True)
- target.write_text(json.dumps(self.to_dict(), ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- return target
- @classmethod
- def load(cls, path: Path, product: str | None = None) -> "ChamberMappingConfig":
- data = json.loads(Path(path).read_text(encoding="utf-8"))
- return cls.from_dict(data, product=product)
- @staticmethod
- def default_config_path(product: str) -> Path:
- base_dir = Path(os.environ.get("PROD2U_CONFIG_DIR", Path.home() / ".prod2u"))
- return base_dir / f"chamber_mapping_{product}.json"
- def extract_chamber_temperatures(
- self,
- state: dict[str, Any],
- chamber_id: int,
- *,
- ignore_zero_ct: bool = False,
- ) -> dict[str, Any]:
- if chamber_id not in CHAMBER_IDS:
- raise ValueError(f"无效腔体编号: {chamber_id}")
- cfg = self.chambers[chamber_id]
- bmc_all = state.get("bmc", {}).get("temperature_c", [])
- ct_all = state.get("ct", {}).get("temperature_c", [])
- bmc_items: list[tuple[int, str, int | None]] = []
- bmc_valid: list[int] = []
- for idx in cfg["bmc"]:
- val = bmc_all[idx] if idx < len(bmc_all) else None
- if val is not None and not (0 <= val <= 254):
- val = None
- bmc_items.append((idx, bmc_channel_label(idx), val))
- if val is not None:
- bmc_valid.append(int(val))
- ct_items: list[tuple[int, str, int | None]] = []
- ct_valid: list[int] = []
- for idx in cfg["ct"]:
- val = ct_all[idx] if idx < len(ct_all) else None
- if val is not None and not (0 <= val <= 254):
- val = None
- if ignore_zero_ct and val == 0:
- val = None
- ct_items.append((idx, ct_channel_label(idx, short=True), val))
- if val is not None:
- ct_valid.append(int(val))
- return {
- "chamber_id": chamber_id,
- "name": cfg["name"],
- "bmc_channels": list(cfg["bmc"]),
- "ct_channels": list(cfg["ct"]),
- "bmc_items": bmc_items,
- "ct_items": ct_items,
- "bmc_valid": bmc_valid,
- "ct_valid": ct_valid,
- "bmc_avg": (sum(bmc_valid) / len(bmc_valid)) if bmc_valid else None,
- "bmc_min": min(bmc_valid) if bmc_valid else None,
- "bmc_max": max(bmc_valid) if bmc_valid else None,
- "ct_avg": (sum(ct_valid) / len(ct_valid)) if ct_valid else None,
- "ct_min": min(ct_valid) if ct_valid else None,
- "ct_max": max(ct_valid) if ct_valid else None,
- }
- def format_realtime_summary(self, state: dict[str, Any], *, ignore_zero_ct: bool = False) -> str:
- parts = []
- for cid in CHAMBER_IDS:
- info = self.extract_chamber_temperatures(state, cid, ignore_zero_ct=ignore_zero_ct)
- if info["bmc_avg"] is not None:
- bmc_str = f"内存均{info['bmc_avg']:.1f}°C({info['bmc_min']}~{info['bmc_max']}°C)"
- else:
- bmc_str = "内存:--"
- ct_parts = [f"CT{idx}={val}°C" if val is not None else f"CT{idx}=--"
- for idx, _, val in info["ct_items"]]
- ct_str = "/".join(ct_parts) if ct_parts else "Sensor:未映射"
- parts.append(f"腔{cid}[{bmc_str} | {ct_str}]")
- return " ".join(parts)
- class TemperatureCurveStore:
- """Stores raw 24-BMC + 27-CT time-series samples so chamber mapping changes re-project history dynamically."""
- def __init__(self, max_capacity: int = 7200):
- self.max_capacity = max_capacity
- self.samples: list[dict[str, Any]] = []
- self._lock = threading.Lock()
- def clear(self) -> None:
- with self._lock:
- self.samples.clear()
- def __len__(self) -> int:
- with self._lock:
- return len(self.samples)
- @staticmethod
- def _normalize_temp_list(values: list[Any], count: int) -> list[int | None]:
- out: list[int | None] = []
- for i in range(count):
- if i < len(values):
- v = values[i]
- if v is None or v == 255 or isinstance(v, bool):
- out.append(None)
- else:
- try:
- iv = int(v)
- out.append(iv if 0 <= iv <= 254 else None)
- except (ValueError, TypeError):
- out.append(None)
- else:
- out.append(None)
- return out
- def record_raw_arrays(
- self,
- bmc: list[Any],
- ct: list[Any],
- *,
- timestamp: float | None = None,
- time_label: str | None = None,
- source: str = "GET_DATA",
- ) -> dict[str, Any]:
- ts = time.time() if timestamp is None else float(timestamp)
- t_lbl = time_label or datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S")
- sample = {
- "timestamp": ts,
- "time_label": t_lbl,
- "bmc": self._normalize_temp_list(bmc, 24),
- "ct": self._normalize_temp_list(ct, 27),
- "source": source,
- }
- with self._lock:
- self.samples.append(sample)
- if len(self.samples) > self.max_capacity:
- del self.samples[: len(self.samples) - self.max_capacity]
- return sample
- def record_state(
- self,
- state: dict[str, Any],
- *,
- timestamp: float | None = None,
- time_label: str | None = None,
- source: str = "GET_DATA",
- ) -> dict[str, Any]:
- bmc = state.get("bmc", {}).get("temperature_c", [])
- ct = state.get("ct", {}).get("temperature_c", [])
- return self.record_raw_arrays(bmc, ct, timestamp=timestamp, time_label=time_label, source=source)
- def snapshot(self, max_points: int = 0) -> list[dict[str, Any]]:
- with self._lock:
- if max_points and max_points > 0:
- return list(self.samples[-max_points:])
- return list(self.samples)
- def chamber_series(
- self,
- mapping: ChamberMappingConfig,
- chamber_id: int,
- *,
- max_points: int = 0,
- ignore_zero_ct: bool = False,
- ) -> dict[str, Any]:
- if chamber_id not in CHAMBER_IDS:
- raise ValueError(f"无效腔体编号: {chamber_id}")
- cfg = mapping.chambers[chamber_id]
- pts = self.snapshot(max_points=max_points)
- t0 = pts[0]["timestamp"] if pts else 0.0
- elapsed = [round(p["timestamp"] - t0, 2) for p in pts]
- time_labels = [p["time_label"] for p in pts]
- bmc_series: dict[int, list[int | None]] = {ch: [] for ch in cfg["bmc"]}
- ct_series: dict[int, list[int | None]] = {ch: [] for ch in cfg["ct"]}
- bmc_avg: list[float | None] = []
- bmc_max: list[int | None] = []
- bmc_min: list[int | None] = []
- ct_avg: list[float | None] = []
- for p in pts:
- b_vals = []
- for ch in cfg["bmc"]:
- v = p["bmc"][ch] if ch < len(p["bmc"]) else None
- bmc_series[ch].append(v)
- if v is not None:
- b_vals.append(v)
- bmc_avg.append(round(sum(b_vals) / len(b_vals), 2) if b_vals else None)
- bmc_max.append(max(b_vals) if b_vals else None)
- bmc_min.append(min(b_vals) if b_vals else None)
- c_vals = []
- for ch in cfg["ct"]:
- v = p["ct"][ch] if ch < len(p["ct"]) else None
- if ignore_zero_ct and v == 0:
- v = None
- ct_series[ch].append(v)
- if v is not None:
- c_vals.append(v)
- ct_avg.append(round(sum(c_vals) / len(c_vals), 2) if c_vals else None)
- u6_local = [p["ct"][0] if p["ct"] else None for p in pts]
- return {
- "chamber_id": chamber_id,
- "name": cfg["name"],
- "bmc_channels": list(cfg["bmc"]),
- "ct_channels": list(cfg["ct"]),
- "sample_count": len(pts),
- "elapsed": elapsed,
- "time_labels": time_labels,
- "bmc_series": bmc_series,
- "ct_series": ct_series,
- "bmc_avg": bmc_avg,
- "bmc_max": bmc_max,
- "bmc_min": bmc_min,
- "ct_avg": ct_avg,
- "u6_local": u6_local,
- }
- def load_from_log_file(self, path: Path, model: Model | None = None) -> int:
- """Import temperature samples from pwm_scope JSONL logs, GUI session logs, or hex dumps."""
- text = Path(path).read_text(encoding="utf-8", errors="replace")
- imported = 0
- base_ts = time.time()
- for line_idx, raw_line in enumerate(text.splitlines()):
- line = raw_line.strip()
- if not line:
- continue
- # 1. Try JSONL (pwm_scope.py or structured event log)
- if line.startswith("{") and line.endswith("}"):
- try:
- rec = json.loads(line)
- ev = rec.get("event")
- t_str = str(rec.get("time", ""))
- t_lbl = t_str[11:19] if len(t_str) >= 19 and "T" in t_str else f"#{imported + 1}"
- ts = base_ts + float(rec.get("elapsed", imported))
- if ev == "CYCLE" and ("ct" in rec or "bmc" in rec):
- bmc_arr = list(rec.get("bmc", [255] * 24))
- ct_arr = list(rec.get("ct", [])) + list(rec.get("ct_reserved", []))
- self.record_raw_arrays(bmc_arr, ct_arr, timestamp=ts, time_label=t_lbl, source="PWM_SCOPE")
- imported += 1
- continue
- hex_field = rec.get("hex", "")
- if hex_field and rec.get("type") in ("42", 0x42, None):
- raw_bytes = parse_hex(hex_field)
- if len(raw_bytes) >= 6 and raw_bytes[:2] == PREAMBLE and raw_bytes[2] == FrameType.GET_DATA:
- imported += self._import_get_data_frame(raw_bytes, model, ts, t_lbl)
- continue
- except Exception:
- pass
- # 2. Try GUI session log line: [HH:MM:SS.mmm] [RX...] A5 5A 42 ...
- m = re.search(r"\[(\d{2}:\d{2}:\d{2})(?:\.\d+)?\]\s*\[[^\]]+\]\s*([0-9A-Fa-f][0-9A-Fa-f\s]+)", line)
- if m:
- t_lbl = m.group(1)
- hex_part = m.group(2).strip()
- try:
- raw_bytes = parse_hex(hex_part)
- imported += self._import_get_data_stream(raw_bytes, model, base_ts + imported, t_lbl)
- continue
- except Exception:
- pass
- # 3. Raw hex line containing A5 5A 42
- if "A5" in line.upper() and "5A" in line.upper():
- try:
- raw_bytes = parse_hex(line)
- imported += self._import_get_data_stream(raw_bytes, model, base_ts + imported, f"#{imported + 1}")
- except Exception:
- pass
- return imported
- def _import_get_data_frame(self, frame_bytes: bytes, model: Model | None, ts: float, t_lbl: str) -> int:
- f = decode_frame(frame_bytes)
- if not f.crc_ok or f.frame_type != FrameType.GET_DATA:
- return 0
- p = f.payload
- if model is not None:
- try:
- st = model.state(p)
- self.record_state(st, timestamp=ts, time_label=t_lbl, source="LOG_FRAME")
- return 1
- except Exception:
- pass
- # Fallback payload layout detection (86/83 bytes for 6400, 63 bytes for MRDIMM)
- if len(p) in (83, 86):
- self.record_raw_arrays(list(p[32:56]), list(p[56:83]), timestamp=ts, time_label=t_lbl, source="LOG_6400")
- return 1
- if len(p) == 63:
- self.record_raw_arrays(list(p[8:32]), list(p[32:59]), timestamp=ts, time_label=t_lbl, source="LOG_MRDIMM")
- return 1
- return 0
- def _import_get_data_stream(self, data: bytes, model: Model | None, ts: float, t_lbl: str) -> int:
- count = 0
- pos = 0
- while pos + 6 <= len(data):
- idx = data.find(PREAMBLE, pos)
- if idx < 0 or idx + 4 > len(data):
- break
- length = data[idx + 3]
- end = idx + 6 + length
- if end > len(data):
- break
- count += self._import_get_data_frame(data[idx:end], model, ts + count * 0.1, t_lbl)
- pos = end
- return count
- def format_duration_mmss(seconds: float | None) -> str:
- """Format duration in seconds into 'XX.Xs (MM:SS)' or '--' if None."""
- if seconds is None:
- return "--"
- sec = max(0.0, float(seconds))
- mins = int(sec // 60)
- rem = int(round(sec - mins * 60))
- if rem == 60:
- mins += 1
- rem = 0
- return f"{sec:.1f}s ({mins:02d}:{rem:02d})"
- class ThermalTestSession:
- """High-temperature hood 4-chamber thermal test session & reach-time analyzer.
- Supports:
- - Independent expected target temperature per chamber (Chambers 1..4, default 70°C)
- - Overall pass minimum temperature across all 4 chambers of the high-temperature hood (default 70°C)
- - Independent calculation of time-to-target for each chamber's Sensor (CT) temperature and Memory (BMC) temperature
- - Continuous data recording: after any chamber reaches its target temperature first, data recording
- continues uninterrupted for all 4 chambers (tracking post_target_samples, peak temperatures, and full curves)
- - Fan speed & fan intervention timing / reference temperature tracking to analyze heating time relationships
- - Local & remote backend (192.168.2.25) synchronization and JSON/CSV report export
- """
- def __init__(
- self,
- product: str = "6400-v2",
- *,
- test_name: str = "6400V2.0 高温罩四腔升温测试",
- overall_pass_min_temp_c: float = 70.0,
- chamber_target_temp_c: dict[int, float] | None = None,
- bmc_eval_mode: str = "avg",
- ct_eval_mode: str = "avg",
- ptc_duty_percent: int = 100,
- ssr_duty_percent: int = 100,
- initial_fan_duty_percent: int = 0,
- active_fan_duty_percent: int = 50,
- fan_intervention_mode: str = "time_s",
- fan_intervention_time_s: float = 120.0,
- fan_intervention_ref_temp_c: float = 55.0,
- fan_intervention_ref_source: str = "ct",
- backend_url: str = "http://192.168.2.25:8766",
- ):
- self.session_id = datetime.datetime.now().strftime("TT-%Y%m%d-%H%M%S")
- self.product = product
- self.test_name = str(test_name).strip() or "高温罩四腔升温测试"
- self.overall_pass_min_temp_c = float(overall_pass_min_temp_c)
- self.chamber_target_temp_c: dict[int, float] = {}
- for cid in CHAMBER_IDS:
- raw_t = (chamber_target_temp_c or {}).get(cid, (chamber_target_temp_c or {}).get(str(cid), 70.0))
- self.chamber_target_temp_c[cid] = float(raw_t)
- self.bmc_eval_mode = bmc_eval_mode if bmc_eval_mode in ("avg", "max", "min") else "avg"
- self.ct_eval_mode = ct_eval_mode if ct_eval_mode in ("avg", "max", "min") else "avg"
- # Fan & Heating experiment parameters
- self.ptc_duty_percent = max(0, min(100, int(ptc_duty_percent)))
- self.ssr_duty_percent = max(0, min(100, int(ssr_duty_percent)))
- self.initial_fan_duty_percent = max(0, min(100, int(initial_fan_duty_percent)))
- self.active_fan_duty_percent = max(0, min(100, int(active_fan_duty_percent)))
- self.fan_intervention_mode = (
- fan_intervention_mode
- if fan_intervention_mode in ("immediate", "time_s", "ref_temp_c", "manual")
- else "time_s"
- )
- self.fan_intervention_time_s = max(0.0, float(fan_intervention_time_s))
- self.fan_intervention_ref_temp_c = float(fan_intervention_ref_temp_c)
- self.fan_intervention_ref_source = (
- fan_intervention_ref_source if fan_intervention_ref_source in ("ct", "bmc", "any") else "ct"
- )
- self.backend_url = str(backend_url).rstrip("/")
- self.active = False
- self.start_timestamp: float | None = None
- self.stop_timestamp: float | None = None
- self.sample_count = 0
- self.fan_intervened = False
- self.fan_intervened_elapsed_s: float | None = None
- self.fan_intervened_temp_c: float | None = None
- self.fan_intervened_reason: str = ""
- self.current_fan_duty_percent: int = self.initial_fan_duty_percent
- self.chamber_stats: dict[int, dict[str, Any]] = {}
- self.first_reached_chamber_id: int | None = None
- self.first_reached_kind: str | None = None
- self.first_reached_elapsed_s: float | None = None
- self.reset_stats()
- def set_targets(
- self,
- overall_pass_min_temp_c: float,
- chamber_targets: dict[int, float] | None = None,
- ) -> None:
- self.overall_pass_min_temp_c = float(overall_pass_min_temp_c)
- if chamber_targets:
- for cid in CHAMBER_IDS:
- if cid in chamber_targets or str(cid) in chamber_targets:
- val = chamber_targets.get(cid, chamber_targets.get(str(cid)))
- self.chamber_target_temp_c[cid] = float(val)
- for cid in CHAMBER_IDS:
- if cid in self.chamber_stats:
- self.chamber_stats[cid]["target_temp_c"] = self.chamber_target_temp_c[cid]
- self.chamber_stats[cid]["pass_min_temp_c"] = self.overall_pass_min_temp_c
- self.chamber_stats[cid]["effective_target_c"] = max(
- self.chamber_target_temp_c[cid], self.overall_pass_min_temp_c
- )
- def reset_stats(self) -> None:
- self.sample_count = 0
- self.first_reached_chamber_id = None
- self.first_reached_kind = None
- self.first_reached_elapsed_s = None
- self.fan_intervened = (self.fan_intervention_mode == "immediate")
- self.fan_intervened_elapsed_s = 0.0 if self.fan_intervened else None
- self.fan_intervened_temp_c = None
- self.fan_intervened_reason = "0s 立即介入" if self.fan_intervened else ""
- self.current_fan_duty_percent = (
- self.active_fan_duty_percent if self.fan_intervened else self.initial_fan_duty_percent
- )
- self.chamber_stats = {}
- for cid in CHAMBER_IDS:
- t_c = self.chamber_target_temp_c.get(cid, 70.0)
- p_c = self.overall_pass_min_temp_c
- self.chamber_stats[cid] = {
- "chamber_id": cid,
- "target_temp_c": t_c,
- "pass_min_temp_c": p_c,
- "effective_target_c": max(t_c, p_c),
- # Sensor (CT) metrics
- "sensor_initial_c": None,
- "sensor_current_c": None,
- "sensor_peak_c": None,
- "sensor_reached_target": False,
- "sensor_time_to_target_s": None,
- "sensor_reached_pass_min": False,
- "sensor_time_to_pass_min_s": None,
- "sensor_reached": False,
- "sensor_reached_at_label": None,
- "sensor_reached_temp_c": None,
- "sensor_post_target_samples": 0,
- # Memory (BMC) metrics
- "memory_initial_c": None,
- "memory_current_c": None,
- "memory_peak_c": None,
- "memory_reached_target": False,
- "memory_time_to_target_s": None,
- "memory_reached_pass_min": False,
- "memory_time_to_pass_min_s": None,
- "memory_reached": False,
- "memory_reached_at_label": None,
- "memory_reached_temp_c": None,
- "memory_post_target_samples": 0,
- # Combined chamber status
- "both_reached": False,
- "chamber_time_to_target_s": None,
- "post_target_samples": 0,
- }
- def start(self, start_timestamp: float | None = None) -> None:
- self.session_id = datetime.datetime.now().strftime("TT-%Y%m%d-%H%M%S")
- self.reset_stats()
- self.start_timestamp = time.time() if start_timestamp is None else float(start_timestamp)
- self.stop_timestamp = None
- self.active = True
- def stop(self, stop_timestamp: float | None = None) -> None:
- if self.active:
- self.stop_timestamp = time.time() if stop_timestamp is None else float(stop_timestamp)
- self.active = False
- def _select_metric(self, info: dict[str, Any], prefix: str, mode: str) -> float | None:
- val = info.get(f"{prefix}_{mode}")
- if val is None and mode != "avg":
- val = info.get(f"{prefix}_avg")
- return float(val) if val is not None else None
- def process_sample(
- self,
- sample: dict[str, Any],
- mapping: ChamberMappingConfig,
- *,
- ignore_zero_ct: bool = False,
- ) -> dict[str, Any]:
- """Process one raw temperature sample; continues recording even after any/all chambers reach target."""
- ts = float(sample.get("timestamp", time.time()))
- t_lbl = str(sample.get("time_label", datetime.datetime.fromtimestamp(ts).strftime("%H:%M:%S")))
- if self.start_timestamp is None:
- self.start_timestamp = ts
- elapsed_s = max(0.0, round(ts - self.start_timestamp, 2))
- self.sample_count += 1
- fake_state = {
- "bmc": {"temperature_c": sample.get("bmc", [])},
- "ct": {"temperature_c": sample.get("ct", [])},
- }
- max_ct_now: float | None = None
- max_bmc_now: float | None = None
- for cid in CHAMBER_IDS:
- info = mapping.extract_chamber_temperatures(fake_state, cid, ignore_zero_ct=ignore_zero_ct)
- st = self.chamber_stats[cid]
- target_c = st["target_temp_c"]
- pass_min_c = st["pass_min_temp_c"]
- eff_c = max(target_c, pass_min_c)
- s_val = self._select_metric(info, "ct", self.ct_eval_mode)
- m_val = self._select_metric(info, "bmc", self.bmc_eval_mode)
- if s_val is not None:
- max_ct_now = s_val if max_ct_now is None else max(max_ct_now, s_val)
- if st["sensor_initial_c"] is None:
- st["sensor_initial_c"] = round(s_val, 2)
- st["sensor_current_c"] = round(s_val, 2)
- st["sensor_peak_c"] = round(s_val if st["sensor_peak_c"] is None else max(st["sensor_peak_c"], s_val), 2)
- if st["sensor_reached"]:
- st["sensor_post_target_samples"] += 1
- else:
- if not st["sensor_reached_target"] and s_val >= target_c:
- st["sensor_reached_target"] = True
- st["sensor_time_to_target_s"] = elapsed_s
- if not st["sensor_reached_pass_min"] and s_val >= pass_min_c:
- st["sensor_reached_pass_min"] = True
- st["sensor_time_to_pass_min_s"] = elapsed_s
- if s_val >= eff_c:
- st["sensor_reached"] = True
- if st["sensor_time_to_target_s"] is None:
- st["sensor_time_to_target_s"] = elapsed_s
- st["sensor_reached_at_label"] = t_lbl
- st["sensor_reached_temp_c"] = round(s_val, 2)
- if self.first_reached_chamber_id is None:
- self.first_reached_chamber_id = cid
- self.first_reached_kind = "sensor"
- self.first_reached_elapsed_s = elapsed_s
- if m_val is not None:
- max_bmc_now = m_val if max_bmc_now is None else max(max_bmc_now, m_val)
- if st["memory_initial_c"] is None:
- st["memory_initial_c"] = round(m_val, 2)
- st["memory_current_c"] = round(m_val, 2)
- st["memory_peak_c"] = round(m_val if st["memory_peak_c"] is None else max(st["memory_peak_c"], m_val), 2)
- if st["memory_reached"]:
- st["memory_post_target_samples"] += 1
- else:
- if not st["memory_reached_target"] and m_val >= target_c:
- st["memory_reached_target"] = True
- st["memory_time_to_target_s"] = elapsed_s
- if not st["memory_reached_pass_min"] and m_val >= pass_min_c:
- st["memory_reached_pass_min"] = True
- st["memory_time_to_pass_min_s"] = elapsed_s
- if m_val >= eff_c:
- st["memory_reached"] = True
- if st["memory_time_to_target_s"] is None:
- st["memory_time_to_target_s"] = elapsed_s
- st["memory_reached_at_label"] = t_lbl
- st["memory_reached_temp_c"] = round(m_val, 2)
- if self.first_reached_chamber_id is None:
- self.first_reached_chamber_id = cid
- self.first_reached_kind = "memory"
- self.first_reached_elapsed_s = elapsed_s
- was_any_reached = st["sensor_reached"] or st["memory_reached"]
- st["both_reached"] = bool(st["sensor_reached"] and st["memory_reached"])
- if st["both_reached"] and st["chamber_time_to_target_s"] is None:
- st["chamber_time_to_target_s"] = max(
- float(st["sensor_time_to_target_s"] or 0.0),
- float(st["memory_time_to_target_s"] or 0.0),
- )
- if was_any_reached:
- st["post_target_samples"] = max(st["sensor_post_target_samples"], st["memory_post_target_samples"])
- # Check fan intervention trigger
- fan_switched_now = False
- if not self.fan_intervened and self.fan_intervention_mode != "manual":
- if self.fan_intervention_mode == "immediate":
- self.fan_intervened = True
- self.fan_intervened_elapsed_s = elapsed_s
- self.fan_intervened_temp_c = max_ct_now if max_ct_now is not None else max_bmc_now
- self.fan_intervened_reason = "立即介入 (0s)"
- self.current_fan_duty_percent = self.active_fan_duty_percent
- fan_switched_now = True
- elif self.fan_intervention_mode == "time_s" and elapsed_s >= self.fan_intervention_time_s:
- self.fan_intervened = True
- self.fan_intervened_elapsed_s = elapsed_s
- self.fan_intervened_temp_c = max_ct_now if max_ct_now is not None else max_bmc_now
- self.fan_intervened_reason = f"达到设定介入时间 {self.fan_intervention_time_s:.1f}s (实测 {elapsed_s:.1f}s)"
- self.current_fan_duty_percent = self.active_fan_duty_percent
- fan_switched_now = True
- elif self.fan_intervention_mode == "ref_temp_c":
- ref_candidates: list[float] = []
- if self.fan_intervention_ref_source in ("ct", "any") and max_ct_now is not None:
- ref_candidates.append(max_ct_now)
- if self.fan_intervention_ref_source in ("bmc", "any") and max_bmc_now is not None:
- ref_candidates.append(max_bmc_now)
- ref_now = max(ref_candidates) if ref_candidates else None
- if ref_now is not None and ref_now >= self.fan_intervention_ref_temp_c:
- self.fan_intervened = True
- self.fan_intervened_elapsed_s = elapsed_s
- self.fan_intervened_temp_c = round(ref_now, 2)
- self.fan_intervened_reason = (
- f"参考温度达到 {ref_now:.1f}°C >= 阈值 {self.fan_intervention_ref_temp_c:.1f}°C (@ {elapsed_s:.1f}s)"
- )
- self.current_fan_duty_percent = self.active_fan_duty_percent
- fan_switched_now = True
- return {
- "elapsed_s": elapsed_s,
- "fan_switched_now": fan_switched_now,
- "current_fan_duty_percent": self.current_fan_duty_percent,
- }
- def evaluate_from_store(
- self,
- store: TemperatureCurveStore,
- mapping: ChamberMappingConfig,
- *,
- ignore_zero_ct: bool = False,
- ) -> dict[str, Any]:
- """Re-evaluate the entire TemperatureCurveStore history from start to end."""
- pts = store.snapshot()
- was_active = self.active
- self.reset_stats()
- self.active = was_active
- if pts:
- self.start_timestamp = float(pts[0]["timestamp"])
- for p in pts:
- self.process_sample(p, mapping, ignore_zero_ct=ignore_zero_ct)
- if not self.active:
- self.stop_timestamp = float(pts[-1]["timestamp"])
- return self.summary()
- def build_set_values(self, model: Model) -> list[int]:
- """Build SET_ALL channel duty array for the current test phase (initial vs post-intervention fan speed)."""
- fan_d = self.current_fan_duty_percent
- ptc_d = self.ptc_duty_percent
- ssr_d = self.ssr_duty_percent
- if model.motor:
- return [fan_d] * 4 + [ptc_d] * 4
- if model.product == "6400-v2":
- return [ptc_d] * 24 + [fan_d] * 8 + [ssr_d] * 3
- return [ptc_d] * 24 + [fan_d] * 8
- def summary(self) -> dict[str, Any]:
- """Return structured summary of all 4 chambers and overall high-temperature hood pass status."""
- sensor_all_reached = all(self.chamber_stats[c]["sensor_reached"] for c in CHAMBER_IDS)
- memory_all_reached = all(self.chamber_stats[c]["memory_reached"] for c in CHAMBER_IDS)
- both_all_reached = sensor_all_reached and memory_all_reached
- s_times = [
- float(self.chamber_stats[c]["sensor_time_to_target_s"])
- for c in CHAMBER_IDS
- if self.chamber_stats[c]["sensor_time_to_target_s"] is not None
- ]
- m_times = [
- float(self.chamber_stats[c]["memory_time_to_target_s"])
- for c in CHAMBER_IDS
- if self.chamber_stats[c]["memory_time_to_target_s"] is not None
- ]
- hood_sensor_time_s = max(s_times) if len(s_times) == 4 else None
- hood_memory_time_s = max(m_times) if len(m_times) == 4 else None
- hood_total_time_s = (
- max(hood_sensor_time_s, hood_memory_time_s)
- if (hood_sensor_time_s is not None and hood_memory_time_s is not None)
- else (hood_sensor_time_s if hood_sensor_time_s is not None else hood_memory_time_s)
- )
- elapsed_total = 0.0
- if self.start_timestamp is not None:
- end_ts = self.stop_timestamp if self.stop_timestamp is not None else time.time()
- elapsed_total = max(0.0, round(end_ts - self.start_timestamp, 2))
- total_post_target_samples = sum(self.chamber_stats[c]["post_target_samples"] for c in CHAMBER_IDS)
- return {
- "schema": "prod2u-thermal-test-report-v1",
- "session_id": self.session_id,
- "product": self.product,
- "test_name": self.test_name,
- "active": self.active,
- "sample_count": self.sample_count,
- "elapsed_total_s": elapsed_total,
- "overall_pass_min_temp_c": self.overall_pass_min_temp_c,
- "chamber_target_temp_c": dict(self.chamber_target_temp_c),
- "bmc_eval_mode": self.bmc_eval_mode,
- "ct_eval_mode": self.ct_eval_mode,
- "experiment_params": {
- "ptc_duty_percent": self.ptc_duty_percent,
- "ssr_duty_percent": self.ssr_duty_percent,
- "initial_fan_duty_percent": self.initial_fan_duty_percent,
- "active_fan_duty_percent": self.active_fan_duty_percent,
- "fan_intervention_mode": self.fan_intervention_mode,
- "fan_intervention_time_s": self.fan_intervention_time_s,
- "fan_intervention_ref_temp_c": self.fan_intervention_ref_temp_c,
- "fan_intervention_ref_source": self.fan_intervention_ref_source,
- "fan_intervened": self.fan_intervened,
- "fan_intervened_elapsed_s": self.fan_intervened_elapsed_s,
- "fan_intervened_temp_c": self.fan_intervened_temp_c,
- "fan_intervened_reason": self.fan_intervened_reason,
- "current_fan_duty_percent": self.current_fan_duty_percent,
- },
- "first_reached": {
- "chamber_id": self.first_reached_chamber_id,
- "kind": self.first_reached_kind,
- "elapsed_s": self.first_reached_elapsed_s,
- "continuous_recording_active": True,
- "total_post_target_samples": total_post_target_samples,
- },
- "hood_summary": {
- "sensor_all_4_reached": sensor_all_reached,
- "memory_all_4_reached": memory_all_reached,
- "hood_all_reached": both_all_reached,
- "sensor_reached_count": len(s_times),
- "memory_reached_count": len(m_times),
- "hood_sensor_reach_time_s": hood_sensor_time_s,
- "hood_memory_reach_time_s": hood_memory_time_s,
- "hood_total_reach_time_s": hood_total_time_s,
- },
- "chambers": {str(cid): dict(self.chamber_stats[cid]) for cid in CHAMBER_IDS},
- }
- def export_summary_csv(self) -> str:
- """Export reach-time and experiment parameter summary as CSV."""
- rep = self.summary()
- exp = rep["experiment_params"]
- headers = [
- "session_id",
- "test_name",
- "chamber",
- "target_temp_c",
- "overall_pass_min_temp_c",
- "sensor_initial_c",
- "sensor_current_c",
- "sensor_peak_c",
- "sensor_reached",
- "sensor_time_to_target_s",
- "sensor_time_mmss",
- "memory_initial_c",
- "memory_current_c",
- "memory_peak_c",
- "memory_reached",
- "memory_time_to_target_s",
- "memory_time_mmss",
- "post_target_samples",
- "ptc_duty_pct",
- "ssr_duty_pct",
- "initial_fan_pct",
- "active_fan_pct",
- "fan_intervention_mode",
- "fan_intervened_elapsed_s",
- "fan_intervened_temp_c",
- ]
- rows = [",".join(headers)]
- for cid in CHAMBER_IDS:
- st = self.chamber_stats[cid]
- row = [
- self.session_id,
- self.test_name.replace(",", ";"),
- f"腔体{cid}",
- f"{st['target_temp_c']:.1f}",
- f"{st['pass_min_temp_c']:.1f}",
- "" if st["sensor_initial_c"] is None else f"{st['sensor_initial_c']:.1f}",
- "" if st["sensor_current_c"] is None else f"{st['sensor_current_c']:.1f}",
- "" if st["sensor_peak_c"] is None else f"{st['sensor_peak_c']:.1f}",
- "PASS" if st["sensor_reached"] else "PENDING",
- "" if st["sensor_time_to_target_s"] is None else f"{st['sensor_time_to_target_s']:.2f}",
- format_duration_mmss(st["sensor_time_to_target_s"]),
- "" if st["memory_initial_c"] is None else f"{st['memory_initial_c']:.1f}",
- "" if st["memory_current_c"] is None else f"{st['memory_current_c']:.1f}",
- "" if st["memory_peak_c"] is None else f"{st['memory_peak_c']:.1f}",
- "PASS" if st["memory_reached"] else "PENDING",
- "" if st["memory_time_to_target_s"] is None else f"{st['memory_time_to_target_s']:.2f}",
- format_duration_mmss(st["memory_time_to_target_s"]),
- str(st["post_target_samples"]),
- str(exp["ptc_duty_percent"]),
- str(exp["ssr_duty_percent"]),
- str(exp["initial_fan_duty_percent"]),
- str(exp["active_fan_duty_percent"]),
- str(exp["fan_intervention_mode"]),
- "" if exp["fan_intervened_elapsed_s"] is None else f"{exp['fan_intervened_elapsed_s']:.2f}",
- "" if exp["fan_intervened_temp_c"] is None else f"{exp['fan_intervened_temp_c']:.1f}",
- ]
- rows.append(",".join(row))
- hs = rep["hood_summary"]
- rows.append(
- ",".join([
- self.session_id,
- self.test_name.replace(",", ";"),
- "高温罩四腔整体",
- f"{max(self.chamber_target_temp_c.values()):.1f}",
- f"{self.overall_pass_min_temp_c:.1f}",
- "",
- "",
- "",
- "PASS" if hs["sensor_all_4_reached"] else f"{hs['sensor_reached_count']}/4",
- "" if hs["hood_sensor_reach_time_s"] is None else f"{hs['hood_sensor_reach_time_s']:.2f}",
- format_duration_mmss(hs["hood_sensor_reach_time_s"]),
- "",
- "",
- "",
- "PASS" if hs["memory_all_4_reached"] else f"{hs['memory_reached_count']}/4",
- "" if hs["hood_memory_reach_time_s"] is None else f"{hs['hood_memory_reach_time_s']:.2f}",
- format_duration_mmss(hs["hood_memory_reach_time_s"]),
- str(rep["first_reached"]["total_post_target_samples"]),
- str(exp["ptc_duty_percent"]),
- str(exp["ssr_duty_percent"]),
- str(exp["initial_fan_duty_percent"]),
- str(exp["active_fan_duty_percent"]),
- str(exp["fan_intervention_mode"]),
- "" if exp["fan_intervened_elapsed_s"] is None else f"{exp['fan_intervened_elapsed_s']:.2f}",
- "" if exp["fan_intervened_temp_c"] is None else f"{exp['fan_intervened_temp_c']:.1f}",
- ])
- )
- return "\n".join(rows) + "\n"
- def sync_to_backend(
- self,
- store: TemperatureCurveStore,
- mapping: ChamberMappingConfig,
- *,
- backend_url: str | None = None,
- timeout: float = 5.0,
- ) -> dict[str, Any]:
- """Push this thermal test session (summary + curve samples + mapping) to the 192.168.2.25 backend."""
- import urllib.request
- url = (backend_url or self.backend_url).rstrip("/") + "/api/runs"
- payload = {
- "report": self.summary(),
- "mapping": mapping.to_dict(),
- "samples": store.snapshot(),
- }
- body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
- req = urllib.request.Request(
- url,
- data=body,
- headers={"Content-Type": "application/json; charset=utf-8"},
- method="POST",
- )
- with urllib.request.urlopen(req, timeout=timeout) as resp:
- return json.loads(resp.read().decode("utf-8"))
- # Embedded 16px bitmap font (ASCII 8x16 + Chinese UI characters 16x16) for dependency-free PNG rendering
- _FONT16_B85 = (
- 'c-nPYe{dUBeqTu&`6=F5D=8!^Tb5R2?Kq&|wXHZZk+o{;9=bNYrfu4~ch`1lTszmMAP5)4MM&Z>pnw5Ea~'
- 'A;tLNQ0UONiUcK?n(GivRFTGgHsp{oxs|gQq06Gs8^vM`mvS*dhIX-|my-0Q()iU48Z0_rCA@zQ5j+gUH-'
- '1mxDy1m8=Wylyy6_lW?`5wn5wFFBXU6H@`e|kg^nxBcZ~Na`{w;w~!|USUvDVc4_Ibpx)#4woz0sw8?x{e'
- 'dK@sd$p)h)^>ZumhSsFP7sinz(x>&wS(hS`YZ?`xU0ar17G}ZAz6?Jd+|=r>g?uCyF&+wHD@Q;FYaWFWRk'
- 'sj*E$qs^+W4&yHOBTmGv~RRD7o}IaR!WYO;`|r~x{m5WR{;${K_=UvRrSLWyjlKv_c;D;##WxeIy9ibLBG'
- '4i8UG7K?5-W$l8tP|yL`Kn+71PU(fh)PX5`#N8C-?m)p3DrF@sxeBStDTW$hqH1o|*WJzOu{rKp$D+!yRN'
- '{){mva%9rJPYqF*l1`@usb>6umF!!flb<vc=Nqh@h~h<)ooa9XasXr@#L7r=RH$YQXwEV1<&&)bM1X`1$7'
- ')_4{-}Q#i*1MN40QK&PG6;mW4Mlr=_GI7KgeLVpNtv8aP~blukdw^~@bPFeTZeNEke;IL-(m4OzzDHdsOl'
- '=W>Ygk|{lqWuv{pK{~%9ecz-#uq0K<#YM_CZ`Ti)?PGn`?7`j6KGd|_q&@nKmD&yKKX>Qz60%n!-o$aJ$n'
- 'EB_K1H<^))rMy4qN@eJBJ7RcuQCXX{XIWc|6Vi9%C|zd%t7dNv<!yT=xFKV312`7*Np(werVLTkjog7)(R'
- 'Q<Ia!sbn%lS$_@fC!c)!>1V~_!w*kV);OXjQ^`;WOv+lczd_d25#Tkt|1Q-%n7yPjO?(d)TWVY(WPKlg&~'
- '+7@nFzew?F81}!W2USyON0dJG7D`2U;W3-`^6eZaRq0$*QzIe%(v&sX`kp?){b!|9}Hh7Xlx$me%T+S{Sp'
- 'h366t>P8BfH6;hP-k5-T<8~}?dTC7QQT8SA7Wld3(Mr{eat&n$+gZ7A%lXl#6kRL#F3~~8nOPu&8jzDNjC'
- 'hd9Wa}M&)^u?+B@_AfaiaNw`MlL}wDIB4!f1x9OdGk|xQPzEwwQj`wZRuN9J8Ppr6Au^egOMEM0b5_zv_S'
- '(7@}M;#O{Euo@vx23^I;ZE9-@K6(nQ!&;SVXw62VsC5y}DsJJPVPhbap!tXMp9gtBs!1yX{69kHhU2xWaf'
- 'g@y?xl*>BEk8J57uB!Gr9);zg2A0K45$XU|zLCG|%RwIHxSaJn#pVE2unk5nc32Ni@jvGpW>j;e9lE1-Yj'
- 'y<8zc(zcWKqPhpMV!JDCT|cE0?3>0!*`?PfoP{N<=|*>#iE0YHnRniAXW;x4zHb#xdA;m-xS><J{L?5tBU'
- 'uX!`L+ZsYoL%9S0ZAjnGz`?<p90CeKX7GY~`%iem#(9GhOni(;?^|obK4MEQ{5Cb$RVnhspiJzAq<G$gNI'
- 'Tb_@I0XIpn?MOp;U>5k1yvf{B=8gPdMg13K`%5hAs}HLA;%?Ny-@n<Kt;3l8-i>-IT__6^%Q#+oPx_h(6J'
- 'UR8;z$rd(un<J#DM9Nk+@F4SJ^ej=dN)N7exb%U}q4j)4TuYY>ir0%2Hq(AMY|2|;IDjZ!lQW-QXo=#0e!'
- '&<DpFG7(>uREWyUO{)W+5)kz2dKGBPPT38_0|_$eReJ$+apvn((3}ia=EdW!AQy)esXJAt>PC{O3O;<#o?'
- 'F_Zx9eTzpgyc;by44Hin>Jrx^&8RlQc=Un^H+E?KU4M`8b~;O5&WjOhK2QwLpAY09cnPaU;@*6s!g-5|SF'
- 'h;V#?CB$CHyKh-Jw<w5zd=~sb7p#1>~`q$=gQhKYYF01u{eZGBx%$B_oQ%s9#0DWYy9pNMMfw(_DbmPd4&'
- 'F43t51jX%_wfPV&%4BHrAy78yrz^MG6u<E!%qVCXDbYM?TNRTmUz&R<&v(nO9#EHP)dbV?CFWq%>{PS7?B'
- '8p(ZDxv-CA-4{i3OHJ`JP;;i^GEf!dD90)o!ASZ0YUY19dL8g(Q|Bq{~jVUDNku9?;ypDd^ZMtAMWC%$5I'
- '!obYXmBB-)WFn*rw5O*oGLWy#2t#JmLIG56gdPyr5?0V|I7KA4D2S4ZAQm!tZJH>O5}EZW1IiA?tGE?6FY'
- 'prT>DaR@qFTa&mt+Pq_@ONsA^>{&b-SlDmrlXbcuX=zX+Aukn0Cy#Q1GXj(IMrvy+NCNdjmj2d$;8gbeaV'
- '=O@`oRa*76$`4#^}U_u)ko#$o%G;^`(87dc7hvgxCpf*q&(udWgsM1()?b*lHrxi=3t=|yz6T2gk2M3B6s'
- '7j_#3yh#s>q3teS-=BDViEWvfZk{U87wBzdmRE04L#SMd$Lt<wWL~$Tm~ZB$nB&Tt>F1aEJ&Ho8Rx>_!j?'
- '>ET*wM)huWF-FAbmyo`1777BESg5{bAh&;LiO3Ys$uavrV?sCyYfzhr{DFglrT@EQz^ArdDF;Yl0L?)mqd'
- 'VOfG0fx%fbF&lX6oCt*WRGDUx&JFC4I;?N2xoRERM95o5vAlHzvFMwNEaQvd|Fnax#uhRRv>k_g!4CGML_'
- 'lm2^klhJ#IOnws__?2Hx=M3Z(XxyCz7peoBQH@yVn#{!AlKLIOos!GvS;|1;KSGk;>cO#cQv;(p;9?_agN'
- 'IDSKo2gdhu=N!|RF^G#5c@4pe{w_lC&^l5YSp(sy{?v;;PdIG>*6L-#UyP8Ty=M{eYyljC^+GUX_i?UDl#'
- 'U9Q3t_BpJ5{z{x2IMI3K)-wSDI1g)YhuY~KFW9T;=DK^ZVo*(a^+ru!`Z!hf`KHUE+d(dfV#|(9;#>O998'
- 'Ofud$>^v@`9o_Lz32D;5xj60FiHqD-?dH>{v8$RS8#uyW~y=^|c<)EzZ1I>PMR>s$)$8>%o@&6#%75JuzE'
- 'EYnj-sJUxgO)3d=_3#Ck?oK2Tbhg?|iVzIJjy$lm2|1xhOi4!q(7O$p&>1mYVrcf1JVvn8UD{e2LYdy3Wi'
- 'nZih~bundSr>sj%xhe2aRe?N=Z)1Wjdu{DO?rCJH|IkU6P7^ckWV)LxG8bRSJ-cA?iV#hlK5v0W@dZxIhS'
- 'rkN}C8@L33Cw1aJZ?W7C57(vgk4?V$3unN{WGcX+mvZKoTKWnWE8h&SDid54wq&EOvxL|=i6;B1{*MFlgP'
- 'E=Hb<;}he0Q%sUEmcn`SOxIhrc<ra4nP-Koe7J9KDX5n)uCmz27zcnU6N~Z4ME4(gT(UYa=bjeG`KjZs<J'
- 'Hiqf8fn)(Y~ApaL-<4%H#<8iQhVnR@W0Qd6d8uCr?%S&~&$<|QW6K5m@LfP+K&&}vqa<rVMw)Mfy&;sNs='
- '%xw;*ZsicWXv5(?vNI<E%Na6doq!!Bq=eLE2BBh+sx-ZRe4@E5OgC6;IZB(CHfQ1?CGHYeO3k!k**Dm>R~'
- '<PS<!`HkGHlR?EV+VN=*_6);5L-w3vpfn!B?hPQXIz`C$b<O)Dk0eJI+JE5W36BY7BcSvwD1yTjCaIF_ej'
- '90^@<~V0LgKbt8HnK|j4!PXM8yNS4zhH%1V2?5U==U>HOLj+nlg+s+JK8amnkMHJG;$}=xAKM0yZPUC_`5'
- 'X^X#j2J<Vl8K;q7zm2KYQ8S%L8D6u>5mu^6qJ^8t~~p$9eTKc8Q_aNv~tAM<Ok(|>7U**y#;%Ejt#d@T9g'
- '*G-(uVK+t6YHT6~rk5%h1(p8S03xUU+3!S<MHU99_zz@aS@2zrY}x&YYaqgAm2_jIUMG<{WHMXZYkg5GJw'
- 'On~JpzJpuMz@hGg4;a3KKEpR5VoyIQ+ol4RsOf&l0s{-%7eWS9SCC-+Ir$2L>=3;PAmOx@@5pEi${M+#L1'
- '7zKJ92j;=%;q!#|u5V{&au3H?5hynf}aZCZ16iv<0q=AiF0*gq)W413~)92=KG8kSgyi3kW)K>Xv<rwV{F'
- 'F>MXfS!n8DvptqXwiS5LjPgYV~Iq@EgbSbG<+HUqjo2vFM^^U_`0>=YKSgAhOtT1k$1~OCA)?J&%l;+|Q#'
- 'AK3_vLg4GJ+aYPPi*^_imqgni!#kEE7gx$WwNA+7|ygm(>cCzpEHfQW#tvS3~{EBG;@%qSe9z>2|y=H>-#'
- '~+)XV^wa3B-O1yl=k?AEjab&8}JF-efTh5#*sY`^n!{=7Ek9}DOG*pB)0#d&eeKR<-ZJo)qWrIDQ~AnR>7'
- '6`UJ58Ks~z>+5mc#BVsYX)ajtRateoa`IxMtTjkARV5H^Le+5fj_Qu;w_o;jws!*P)sJnE;4wVtci?H=3z'
- '5vo_?_8ybz^oT+S6-~v7XuuQc1!lD|D%QW^`dk<_9?dB|0dm!Zuu_PD-hgRFce4B~sY|<Pkk$y9l7y-)fC'
- '?bWRskp}&qbn73~2s8>$eHC>Pd%M#27t)tsa$_e=>eU>0Zue^QPHm61K{6)>|+TR5q%^WpGOb8)D5Ut>}U'
- 'HeKE098gISag{YsGAacBK<v6st2n8I{RkJcD95Bq8n0)5tZp|LvT#<@S%Zv6YMz$<{ULwDFs#Z$~ikrL1B'
- 'b+MO+HkVb6-s^CIpzU?Z{eE4%7}ir_cG{tf$k_V3z%8{9WQ>)Ssx-8%-L3-2(Qx{Qs)WjM(o=>o%RH#eT~'
- 'pBX%Z`EKRIS+==R^CaD7y61P-x6He9ZZ0I>c4pViT@YATfBZp9`ET0$14*Q2jCJPVUI0CQwz+%N3^GoZB1'
- '?${vgYa7BZ$NXu{aKu6D25!uxx?CTU13A(y)pkJBTTvcs*W<gO=2J^~&g4&*`2EJ##&YsY3vIx^WaBjK?y'
- 'uy`gjjDqlelEhp=-%BHFp)^7C~J1Huq(NfUd!{5PsuWnMhl~HBq7n=kEbq;`@d#YJvIk>?LmRIdr&Db7mZ'
- 'j)Az+kS_u7KF-RpcHLA&7%vvdi+<dS&Hpm?RMG$1fZ8bS|1LZ3AP#OR!_3BHW68N0mO<3xNp%6hy}!ppi_'
- ';5GYvOMWwAP1-Btae`4AuHci%|D))+u<yvqujl;NxRR7hno{axlR<u>y+B?7xo0L@;!^?b&fxQEtu(HRUF'
- 't8c%^>Vl+9`aGwLXM&*0a9^UYPa-PO+o8x>edpr(vbJ|3hP5-tG)47v<_t5Hh#9Xa75K62KplZ%T{D}?BT'
- ')FQo;}9$UBn!n+c{@x8{7*@EmpCvp0&M2N=MRhQ>i#AxF^Gbo4c~ri!46vBjZw9G<Pj0(<JX(PAZ8$P7P;'
- 'AegmKnr<;*ZDvRaea?<E4OXV$a=gJ-BL>WO(GLXj%!lq`o@~9FteXxxmP#lU^c@$^&p?xMsYNRF^K2b9ti'
- '3MZ680>~YEnfZ+NI<KX-(~t9+>3UAA8#G^o)Owg5b4&QU=^#Llp)*k$;F=Xc3$B|O+`kUg5lPl`gzki*=E'
- '_gvlc*4pKG4bV5Pc2#={(bVe>*<hzm*_3%|9Q#~H{fW<{u=JS0j+h$FFy^YA_peC>_XE#6XMi{dN^OUZ0Z'
- '2ET)VvG#VEMU~<7usM8ccZGwcAd;u*kvtXGd}tm)Z?Z}(Y;IBF6WW+o)%IzoR?#Z`X1~~vDmZJ`<9=DoM;'
- '4+NMpf;K3kJkMk0;7l`>wHV5+_R#0XU!>6v;qYvbb?ksA3#nJI5+9@L!MV;+_1_t3f4*AEo<?Zpg0)I>#K'
- 'r2l3w{JYv#1QMYQt&|>f;faV(K;{kIc@4Vrh_|Zg{*~xd_=sezeJbWXJdV24PhCP|u1eqXvwJPEI%>J3gO'
- 'u|fZbnV_}!=+Q{+l|{7v~i;LW&0NT&Ayqwnbb@ULCjQOXQ3Ce;$pD8N4R4ea&f(*mYgQj1Q+=7xt8dgm*z'
- 'K5Z=T(CMw5A!SGBA%&f~INKHum`PRTyAdv<ho=d3on$@F3icL06NLNr8VN%Wd{fH5M{b5T*Mr?_nt#17Gu'
- '19d!b!Mw0X?E>nA5|V+~$wNhjx7$sw!c`KLhzUDJu~THA*I0Z~!TUY1i#|&A&9=%ZaP#XWb{4G<z(P1-f!'
- 'oZ)TyQRUzAGM1hPYuKK`*mq*#?o0EW<u{?5No}21_#r^nFaP*B@gWE^(l;74{k~<8DZbo%ToKED$S36T6o'
- '?Gwu5v;vORmVW>0HnQ4F?Kh2I|`J^`Mi*@yF?9)zjF^mO3Neu;m;@L)s&I`Q8??lS)8XHP$>1aCoEe#U&^'
- '{1G|bK0_l_`pLvDyzt#9;@P+*!34*XXh$m*sI=aIw0tHfHc#i5P72<!r_j;WP=t(C}-qF4q6Oo+Kgw$V|r'
- ')0LF3m?oMu~+E|UoI*ARlvH}@?F+Wv)dNIAq>8}w4+|CUjshxCvg#!k{>^yodYor$Ozm7-q&=#}?aq{BHy'
- 'r~7Y&b9fFtaxzlq)V5`)e8lT-KG%9YA&zeu_b&yiu=}Y77PcHr-XV7Y=oi&y=t1wt@Q#^^N*99<%JgBiam'
- 'Je1ozT>srUrW-`pI#boqKmeD*L}n<>tvZ{Z~X>M-nF>=veFjP@=Uhw+Y`+IRwpo)BjQu{cnj-(97%ozT>1'
- '@fE0B3wOe}#b3=Ue3YTNw{~vZP_jm'
- )
- _FONT16_CACHE: dict[str, tuple[int, bytes]] | None = None
- def _get_font16() -> dict[str, tuple[int, bytes]]:
- global _FONT16_CACHE
- if _FONT16_CACHE is not None:
- return _FONT16_CACHE
- raw = zlib.decompress(base64.b85decode(_FONT16_B85))
- table: dict[str, tuple[int, bytes]] = {}
- pos = 0
- while pos < len(raw):
- cb_len = raw[pos]
- w = raw[pos + 1]
- pos += 2
- ch = raw[pos : pos + cb_len].decode("utf-8")
- pos += cb_len
- byte_len = 16 if w == 8 else 32
- bits = raw[pos : pos + byte_len]
- pos += byte_len
- table[ch] = (w, bits)
- _FONT16_CACHE = table
- return table
- def _hex_rgb(hex_color: str) -> tuple[int, int, int]:
- c = hex_color.lstrip("#")
- return (int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16))
- class _PurePngCanvas:
- """Lightweight pure-Python RGB rasterizer + PNG encoder for dependency-free curve image printing."""
- def __init__(self, width: int, height: int, bg: tuple[int, int, int] = (248, 250, 252)):
- self.width = int(width)
- self.height = int(height)
- self.buf = bytearray(bytes(bg) * (self.width * self.height))
- self.font = _get_font16()
- def set_px(self, x: int, y: int, rgb: tuple[int, int, int]) -> None:
- if 0 <= x < self.width and 0 <= y < self.height:
- off = (y * self.width + x) * 3
- self.buf[off] = rgb[0]
- self.buf[off + 1] = rgb[1]
- self.buf[off + 2] = rgb[2]
- def fill_rect(self, x0: int, y0: int, x1: int, y1: int, rgb: tuple[int, int, int]) -> None:
- xa = max(0, min(x0, x1))
- xb = min(self.width - 1, max(x0, x1))
- ya = max(0, min(y0, y1))
- yb = min(self.height - 1, max(y0, y1))
- if xa > xb or ya > yb:
- return
- row_bytes = bytes(rgb) * (xb - xa + 1)
- w3 = self.width * 3
- start_x = xa * 3
- end_x = (xb + 1) * 3
- for y in range(ya, yb + 1):
- base = y * w3
- self.buf[base + start_x : base + end_x] = row_bytes
- def draw_rect(self, x0: int, y0: int, x1: int, y1: int, rgb: tuple[int, int, int], thickness: int = 1) -> None:
- for t in range(thickness):
- self.fill_rect(x0 + t, y0 + t, x1 - t, y0 + t, rgb)
- self.fill_rect(x0 + t, y1 - t, x1 - t, y1 - t, rgb)
- self.fill_rect(x0 + t, y0 + t, x0 + t, y1 - t, rgb)
- self.fill_rect(x1 - t, y0 + t, x1 - t, y1 - t, rgb)
- def draw_line(
- self,
- x0: int,
- y0: int,
- x1: int,
- y1: int,
- rgb: tuple[int, int, int],
- thickness: int = 1,
- dashed: bool = False,
- ) -> None:
- dx = abs(x1 - x0)
- dy = -abs(y1 - y0)
- sx = 1 if x0 < x1 else -1
- sy = 1 if y0 < y1 else -1
- err = dx + dy
- step = 0
- r = max(0, thickness - 1)
- while True:
- if not dashed or (step // 6) % 2 == 0:
- if r == 0:
- self.set_px(x0, y0, rgb)
- else:
- self.fill_rect(x0 - r // 2, y0 - r // 2, x0 + (r + 1) // 2, y0 + (r + 1) // 2, rgb)
- if x0 == x1 and y0 == y1:
- break
- e2 = 2 * err
- if e2 >= dy:
- err += dy
- x0 += sx
- if e2 <= dx:
- err += dx
- y0 += sy
- step += 1
- def draw_marker(self, cx: int, cy: int, rgb: tuple[int, int, int], radius: int = 3, diamond: bool = False) -> None:
- for dy in range(-radius, radius + 1):
- for dx in range(-radius, radius + 1):
- if diamond:
- if abs(dx) + abs(dy) <= radius + 1:
- self.set_px(cx + dx, cy + dy, rgb)
- else:
- if dx * dx + dy * dy <= radius * radius + 1:
- self.set_px(cx + dx, cy + dy, rgb)
- def text_width(self, text: str) -> int:
- total = 0
- for ch in str(text):
- g = self.font.get(ch)
- total += g[0] if g else (8 if ord(ch) < 128 else 16)
- return total
- def draw_text(self, x: int, y: int, text: str, rgb: tuple[int, int, int], align: str = "left") -> None:
- s = str(text)
- w_total = self.text_width(s)
- cur_x = x
- if align == "center":
- cur_x = x - w_total // 2
- elif align == "right":
- cur_x = x - w_total
- for ch in s:
- g = self.font.get(ch)
- if g is None:
- g = self.font.get("?")
- if g is None:
- cur_x += 8
- continue
- gw, bits = g
- if gw == 8:
- for row in range(16):
- b = bits[row]
- if not b:
- continue
- py = y + row
- for col in range(8):
- if b & (1 << (7 - col)):
- self.set_px(cur_x + col, py, rgb)
- else:
- for row in range(16):
- b = (bits[row * 2] << 8) | bits[row * 2 + 1]
- if not b:
- continue
- py = y + row
- for col in range(16):
- if b & (1 << (15 - col)):
- self.set_px(cur_x + col, py, rgb)
- cur_x += gw
- def to_png_bytes(self) -> bytes:
- w, h = self.width, self.height
- stride = w * 3
- raw_rows = bytearray((stride + 1) * h)
- for y in range(h):
- dst = y * (stride + 1)
- raw_rows[dst] = 0 # Filter type 0 (None)
- src = y * stride
- raw_rows[dst + 1 : dst + 1 + stride] = self.buf[src : src + stride]
- def chunk(tag: bytes, data: bytes) -> bytes:
- crc = zlib.crc32(tag + data) & 0xFFFFFFFF
- return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc)
- ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
- idat = zlib.compress(bytes(raw_rows), 6)
- return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", idat) + chunk(b"IEND", b"")
- def _compute_chamber_plot_traces(
- series: dict[str, Any],
- mode: str = "detail_and_avg",
- ) -> list[dict[str, Any]]:
- """Build ordered curve traces for one chamber: Memory (BMC) and Sensor (CT) curves."""
- traces: list[dict[str, Any]] = []
- if mode in ("detail_and_avg", "detail_only"):
- for idx, ch in enumerate(series["bmc_channels"]):
- vals = series["bmc_series"].get(ch, [])
- if any(v is not None for v in vals):
- traces.append({
- "label": f"BMC{ch}",
- "values": vals,
- "color": BMC_CURVE_COLORS[idx % len(BMC_CURVE_COLORS)],
- "width": 1,
- "dashed": False,
- "diamond": False,
- "kind": "bmc",
- })
- if mode in ("detail_and_avg", "avg_only"):
- if any(v is not None for v in series["bmc_avg"]):
- traces.append({
- "label": "内存均温",
- "values": series["bmc_avg"],
- "color": BMC_AVG_COLOR,
- "width": 2,
- "dashed": False,
- "diamond": False,
- "kind": "bmc_avg",
- })
- if mode == "avg_only" and any(v is not None for v in series["bmc_max"]):
- traces.append({
- "label": "内存最高",
- "values": series["bmc_max"],
- "color": BMC_MAX_COLOR,
- "width": 1,
- "dashed": True,
- "diamond": False,
- "kind": "bmc_max",
- })
- # Sensor (CT) traces are always drawn prominently so memory vs sensor comparison is clear
- for idx, ch in enumerate(series["ct_channels"]):
- vals = series["ct_series"].get(ch, [])
- if any(v is not None for v in vals) or mode != "avg_only":
- traces.append({
- "label": ct_channel_label(ch, short=True),
- "values": vals,
- "color": CT_CURVE_COLORS[idx % len(CT_CURVE_COLORS)],
- "width": 2,
- "dashed": True,
- "diamond": True,
- "kind": "ct",
- })
- if mode == "avg_only" and len(series["ct_channels"]) > 1 and any(v is not None for v in series["ct_avg"]):
- traces.append({
- "label": "Sensor均温",
- "values": series["ct_avg"],
- "color": CT_AVG_COLOR,
- "width": 2,
- "dashed": False,
- "diamond": True,
- "kind": "ct_avg",
- })
- return traces
- def _y_axis_bounds(traces: list[dict[str, Any]], target_temp_c: float | None = None) -> tuple[float, float]:
- vals = [float(v) for tr in traces for v in tr["values"] if v is not None]
- if target_temp_c is not None:
- vals.append(float(target_temp_c))
- if not vals:
- return (0.0, 100.0)
- lo = min(vals)
- hi = max(vals)
- span = max(8.0, hi - lo)
- y_min = max(0.0, math.floor((lo - span * 0.15) / 5.0) * 5.0)
- y_max = min(255.0, math.ceil((hi + span * 0.15) / 5.0) * 5.0)
- if y_max - y_min < 10.0:
- y_max = min(255.0, y_min + 10.0)
- return (y_min, y_max)
- def render_chamber_curves_png(
- store: TemperatureCurveStore,
- mapping: ChamberMappingConfig,
- *,
- product: str = "6400-v2",
- board: str = "6400V2.0",
- mode: str = "detail_and_avg",
- max_points: int = 0,
- ignore_zero_ct: bool = False,
- thermal_session: ThermalTestSession | None = None,
- width: int = 1600,
- height: int = 1080,
- ) -> bytes:
- """Render all 4 chambers' Memory (BMC) and Sensor (CT) temperature curves into a high-resolution PNG."""
- canvas = _PurePngCanvas(width, height, bg=(244, 247, 251))
- # Header bar
- canvas.fill_rect(0, 0, width - 1, 54, (21, 50, 89))
- now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- pts_all = store.snapshot(max_points=max_points)
- u6_str = "--"
- if pts_all and pts_all[-1]["ct"] and pts_all[-1]["ct"][0] is not None:
- u6_str = f"{pts_all[-1]['ct'][0]}°C"
- title = f"{board} ({product}) — 四腔体内存温度(BMC)与Sensor温度(CT)曲线图"
- sub = f"导出时间: {now_str} | 采样点数: {len(pts_all)} | U6本地(CT0): {u6_str}"
- if thermal_session is not None:
- rep = thermal_session.summary()
- hs = rep["hood_summary"]
- sub += (
- f" | 高温罩通过温度>={thermal_session.overall_pass_min_temp_c:.0f}°C "
- f"| Sensor达标:{hs['sensor_reached_count']}/4({format_duration_mmss(hs['hood_sensor_reach_time_s'])}) "
- f"内存达标:{hs['memory_reached_count']}/4({format_duration_mmss(hs['hood_memory_reach_time_s'])})"
- )
- canvas.draw_text(20, 10, title, (255, 255, 255))
- canvas.draw_text(20, 31, sub, (205, 224, 247))
- pad_x = 16
- pad_y = 66
- cell_w = (width - pad_x * 3) // 2
- cell_h = (height - pad_y - pad_x * 2) // 2
- for idx, cid in enumerate(CHAMBER_IDS):
- col = idx % 2
- row = idx // 2
- cx0 = pad_x + col * (cell_w + pad_x)
- cy0 = pad_y + row * (cell_h + pad_x)
- cx1 = cx0 + cell_w
- cy1 = cy0 + cell_h
- # Card background & border
- canvas.fill_rect(cx0, cy0, cx1, cy1, (255, 255, 255))
- canvas.draw_rect(cx0, cy0, cx1, cy1, (203, 213, 225), thickness=2)
- canvas.fill_rect(cx0 + 2, cy0 + 2, cx1 - 2, cy0 + 46, (238, 243, 249))
- series = store.chamber_series(mapping, cid, max_points=max_points, ignore_zero_ct=ignore_zero_ct)
- bmc_spec = format_channel_spec(series["bmc_channels"]) or "无"
- ct_spec = format_channel_spec(series["ct_channels"]) or "无"
- ch_target_c: float | None = None
- reach_badge = ""
- if thermal_session is not None:
- st_c = thermal_session.chamber_stats.get(cid, {})
- ch_target_c = float(st_c.get("effective_target_c", 70.0))
- s_t = format_duration_mmss(st_c.get("sensor_time_to_target_s"))
- m_t = format_duration_mmss(st_c.get("memory_time_to_target_s"))
- reach_badge = f" [目标{ch_target_c:.0f}°C | Sensor达标:{s_t} | 内存达标:{m_t}]"
- hdr_left = f"{series['name']} [内存BMC: {bmc_spec} | Sensor CT: {ct_spec}]{reach_badge}"
- canvas.draw_text(cx0 + 12, cy0 + 7, hdr_left, (15, 39, 71))
- # Latest reading summary
- latest_b = next((v for v in reversed(series["bmc_avg"]) if v is not None), None)
- latest_c_parts = []
- for ch in series["ct_channels"]:
- v_list = series["ct_series"].get(ch, [])
- v_last = next((v for v in reversed(v_list) if v is not None), None)
- latest_c_parts.append(f"CT{ch}:{v_last}°C" if v_last is not None else f"CT{ch}:--")
- stat_line = (
- f"当前内存均温: {latest_b:.1f}°C" if latest_b is not None else "当前内存均温: --(无有效数据)"
- ) + " | Sensor: " + (", ".join(latest_c_parts) if latest_c_parts else "无")
- canvas.draw_text(cx0 + 12, cy0 + 26, stat_line, (65, 85, 110))
- # Plot box
- px0 = cx0 + 54
- py0 = cy0 + 58
- px1 = cx1 - 182
- py1 = cy1 - 36
- pw = max(40, px1 - px0)
- ph = max(40, py1 - py0)
- canvas.fill_rect(px0, py0, px1, py1, (252, 253, 255))
- canvas.draw_rect(px0, py0, px1, py1, (180, 194, 210), thickness=1)
- traces = _compute_chamber_plot_traces(series, mode=mode)
- y_min, y_max = _y_axis_bounds(traces, target_temp_c=ch_target_c)
- # Horizontal grid lines & Y labels
- for step_i in range(6):
- frac = step_i / 5.0
- val_y = y_min + (y_max - y_min) * frac
- gy = int(round(py1 - frac * ph))
- if 0 < step_i < 5:
- canvas.draw_line(px0 + 1, gy, px1 - 1, gy, (226, 232, 240), thickness=1, dashed=True)
- canvas.draw_text(px0 - 6, gy - 8, f"{int(round(val_y))}°C", (90, 105, 120), align="right")
- # Draw target temperature line if configured
- if ch_target_c is not None and y_min <= ch_target_c <= y_max:
- ty = int(round(py1 - ((ch_target_c - y_min) / max(1e-6, y_max - y_min)) * ph))
- canvas.draw_line(px0 + 1, ty, px1 - 1, ty, (217, 119, 6), thickness=2, dashed=True)
- canvas.draw_text(px1 - 6, max(py0 + 2, ty - 16), f"目标 {ch_target_c:.0f}°C", (180, 83, 9), align="right")
- # X axis labels & vertical grid
- n_pts = series["sample_count"]
- elapsed = series["elapsed"]
- t_span = max(1.0, (elapsed[-1] - elapsed[0]) if len(elapsed) >= 2 else 1.0)
- for step_x in range(5):
- fx = step_x / 4.0
- gx = int(round(px0 + fx * pw))
- if 0 < step_x < 4:
- canvas.draw_line(gx, py0 + 1, gx, py1 - 1, (232, 237, 243), thickness=1, dashed=True)
- if n_pts >= 2:
- idx_pt = min(n_pts - 1, int(round(fx * (n_pts - 1))))
- lbl_x = f"{elapsed[idx_pt]:.0f}s"
- elif n_pts == 1 and step_x == 2:
- lbl_x = series["time_labels"][0]
- else:
- lbl_x = f"{int(fx * 60)}s" if n_pts == 0 else ""
- if lbl_x:
- canvas.draw_text(gx, py1 + 8, lbl_x, (90, 105, 120), align="center")
- # Draw curves
- has_any_point = False
- for tr in traces:
- rgb = _hex_rgb(tr["color"])
- pts_xy: list[tuple[int, int]] = []
- vals = tr["values"]
- for i, v in enumerate(vals):
- if v is None:
- continue
- if n_pts <= 1:
- x = px0 + pw // 2
- else:
- x = int(round(px0 + ((elapsed[i] - elapsed[0]) / t_span) * pw)) if elapsed[-1] > elapsed[0] else int(round(px0 + (i / (n_pts - 1)) * pw))
- y = int(round(py1 - ((float(v) - y_min) / max(1e-6, y_max - y_min)) * ph))
- y = max(py0 + 1, min(py1 - 1, y))
- pts_xy.append((x, y))
- if pts_xy:
- has_any_point = True
- for k in range(len(pts_xy) - 1):
- canvas.draw_line(
- pts_xy[k][0],
- pts_xy[k][1],
- pts_xy[k + 1][0],
- pts_xy[k + 1][1],
- rgb,
- thickness=tr["width"],
- dashed=tr["dashed"],
- )
- marker_stride = max(1, len(pts_xy) // 20)
- for k, (mx, my) in enumerate(pts_xy):
- if k == 0 or k == len(pts_xy) - 1 or k % marker_stride == 0:
- canvas.draw_marker(mx, my, rgb, radius=3 if tr["width"] >= 2 else 2, diamond=tr["diamond"])
- if not has_any_point:
- canvas.draw_text(
- px0 + pw // 2,
- py0 + ph // 2 - 8,
- "等待 0x42 温度数据或导入日志生成曲线...",
- (140, 155, 175),
- align="center",
- )
- # Right-side Legend panel
- lx0 = px1 + 10
- ly = py0 + 2
- canvas.draw_text(lx0, ly, "图例 / 最新值", (40, 60, 85))
- ly += 20
- for tr in traces[:14]:
- rgb = _hex_rgb(tr["color"])
- last_v = next((v for v in reversed(tr["values"]) if v is not None), None)
- v_txt = f"{last_v:.1f}°C" if isinstance(last_v, float) else (f"{last_v}°C" if last_v is not None else "--")
- canvas.draw_line(lx0, ly + 8, lx0 + 16, ly + 8, rgb, thickness=max(2, tr["width"]), dashed=tr["dashed"])
- canvas.draw_marker(lx0 + 8, ly + 8, rgb, radius=2, diamond=tr["diamond"])
- canvas.draw_text(lx0 + 20, ly, f"{tr['label']}:{v_txt}", rgb)
- ly += 18
- if ly + 18 > py1:
- break
- return canvas.to_png_bytes()
- def render_chamber_curves_svg(
- store: TemperatureCurveStore,
- mapping: ChamberMappingConfig,
- *,
- product: str = "6400-v2",
- board: str = "6400V2.0",
- mode: str = "detail_and_avg",
- max_points: int = 0,
- ignore_zero_ct: bool = False,
- thermal_session: ThermalTestSession | None = None,
- width: int = 1600,
- height: int = 1080,
- ) -> str:
- """Render all 4 chambers' Memory (BMC) and Sensor (CT) temperature curves into a vector SVG."""
- def esc(s: Any) -> str:
- return (
- str(s)
- .replace("&", "&")
- .replace("<", "<")
- .replace(">", ">")
- .replace('"', """)
- )
- now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
- pts_all = store.snapshot(max_points=max_points)
- u6_str = f"{pts_all[-1]['ct'][0]}°C" if (pts_all and pts_all[-1]["ct"] and pts_all[-1]["ct"][0] is not None) else "--"
- sub_extra = ""
- if thermal_session is not None:
- rep = thermal_session.summary()
- hs = rep["hood_summary"]
- sub_extra = (
- f" | 高温罩通过温度>={thermal_session.overall_pass_min_temp_c:.0f}°C "
- f"| Sensor达标:{hs['sensor_reached_count']}/4({format_duration_mmss(hs['hood_sensor_reach_time_s'])}) "
- f"内存达标:{hs['memory_reached_count']}/4({format_duration_mmss(hs['hood_memory_reach_time_s'])})"
- )
- lines = [
- f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}" font-family="Microsoft YaHei, Noto Sans CJK SC, Consolas, sans-serif">',
- f' <rect width="{width}" height="{height}" fill="#F4F7FB"/>',
- f' <rect width="{width}" height="54" fill="#153259"/>',
- f' <text x="20" y="24" fill="#FFFFFF" font-size="16" font-weight="bold">{esc(board)} ({esc(product)}) — 四腔体内存温度(BMC)与Sensor温度(CT)曲线图</text>',
- f' <text x="20" y="45" fill="#CDE0F7" font-size="12">导出时间: {esc(now_str)} | 采样点数: {len(pts_all)} | U6本地(CT0): {esc(u6_str)}{esc(sub_extra)}</text>',
- ]
- pad_x = 16
- pad_y = 66
- cell_w = (width - pad_x * 3) // 2
- cell_h = (height - pad_y - pad_x * 2) // 2
- for idx, cid in enumerate(CHAMBER_IDS):
- col = idx % 2
- row = idx // 2
- cx0 = pad_x + col * (cell_w + pad_x)
- cy0 = pad_y + row * (cell_h + pad_x)
- series = store.chamber_series(mapping, cid, max_points=max_points, ignore_zero_ct=ignore_zero_ct)
- bmc_spec = format_channel_spec(series["bmc_channels"]) or "无"
- ct_spec = format_channel_spec(series["ct_channels"]) or "无"
- ch_target_c: float | None = None
- reach_badge = ""
- if thermal_session is not None:
- st_c = thermal_session.chamber_stats.get(cid, {})
- ch_target_c = float(st_c.get("effective_target_c", 70.0))
- s_t = format_duration_mmss(st_c.get("sensor_time_to_target_s"))
- m_t = format_duration_mmss(st_c.get("memory_time_to_target_s"))
- reach_badge = f" [目标{ch_target_c:.0f}°C | Sensor达标:{s_t} | 内存达标:{m_t}]"
- latest_b = next((v for v in reversed(series["bmc_avg"]) if v is not None), None)
- latest_c_parts = [
- f"CT{ch}:{next((v for v in reversed(series['ct_series'].get(ch, [])) if v is not None), '--')}°C"
- for ch in series["ct_channels"]
- ]
- stat_line = (
- f"当前内存均温: {latest_b:.1f}°C" if latest_b is not None else "当前内存均温: --(无有效数据)"
- ) + " | Sensor: " + (", ".join(latest_c_parts) if latest_c_parts else "无")
- lines.append(f' <rect x="{cx0}" y="{cy0}" width="{cell_w}" height="{cell_h}" fill="#FFFFFF" stroke="#CBD5E1" stroke-width="2" rx="4"/>')
- lines.append(f' <rect x="{cx0+2}" y="{cy0+2}" width="{cell_w-4}" height="44" fill="#EEF3F9"/>')
- lines.append(f' <text x="{cx0+12}" y="{cy0+20}" fill="#0F2747" font-size="14" font-weight="bold">{esc(series["name"])} [内存BMC: {esc(bmc_spec)} | Sensor CT: {esc(ct_spec)}]{esc(reach_badge)}</text>')
- lines.append(f' <text x="{cx0+12}" y="{cy0+39}" fill="#41556E" font-size="12">{esc(stat_line)}</text>')
- px0 = cx0 + 54
- py0 = cy0 + 58
- px1 = cx0 + cell_w - 182
- py1 = cy0 + cell_h - 36
- pw = max(40, px1 - px0)
- ph = max(40, py1 - py0)
- lines.append(f' <rect x="{px0}" y="{py0}" width="{pw}" height="{ph}" fill="#FCFDFF" stroke="#B4C2D2" stroke-width="1"/>')
- traces = _compute_chamber_plot_traces(series, mode=mode)
- y_min, y_max = _y_axis_bounds(traces, target_temp_c=ch_target_c)
- for step_i in range(6):
- frac = step_i / 5.0
- val_y = y_min + (y_max - y_min) * frac
- gy = round(py1 - frac * ph, 1)
- if 0 < step_i < 5:
- lines.append(f' <line x1="{px0}" y1="{gy}" x2="{px1}" y2="{gy}" stroke="#E2E8F0" stroke-dasharray="4,4"/>')
- lines.append(f' <text x="{px0-6}" y="{gy+4}" fill="#5A6978" font-size="11" text-anchor="end">{int(round(val_y))}°C</text>')
- if ch_target_c is not None and y_min <= ch_target_c <= y_max:
- ty = round(py1 - ((ch_target_c - y_min) / max(1e-6, y_max - y_min)) * ph, 1)
- lines.append(f' <line x1="{px0}" y1="{ty}" x2="{px1}" y2="{ty}" stroke="#D97706" stroke-width="2" stroke-dasharray="6,4"/>')
- lines.append(f' <text x="{px1-6}" y="{max(py0+12, ty-4)}" fill="#B45309" font-size="11" font-weight="bold" text-anchor="end">目标 {ch_target_c:.0f}°C</text>')
- n_pts = series["sample_count"]
- elapsed = series["elapsed"]
- t_span = max(1.0, (elapsed[-1] - elapsed[0]) if len(elapsed) >= 2 else 1.0)
- for step_x in range(5):
- fx = step_x / 4.0
- gx = round(px0 + fx * pw, 1)
- if 0 < step_x < 4:
- lines.append(f' <line x1="{gx}" y1="{py0}" x2="{gx}" y2="{py1}" stroke="#E8EDF3" stroke-dasharray="4,4"/>')
- if n_pts >= 2:
- idx_pt = min(n_pts - 1, int(round(fx * (n_pts - 1))))
- lbl_x = f"{elapsed[idx_pt]:.0f}s"
- elif n_pts == 1 and step_x == 2:
- lbl_x = series["time_labels"][0]
- else:
- lbl_x = f"{int(fx * 60)}s" if n_pts == 0 else ""
- if lbl_x:
- lines.append(f' <text x="{gx}" y="{py1+18}" fill="#5A6978" font-size="11" text-anchor="middle">{esc(lbl_x)}</text>')
- has_any = False
- for tr in traces:
- pts_xy = []
- for i, v in enumerate(tr["values"]):
- if v is None:
- continue
- if n_pts <= 1:
- x = px0 + pw / 2.0
- else:
- x = px0 + ((elapsed[i] - elapsed[0]) / t_span) * pw if elapsed[-1] > elapsed[0] else px0 + (i / (n_pts - 1)) * pw
- y = py1 - ((float(v) - y_min) / max(1e-6, y_max - y_min)) * ph
- y = max(py0 + 1, min(py1 - 1, y))
- pts_xy.append((round(x, 1), round(y, 1)))
- if pts_xy:
- has_any = True
- dash = ' stroke-dasharray="6,4"' if tr["dashed"] else ""
- if len(pts_xy) >= 2:
- pts_str = " ".join(f"{x},{y}" for x, y in pts_xy)
- lines.append(f' <polyline fill="none" stroke="{tr["color"]}" stroke-width="{tr["width"]+0.5}"{dash} points="{pts_str}"/>')
- for x, y in pts_xy[::max(1, len(pts_xy) // 20)]:
- lines.append(f' <circle cx="{x}" cy="{y}" r="3" fill="{tr["color"]}"/>')
- if not has_any:
- lines.append(f' <text x="{px0 + pw/2}" y="{py0 + ph/2}" fill="#8C9BAF" font-size="13" text-anchor="middle">等待 0x42 温度数据或导入日志生成曲线...</text>')
- lx0 = px1 + 10
- ly = py0 + 14
- lines.append(f' <text x="{lx0}" y="{ly}" fill="#283C55" font-size="12" font-weight="bold">图例 / 最新值</text>')
- ly += 18
- for tr in traces[:14]:
- last_v = next((v for v in reversed(tr["values"]) if v is not None), None)
- v_txt = f"{last_v:.1f}°C" if isinstance(last_v, float) else (f"{last_v}°C" if last_v is not None else "--")
- lines.append(f' <text x="{lx0}" y="{ly}" fill="{tr["color"]}" font-size="11">● {esc(tr["label"])}: {esc(v_txt)}</text>')
- ly += 16
- if ly > py1:
- break
- lines.append("</svg>\n")
- return "\n".join(lines)
- def export_chamber_curves_csv(
- store: TemperatureCurveStore,
- mapping: ChamberMappingConfig,
- *,
- max_points: int = 0,
- ignore_zero_ct: bool = False,
- ) -> str:
- """Export per-chamber mapped temperature series and raw channels as CSV."""
- pts = store.snapshot(max_points=max_points)
- t0 = pts[0]["timestamp"] if pts else 0.0
- headers = ["sample_index", "time_label", "elapsed_s"]
- for cid in CHAMBER_IDS:
- cfg = mapping.chambers[cid]
- headers.append(f"C{cid}_BMC_AVG")
- for ch in cfg["bmc"]:
- headers.append(f"C{cid}_BMC{ch}")
- headers.append(f"C{cid}_CT_AVG")
- for ch in cfg["ct"]:
- headers.append(f"C{cid}_CT{ch}")
- headers.append("U6_LOCAL_CT0")
- rows = [",".join(headers)]
- for idx, p in enumerate(pts):
- row = [str(idx + 1), str(p["time_label"]), f"{p['timestamp'] - t0:.2f}"]
- for cid in CHAMBER_IDS:
- cfg = mapping.chambers[cid]
- b_vals = [p["bmc"][ch] for ch in cfg["bmc"] if ch < len(p["bmc"]) and p["bmc"][ch] is not None]
- row.append(f"{sum(b_vals)/len(b_vals):.2f}" if b_vals else "")
- for ch in cfg["bmc"]:
- v = p["bmc"][ch] if ch < len(p["bmc"]) else None
- row.append("" if v is None else str(v))
- c_vals = []
- for ch in cfg["ct"]:
- v = p["ct"][ch] if ch < len(p["ct"]) else None
- if ignore_zero_ct and v == 0:
- v = None
- if v is not None:
- c_vals.append(v)
- row.append(f"{sum(c_vals)/len(c_vals):.2f}" if c_vals else "")
- for ch in cfg["ct"]:
- v = p["ct"][ch] if ch < len(p["ct"]) else None
- if ignore_zero_ct and v == 0:
- v = None
- row.append("" if v is None else str(v))
- u6 = p["ct"][0] if p["ct"] else None
- row.append("" if u6 is None else str(u6))
- rows.append(",".join(row))
- return "\n".join(rows) + "\n"
- def self_test(product: str) -> int:
- model = Model(product)
- # 1. Golden GET_ALL frame
- get_frame = encode_frame(FrameType.GET_ALL)
- assert get_frame == bytes.fromhex("A55A02006D7B"), f"GET golden mismatch: {get_frame.hex()}"
- exp_get = model.explain(get_frame)
- assert exp_get["crc_ok"] is True
- assert "GET_ALL" in exp_get["type"]
- # 2. Golden ACKs
- set_ack = bytes.fromhex("A55A8100A635")
- get_ack = bytes.fromhex("A55A8200F560")
- assert decode_frame(set_ack).crc_ok
- assert decode_frame(get_ack).crc_ok
- assert model.parse(set_ack)[0]["kind"] == "ack"
- assert model.parse(get_ack)[0]["kind"] == "ack"
- assert model.explain(set_ack)["crc_ok"] is True
- assert model.explain(get_ack)["crc_ok"] is True
- # 3. Golden NACK
- nack = bytes.fromhex("A55AC0020104B12A")
- assert decode_frame(nack).crc_ok
- parsed_nack = model.parse(nack)[0]
- assert parsed_nack["kind"] == "nack"
- assert parsed_nack["reason"] == "QUEUE_FULL"
- exp_nack = model.explain(nack)
- assert exp_nack["crc_ok"] is True
- assert "QUEUE_FULL" in exp_nack["fields"][1]
- # 4. SET_ALL generation
- values = [val for _, count, val in model.groups() for _ in range(count)]
- frame = model.set_all(values, buzzer=1 if (model.motor or product == "6400-v2") else 0)
- parsed = decode_frame(frame)
- assert parsed.crc_ok
- expected_len = 69 if model.motor else (36 if product == "6400-v2" else sum(count for _, count, _ in model.groups()))
- assert len(parsed.payload) == expected_len
- exp_set = model.explain(frame)
- assert exp_set["crc_ok"] is True
- if model.motor:
- # Golden MOTOR_DONE frames
- done_ul = bytes.fromhex("A55A500404022311B602")
- assert decode_frame(done_ul).crc_ok
- p_done = model.parse(done_ul)[0]
- assert p_done["axis"] == 4 and p_done["reason"] == "UPPER_LIMIT" and p_done["steps_done"] == 4387
- exp_done_ul = model.explain(done_ul)
- assert exp_done_ul["crc_ok"] is True
- assert "4387" in exp_done_ul["fields"][2]
- done_bl = bytes.fromhex("A55A5004040300002364")
- assert decode_frame(done_bl).crc_ok
- p_done_bl = model.parse(done_bl)[0]
- assert p_done_bl["axis"] == 4 and p_done_bl["reason"] == "BOTH_LIMITS" and p_done_bl["steps_done"] == 0
- # V3.3.0 65B GET_DATA (hood_switch=1, buzzer=1) + 8B DIAGNOSTIC
- mr_status = bytes([20] * 4 + [0] * 4 + [255] * 51 + [0, 0, 0, 0, 1, 1])
- mr_dec = model.state(mr_status)
- assert mr_dec["hood_switch"] is True and mr_dec["buzzer"] is True
- mr_diag = bytes([2, 0x80, 3, 3, 0, 0x0B, 0x05, 0x00])
- p_diag = model.parse(encode_frame(FrameType.DIAGNOSTIC, mr_diag))[0]["diagnostic"]
- assert p_diag["supported"] and p_diag["firmware_version"] == "3.3.0" and p_diag["buzzer_on"] and p_diag["active_axes"] == [0, 2]
- if product == "6400-v2":
- # V3.3.0 90B GET_DATA (EPB1=1, SB1=1, SB2=0, buzzer=1)
- status = bytes([0] * 24 + [20] * 8 + [255] * 51 + [0, 25, 100, 1, 1, 0, 1])
- decoded = model.state(status)
- assert decoded["ssr"] == [0, 25, 100]
- assert decoded["estop_btn"] is True and decoded["hood_open_btn"] is True
- assert decoded["hood_close_btn"] is False and decoded["buzzer"] is True
- assert len(decoded["ct"]["raw"]) == 27
- diagnostic = bytes([1, 0x64, 3, 3, 0, 0x23, 0, 0, 0x4C, 0, 0, 0x80, 0x0C, 25, 1, 0, 1, 1, 0, 48])
- d_parsed = model.parse(encode_frame(FrameType.DIAGNOSTIC, diagnostic))[0]["diagnostic"]
- assert d_parsed["temperature_c"] == 25 and d_parsed["buzzer_on"] is True and d_parsed["firmware_version"] == "3.3.0"
- # 5. Chamber mapping default + custom configuration & curve image generation
- cmap = ChamberMappingConfig.default(product)
- assert cmap.chambers[1]["bmc"] == [0, 1, 2, 3, 4, 5] and cmap.chambers[1]["ct"] == [1, 2]
- assert cmap.chambers[2]["bmc"] == [6, 7, 8, 9, 10, 11] and cmap.chambers[2]["ct"] == [3, 4]
- assert cmap.chambers[3]["bmc"] == [12, 13, 14, 15, 16, 17] and cmap.chambers[3]["ct"] == [5, 6]
- assert cmap.chambers[4]["bmc"] == [18, 19, 20, 21, 22, 23] and cmap.chambers[4]["ct"] == [7, 8]
- cmap.set_chamber(1, "0-2, 5", "CT5, CT6")
- assert cmap.chambers[1]["bmc"] == [0, 1, 2, 5] and cmap.chambers[1]["ct"] == [5, 6]
- cmap.reset_to_default()
- store = TemperatureCurveStore()
- store.record_raw_arrays(
- [30 + (i % 6) for i in range(24)],
- [25, 22, 28, 23, 29, 24, 31, 25, 32] + [255] * 18,
- timestamp=1000.0,
- time_label="10:00:00",
- )
- store.record_raw_arrays(
- [32 + (i % 6) for i in range(24)],
- [26, 24, 31, 25, 32, 26, 34, 27, 35] + [255] * 18,
- timestamp=1001.0,
- time_label="10:00:01",
- )
- png_bytes = render_chamber_curves_png(store, cmap, product=product, board=model.board, width=800, height=540)
- assert png_bytes.startswith(b"\x89PNG\r\n\x1a\n") and len(png_bytes) > 500
- svg_str = render_chamber_curves_svg(store, cmap, product=product, board=model.board, width=800, height=540)
- assert "<svg" in svg_str and "腔体 1" in svg_str
- csv_str = export_chamber_curves_csv(store, cmap)
- assert "C1_BMC_AVG" in csv_str and "C4_CT8" in csv_str
- # 6. ThermalTestSession reach-time calculation & continuous recording after first chamber reaches target
- tt = ThermalTestSession(
- product,
- overall_pass_min_temp_c=70.0,
- chamber_target_temp_c={1: 70.0, 2: 72.0, 3: 70.0, 4: 70.0},
- fan_intervention_mode="ref_temp_c",
- fan_intervention_ref_temp_c=55.0,
- initial_fan_duty_percent=0,
- active_fan_duty_percent=50,
- )
- tt.start(start_timestamp=2000.0)
- tt_store = TemperatureCurveStore()
- # t=0s: initial room temp 30C
- s0 = tt_store.record_raw_arrays([30] * 24, [25] + [30] * 8 + [255] * 18, timestamp=2000.0, time_label="10:00:00")
- tt.process_sample(s0, cmap)
- assert not tt.fan_intervened
- # t=60s: Chamber 1 reaches 70C first; fan ref temp 55C also crossed -> fan intervenes
- s1 = tt_store.record_raw_arrays(
- [71] * 6 + [56] * 18,
- [28, 70, 72, 55, 56, 54, 55, 52, 53] + [255] * 18,
- timestamp=2060.0,
- time_label="10:01:00",
- )
- res1 = tt.process_sample(s1, cmap)
- assert res1["fan_switched_now"] is True and tt.current_fan_duty_percent == 50
- assert tt.chamber_stats[1]["sensor_reached"] is True and tt.chamber_stats[1]["sensor_time_to_target_s"] == 60.0
- assert tt.chamber_stats[1]["memory_reached"] is True and tt.chamber_stats[1]["memory_time_to_target_s"] == 60.0
- assert tt.chamber_stats[2]["sensor_reached"] is False
- # t=120s: Chamber 1 already reached target at 60s, MUST continue recording data!
- s2 = tt_store.record_raw_arrays(
- [75] * 6 + [73] * 18,
- [30, 74, 76, 73, 73, 71, 71, 70, 71] + [255] * 18,
- timestamp=2120.0,
- time_label="10:02:00",
- )
- tt.process_sample(s2, cmap)
- assert tt.chamber_stats[1]["sensor_time_to_target_s"] == 60.0 # locked at first reach time
- assert tt.chamber_stats[1]["post_target_samples"] == 1 # continued recording after target!
- assert tt.chamber_stats[1]["sensor_peak_c"] == 75.0
- assert tt.chamber_stats[2]["sensor_time_to_target_s"] == 120.0
- rep = tt.summary()
- assert rep["hood_summary"]["hood_all_reached"] is True
- assert rep["hood_summary"]["hood_sensor_reach_time_s"] == 120.0
- assert "PASS" in tt.export_summary_csv()
- return 0
- def describe(model: Model, frame: bytes) -> str:
- values = model.parse(frame)
- return json.dumps(
- values[0]["state"] if len(values) == 1 and values[0]["kind"] == "status" else values,
- ensure_ascii=False,
- indent=2,
- )
- def reset_motor_actions(axis_slots: list[dict[str, Any]]) -> None:
- """A later thermal SET must not replay a previously selected motion."""
- for slot in axis_slots:
- slot["action_var"].set("NOTHING")
- # ---------------------------------------------------------------------------
- # Full Tkinter GUI Implementation
- # ---------------------------------------------------------------------------
- def run_gui(product: str) -> int:
- try:
- import tkinter as tk
- from tkinter import ttk, messagebox, filedialog
- except ImportError:
- if sys.stderr:
- print("Tkinter unavailable in headless environment; run --self-test instead.", file=sys.stderr)
- return 1
- model = Model(product)
- try:
- root = tk.Tk()
- except Exception as exc:
- if sys.stderr:
- print(f"Display unavailable ({exc}); run --self-test instead or use xvfb-run.", file=sys.stderr)
- return 1
- root.title(f"{model.board} | 软件 v{model.release_version} | Prod2U 调试与监控")
- root.geometry("1180x820")
- root.minsize(960, 640)
- # Global serial state & communication engine
- serial_port_obj: Any = None
- serial_lock = threading.Lock()
- poll_active = False
- poll_generation = 0
- poll_stop_event = threading.Event()
- connection_epoch = 0
- disk_logger = SessionDiskLogger(product)
- tracker = TransactionTracker()
- receiver = StreamReceiver(product)
- request_queue: queue.Queue = queue.Queue()
- scheduler_lock = threading.Lock()
- def dispatch_next_request():
- nonlocal serial_port_obj
- with scheduler_lock:
- t_evt = tracker.check_request_timeout()
- if t_evt:
- root.after(0, append_log, "ERR", "", t_evt["msg"])
- root.after(0, lbl_realtime_stat.config, {"text": t_evt["msg"]})
- if tracker.tx_state != "IDLE":
- return
- if request_queue.empty():
- return
- try:
- item = request_queue.get_nowait()
- if len(item) == 4:
- req_type, frame_bytes, desc, nonce = item
- else:
- req_type, frame_bytes, desc = item
- nonce = None
- except queue.Empty:
- return
- with serial_lock:
- sp = serial_port_obj
- if sp and sp.is_open:
- try:
- tracker.on_request_sent(req_type, timeout=1.0, nonce=nonce)
- sp.write(frame_bytes)
- if model.motor and req_type == "SET":
- root.after(0, reset_motor_actions, axis_slots)
- root.after(0, append_log, "TX", frame_hex(frame_bytes), desc)
- except Exception as exc:
- root.after(0, append_log, "ERR", "", f"发送失败: {exc}")
- # Notebook
- notebook = ttk.Notebook(root)
- notebook.pack(fill="both", expand=True, padx=8, pady=8)
- # -----------------------------------------------------------------------
- # TAB 1: 串口连接与实时控制 (Serial & Realtime Control)
- # -----------------------------------------------------------------------
- tab_serial = ttk.Frame(notebook, padding=10)
- notebook.add(tab_serial, text="📡 串口连接与实时控制")
- # Connection bar
- conn_frame = ttk.LabelFrame(tab_serial, text=f"Host UART · 固件构建速率 {model.host_baud} · 8N1 · BMC 独立 115200", padding=8)
- conn_frame.pack(fill="x", pady=4)
- ttk.Label(conn_frame, text="COM 端口:").pack(side="left", padx=4)
- port_combo = ttk.Combobox(conn_frame, width=14, state="readonly")
- port_combo.pack(side="left", padx=4)
- def refresh_ports():
- if HAVE_SERIAL:
- ports = [p.device for p in serial.tools.list_ports.comports()]
- port_combo["values"] = ports
- if ports and not port_combo.get():
- port_combo.set(ports[0])
- elif not ports:
- port_combo.set("")
- else:
- port_combo["values"] = ["(pyserial 未安装)"]
- port_combo.set("(pyserial 未安装)")
- refresh_ports()
- ttk.Button(conn_frame, text="刷新端口", command=refresh_ports).pack(side="left", padx=4)
- ttk.Label(conn_frame, text="波特率:").pack(side="left", padx=8)
- baud_combo = ttk.Combobox(conn_frame, width=10, values=[str(rate) for rate in HOST_BAUDRATES], state="readonly")
- baud_combo.set(str(model.host_baud))
- baud_combo.pack(side="left", padx=4)
- ttk.Label(conn_frame, text="需与烧录固件速率一致", foreground="gray").pack(side="left", padx=4)
- btn_connect = ttk.Button(conn_frame, text="打开串口")
- btn_connect.pack(side="left", padx=10)
- lbl_conn_status = ttk.Label(conn_frame, text="未连接", foreground="gray", font=("", 10, "bold"))
- lbl_conn_status.pack(side="left", padx=8)
- # Realtime control bar
- ctrl_bar = ttk.Frame(tab_serial, padding=4)
- ctrl_bar.pack(fill="x", pady=6)
- btn_send_get = ttk.Button(ctrl_bar, text="🔍 发送 GET_ALL 查询", state="disabled")
- btn_send_get.pack(side="left", padx=5)
- btn_send_set = ttk.Button(ctrl_bar, text="⚡ 发送当前 SET 配置", state="disabled")
- btn_send_set.pack(side="left", padx=5)
- btn_heartbeat = ttk.Button(ctrl_bar, text="💓 心跳测试 (Ping)", state="disabled")
- btn_heartbeat.pack(side="left", padx=5)
- poll_var = tk.BooleanVar(value=False)
- chk_poll = ttk.Checkbutton(ctrl_bar, text="自动每秒轮询 GET_ALL (维持看门狗)", variable=poll_var, state="disabled")
- chk_poll.pack(side="left", padx=15)
- # Realtime status summary
- stat_summary_frame = ttk.LabelFrame(tab_serial, text="单板实时状态概要", padding=8)
- stat_summary_frame.pack(fill="x", pady=4)
- lbl_realtime_stat = ttk.Label(stat_summary_frame, text="等待查询或接收单板响应...", font=("", 10))
- lbl_realtime_stat.pack(anchor="w")
- lbl_realtime_ptc = ttk.Label(stat_summary_frame, text="【PTC 生效占空比】: 待查询", font=("Consolas", 9), foreground="#003366")
- lbl_realtime_ptc.pack(anchor="w", pady=2)
- lbl_realtime_chambers = ttk.Label(
- stat_summary_frame,
- text="【四腔实时温度 (可配置映射)】: 腔1[内存:-- | CT1=--/CT2=--] 腔2[内存:-- | CT3=--/CT4=--] 腔3[内存:-- | CT5=--/CT6=--] 腔4[内存:-- | CT7=--/CT8=--]",
- font=("Consolas", 9),
- foreground="#0B5345",
- wraplength=1100,
- )
- lbl_realtime_chambers.pack(anchor="w", pady=2)
- lbl_realtime_diag = ttk.Label(stat_summary_frame, text="【固件自主诊断】: 等待 0x52 自动上报",
- font=("Consolas", 9), foreground="#704010", wraplength=1050)
- if product in ("6400-v2", "mrdimm-chamber"):
- lbl_realtime_diag.pack(anchor="w", pady=2)
- # Serial Log area
- log_frame = ttk.LabelFrame(tab_serial, text="通信原始报文日志 (TX / RX 流)", padding=8)
- log_frame.pack(fill="both", expand=True, pady=6)
- text_log = tk.Text(log_frame, height=14, wrap="char", font=("Consolas", 9))
- text_log.pack(fill="both", expand=True, side="left")
- scroll_log = ttk.Scrollbar(log_frame, command=text_log.yview)
- scroll_log.pack(side="right", fill="y")
- text_log.config(yscrollcommand=scroll_log.set)
- def append_log(direction: str, hex_str: str, note: str = ""):
- now = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3]
- if direction.startswith("TX"):
- tag = "tx"
- elif direction in ("RX", "RX_AUTO", "BOARD_DIAG"):
- tag = "rx"
- elif direction == "RX_RAW":
- tag = "rx_raw"
- elif direction == "NOISE":
- tag = "noise"
- else:
- tag = "err"
- line = f"[{now}] [{direction:6s}] {hex_str}"
- if note:
- line += f" ({note})"
- line += "\n"
- text_log.insert("end", line, tag)
- text_log.see("end")
- disk_logger.log_event(direction, hex_str, note)
- text_log.tag_config("tx", foreground="#0066CC")
- text_log.tag_config("rx", foreground="#008800")
- text_log.tag_config("rx_raw", foreground="#777777")
- text_log.tag_config("noise", foreground="#AA6600")
- text_log.tag_config("err", foreground="#CC0000")
- def open_log_dir():
- log_dir = str(disk_logger.log_dir)
- try:
- if sys.platform == "win32":
- os.startfile(log_dir)
- elif sys.platform == "darwin":
- subprocess.Popen(["open", log_dir])
- else:
- subprocess.Popen(["xdg-open", log_dir])
- except Exception as e:
- messagebox.showinfo("日志目录", f"日志存储在:\n{disk_logger.log_dir}\n打开失败: {e}")
- def export_diagnosis():
- try:
- info = [
- f"=== Prod2U GUI 会话诊断快照 ===",
- f"会话 ID: {disk_logger.session_id}",
- f"产品型号: {product} ({model.board})",
- f"当前连接状态: {tracker.state}",
- f"日志落盘路径:\n{disk_logger.log_path}",
- "",
- "如需提供给 ChatGPT 或技术支持分析,请将上述日志文件直接发送。",
- ]
- messagebox.showinfo("本次诊断信息", "\n".join(info))
- except Exception as e:
- messagebox.showerror("诊断导出失败", str(e))
- btn_clear_log = ttk.Button(ctrl_bar, text="清空日志", command=lambda: text_log.delete("1.0", "end"))
- btn_clear_log.pack(side="right", padx=3)
- btn_open_log = ttk.Button(ctrl_bar, text="📁 打开日志目录", command=open_log_dir)
- btn_open_log.pack(side="right", padx=3)
- btn_export_diag = ttk.Button(ctrl_bar, text="📋 诊断信息", command=export_diagnosis)
- btn_export_diag.pack(side="right", padx=3)
- # -----------------------------------------------------------------------
- # TAB 2: 腔体温度曲线与映射 (Chamber Temperature Curves & Mapping)
- # -----------------------------------------------------------------------
- tab_curves = ttk.Frame(notebook, padding=8)
- notebook.add(tab_curves, text="📈 腔体温度曲线与映射")
- curve_store = TemperatureCurveStore()
- chamber_mapping = ChamberMappingConfig.default(product)
- default_map_path = ChamberMappingConfig.default_config_path(product)
- if default_map_path.is_file():
- try:
- chamber_mapping = ChamberMappingConfig.load(default_map_path, product=product)
- except Exception:
- chamber_mapping = ChamberMappingConfig.default(product)
- thermal_session = ThermalTestSession(product)
- experiment_history: list[dict[str, Any]] = []
- # 1. Configurable Chamber Mapping Frame
- map_frame = ttk.LabelFrame(
- tab_curves,
- text="⚙️ 各腔体通道映射配置 (默认值: 腔1~4 内存=BMC 0-5/6-11/12-17/18-23,Sensor=CT 1,2/3,4/5,6/7,8;支持范围如 0-5 或逗号 1,2)",
- padding=6,
- )
- map_frame.pack(fill="x", pady=3)
- map_grid = ttk.Frame(map_frame)
- map_grid.pack(fill="x", pady=2)
- chamber_bmc_vars: dict[int, tk.StringVar] = {}
- chamber_ct_vars: dict[int, tk.StringVar] = {}
- def open_channel_selector(cid: int, kind: str):
- is_bmc = (kind == "bmc")
- max_ch = 23 if is_bmc else 26
- title_str = f"选择 腔体{cid} 的 {'内存温度 (BMC0..23)' if is_bmc else 'Sensor温度 (CT0..26)'} 通道"
- var_target = chamber_bmc_vars[cid] if is_bmc else chamber_ct_vars[cid]
- try:
- current_set = set(parse_channel_spec(var_target.get(), max_ch))
- except Exception:
- current_set = set()
- dlg = tk.Toplevel(root)
- dlg.title(title_str)
- dlg.geometry("680x360" if not is_bmc else "640x320")
- dlg.transient(root)
- dlg.grab_set()
- ttk.Label(dlg, text=title_str, font=("", 10, "bold")).pack(anchor="w", padx=10, pady=6)
- chk_container = ttk.Frame(dlg, padding=8)
- chk_container.pack(fill="both", expand=True)
- chk_vars: dict[int, tk.BooleanVar] = {}
- cols = 6 if is_bmc else 5
- for idx in range(max_ch + 1):
- bv = tk.BooleanVar(value=(idx in current_set))
- chk_vars[idx] = bv
- lbl = bmc_channel_label(idx, short=False) if is_bmc else ct_channel_label(idx, short=False)
- cb = ttk.Checkbutton(chk_container, text=lbl, variable=bv)
- cb.grid(row=idx // cols, column=idx % cols, sticky="w", padx=6, pady=3)
- btn_row = ttk.Frame(dlg, padding=8)
- btn_row.pack(fill="x")
- def select_all_ch(state: bool):
- for bv in chk_vars.values():
- bv.set(state)
- def confirm_selection():
- chosen = [idx for idx, bv in sorted(chk_vars.items()) if bv.get()]
- var_target.set(format_channel_spec(chosen))
- dlg.destroy()
- apply_chamber_mapping(silent=True)
- ttk.Button(btn_row, text="全选", command=lambda: select_all_ch(True)).pack(side="left", padx=4)
- ttk.Button(btn_row, text="全不选", command=lambda: select_all_ch(False)).pack(side="left", padx=4)
- ttk.Button(btn_row, text="取消", command=dlg.destroy).pack(side="right", padx=4)
- ttk.Button(btn_row, text="✅ 确定并应用", command=confirm_selection).pack(side="right", padx=4)
- for idx, cid in enumerate(CHAMBER_IDS):
- c_col = idx % 2
- c_row = idx // 2
- cell_f = ttk.Frame(map_grid)
- cell_f.grid(row=c_row, column=c_col, sticky="ew", padx=8, pady=2)
- map_grid.columnconfigure(c_col, weight=1)
- ttk.Label(cell_f, text=f"【腔体 {cid}】", font=("", 9, "bold"), foreground="#153259").pack(side="left", padx=2)
- ttk.Label(cell_f, text="内存(BMC):").pack(side="left", padx=2)
- b_var = tk.StringVar(value=format_channel_spec(chamber_mapping.chambers[cid]["bmc"]))
- chamber_bmc_vars[cid] = b_var
- ttk.Entry(cell_f, textvariable=b_var, width=10, font=("Consolas", 9)).pack(side="left", padx=2)
- ttk.Button(cell_f, text="选择", width=4, command=lambda c=cid: open_channel_selector(c, "bmc")).pack(side="left", padx=2)
- ttk.Label(cell_f, text="Sensor(CT):").pack(side="left", padx=(8, 2))
- c_var = tk.StringVar(value=format_channel_spec(chamber_mapping.chambers[cid]["ct"]))
- chamber_ct_vars[cid] = c_var
- ttk.Entry(cell_f, textvariable=c_var, width=10, font=("Consolas", 9)).pack(side="left", padx=2)
- ttk.Button(cell_f, text="选择", width=4, command=lambda c=cid: open_channel_selector(c, "ct")).pack(side="left", padx=2)
- map_btn_bar = ttk.Frame(map_frame)
- map_btn_bar.pack(fill="x", pady=(4, 0))
- lbl_map_status = ttk.Label(map_btn_bar, text="当前使用默认/已存映射,修改后点击【应用映射】即时重绘四腔曲线", foreground="#2E7D32")
- lbl_map_status.pack(side="right", padx=6)
- def sync_vars_from_mapping():
- for cid in CHAMBER_IDS:
- chamber_bmc_vars[cid].set(format_channel_spec(chamber_mapping.chambers[cid]["bmc"]))
- chamber_ct_vars[cid].set(format_channel_spec(chamber_mapping.chambers[cid]["ct"]))
- def apply_chamber_mapping(silent: bool = False) -> bool:
- try:
- for cid in CHAMBER_IDS:
- chamber_mapping.set_chamber(cid, chamber_bmc_vars[cid].get(), chamber_ct_vars[cid].get())
- sync_vars_from_mapping()
- try:
- chamber_mapping.save(default_map_path)
- except Exception:
- pass
- lbl_map_status.config(
- text=f"映射已生效 ({datetime.datetime.now().strftime('%H:%M:%S')}) — 历史数据已按新映射重绘",
- foreground="#006600",
- )
- redraw_all_chamber_canvases()
- return True
- except Exception as exc:
- lbl_map_status.config(text=f"映射格式错误: {exc}", foreground="#CC0000")
- if not silent:
- messagebox.showerror("腔体映射配置错误", str(exc))
- return False
- def reset_chamber_mapping():
- chamber_mapping.reset_to_default()
- sync_vars_from_mapping()
- apply_chamber_mapping(silent=True)
- lbl_map_status.config(text="已恢复默认腔体映射 (BMC: 0-5/6-11/12-17/18-23, CT: 1,2/3,4/5,6/7,8)", foreground="#0055AA")
- def swap_ct_pairs():
- if not apply_chamber_mapping(silent=False):
- return
- chamber_mapping.swap_pairs(swap_bmc=False, swap_ct=True)
- sync_vars_from_mapping()
- apply_chamber_mapping(silent=True)
- lbl_map_status.config(text="已对调腔体 1<->3 与 2<->4 的 Sensor(CT) 通道映射", foreground="#0055AA")
- def swap_bmc_pairs():
- if not apply_chamber_mapping(silent=False):
- return
- chamber_mapping.swap_pairs(swap_bmc=True, swap_ct=False)
- sync_vars_from_mapping()
- apply_chamber_mapping(silent=True)
- lbl_map_status.config(text="已对调腔体 1<->3 与 2<->4 的 内存(BMC) 通道映射", foreground="#0055AA")
- def export_mapping_file():
- if not apply_chamber_mapping(silent=False):
- return
- path = filedialog.asksaveasfilename(
- title="保存腔体映射配置 JSON",
- defaultextension=".json",
- initialfile=f"chamber_mapping_{product}.json",
- filetypes=[("JSON 映射配置", "*.json"), ("所有文件", "*.*")],
- )
- if path:
- try:
- saved = chamber_mapping.save(Path(path))
- lbl_map_status.config(text=f"映射配置已保存: {saved.name}", foreground="#006600")
- except Exception as exc:
- messagebox.showerror("保存失败", str(exc))
- def import_mapping_file():
- path = filedialog.askopenfilename(
- title="载入腔体映射配置 JSON",
- filetypes=[("JSON 映射配置", "*.json"), ("所有文件", "*.*")],
- )
- if path:
- try:
- loaded = ChamberMappingConfig.load(Path(path), product=product)
- for cid in CHAMBER_IDS:
- chamber_mapping.chambers[cid] = dict(loaded.chambers[cid])
- sync_vars_from_mapping()
- apply_chamber_mapping(silent=True)
- lbl_map_status.config(text=f"已载入映射配置: {Path(path).name}", foreground="#006600")
- except Exception as exc:
- messagebox.showerror("载入映射失败", str(exc))
- ttk.Button(map_btn_bar, text="✅ 应用映射", command=lambda: apply_chamber_mapping(False)).pack(side="left", padx=3)
- ttk.Button(map_btn_bar, text="🔄 恢复默认映射", command=reset_chamber_mapping).pack(side="left", padx=3)
- ttk.Button(map_btn_bar, text="🔀 1/2与3/4腔Sensor对调", command=swap_ct_pairs).pack(side="left", padx=3)
- ttk.Button(map_btn_bar, text="🔀 1/2与3/4腔内存对调", command=swap_bmc_pairs).pack(side="left", padx=3)
- ttk.Button(map_btn_bar, text="💾 导出映射JSON", command=export_mapping_file).pack(side="left", padx=3)
- ttk.Button(map_btn_bar, text="📂 导入映射JSON", command=import_mapping_file).pack(side="left", padx=3)
- # 2. Curve Display & Image Printing Toolbar
- plot_ctrl_bar = ttk.Frame(tab_curves, padding=4)
- plot_ctrl_bar.pack(fill="x", pady=2)
- ttk.Label(plot_ctrl_bar, text="显示模式:").pack(side="left", padx=2)
- MODE_LABELS = {
- "通道明细 + 腔体均值 (推荐)": "detail_and_avg",
- "仅腔体均值与极值 (简洁)": "avg_only",
- "仅各通道独立曲线": "detail_only",
- }
- curve_mode_var = tk.StringVar(value="通道明细 + 腔体均值 (推荐)")
- combo_mode = ttk.Combobox(plot_ctrl_bar, textvariable=curve_mode_var, values=list(MODE_LABELS.keys()), width=23, state="readonly")
- combo_mode.pack(side="left", padx=4)
- ttk.Label(plot_ctrl_bar, text="时间窗口:").pack(side="left", padx=4)
- WINDOW_LABELS = {
- "全部历史": 0,
- "最近 60 点": 60,
- "最近 300 点": 300,
- "最近 900 点 (15分钟)": 900,
- }
- curve_win_var = tk.StringVar(value="全部历史")
- combo_win = ttk.Combobox(plot_ctrl_bar, textvariable=curve_win_var, values=list(WINDOW_LABELS.keys()), width=16, state="readonly")
- combo_win.pack(side="left", padx=4)
- ignore_zero_ct_var = tk.BooleanVar(value=False)
- chk_ignore_zero = ttk.Checkbutton(
- plot_ctrl_bar,
- text="过滤 Sensor 0°C (未接探头)",
- variable=ignore_zero_ct_var,
- command=lambda: redraw_all_chamber_canvases(),
- )
- chk_ignore_zero.pack(side="left", padx=8)
- lbl_curve_count = ttk.Label(plot_ctrl_bar, text="采样点: 0", font=("Consolas", 9, "bold"), foreground="#153259")
- lbl_curve_count.pack(side="left", padx=8)
- # 3. 2x2 Grid of 4 Chamber Curve Canvases
- plots_grid = ttk.Frame(tab_curves)
- plots_grid.pack(fill="both", expand=True, pady=4)
- plots_grid.columnconfigure(0, weight=1)
- plots_grid.columnconfigure(1, weight=1)
- plots_grid.rowconfigure(0, weight=1)
- plots_grid.rowconfigure(1, weight=1)
- chamber_canvases: dict[int, tk.Canvas] = {}
- chamber_hover_idx: dict[int, int | None] = {1: None, 2: None, 3: None, 4: None}
- chamber_plot_geom: dict[int, dict[str, Any]] = {}
- for idx, cid in enumerate(CHAMBER_IDS):
- r = idx // 2
- c = idx % 2
- cv = tk.Canvas(plots_grid, bg="#FFFFFF", highlightthickness=1, highlightbackground="#CBD5E1")
- cv.grid(row=r, column=c, sticky="nsew", padx=4, pady=4)
- chamber_canvases[cid] = cv
- def _current_mode_and_window() -> tuple[str, int, bool]:
- m = MODE_LABELS.get(curve_mode_var.get(), "detail_and_avg")
- w = WINDOW_LABELS.get(curve_win_var.get(), 0)
- z = bool(ignore_zero_ct_var.get())
- return m, w, z
- def draw_single_chamber_canvas(cid: int):
- cv = chamber_canvases[cid]
- w = max(320, cv.winfo_width())
- h = max(190, cv.winfo_height())
- cv.delete("all")
- mode, max_pts, ign_zero = _current_mode_and_window()
- series = curve_store.chamber_series(chamber_mapping, cid, max_points=max_pts, ignore_zero_ct=ign_zero)
- bmc_spec = format_channel_spec(series["bmc_channels"]) or "无"
- ct_spec = format_channel_spec(series["ct_channels"]) or "无"
- # Header band
- ch_st = thermal_session.chamber_stats.get(cid, {})
- ch_target_c = float(ch_st.get("effective_target_c", 70.0))
- s_t_str = format_duration_mmss(ch_st.get("sensor_time_to_target_s"))
- m_t_str = format_duration_mmss(ch_st.get("memory_time_to_target_s"))
- cv.create_rectangle(0, 0, w, 40, fill="#EEF3F9", outline="#CBD5E1")
- cv.create_text(
- 10,
- 11,
- anchor="w",
- text=f"{series['name']} [BMC:{bmc_spec} | CT:{ct_spec}] 🎯目标{ch_target_c:.0f}°C (Sensor达标:{s_t_str} | 内存达标:{m_t_str})",
- font=("Microsoft YaHei", 9, "bold"),
- fill="#0F2747",
- )
- latest_b = next((v for v in reversed(series["bmc_avg"]) if v is not None), None)
- latest_c_parts = []
- for ch in series["ct_channels"]:
- v_list = series["ct_series"].get(ch, [])
- v_last = next((v for v in reversed(v_list) if v is not None), None)
- latest_c_parts.append(f"CT{ch}={v_last}°C" if v_last is not None else f"CT{ch}=--")
- stat_txt = (
- f"当前内存均温: {latest_b:.1f}°C" if latest_b is not None else "当前内存均温: --"
- ) + " | Sensor: " + (", ".join(latest_c_parts) if latest_c_parts else "无")
- cv.create_text(10, 29, anchor="w", text=stat_txt, font=("Consolas", 8), fill="#334E68")
- legend_w = 132 if w >= 460 else 108
- px0 = 46
- py0 = 48
- px1 = max(px0 + 60, w - legend_w - 8)
- py1 = max(py0 + 40, h - 24)
- pw = px1 - px0
- ph = py1 - py0
- cv.create_rectangle(px0, py0, px1, py1, fill="#FCFDFF", outline="#B4C2D2")
- traces = _compute_chamber_plot_traces(series, mode=mode)
- y_min, y_max = _y_axis_bounds(traces, target_temp_c=ch_target_c)
- # Horizontal grid & Y axis labels
- for step_i in range(5):
- frac = step_i / 4.0
- val_y = y_min + (y_max - y_min) * frac
- gy = py1 - frac * ph
- if 0 < step_i < 4:
- cv.create_line(px0 + 1, gy, px1 - 1, gy, fill="#E2E8F0", dash=(3, 3))
- cv.create_text(px0 - 4, gy, anchor="e", text=f"{int(round(val_y))}°C", font=("Consolas", 8), fill="#5A6978")
- if y_min <= ch_target_c <= y_max:
- ty = py1 - ((ch_target_c - y_min) / max(1e-6, y_max - y_min)) * ph
- cv.create_line(px0 + 1, ty, px1 - 1, ty, fill="#D97706", width=1.5, dash=(5, 3))
- cv.create_text(px1 - 4, max(py0 + 8, ty - 7), anchor="e", text=f"目标{ch_target_c:.0f}°C", font=("Consolas", 8, "bold"), fill="#B45309")
- # Vertical grid & X axis labels
- n_pts = series["sample_count"]
- elapsed = series["elapsed"]
- t_span = max(1.0, (elapsed[-1] - elapsed[0]) if len(elapsed) >= 2 else 1.0)
- for step_x in range(5):
- fx = step_x / 4.0
- gx = px0 + fx * pw
- if 0 < step_x < 4:
- cv.create_line(gx, py0 + 1, gx, py1 - 1, fill="#E8EDF3", dash=(3, 3))
- if n_pts >= 2:
- idx_pt = min(n_pts - 1, int(round(fx * (n_pts - 1))))
- lbl_x = f"{elapsed[idx_pt]:.0f}s"
- elif n_pts == 1 and step_x == 2:
- lbl_x = series["time_labels"][0]
- else:
- lbl_x = f"{int(fx * 60)}s" if n_pts == 0 else ""
- if lbl_x:
- cv.create_text(gx, py1 + 11, anchor="center", text=lbl_x, font=("Consolas", 8), fill="#5A6978")
- chamber_plot_geom[cid] = {
- "px0": px0, "py0": py0, "px1": px1, "py1": py1, "pw": pw, "ph": ph,
- "n_pts": n_pts, "elapsed": elapsed, "t_span": t_span, "series": series, "traces": traces,
- }
- has_any_point = False
- for tr in traces:
- pts_xy = []
- for i, v in enumerate(tr["values"]):
- if v is None:
- continue
- if n_pts <= 1:
- x = px0 + pw / 2.0
- else:
- x = px0 + ((elapsed[i] - elapsed[0]) / t_span) * pw if elapsed[-1] > elapsed[0] else px0 + (i / (n_pts - 1)) * pw
- y = py1 - ((float(v) - y_min) / max(1e-6, y_max - y_min)) * ph
- y = max(py0 + 2, min(py1 - 2, y))
- pts_xy.append((x, y))
- if pts_xy:
- has_any_point = True
- if len(pts_xy) >= 2:
- flat = [coord for pt in pts_xy for coord in pt]
- dash_pat = (5, 3) if tr["dashed"] else ()
- cv.create_line(*flat, fill=tr["color"], width=tr["width"] + 0.5, dash=dash_pat)
- stride = max(1, len(pts_xy) // 18)
- for k, (mx, my) in enumerate(pts_xy):
- if k == 0 or k == len(pts_xy) - 1 or k % stride == 0:
- r_mk = 3 if tr["width"] >= 2 else 2
- if tr["diamond"]:
- cv.create_polygon(mx, my - r_mk - 1, mx + r_mk + 1, my, mx, my + r_mk + 1, mx - r_mk - 1, my, fill=tr["color"], outline="")
- else:
- cv.create_oval(mx - r_mk, my - r_mk, mx + r_mk, my + r_mk, fill=tr["color"], outline="")
- if not has_any_point:
- cv.create_text(
- px0 + pw / 2,
- py0 + ph / 2,
- text="等待接收 0x42 温度数据,或点击【导入日志绘图】...",
- font=("Microsoft YaHei", 9),
- fill="#8C9BAF",
- )
- # Hover crosshair & tooltip
- h_idx = chamber_hover_idx.get(cid)
- if h_idx is not None and 0 <= h_idx < n_pts:
- if n_pts <= 1:
- hx = px0 + pw / 2.0
- else:
- hx = px0 + ((elapsed[h_idx] - elapsed[0]) / t_span) * pw if elapsed[-1] > elapsed[0] else px0 + (h_idx / (n_pts - 1)) * pw
- cv.create_line(hx, py0, hx, py1, fill="#475569", dash=(2, 2))
- tip_items = [f"点#{h_idx+1} ({series['time_labels'][h_idx]}, +{elapsed[h_idx]:.1f}s)"]
- for tr in traces[:8]:
- v_at = tr["values"][h_idx] if h_idx < len(tr["values"]) else None
- if v_at is not None:
- v_s = f"{v_at:.1f}°C" if isinstance(v_at, float) else f"{v_at}°C"
- tip_items.append(f"{tr['label']}:{v_s}")
- tip_text = " | ".join(tip_items)
- cv.create_rectangle(px0 + 4, py0 + 3, min(px1 - 4, px0 + 10 + len(tip_text) * 6), py0 + 21, fill="#FFFDE7", outline="#FBC02D")
- cv.create_text(px0 + 8, py0 + 12, anchor="w", text=tip_text, font=("Consolas", 8), fill="#1E293B")
- # Legend on right side
- lx0 = px1 + 6
- ly = py0 + 6
- cv.create_text(lx0, ly, anchor="w", text="图例 / 最新值", font=("Microsoft YaHei", 8, "bold"), fill="#1E293B")
- ly += 15
- for tr in traces[:12]:
- last_v = next((v for v in reversed(tr["values"]) if v is not None), None)
- v_txt = f"{last_v:.1f}°C" if isinstance(last_v, float) else (f"{last_v}°C" if last_v is not None else "--")
- dash_pat = (3, 2) if tr["dashed"] else ()
- cv.create_line(lx0, ly, lx0 + 12, ly, fill=tr["color"], width=max(2, tr["width"]), dash=dash_pat)
- cv.create_text(lx0 + 15, ly, anchor="w", text=f"{tr['label']}:{v_txt}", font=("Consolas", 8), fill=tr["color"])
- ly += 14
- if ly > py1:
- break
- def redraw_all_chamber_canvases(*_):
- lbl_curve_count.config(text=f"采样点: {len(curve_store)}")
- for cid in CHAMBER_IDS:
- draw_single_chamber_canvas(cid)
- for cid, cv in chamber_canvases.items():
- cv.bind("<Configure>", lambda _e, c=cid: draw_single_chamber_canvas(c))
- def _on_motion(event, c=cid):
- g = chamber_plot_geom.get(c)
- if not g or g["n_pts"] == 0:
- return
- if g["px0"] <= event.x <= g["px1"] and g["py0"] <= event.y <= g["py1"]:
- if g["n_pts"] == 1:
- idx_near = 0
- else:
- rel_x = (event.x - g["px0"]) / max(1.0, g["pw"])
- target_t = g["elapsed"][0] + rel_x * g["t_span"]
- idx_near = min(range(g["n_pts"]), key=lambda i: abs(g["elapsed"][i] - target_t))
- if chamber_hover_idx.get(c) != idx_near:
- chamber_hover_idx[c] = idx_near
- draw_single_chamber_canvas(c)
- elif chamber_hover_idx.get(c) is not None:
- chamber_hover_idx[c] = None
- draw_single_chamber_canvas(c)
- def _on_leave(_event, c=cid):
- if chamber_hover_idx.get(c) is not None:
- chamber_hover_idx[c] = None
- draw_single_chamber_canvas(c)
- cv.bind("<Motion>", _on_motion)
- cv.bind("<Leave>", _on_leave)
- combo_mode.bind("<<ComboboxSelected>>", redraw_all_chamber_canvases)
- combo_win.bind("<<ComboboxSelected>>", redraw_all_chamber_canvases)
- def print_or_export_curves(direct_print: bool = True):
- if not apply_chamber_mapping(silent=False):
- return
- mode, max_pts, ign_zero = _current_mode_and_window()
- ts_tag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
- out_dir = Path(disk_logger.log_dir)
- out_dir.mkdir(parents=True, exist_ok=True)
- png_path = out_dir / f"chamber_curves_{product}_{ts_tag}.png"
- svg_path = out_dir / f"chamber_curves_{product}_{ts_tag}.svg"
- csv_path = out_dir / f"chamber_curves_{product}_{ts_tag}.csv"
- try:
- png_bytes = render_chamber_curves_png(
- curve_store, chamber_mapping, product=product, board=model.board,
- mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
- thermal_session=thermal_session,
- )
- png_path.write_bytes(png_bytes)
- svg_text = render_chamber_curves_svg(
- curve_store, chamber_mapping, product=product, board=model.board,
- mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
- thermal_session=thermal_session,
- )
- svg_path.write_text(svg_text, encoding="utf-8")
- csv_text = export_chamber_curves_csv(
- curve_store, chamber_mapping, max_points=max_pts, ignore_zero_ct=ign_zero,
- )
- csv_path.write_text(csv_text, encoding="utf-8-sig")
- lbl_map_status.config(text=f"已生成图像: {png_path.name}", foreground="#006600")
- if direct_print:
- opened = False
- if sys.platform == "win32":
- try:
- os.startfile(str(png_path))
- opened = True
- except Exception:
- pass
- elif sys.platform == "darwin":
- try:
- subprocess.Popen(["open", str(png_path)])
- opened = True
- except Exception:
- pass
- else:
- try:
- subprocess.Popen(["xdg-open", str(png_path)])
- opened = True
- except Exception:
- pass
- messagebox.showinfo(
- "四腔温度曲线图像已生成",
- f"已直接生成四腔体内存温度与Sensor温度曲线图:\n\n"
- f"• 高清 PNG 图像:\n {png_path}\n"
- f"• 矢量 SVG 图像:\n {svg_path}\n"
- f"• 曲线数据 CSV:\n {csv_path}\n\n"
- + ("已自动调用系统查看器打开图像,可直接查看或 Ctrl+P 打印。" if opened else "可在日志目录中直接打开或打印该图像。"),
- )
- except Exception as exc:
- messagebox.showerror("图像打印/导出失败", str(exc))
- def save_curves_as_dialog():
- if not apply_chamber_mapping(silent=False):
- return
- mode, max_pts, ign_zero = _current_mode_and_window()
- ts_tag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
- path = filedialog.asksaveasfilename(
- title="另存四腔温度曲线图像或数据",
- defaultextension=".png",
- initialfile=f"chamber_curves_{product}_{ts_tag}.png",
- filetypes=[
- ("PNG 高清曲线图", "*.png"),
- ("SVG 矢量曲线图", "*.svg"),
- ("CSV 温度数据表", "*.csv"),
- ],
- )
- if not path:
- return
- target = Path(path)
- try:
- ext = target.suffix.lower()
- if ext == ".svg":
- target.write_text(
- render_chamber_curves_svg(
- curve_store, chamber_mapping, product=product, board=model.board,
- mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
- ),
- encoding="utf-8",
- )
- elif ext == ".csv":
- target.write_text(
- export_chamber_curves_csv(
- curve_store, chamber_mapping, max_points=max_pts, ignore_zero_ct=ign_zero,
- ),
- encoding="utf-8-sig",
- )
- else:
- target.write_bytes(
- render_chamber_curves_png(
- curve_store, chamber_mapping, product=product, board=model.board,
- mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
- )
- )
- lbl_map_status.config(text=f"已另存为: {target.name}", foreground="#006600")
- except Exception as exc:
- messagebox.showerror("另存失败", str(exc))
- def import_log_for_curves():
- path = filedialog.askopenfilename(
- title="导入日志文件生成温度曲线 (支持 pwm_scope JSONL / GUI 会话日志)",
- initialdir=str(disk_logger.log_dir),
- filetypes=[
- ("日志与数据文件", "*.jsonl *.log *.txt"),
- ("所有文件", "*.*"),
- ],
- )
- if not path:
- return
- try:
- count = curve_store.load_from_log_file(Path(path), model=model)
- thermal_session.evaluate_from_store(curve_store, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get())
- refresh_thermal_test_ui()
- redraw_all_chamber_canvases()
- lbl_map_status.config(text=f"从 {Path(path).name} 导入了 {count} 条温度记录", foreground="#006600")
- if count == 0:
- messagebox.showwarning("未找到温度帧", "所选日志文件中未解析到有效的 0x42 GET_DATA 温度记录或 CYCLE 数据。")
- except Exception as exc:
- messagebox.showerror("导入日志失败", str(exc))
- def clear_curves():
- curve_store.clear()
- thermal_session.reset_stats()
- refresh_thermal_test_ui()
- redraw_all_chamber_canvases()
- lbl_map_status.config(text="已清空曲线历史数据与达标统计", foreground="#555555")
- ttk.Button(plot_ctrl_bar, text="🗑 清空曲线", command=clear_curves).pack(side="right", padx=3)
- ttk.Button(plot_ctrl_bar, text="📂 导入日志绘图", command=import_log_for_curves).pack(side="right", padx=3)
- ttk.Button(plot_ctrl_bar, text="💾 另存图像为...", command=save_curves_as_dialog).pack(side="right", padx=3)
- ttk.Button(plot_ctrl_bar, text="🖨 直接打印/导出曲线图 (PNG/SVG)", command=lambda: print_or_export_curves(True)).pack(side="right", padx=4)
- # -----------------------------------------------------------------------
- # TAB 2.5: 高温罩温度测试 (High-Temperature Hood Thermal Test & Fan Study)
- # -----------------------------------------------------------------------
- tab_thermal_test = ttk.Frame(notebook, padding=8)
- notebook.add(tab_thermal_test, text="🔥 高温罩温度测试")
- # Section A: Target Temperature & Pass Minimum Configuration
- tt_target_frame = ttk.LabelFrame(
- tab_thermal_test,
- text="🎯 1. 高温罩四腔预期目标温度与最低通过温度配置 (暂定 70°C;先达标腔体锁定耗时后仍持续记录全部腔体数据)",
- padding=6,
- )
- tt_target_frame.pack(fill="x", pady=3)
- tt_row1 = ttk.Frame(tt_target_frame)
- tt_row1.pack(fill="x", pady=2)
- ttk.Label(tt_row1, text="测试名称:").pack(side="left", padx=2)
- tt_name_var = tk.StringVar(value=f"{model.board} 高温罩升温测试")
- ttk.Entry(tt_row1, textvariable=tt_name_var, width=24).pack(side="left", padx=4)
- ttk.Label(tt_row1, text="高温罩四腔最低通过温度(°C):", font=("", 9, "bold"), foreground="#B45309").pack(side="left", padx=(10, 2))
- tt_pass_min_var = tk.StringVar(value="70")
- ttk.Spinbox(tt_row1, from_=20, to=200, width=5, textvariable=tt_pass_min_var).pack(side="left", padx=2)
- tt_chamber_target_vars: dict[int, tk.StringVar] = {}
- for cid in CHAMBER_IDS:
- ttk.Label(tt_row1, text=f"腔{cid}目标(°C):").pack(side="left", padx=(8, 2))
- v_t = tk.StringVar(value="70")
- tt_chamber_target_vars[cid] = v_t
- ttk.Spinbox(tt_row1, from_=20, to=200, width=5, textvariable=v_t).pack(side="left", padx=2)
- def sync_all_chamber_targets_to_pass_min():
- p_val = tt_pass_min_var.get().strip() or "70"
- for cid in CHAMBER_IDS:
- tt_chamber_target_vars[cid].set(p_val)
- apply_thermal_test_config(recalc=True)
- ttk.Button(tt_row1, text="同步至四腔", command=sync_all_chamber_targets_to_pass_min).pack(side="left", padx=6)
- EVAL_MODE_MAP = {"腔体均温 (AVG)": "avg", "腔体最高 (MAX)": "max", "腔体最低 (MIN)": "min"}
- ttk.Label(tt_row1, text="Sensor判定:").pack(side="left", padx=(8, 2))
- tt_ct_eval_var = tk.StringVar(value="腔体均温 (AVG)")
- ttk.Combobox(tt_row1, textvariable=tt_ct_eval_var, values=list(EVAL_MODE_MAP.keys()), width=13, state="readonly").pack(side="left", padx=2)
- ttk.Label(tt_row1, text="内存判定:").pack(side="left", padx=(6, 2))
- tt_bmc_eval_var = tk.StringVar(value="腔体均温 (AVG)")
- ttk.Combobox(tt_row1, textvariable=tt_bmc_eval_var, values=list(EVAL_MODE_MAP.keys()), width=13, state="readonly").pack(side="left", padx=2)
- # Section B: Fan Speed & Fan Intervention Timing / Reference Temperature Study
- tt_fan_frame = ttk.LabelFrame(
- tab_thermal_test,
- text="🌀 2. 风扇转速与介入时机实验参数 (探究风扇转速、风扇开始介入时间或参考温度与腔体升温达标时间的关系)",
- padding=6,
- )
- tt_fan_frame.pack(fill="x", pady=3)
- tt_row2 = ttk.Frame(tt_fan_frame)
- tt_row2.pack(fill="x", pady=2)
- ttk.Label(tt_row2, text="PTC加热(%):").pack(side="left", padx=2)
- tt_ptc_duty_var = tk.StringVar(value="100")
- ttk.Spinbox(tt_row2, from_=0, to=100, width=4, textvariable=tt_ptc_duty_var).pack(side="left", padx=2)
- ttk.Label(tt_row2, text="SSR加热(%):").pack(side="left", padx=(6, 2))
- tt_ssr_duty_var = tk.StringVar(value="100")
- ttk.Spinbox(tt_row2, from_=0, to=100, width=4, textvariable=tt_ssr_duty_var).pack(side="left", padx=2)
- ttk.Label(tt_row2, text="初始风扇(%):").pack(side="left", padx=(8, 2))
- tt_init_fan_var = tk.StringVar(value="0")
- ttk.Spinbox(tt_row2, from_=0, to=100, width=4, textvariable=tt_init_fan_var).pack(side="left", padx=2)
- ttk.Label(tt_row2, text="介入后风扇(%):", font=("", 9, "bold"), foreground="#153259").pack(side="left", padx=(8, 2))
- tt_active_fan_var = tk.StringVar(value="50")
- ttk.Spinbox(tt_row2, from_=0, to=100, width=4, textvariable=tt_active_fan_var).pack(side="left", padx=2)
- INTERVENTION_MODE_MAP = {
- "按介入时间 (秒)": "time_s",
- "按参考温度 (°C)": "ref_temp_c",
- "立即介入 (0s)": "immediate",
- "仅手动/纯观测": "manual",
- }
- ttk.Label(tt_row2, text="风扇介入方式:").pack(side="left", padx=(8, 2))
- tt_intervene_mode_var = tk.StringVar(value="按介入时间 (秒)")
- ttk.Combobox(tt_row2, textvariable=tt_intervene_mode_var, values=list(INTERVENTION_MODE_MAP.keys()), width=14, state="readonly").pack(side="left", padx=2)
- ttk.Label(tt_row2, text="介入时间(s):").pack(side="left", padx=(6, 2))
- tt_intervene_time_var = tk.StringVar(value="120")
- ttk.Spinbox(tt_row2, from_=0, to=3600, width=5, textvariable=tt_intervene_time_var).pack(side="left", padx=2)
- ttk.Label(tt_row2, text="参考温度(°C):").pack(side="left", padx=(6, 2))
- tt_intervene_temp_var = tk.StringVar(value="55")
- ttk.Spinbox(tt_row2, from_=20, to=200, width=5, textvariable=tt_intervene_temp_var).pack(side="left", padx=2)
- tt_auto_ctrl_var = tk.BooleanVar(value=True)
- ttk.Checkbutton(
- tt_row2,
- text="测试时自动下发SET并轮询GET",
- variable=tt_auto_ctrl_var,
- ).pack(side="left", padx=8)
- # Section C: Controls & Backend Sync Bar
- tt_ctrl_bar = ttk.Frame(tab_thermal_test, padding=3)
- tt_ctrl_bar.pack(fill="x", pady=2)
- lbl_tt_status = ttk.Label(
- tt_ctrl_bar,
- text="状态: 待机 (点击【开始温度测试】或【重新统计当前曲线】计算各腔 Sensor 与内存达标时间)",
- font=("Microsoft YaHei", 9, "bold"),
- foreground="#153259",
- )
- lbl_tt_status.pack(side="left", padx=4)
- tt_backend_url_var = tk.StringVar(value=os.environ.get("PROD2U_THERMAL_BACKEND_URL", "http://192.168.2.25:8766"))
- # Section D: 4-Chamber + Overall Hood Reach-Time Treeview Table
- tt_table_frame = ttk.LabelFrame(
- tab_thermal_test,
- text="⏱️ 3. 各腔体 Sensor(CT) 温度与 内存(BMC) 温度达标时间实时统计表 (先达标腔体持续记录验证)",
- padding=6,
- )
- tt_table_frame.pack(fill="both", expand=True, pady=3)
- tt_cols = (
- "chamber",
- "target",
- "sensor_temps",
- "sensor_time",
- "memory_temps",
- "memory_time",
- "continuous_status",
- )
- tt_tree = ttk.Treeview(tt_table_frame, columns=tt_cols, show="headings", height=6)
- tt_tree.heading("chamber", text="腔体 / 区域")
- tt_tree.heading("target", text="预期目标 / 最低通过")
- tt_tree.heading("sensor_temps", text="Sensor温度 (初始 / 当前 / 峰值)")
- tt_tree.heading("sensor_time", text="Sensor 达到目标耗时")
- tt_tree.heading("memory_temps", text="内存BMC温度 (初始 / 当前 / 峰值)")
- tt_tree.heading("memory_time", text="内存BMC 达到目标耗时")
- tt_tree.heading("continuous_status", text="状态与达标后持续记录点数")
- tt_tree.column("chamber", width=130, anchor="center")
- tt_tree.column("target", width=135, anchor="center")
- tt_tree.column("sensor_temps", width=185, anchor="center")
- tt_tree.column("sensor_time", width=155, anchor="center")
- tt_tree.column("memory_temps", width=185, anchor="center")
- tt_tree.column("memory_time", width=155, anchor="center")
- tt_tree.column("continuous_status", width=210, anchor="center")
- tt_tree.pack(fill="both", expand=True)
- # Section E: Multi-Run Experiment Comparison Table + Backend Bar
- tt_exp_frame = ttk.LabelFrame(
- tab_thermal_test,
- text="🔬 4. 风扇转速 / 介入时间 / 参考温度 vs 升温达标时间多轮实验对比与远程后端 (192.168.2.25)",
- padding=6,
- )
- tt_exp_frame.pack(fill="both", expand=True, pady=3)
- exp_cols = (
- "run_id",
- "fan_cfg",
- "intervene",
- "c1_reach",
- "c2_reach",
- "c3_reach",
- "c4_reach",
- "hood_reach",
- )
- exp_tree = ttk.Treeview(tt_exp_frame, columns=exp_cols, show="headings", height=4)
- exp_tree.heading("run_id", text="实验轮次 / 名称")
- exp_tree.heading("fan_cfg", text="加热 / 风扇转速")
- exp_tree.heading("intervene", text="风扇介入时机 / 温度")
- exp_tree.heading("c1_reach", text="腔1 (Sensor/内存)")
- exp_tree.heading("c2_reach", text="腔2 (Sensor/内存)")
- exp_tree.heading("c3_reach", text="腔3 (Sensor/内存)")
- exp_tree.heading("c4_reach", text="腔4 (Sensor/内存)")
- exp_tree.heading("hood_reach", text="四腔整体通过耗时")
- exp_tree.column("run_id", width=165, anchor="w")
- exp_tree.column("fan_cfg", width=145, anchor="center")
- exp_tree.column("intervene", width=165, anchor="center")
- exp_tree.column("c1_reach", width=125, anchor="center")
- exp_tree.column("c2_reach", width=125, anchor="center")
- exp_tree.column("c3_reach", width=125, anchor="center")
- exp_tree.column("c4_reach", width=125, anchor="center")
- exp_tree.column("hood_reach", width=145, anchor="center")
- exp_tree.pack(fill="both", expand=True, pady=2)
- backend_bar = ttk.Frame(tt_exp_frame)
- backend_bar.pack(fill="x", pady=2)
- ttk.Label(backend_bar, text="远程测试后端地址 (192.168.2.25 容器):").pack(side="left", padx=2)
- ttk.Entry(backend_bar, textvariable=tt_backend_url_var, width=28, font=("Consolas", 9)).pack(side="left", padx=4)
- def apply_thermal_test_config(recalc: bool = False) -> bool:
- try:
- pass_min = float(tt_pass_min_var.get().strip() or "70")
- c_targets = {
- cid: float(tt_chamber_target_vars[cid].get().strip() or "70")
- for cid in CHAMBER_IDS
- }
- thermal_session.test_name = tt_name_var.get().strip() or f"{model.board} 高温罩升温测试"
- thermal_session.bmc_eval_mode = EVAL_MODE_MAP.get(tt_bmc_eval_var.get(), "avg")
- thermal_session.ct_eval_mode = EVAL_MODE_MAP.get(tt_ct_eval_var.get(), "avg")
- thermal_session.ptc_duty_percent = max(0, min(100, int(float(tt_ptc_duty_var.get() or "100"))))
- thermal_session.ssr_duty_percent = max(0, min(100, int(float(tt_ssr_duty_var.get() or "100"))))
- thermal_session.initial_fan_duty_percent = max(0, min(100, int(float(tt_init_fan_var.get() or "0"))))
- thermal_session.active_fan_duty_percent = max(0, min(100, int(float(tt_active_fan_var.get() or "50"))))
- thermal_session.fan_intervention_mode = INTERVENTION_MODE_MAP.get(tt_intervene_mode_var.get(), "time_s")
- thermal_session.fan_intervention_time_s = max(0.0, float(tt_intervene_time_var.get() or "120"))
- thermal_session.fan_intervention_ref_temp_c = float(tt_intervene_temp_var.get() or "55")
- thermal_session.backend_url = tt_backend_url_var.get().strip()
- thermal_session.set_targets(pass_min, c_targets)
- if recalc:
- thermal_session.evaluate_from_store(curve_store, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get())
- refresh_thermal_test_ui()
- redraw_all_chamber_canvases()
- return True
- except Exception as exc:
- messagebox.showerror("温度测试参数错误", str(exc))
- return False
- def refresh_thermal_test_ui():
- for item in tt_tree.get_children():
- tt_tree.delete(item)
- rep = thermal_session.summary()
- for cid in CHAMBER_IDS:
- st = thermal_session.chamber_stats[cid]
- s_t_txt = (
- f"{st['sensor_initial_c'] or '--'} / {st['sensor_current_c'] or '--'} / {st['sensor_peak_c'] or '--'} °C"
- )
- m_t_txt = (
- f"{st['memory_initial_c'] or '--'} / {st['memory_current_c'] or '--'} / {st['memory_peak_c'] or '--'} °C"
- )
- s_reach_txt = (
- f"✅ {format_duration_mmss(st['sensor_time_to_target_s'])}"
- if st["sensor_reached"]
- else "⏳ 未达标"
- )
- m_reach_txt = (
- f"✅ {format_duration_mmss(st['memory_time_to_target_s'])}"
- if st["memory_reached"]
- else "⏳ 未达标"
- )
- if st["both_reached"]:
- status_txt = f"✅ 双达标 (持续记录 +{st['post_target_samples']} 点)"
- elif st["sensor_reached"] or st["memory_reached"]:
- status_txt = f"🌓 单项达标 (持续记录 +{st['post_target_samples']} 点)"
- else:
- status_txt = "🔥 加热升温中..." if thermal_session.active else "待达标"
- tt_tree.insert(
- "",
- "end",
- values=(
- f"腔体 {cid}",
- f"目标 {st['target_temp_c']:.0f}°C / 通过≥{st['pass_min_temp_c']:.0f}°C",
- s_t_txt,
- s_reach_txt,
- m_t_txt,
- m_reach_txt,
- status_txt,
- ),
- )
- hs = rep["hood_summary"]
- first_info = rep["first_reached"]
- first_str = (
- f"腔{first_info['chamber_id']}于{first_info['elapsed_s']:.1f}s率先达标,已持续追记+{first_info['total_post_target_samples']}点"
- if first_info["chamber_id"] is not None
- else "尚无腔体达标"
- )
- tt_tree.insert(
- "",
- "end",
- values=(
- "🏆 高温罩四腔汇总",
- f"四腔最低通过 ≥{thermal_session.overall_pass_min_temp_c:.0f}°C",
- f"已达标: {hs['sensor_reached_count']}/4 腔",
- f"🌟 {format_duration_mmss(hs['hood_sensor_reach_time_s'])}" if hs["sensor_all_4_reached"] else f"{hs['sensor_reached_count']}/4 达标",
- f"已达标: {hs['memory_reached_count']}/4 腔",
- f"🌟 {format_duration_mmss(hs['hood_memory_reach_time_s'])}" if hs["memory_all_4_reached"] else f"{hs['memory_reached_count']}/4 达标",
- first_str,
- ),
- )
- exp = rep["experiment_params"]
- fan_badge = (
- f"风扇已介入({exp['active_fan_duty_percent']}% @ {exp['fan_intervened_reason']})"
- if exp["fan_intervened"]
- else f"风扇待介入(当前{exp['current_fan_duty_percent']}% -> 目标{exp['active_fan_duty_percent']}%)"
- )
- state_word = "🟢 正在测试 (持续记录中)" if thermal_session.active else "⚪ 未运行/已完成"
- lbl_tt_status.config(
- text=f"{state_word} | 已耗时: {rep['elapsed_total_s']:.1f}s | 样本: {rep['sample_count']} | {fan_badge}"
- )
- def send_thermal_test_set(note_prefix: str = "温度测试自动控制"):
- vals = thermal_session.build_set_values(model)
- for i, v in enumerate(vals):
- if i < len(set_vars):
- set_vars[i].set(str(v))
- with serial_lock:
- sp = serial_port_obj
- if sp and sp.is_open and tt_auto_ctrl_var.get():
- try:
- f = model.set_all(vals)
- request_queue.put(("SET", f, f"{note_prefix}: PTC={thermal_session.ptc_duty_percent}% FAN={thermal_session.current_fan_duty_percent}%"))
- dispatch_next_request()
- except Exception as exc:
- append_log("ERR", "", f"温度测试下发 SET 失败: {exc}")
- def start_thermal_test():
- if not apply_thermal_test_config(recalc=False):
- return
- curve_store.clear()
- thermal_session.start()
- refresh_thermal_test_ui()
- redraw_all_chamber_canvases()
- send_thermal_test_set("温度测试启动阶段")
- with serial_lock:
- sp = serial_port_obj
- if sp and sp.is_open and tt_auto_ctrl_var.get() and not poll_var.get():
- poll_var.set(True)
- on_poll_toggle()
- def stop_thermal_test():
- thermal_session.stop()
- record_run_to_comparison_table()
- refresh_thermal_test_ui()
- def record_run_to_comparison_table():
- rep = thermal_session.summary()
- exp = rep["experiment_params"]
- hs = rep["hood_summary"]
- experiment_history.append(rep)
- fan_cfg = f"PTC{exp['ptc_duty_percent']}% | 风扇{exp['initial_fan_duty_percent']}%→{exp['active_fan_duty_percent']}%"
- if exp["fan_intervened"]:
- intervene_txt = f"{exp['fan_intervened_elapsed_s']:.0f}s / {exp['fan_intervened_temp_c'] or '--'}°C"
- elif exp["fan_intervention_mode"] == "time_s":
- intervene_txt = f"定时 {exp['fan_intervention_time_s']:.0f}s"
- elif exp["fan_intervention_mode"] == "ref_temp_c":
- intervene_txt = f"定温 {exp['fan_intervention_ref_temp_c']:.0f}°C"
- else:
- intervene_txt = exp["fan_intervention_mode"]
- def ch_pair(c_id: int) -> str:
- st_c = thermal_session.chamber_stats[c_id]
- s_v = f"{st_c['sensor_time_to_target_s']:.0f}s" if st_c["sensor_time_to_target_s"] is not None else "--"
- m_v = f"{st_c['memory_time_to_target_s']:.0f}s" if st_c["memory_time_to_target_s"] is not None else "--"
- return f"S:{s_v} / M:{m_v}"
- hood_txt = (
- f"S:{hs['hood_sensor_reach_time_s'] or '--'}s / M:{hs['hood_memory_reach_time_s'] or '--'}s"
- )
- exp_tree.insert(
- "",
- "end",
- values=(
- f"{rep['session_id']} ({rep['test_name'][:10]})",
- fan_cfg,
- intervene_txt,
- ch_pair(1),
- ch_pair(2),
- ch_pair(3),
- ch_pair(4),
- hood_txt,
- ),
- )
- def export_thermal_test_report():
- if not apply_thermal_test_config(recalc=False):
- return
- if thermal_session.sample_count == 0 and len(curve_store) > 0:
- thermal_session.evaluate_from_store(curve_store, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get())
- refresh_thermal_test_ui()
- ts_tag = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
- out_dir = Path(disk_logger.log_dir)
- out_dir.mkdir(parents=True, exist_ok=True)
- json_path = out_dir / f"thermal_test_report_{product}_{ts_tag}.json"
- csv_path = out_dir / f"thermal_test_summary_{product}_{ts_tag}.csv"
- png_path = out_dir / f"thermal_test_curves_{product}_{ts_tag}.png"
- try:
- mode, max_pts, ign_zero = _current_mode_and_window()
- full_report = {
- "report": thermal_session.summary(),
- "mapping": chamber_mapping.to_dict(),
- "experiment_history": experiment_history,
- }
- json_path.write_text(json.dumps(full_report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- csv_path.write_text(thermal_session.export_summary_csv(), encoding="utf-8-sig")
- png_path.write_bytes(
- render_chamber_curves_png(
- curve_store, chamber_mapping, product=product, board=model.board,
- mode=mode, max_points=max_pts, ignore_zero_ct=ign_zero,
- thermal_session=thermal_session,
- )
- )
- messagebox.showinfo(
- "温度测试报告已导出",
- f"已导出高温罩四腔温度测试报告:\n\n"
- f"• JSON 详细报告:\n {json_path}\n"
- f"• CSV 达标时间统计表:\n {csv_path}\n"
- f"• PNG 带目标温度线四腔曲线图:\n {png_path}",
- )
- except Exception as exc:
- messagebox.showerror("导出温度测试报告失败", str(exc))
- def sync_thermal_test_to_backend():
- if not apply_thermal_test_config(recalc=False):
- return
- if thermal_session.sample_count == 0 and len(curve_store) > 0:
- thermal_session.evaluate_from_store(curve_store, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get())
- refresh_thermal_test_ui()
- try:
- res = thermal_session.sync_to_backend(
- curve_store, chamber_mapping, backend_url=tt_backend_url_var.get().strip()
- )
- record_run_to_comparison_table()
- messagebox.showinfo(
- "已同步至远程测试后端",
- f"测试数据已成功上传至后端 ({tt_backend_url_var.get().strip()}):\n"
- f"会话 ID: {res.get('session_id', thermal_session.session_id)}\n"
- f"当前后端累计实验组数: {res.get('total_runs', '--')}",
- )
- except Exception as exc:
- messagebox.showerror(
- "同步远程后端失败",
- f"无法连接温度测试后端 {tt_backend_url_var.get().strip()}:\n{exc}\n\n"
- f"请确认 192.168.2.25 容器内 thermal_test_server.py 已启动。",
- )
- def open_thermal_web_frontend():
- import webbrowser
- url = tt_backend_url_var.get().strip() or "http://192.168.2.25:8766"
- webbrowser.open(url)
- ttk.Button(tt_ctrl_bar, text="📊 导出测试报告(JSON/CSV/PNG)", command=export_thermal_test_report).pack(side="right", padx=3)
- ttk.Button(tt_ctrl_bar, text="📌 记录至对比表", command=record_run_to_comparison_table).pack(side="right", padx=3)
- ttk.Button(tt_ctrl_bar, text="🔄 重新统计当前曲线", command=lambda: apply_thermal_test_config(recalc=True)).pack(side="right", padx=3)
- ttk.Button(tt_ctrl_bar, text="⏹ 停止温度测试", command=stop_thermal_test).pack(side="right", padx=3)
- ttk.Button(tt_ctrl_bar, text="▶️ 开始温度测试 (持续记录)", command=start_thermal_test).pack(side="right", padx=3)
- ttk.Button(backend_bar, text="☁️ 同步当前测试至后端", command=sync_thermal_test_to_backend).pack(side="left", padx=4)
- ttk.Button(backend_bar, text="🌐 打开网页前端 (查看/对比/导出)", command=open_thermal_web_frontend).pack(side="left", padx=4)
- refresh_thermal_test_ui()
- # Quick jump buttons on Tab 1 control bar
- ttk.Button(
- ctrl_bar,
- text="🔥 高温罩温度测试",
- command=lambda: (notebook.select(tab_thermal_test), refresh_thermal_test_ui()),
- ).pack(side="right", padx=4)
- ttk.Button(
- ctrl_bar,
- text="📈 腔体温度曲线 / 图像打印",
- command=lambda: (notebook.select(tab_curves), redraw_all_chamber_canvases()),
- ).pack(side="right", padx=4)
- # -----------------------------------------------------------------------
- # TAB 3: SET 命令生成与下发 (SET_ALL Builder & Decoder)
- # -----------------------------------------------------------------------
- if product == "6400-v2":
- tab_set_view = ttk.Frame(notebook)
- notebook.add(tab_set_view, text="⚙️ SET 命令生成与解析")
- set_scroll = ttk.Scrollbar(tab_set_view, orient="vertical")
- set_scroll.pack(side="right", fill="y")
- set_canvas = tk.Canvas(tab_set_view, highlightthickness=0, yscrollcommand=set_scroll.set)
- set_canvas.pack(side="left", fill="both", expand=True)
- set_scroll.config(command=set_canvas.yview)
- tab_set = ttk.Frame(set_canvas, padding=10)
- set_window = set_canvas.create_window((0, 0), window=tab_set, anchor="nw")
- tab_set.bind("<Configure>", lambda event: set_canvas.configure(scrollregion=set_canvas.bbox("all")))
- set_canvas.bind("<Configure>", lambda event: set_canvas.itemconfigure(set_window, width=event.width))
- else:
- tab_set = ttk.Frame(notebook, padding=10)
- notebook.add(tab_set, text="⚙️ SET 命令生成与解析")
- ttk.Label(tab_set, text=f"{model.board} ({product}) — 输出通道百分比设置 (0..100 %)", font=("", 11, "bold")).pack(anchor="w", pady=4)
- set_vars = []
- for grp, cnt, default in model.groups():
- frame_grp = ttk.LabelFrame(tab_set, text=f"{model.group_label(grp)} 通道 ({cnt} 路)", padding=6)
- frame_grp.pack(fill="x", pady=4)
- grp_vars = []
- # Batch preset bar for large channel groups (e.g. PTC 24 channels)
- if cnt >= 8:
- preset_bar = ttk.Frame(frame_grp)
- preset_bar.pack(fill="x", pady=2)
- ttk.Label(preset_bar, text=f"快捷预设全部 {grp}:", font=("", 9, "bold")).pack(side="left", padx=4)
- def make_set_all_fn(vs, val):
- def fn():
- for v in vs:
- v.set(str(val))
- return fn
- for p_val in (0, 20, 50, 100):
- ttk.Button(preset_bar, text=f"全设 {p_val}%", width=8,
- command=make_set_all_fn(grp_vars, p_val)).pack(side="left", padx=2)
- # Multi-column grid for channels (8 cols for 24 channels -> 3 rows of 8)
- grid_frame = ttk.Frame(frame_grp)
- grid_frame.pack(fill="x", pady=2)
- cols = 8 if cnt >= 16 else (4 if cnt <= 4 else 6)
- if product == "6400-v2":
- cols = 6 if grp == "PTC" else (2 if grp in FAN_GROUP_NAMES else 3)
- for i in range(cnt):
- row = i // cols
- col = i % cols
- cell = ttk.Frame(grid_frame)
- cell.grid(row=row, column=col, padx=4, pady=2, sticky="w")
- label_text = model.output_label(grp, i) + ":"
- label_width = 24 if product == "6400-v2" and grp in (*FAN_GROUP_NAMES, "SSR") else 7
- ttk.Label(cell, text=label_text, width=label_width, font=("Consolas", 9)).pack(side="left")
- var = tk.StringVar(value=str(default))
- set_vars.append(var)
- grp_vars.append(var)
- ttk.Spinbox(cell, from_=0, to=100, width=4, textvariable=var).pack(side="left")
- ttk.Label(cell, text="%", font=("Consolas", 8), foreground="gray").pack(side="left")
- axis_slots = []
- if model.motor:
- frame_motor = ttk.LabelFrame(tab_set, text="12 轴运动段配置 (每轴 5 字节: action + steps:u16le + half_us:u16le)", padding=6)
- frame_motor.pack(fill="x", pady=4)
- ttk.Label(frame_motor, text="不同轴可同时运行;同一轴收到 MOTOR_DONE 后再 PUSH,或先 STOP_CLEAR。发送后动作自动回 NOTHING,温控值保留。",
- foreground="#555555").pack(anchor="w", pady=2)
- for ax in range(12):
- ax_frame = ttk.Frame(frame_motor)
- ax_frame.pack(anchor="w", pady=2)
- ttk.Label(ax_frame, text=f"{MRDIMM_AXIS_NAMES[ax]}: ", width=24, font=("Consolas", 9)).pack(side="left")
- act_var = tk.StringVar(value="NOTHING")
- ttk.Combobox(ax_frame, textvariable=act_var, values=("NOTHING", "PUSH_DOWN", "PUSH_UP", "STOP_CLEAR"), width=11, state="readonly").pack(side="left", padx=2)
- ttk.Label(ax_frame, text="步数:").pack(side="left", padx=2)
- steps_var = tk.StringVar(value="0")
- ttk.Entry(ax_frame, textvariable=steps_var, width=7).pack(side="left", padx=2)
- ttk.Label(ax_frame, text="半周期(us):").pack(side="left", padx=2)
- half_var = tk.StringVar(value="0")
- ttk.Entry(ax_frame, textvariable=half_var, width=7).pack(side="left", padx=2)
- axis_slots.append({"action_var": act_var, "steps_var": steps_var, "half_var": half_var})
- buzzer_var = tk.BooleanVar(value=False)
- if product in ("6400-v2", "mrdimm-chamber"):
- frame_buz = ttk.LabelFrame(tab_set, text="🔔 蜂鸣器触发控制 (SET_ALL 末尾字节,CON146.1/H6;开启输出 4000Hz 80% 占空比方波,看门狗超时自动关闭)", padding=6)
- frame_buz.pack(fill="x", pady=4)
- ttk.Checkbutton(frame_buz, text="触发蜂鸣器开启 (1=ON 4000Hz/80%, 0=OFF)", variable=buzzer_var).pack(side="left", padx=6)
- # Generated SET frame display
- frame_set_res = ttk.LabelFrame(tab_set, text="生成的 SET_ALL 命令报文 (HEX 与逐字段拆解)", padding=8)
- frame_set_res.pack(fill="both", expand=True, pady=6)
- set_btn_bar = ttk.Frame(frame_set_res)
- set_btn_bar.pack(fill="x", pady=2)
- text_set_hex = tk.Text(frame_set_res, height=3, wrap="char", font=("Consolas", 10, "bold"), foreground="#003399")
- text_set_hex.pack(fill="x", pady=4)
- text_set_explain = tk.Text(frame_set_res, height=10, wrap="word", font=("Consolas", 9))
- text_set_explain.pack(fill="both", expand=True, pady=4)
- def do_generate_set() -> bytes:
- vals = [int(v.get()) for v in set_vars]
- motor_reqs = None
- if model.motor:
- act_map = {"NOTHING": 0, "PUSH_DOWN": 1, "PUSH_UP": 2, "STOP_CLEAR": 255}
- motor_reqs = [
- {
- "action": act_map[s["action_var"].get()],
- "steps": int(s["steps_var"].get()),
- "half_period_us": int(s["half_var"].get()),
- }
- for s in axis_slots
- ]
- f = model.set_all(vals, motor_reqs, buzzer=1 if buzzer_var.get() else 0)
- text_set_hex.delete("1.0", "end")
- text_set_hex.insert("1.0", frame_hex(f))
- exp = model.explain(f)
- text_set_explain.delete("1.0", "end")
- text_set_explain.insert("end", f"【报文概览】: {exp['summary']}\n")
- text_set_explain.insert("end", f"【帧类型】: {exp['type']} | 【载荷长度】: {exp['length']} | 【CRC-16/CCITT-FALSE】: {exp['crc_hex']} ({exp['crc_status']})\n")
- text_set_explain.insert("end", "【逐通道明细】:\n")
- for fld in exp.get("fields", []):
- text_set_explain.insert("end", f" • {fld}\n")
- return f
- ttk.Button(set_btn_bar, text="🔨 生成 SET_ALL 命令", command=do_generate_set).pack(side="left", padx=4)
- # -----------------------------------------------------------------------
- # TAB 3: GET 命令生成与解析 (GET_ALL & GET_DATA Decoder)
- # -----------------------------------------------------------------------
- tab_get = ttk.Frame(notebook, padding=10)
- notebook.add(tab_get, text="📊 GET 命令生成与解析")
- # Command Generator block
- frame_get_cmd = ttk.LabelFrame(tab_get, text="1. GET_ALL 查询命令生成", padding=8)
- frame_get_cmd.pack(fill="x", pady=4)
- get_cmd_bar = ttk.Frame(frame_get_cmd)
- get_cmd_bar.pack(fill="x")
- ttk.Label(get_cmd_bar, text="标准 GET_ALL 请求报文 (HEX):", font=("", 10, "bold")).pack(side="left", padx=4)
- lbl_get_hex = ttk.Label(get_cmd_bar, text="A5 5A 02 00 6D 7B", font=("Consolas", 11, "bold"), foreground="#0066CC")
- lbl_get_hex.pack(side="left", padx=8)
- lbl_get_desc = ttk.Label(frame_get_cmd, text="解析: 同步头=A5 5A | 帧类型=0x02 (GET_ALL) | 载荷长度=0x00 | CRC16=0x6D 0x7B (低字节在先) | 语义: 请求单板返回实时占空比、BMC 24 通道与 CT7428 27 通道温度", foreground="#555555")
- lbl_get_desc.pack(anchor="w", pady=2)
- # Response Decoder block
- frame_get_resp = ttk.LabelFrame(tab_get, text="2. GET 响应报文解析 (支持粘贴 GET_ACK、GET_DATA 或连续流)", padding=8)
- frame_get_resp.pack(fill="both", expand=True, pady=6)
- ttk.Label(frame_get_resp, text="粘贴单板返回的 HEX 响应:").pack(anchor="w")
- text_get_resp_in = tk.Text(frame_get_resp, height=3, wrap="char", font=("Consolas", 9))
- text_get_resp_in.pack(fill="x", pady=4)
- resp_btn_bar = ttk.Frame(frame_get_resp)
- resp_btn_bar.pack(fill="x", pady=2)
- text_get_resp_out = tk.Text(frame_get_resp, height=15, wrap="word", font=("Consolas", 9))
- text_get_resp_out.pack(fill="both", expand=True, pady=4)
- def do_parse_get_resp(raw_hex_str: str | None = None):
- raw = (raw_hex_str if raw_hex_str is not None else text_get_resp_in.get("1.0", "end")).strip()
- if not raw:
- return
- try:
- data = parse_hex(raw)
- parsed_list = model.parse(data)
- text_get_resp_out.delete("1.0", "end")
- for idx, item in enumerate(parsed_list):
- kind = item.get("kind")
- if kind == "ack":
- text_get_resp_out.insert("end", f"=== [帧 {idx+1}] {item.get('type')} ===\n")
- text_get_resp_out.insert("end", "单板已确认受理查询请求 (GET_ACK 0x82),随后将传输 GET_DATA 状态帧。\n\n")
- elif kind == "status":
- state = item.get("state", {})
- text_get_resp_out.insert("end", f"=== [帧 {idx+1}] GET_DATA (0x42) 详细解码 ===\n")
- # Show duties
- groups = model.groups()
- for grp, cnt, _ in groups:
- duties = state.get(grp.lower(), [])
- if cnt >= 8:
- text_get_resp_out.insert("end", f"【{grp} 实际生效占空比 (共 {len(duties)} 路)】:\n")
- line = ""
- for i, val in enumerate(duties):
- line += f" {grp}{i:02d}: {val:3d} %"
- if (i + 1) % 6 == 0:
- text_get_resp_out.insert("end", line + "\n")
- line = ""
- else:
- line += " | "
- if line:
- text_get_resp_out.insert("end", line.rstrip(" | ") + "\n")
- else:
- ch_strs = [f"{model.output_label(grp, i)}: {v}%" for i, v in enumerate(duties)]
- text_get_resp_out.insert("end", f"【{model.group_label(grp)} 实际生效占空比 ({len(duties)} 路)】: {' | '.join(ch_strs)}\n")
- if model.motor:
- lm = state.get("lower_limit_mask", 0)
- um = state.get("upper_limit_mask", 0)
- text_get_resp_out.insert("end", f"【限位状态】: 下限位掩码=0x{lm:04X} (二进制={lm:012b}), 上限位掩码=0x{um:04X} (二进制={um:012b})\n")
- for ax in range(12):
- l_act = "触发阻断" if (lm & (1 << ax)) else "正常"
- u_act = "触发阻断" if (um & (1 << ax)) else "正常"
- if (lm & (1 << ax)) or (um & (1 << ax)):
- ax_lbl = MRDIMM_AXIS_NAMES[ax] if ax < len(MRDIMM_AXIS_NAMES) else f"Axis{ax}"
- text_get_resp_out.insert("end", f" • {ax_lbl}: 下限位={l_act}, 上限位={u_act}\n")
- if product == "6400-v2":
- epb_txt = "按下(1)" if state.get("estop_btn") else "未按(0)"
- sb1_txt = "按下(1)" if state.get("hood_open_btn") else "未按(0)"
- sb2_txt = "按下(1)" if state.get("hood_close_btn") else "未按(0)"
- buz_txt = "开启 4000Hz/80%(1)" if state.get("buzzer") else "关闭(0)"
- text_get_resp_out.insert(
- "end",
- f"【按钮检测 (仅GET_ALL)】: 急停EPB1(F8)={epb_txt} | 开罩SB1(C11)={sb1_txt} | 合罩SB2(A11)={sb2_txt} | 【蜂鸣器(H6)】: {buz_txt}\n",
- )
- elif product == "mrdimm-chamber":
- hood_txt = "按下 (高电平=1)" if state.get("hood_switch") else "未按下/默认 (低电平=0)"
- buz_txt = "开启 4000Hz/80%(1)" if state.get("buzzer") else "关闭 (0)"
- text_get_resp_out.insert("end", f"【高温罩开关检测】: {hood_txt} | 【蜂鸣器状态】: {buz_txt}\n")
- # Temperatures
- bmc = state.get("bmc", {}).get("temperature_c", [])
- ct = state.get("ct", {}).get("temperature_c", [])
- bmc_valid_cnt = sum(1 for t in bmc if t is not None)
- if bmc_valid_cnt == 0:
- bmc_status_note = " (尚无有效采样;0xFF)"
- else:
- bmc_status_note = f" ({bmc_valid_cnt}/24 通道已就绪)"
- text_get_resp_out.insert("end", f"\n【BMC 24 通道温度遥测】{bmc_status_note}:\n")
- for i, t in enumerate(bmc):
- t_str = f"{t:3d} °C" if t is not None else "--(无效/未采样)"
- text_get_resp_out.insert("end", f" BMC{i:02d}: {t_str}" + ("\n" if (i + 1) % 6 == 0 else " | "))
- text_get_resp_out.insert("end", "\n【CT7428 27 通道温度遥测】:\n")
- for i, t in enumerate(ct):
- t_str = f"{t:3d} °C" if t is not None else "--(无效/未采样)"
- text_get_resp_out.insert("end", f" CT{i:02d}: {t_str}" + ("\n" if (i + 1) % 6 == 0 else " | "))
- text_get_resp_out.insert("end", "\n【四腔映射温度汇总 (可配置映射)】:\n")
- text_get_resp_out.insert(
- "end",
- " " + chamber_mapping.format_realtime_summary(state, ignore_zero_ct=ignore_zero_ct_var.get()) + "\n\n",
- )
- if raw_hex_str is None:
- sample_rec = curve_store.record_state(state)
- tt_evt = thermal_session.process_sample(
- sample_rec, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get()
- )
- if thermal_session.active and tt_evt.get("fan_switched_now"):
- send_thermal_test_set("风扇到达介入条件自动调速")
- refresh_thermal_test_ui()
- lbl_realtime_chambers.config(
- text="【四腔实时温度 (可配置映射)】: "
- + chamber_mapping.format_realtime_summary(state, ignore_zero_ct=ignore_zero_ct_var.get())
- )
- redraw_all_chamber_canvases()
- else:
- text_get_resp_out.insert("end", f"=== [帧 {idx+1}] {item} ===\n\n")
- except Exception as exc:
- text_get_resp_out.delete("1.0", "end")
- text_get_resp_out.insert("1.0", f"解析失败: {exc}")
- ttk.Button(resp_btn_bar, text="🔍 解析 GET 响应", command=lambda: do_parse_get_resp()).pack(side="left", padx=4)
- # -----------------------------------------------------------------------
- # TAB 4: 通用报文检查器 (Universal Frame Inspector)
- # -----------------------------------------------------------------------
- tab_inspect = ttk.Frame(notebook, padding=10)
- notebook.add(tab_inspect, text="🔬 通用报文检查器 (Inspector)")
- ttk.Label(tab_inspect, text="输入或粘贴任意 HEX 报文(支持空格、冒号分隔,不区分大小写):", font=("", 10, "bold")).pack(anchor="w")
- text_insp_in = tk.Text(tab_inspect, height=4, wrap="char", font=("Consolas", 10))
- text_insp_in.pack(fill="x", pady=4)
- # Quick golden templates bar
- quick_bar = ttk.LabelFrame(tab_inspect, text="快速载入标准 Golden 帧测试模板", padding=6)
- quick_bar.pack(fill="x", pady=4)
- def load_template(hex_str: str):
- text_insp_in.delete("1.0", "end")
- text_insp_in.insert("1.0", hex_str)
- do_inspect()
- ttk.Button(quick_bar, text="GET_ALL 请求", command=lambda: load_template("A5 5A 02 00 6D 7B")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="SET_ACK 应答", command=lambda: load_template("A5 5A 81 00 A6 35")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="GET_ACK 应答", command=lambda: load_template("A5 5A 82 00 F5 60")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="心跳请求(Ping)", command=lambda: load_template("A5 5A 03 00 5C 48")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="心跳应答(Pong)", command=lambda: load_template("A5 5A 83 00 C4 53")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="NACK 队列满", command=lambda: load_template("A5 5A C0 02 01 04 B1 2A")).pack(side="left", padx=3)
- if model.motor:
- ttk.Button(quick_bar, text="MOTOR_DONE(上限位4387步)", command=lambda: load_template("A5 5A 50 04 04 02 23 11 B6 02")).pack(side="left", padx=3)
- ttk.Button(quick_bar, text="MOTOR_DONE(双限位0步)", command=lambda: load_template("A5 5A 50 04 04 03 00 00 23 64")).pack(side="left", padx=3)
- else:
- ttk.Button(quick_bar, text="6400 安全 SET 帧", command=lambda: load_template(frame_hex(model.set_all([default for _, count, default in model.groups() for _ in range(count)])))).pack(side="left", padx=3)
- # Inspector output
- insp_out_frame = ttk.LabelFrame(tab_inspect, text="报文逐字节解析与语义拆解", padding=8)
- insp_out_frame.pack(fill="both", expand=True, pady=4)
- text_insp_out = tk.Text(insp_out_frame, wrap="word", font=("Consolas", 10))
- text_insp_out.pack(fill="both", expand=True)
- def do_inspect():
- raw_text = text_insp_in.get("1.0", "end").strip()
- if not raw_text:
- return
- try:
- raw_bytes = parse_hex(raw_text)
- exp = model.explain(raw_bytes)
- text_insp_out.delete("1.0", "end")
- text_insp_out.insert("end", f"【原始 HEX】: {exp['hex']}\n")
- text_insp_out.insert("end", f"【帧类型】: {exp['type']}\n")
- text_insp_out.insert("end", f"【载荷长度】: {exp['length']}\n")
- text_insp_out.insert("end", f"【CRC-16 校验码】: {exp['crc_hex']} -> {exp['crc_status']}\n")
- text_insp_out.insert("end", f"【业务含义总结】: {exp['summary']}\n")
- text_insp_out.insert("end", "-" * 70 + "\n")
- text_insp_out.insert("end", "【字段详细拆解】:\n")
- for f in exp.get("fields", []):
- text_insp_out.insert("end", f" • {f}\n")
- except Exception as exc:
- text_insp_out.delete("1.0", "end")
- text_insp_out.insert("1.0", f"报文解析异常: {exc}")
- ttk.Button(tab_inspect, text="🚀 立即解码报文", command=do_inspect).pack(pady=4)
- # -----------------------------------------------------------------------
- # TAB 5: 构建与工程信息 (Build & Info)
- # -----------------------------------------------------------------------
- tab_info = ttk.Frame(notebook, padding=10)
- notebook.add(tab_info, text="ℹ️ 构建与协议信息")
- text_info = tk.Text(tab_info, height=18, font=("Consolas", 10))
- text_info.pack(fill="both", expand=True)
- info_dict = {
- "product": product,
- "board": model.board,
- "device": "EF2L45BG256B",
- "clock_hz": 25000000,
- "release_version": model.release_version,
- "firmware_host_baud": model.host_baud,
- "selectable_host_baud": list(HOST_BAUDRATES),
- "bmc_baud": 115200,
- "auto_output": "0x51 自发信标" if model.motor else ("每秒 0x42 状态 + 0x52 芯片诊断" if product == "6400-v2" else "0x42 自动状态遥测,GET_ACK 后的数据才完成查询"),
- "motor_usage": "每轴 1 个未完成动作;不同轴可并行;同轴等待 DONE 或先 STOP_CLEAR,发送后动作回 NOTHING" if model.motor else "无电机",
- "wire_format": "8N1",
- "wire_framing": "A5 5A | TYPE:u8 | LENGTH:u8 | PAYLOAD | CRC_L:u8 | CRC_H:u8",
- "crc_algorithm": "CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF, refin/refout false, xorout 0x0000, LSB first)",
- "watchdog_timeout_sec": 30,
- "temperature_representation": "单字节 uint8 摄氏度 (00..FE = 0..254 °C, FF = 无效)",
- "contract_sha256": model.contract.get("contract_sha256"),
- "metadata": model.metadata,
- }
- text_info.insert("1.0", json.dumps(info_dict, ensure_ascii=False, indent=2))
- # -----------------------------------------------------------------------
- # Serial Port Handler & Background Thread
- # -----------------------------------------------------------------------
- def serial_read_loop(my_epoch: int):
- nonlocal serial_port_obj
- receiver.clear()
- while True:
- if my_epoch != connection_epoch:
- break
- with serial_lock:
- sp = serial_port_obj
- if sp is None or not sp.is_open:
- break
- try:
- waiting = sp.in_waiting
- if waiting > 0:
- chunk = sp.read(waiting)
- if chunk:
- events = receiver.feed_bytes(chunk)
- for evt_type, data in events:
- if evt_type == "RX_RAW":
- root.after(0, append_log, "RX_RAW", data.hex(" ").upper(), f"底层串口读取 {len(data)} 字节")
- elif evt_type == "DISCARDED_NOISE":
- try:
- text = data.decode("ascii", errors="replace").strip()
- # If printable ASCII text, display as BMC diagnostic log
- if text and any(c.isalnum() for c in text):
- root.after(0, append_log, "BOARD_DIAG", text, "板端自动调试文本/回显")
- else:
- root.after(0, append_log, "NOISE", data.hex(" ").upper(), f"过滤无效字节 ({len(data)} 字节)")
- except Exception:
- root.after(0, append_log, "NOISE", data.hex(" ").upper(), f"过滤无效字节 ({len(data)} 字节)")
- elif evt_type == "FRAME_REJECTED":
- rej_data = data["data"].hex(" ").upper() if isinstance(data, dict) and "data" in data else ""
- rej_reason = data["reason"] if isinstance(data, dict) and "reason" in data else str(data)
- root.after(0, append_log, "RX_ERR", rej_data, f"报文拒绝: {rej_reason}")
- root.after(0, lbl_realtime_stat.config, {"text": f"报文拒绝: {rej_reason}"})
- elif evt_type == "FRAME_VALID":
- frame_bytes = data["frame_bytes"]
- ftype = data["frame_type"]
- payload = data["payload"]
- exp = model.explain(frame_bytes)
- tx_res = tracker.on_valid_frame(ftype, payload)
- rx_tag = "RX_AUTO" if tx_res["status_code"] in ("UNSOLICITED_DATA", "BEACON", "DIAGNOSTIC") else "RX"
- root.after(0, append_log, rx_tag, frame_hex(frame_bytes), tx_res.get("msg") or exp.get("type", ftype.name))
- if tx_res.get("msg"):
- root.after(0, lbl_realtime_stat.config, {"text": tx_res["msg"]})
- if ftype == FrameType.GET_DATA:
- root.after(0, update_realtime_status, frame_bytes, tx_res.get("is_match", False))
- elif ftype == FrameType.DIAGNOSTIC:
- root.after(0, lbl_realtime_diag.config, {"text": exp["summary"]})
- dispatch_next_request()
- else:
- # Check inter-byte timeout for stalled partial frames
- timeout_evts = receiver.check_timeout()
- for evt_type, data in timeout_evts:
- if evt_type == "FRAME_REJECTED":
- rej_data = data["data"].hex(" ").upper() if isinstance(data, dict) and "data" in data else ""
- rej_reason = data["reason"] if isinstance(data, dict) and "reason" in data else str(data)
- root.after(0, append_log, "RX_ERR", rej_data, f"超时重置: {rej_reason}")
- elif evt_type == "FRAME_VALID":
- frame_bytes = data["frame_bytes"]
- ftype = data["frame_type"]
- payload = data["payload"]
- exp = model.explain(frame_bytes)
- tx_res = tracker.on_valid_frame(ftype, payload)
- rx_tag = "RX_AUTO" if tx_res["status_code"] in ("UNSOLICITED_DATA", "BEACON", "DIAGNOSTIC") else "RX"
- root.after(0, append_log, rx_tag, frame_hex(frame_bytes), tx_res.get("msg") or exp.get("type", ftype.name))
- if tx_res.get("msg"):
- root.after(0, lbl_realtime_stat.config, {"text": tx_res["msg"]})
- if ftype == FrameType.GET_DATA:
- root.after(0, update_realtime_status, frame_bytes, tx_res.get("is_match", False))
- elif ftype == FrameType.DIAGNOSTIC:
- root.after(0, lbl_realtime_diag.config, {"text": exp["summary"]})
- dispatch_next_request()
- time.sleep(0.02)
- except Exception as exc:
- root.after(0, append_log, "ERR", "", f"串口读取异常: {exc}")
- break
- def update_realtime_status(frame_data: bytes, matched_query: bool = False):
- try:
- parsed = model.parse(frame_data)
- for item in parsed:
- if item.get("kind") == "status":
- st = item["state"]
- bmc_valid = sum(1 for t in st.get("bmc", {}).get("temperature_c", []) if t is not None)
- ct_valid = sum(1 for t in st.get("ct", {}).get("temperature_c", []) if t is not None)
- bmc_note = "无有效采样" if bmc_valid == 0 else f"{bmc_valid}/24 通道就绪"
- origin = "查询应答" if matched_query else "自动遥测(未关联查询)"
- summary = f"{origin} | BMC: {bmc_note} | CT7428 有效: {ct_valid}/27 通道"
- if product == "6400-v2":
- epb_s = "按下(1)" if st.get("estop_btn") else "未按(0)"
- sb1_s = "按下(1)" if st.get("hood_open_btn") else "未按(0)"
- sb2_s = "按下(1)" if st.get("hood_close_btn") else "未按(0)"
- buz_s = "开(1)" if st.get("buzzer") else "关(0)"
- summary += f" | 急停EPB1={epb_s} | 开罩SB1={sb1_s} | 合罩SB2={sb2_s} | 蜂鸣器={buz_s}"
- elif product == "mrdimm-chamber":
- hood_s = "按下(1)" if st.get("hood_switch") else "未按(0)"
- buz_s = "开(1)" if st.get("buzzer") else "关(0)"
- summary += f" | 高温罩开关={hood_s} | 蜂鸣器={buz_s}"
- if model.motor:
- lm = st.get("lower_limit_mask", 0)
- um = st.get("upper_limit_mask", 0)
- summary += f" | 下限位=0x{lm:03X} | 上限位=0x{um:03X}"
- fan_d = st.get("fan", [])
- ptc_d = st.get("ptc", [])
- lbl_realtime_ptc.config(text=f"【FAN 4路占空比】: {fan_d} | 【PTC 4路占空比】: {ptc_d}")
- else:
- ptc_d = st.get("ptc", [])
- if ptc_d:
- lines = []
- for c in range(0, len(ptc_d), 8):
- chunk = ptc_d[c : c + 8]
- lines.append(" | ".join(f"PTC{c+j:02d}:{v:3d}%" for j, v in enumerate(chunk)))
- front_d = st.get("front", [])
- rear_d = st.get("rear", [])
- fan_lines = [f"{model.output_label(group, index)}: {value}%"
- for group, duties in (("Front", front_d), ("Rear", rear_d))
- for index, value in enumerate(duties)]
- ssr_lines = [f"{model.output_label('SSR', index)}: {value}%"
- for index, value in enumerate(st.get("ssr", []))]
- ssr_text = "\n【加热布 SSR(20 Hz,50 ms 周期)】:\n " + " | ".join(ssr_lines) if ssr_lines else ""
- lbl_realtime_ptc.config(text=f"【PTC 生效占空比 (共{len(ptc_d)}路)】:\n " + "\n ".join(lines) + "\n【风扇占空比】:\n " + "\n ".join(" | ".join(fan_lines[n:n+2]) for n in range(0, len(fan_lines), 2)) + ssr_text)
- lbl_realtime_stat.config(text=summary)
- sample_rec = curve_store.record_state(st)
- tt_evt = thermal_session.process_sample(
- sample_rec, chamber_mapping, ignore_zero_ct=ignore_zero_ct_var.get()
- )
- if thermal_session.active and tt_evt.get("fan_switched_now"):
- send_thermal_test_set("风扇到达介入条件自动调速")
- refresh_thermal_test_ui()
- lbl_realtime_chambers.config(
- text="【四腔实时温度 (可配置映射)】: "
- + chamber_mapping.format_realtime_summary(st, ignore_zero_ct=ignore_zero_ct_var.get())
- )
- redraw_all_chamber_canvases()
- # Also update TAB 3 output
- do_parse_get_resp(frame_hex(frame_data))
- except Exception:
- pass
- def poll_loop(my_epoch: int, my_gen: int):
- while not poll_stop_event.is_set():
- if my_epoch != connection_epoch or my_gen != poll_generation:
- break
- with serial_lock:
- sp = serial_port_obj
- if sp and sp.is_open:
- get_frame = model.get_all()
- request_queue.put(("GET", get_frame, "自动轮询 GET_ALL (维持看门狗)"))
- dispatch_next_request()
- poll_stop_event.wait(timeout=1.0)
- def toggle_connect():
- nonlocal serial_port_obj, poll_active, connection_epoch, poll_generation
- if not HAVE_SERIAL:
- messagebox.showerror("缺少库", "未检测到 pyserial 库,无法进行串口通信。\n可在命令行运行: pip install pyserial")
- return
- with serial_lock:
- if serial_port_obj and serial_port_obj.is_open:
- connection_epoch += 1
- poll_generation += 1
- poll_stop_event.set()
- poll_var.set(False)
- while not request_queue.empty():
- try:
- request_queue.get_nowait()
- except queue.Empty:
- break
- try:
- serial_port_obj.close()
- except Exception:
- pass
- serial_port_obj = None
- tracker.on_port_closed()
- btn_connect.config(text="打开串口")
- lbl_conn_status.config(text="已断开", foreground="gray")
- btn_send_get.config(state="disabled")
- btn_send_set.config(state="disabled")
- btn_heartbeat.config(state="disabled")
- chk_poll.config(state="disabled")
- return
- port = port_combo.get().strip()
- if not port:
- messagebox.showwarning("提示", "请先选择有效的 COM 端口")
- return
- baud = int(baud_combo.get().strip())
- try:
- connection_epoch += 1
- sp = serial.Serial(port, baudrate=baud, timeout=0.1)
- with serial_lock:
- serial_port_obj = sp
- tracker.on_port_opened(port, baud)
- btn_connect.config(text="关闭串口")
- lbl_conn_status.config(text=f"已连接 {port} @ {baud}", foreground="green")
- btn_send_get.config(state="normal")
- btn_send_set.config(state="normal")
- btn_heartbeat.config(state="normal")
- chk_poll.config(state="normal")
- # Start reading thread with this epoch
- threading.Thread(target=serial_read_loop, args=(connection_epoch,), daemon=True).start()
- except PermissionError as exc:
- messagebox.showerror(
- "端口占用",
- f"无法打开串口 {port} (拒绝访问 / Access Denied)!\n\n"
- f"根因诊断:该端口当前已被其他程序独占占用(如灵光串口调试助手 SerialDebug.exe 或另一个上位机进程)。\n\n"
- f"解决办法:请先在任务管理器或相关软件中关闭占用 {port} 的程序,然后再点击打开串口。"
- )
- except Exception as exc:
- err_str = str(exc)
- if "Access is denied" in err_str or "PermissionError" in err_str:
- msg = (
- f"无法打开串口 {port} (拒绝访问)!\n\n"
- f"检测到该端口正被另一个进程独占占用。请关闭占用该串口的工具后重试。"
- )
- else:
- msg = f"无法打开串口 {port}:\n{exc}"
- messagebox.showerror("连接失败", msg)
- def send_get_clicked():
- with serial_lock:
- sp = serial_port_obj
- if not sp or not sp.is_open:
- messagebox.showwarning("提示", "串口未连接")
- return
- get_frame = model.get_all()
- request_queue.put(("GET", get_frame, "GET_ALL 查询 (等待应答)"))
- dispatch_next_request()
- def send_set_clicked():
- with serial_lock:
- sp = serial_port_obj
- if not sp or not sp.is_open:
- messagebox.showwarning("提示", "串口未连接")
- return
- try:
- set_frame = do_generate_set()
- request_queue.put(("SET", set_frame, "SET_ALL 配置下发 (等待确认)"))
- dispatch_next_request()
- except Exception as exc:
- messagebox.showerror("发送失败", str(exc))
- def send_heartbeat_clicked():
- with serial_lock:
- sp = serial_port_obj
- if not sp or not sp.is_open:
- messagebox.showwarning("提示", "串口未连接")
- return
- nonce = os.urandom(4)
- hb_frame = model.heartbeat(nonce=nonce)
- request_queue.put(("PING", hb_frame, f"HEARTBEAT 心跳测试 Ping (Nonce: 0x{nonce.hex().upper()})", nonce))
- dispatch_next_request()
- def on_poll_toggle():
- nonlocal poll_generation
- poll_generation += 1
- is_active = poll_var.get()
- if is_active:
- poll_stop_event.clear()
- threading.Thread(target=poll_loop, args=(connection_epoch, poll_generation), daemon=True).start()
- else:
- poll_stop_event.set()
- btn_connect.config(command=toggle_connect)
- btn_send_get.config(command=send_get_clicked)
- btn_send_set.config(command=send_set_clicked)
- btn_heartbeat.config(command=send_heartbeat_clicked)
- chk_poll.config(command=on_poll_toggle)
- # Initial generation
- do_generate_set()
- root.mainloop()
- return 0
- def main(product: str, argv: list[str] | None = None) -> int:
- args = sys.argv if argv is None else argv
- if "--self-test" in args:
- report_path = None
- if "--self-test-report" in args:
- report_path = Path(args[args.index("--self-test-report") + 1])
- report = {"schema": "prod2u-gui-self-test-v1", "product": product,
- "status": "FAIL", "serial_opened": False,
- "hardware_validation": "NOT_RUN", "visual_gui_validation": "NOT_RUN"}
- try:
- code = self_test(product)
- model = Model(product)
- report.update(status="PASS" if code == 0 else "FAIL",
- release_version=model.release_version, host_baud=model.host_baud,
- metadata=model.metadata)
- return code
- except Exception as exc:
- report["error"] = str(exc)
- return 1
- finally:
- if report_path is not None:
- report_path.parent.mkdir(parents=True, exist_ok=True)
- report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
- if "--plot-log" in args and "--plot-out" in args:
- log_path = Path(args[args.index("--plot-log") + 1])
- out_path = Path(args[args.index("--plot-out") + 1])
- model = Model(product)
- cfg = ChamberMappingConfig.default(product)
- if "--chamber-map" in args:
- cfg = ChamberMappingConfig.load(Path(args[args.index("--chamber-map") + 1]), product=product)
- store = TemperatureCurveStore()
- count = store.load_from_log_file(log_path, model)
- out_path.parent.mkdir(parents=True, exist_ok=True)
- suffix = out_path.suffix.lower()
- if suffix == ".svg":
- out_path.write_text(render_chamber_curves_svg(store, cfg, product=product, board=model.board), encoding="utf-8")
- elif suffix == ".csv":
- out_path.write_text(export_chamber_curves_csv(store, cfg), encoding="utf-8")
- else:
- out_path.write_bytes(render_chamber_curves_png(store, cfg, product=product, board=model.board))
- print(f"OK: imported {count} samples from {log_path} -> {out_path}")
- return 0
- return run_gui(product)
- if __name__ == "__main__":
- prod = sys.argv[1] if len(sys.argv) > 1 and sys.argv[1] in ("6400-front-rear", "mrdimm-chamber", "6400-v2") else "6400-front-rear"
- sys.exit(main(prod))
|