| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145 |
- import serial, time, zlib
- def calc_crc32(data):
- crc = 0xFFFFFFFF
- for b in data:
- crc ^= b
- for _ in range(8):
- if crc & 1: crc = (crc >> 1) ^ 0xEDB88320
- else: crc >>= 1
- return (crc ^ 0xFFFFFFFF) & 0xFFFFFFFF
- s = serial.Serial('COM9', 115200, timeout=0.3)
- print(f"[{time.strftime('%H:%M:%S')}] COM9 打开")
- # 先让板子启动 sm2
- s.write(b'{"zt":"sm2","neirong":"01"}\n')
- s.flush()
- print(f"[{time.strftime('%H:%M:%S')}] 已发 sm2,01")
- # 等 30 秒抓数据
- print("\n=== 抓 30 秒 SM7OK 帧 ===\n")
- end = time.time() + 30
- buf = b''
- all_sm7ok = []
- all_json = []
- while time.time() < end:
- data = s.read(2048)
- if data:
- buf += data
- while b'\n' in buf:
- line, buf = buf.split(b'\n', 1)
- try:
- t = line.decode('ascii', errors='replace').strip()
- except:
- continue
- if t.startswith('SM7OK'):
- all_sm7ok.append(t)
- print(f" [{t.split(':')[1].strip().split()[11] if ':' in t and len(t.split(':')[1].strip().split())>11 else '??'}] {t[:120]}")
- elif t.startswith('{') and ('pl2' in t or 'qx2' in t or 'sm2' in t):
- all_json.append(t)
- s.close()
- # 统计
- counts = {}
- for t in all_sm7ok:
- if ':' in t:
- parts = t.split(':')[1].strip().split()
- if len(parts) >= 13:
- cmd = f"0x{parts[11].upper()}{parts[12].upper()}"
- else:
- cmd = "short"
- counts[cmd] = counts.get(cmd, 0) + 1
- print(f"\n=== 帧类型统计 ({len(all_sm7ok)} 帧) ===")
- for k, v in sorted(counts.items()):
- print(f" {k}: {v}")
- # 详细分析每个 Command
- def parse_frame(t):
- if ':' not in t: return None
- parts = t.split(':')[1].strip().split()
- if len(parts) < 15: return None
- cmd = f"0x{parts[11].upper()}{parts[12].upper()}"
- # parts: [0]=EF [1]=AA [2]=55 [3]=LenH [4]=LenL [5]=Ver [6]=TypeH [7]=TypeL
- # [8]=SeqH [9]=SeqL [10]=Ch [11]=CmdH [12]=CmdL [13]=DataField[0] [14]=DataField[1] ...
- result = {"cmd": cmd, "parts": parts, "len": len(parts)}
-
- # 验证 CRC32
- crc_input = bytes([int(p,16) for p in parts[1:-5]]) # 去掉 EF 头 + CRC32 + FE
- recv_crc = (int(parts[-5],16) << 24) | (int(parts[-4],16) << 16) | (int(parts[-3],16) << 8) | int(parts[-2],16)
- calc_crc = calc_crc32(crc_input)
- result["crc_ok"] = calc_crc == recv_crc
-
- # DataField 解析
- if cmd == "0x0202": # HR/RR
- result["detail"] = f"Res={parts[13]} HR={parts[14]} RR={parts[15]} state={parts[16]}"
- elif cmd == "0x0206": # 睡眠查询回复
- result["detail"] = f"Err={parts[13]} sleep={parts[14]} (0=觉醒,1=浅睡,2=深睡,3=REM,4=离床)"
- elif cmd == "0x0207": # 疲劳查询回复
- result["detail"] = f"Err={parts[13]} fatigue={parts[14]} (0=离床,10-60=疲劳)"
- elif cmd == "0x0208": # 憋气查询回复
- result["detail"] = f"Err={parts[13]} breath_hold={parts[14]} (0=正常,1=憋气,4=离床)"
- elif cmd == "0x0209": # 压力查询回复
- if len(parts) >= 17:
- result["detail"] = f"Err={parts[13]} s1={parts[14]} s2={parts[15]} bed={parts[16]}"
- elif cmd == "0x020B": # 组数据上报 ★ 最关注!
- if len(parts) >= 20:
- result["detail"] = f"Res={parts[13]} sleep={parts[14]} fatigue={parts[15]} breath={parts[16]} s1={parts[17]} s2={parts[18]} bed={parts[19]}"
- else:
- result["detail"] = f"DataField: {' '.join(parts[13:-5])}"
- elif cmd == "0x0201" and parts[6] == "0x02".upper(): # 开关设置回复
- if len(parts) >= 15:
- result["detail"] = f"Err={parts[13]}"
- if len(parts) >= 16: result["detail"] += f" state={parts[14]}"
- elif cmd == "0x020A" and parts[6] == "0x02".upper(): # 组开关设置回复
- if len(parts) >= 16:
- result["detail"] = f"Err={parts[13]} state={parts[14]}"
- return result
- print(f"\n=== Enable 开关设置回复 ===")
- found_enable_reply = False
- for t in all_sm7ok:
- r = parse_frame(t)
- if r and r["cmd"] in ("0x0201", "0x020A") and r["crc_ok"]:
- print(f" ✅ {r['cmd']}: {r['detail']}")
- found_enable_reply = True
- if not found_enable_reply:
- print(" ❌ 没有收到开关设置回复帧!")
- print(f"\n=== ★ 0x020B 组数据主动上报 (关键!) ===")
- found_020b = False
- for t in all_sm7ok:
- r = parse_frame(t)
- if r and r["cmd"] == "0x020B":
- print(f" ✅ 收到 0x020B 帧: {r['detail']} CRC={'✅' if r['crc_ok'] else '❌'}")
- found_020b = True
- if not found_020b:
- print(" ❌ 还是没有 0x020B 帧...")
- print(f"\n=== 0x0207 疲劳查询回复 (所有) ===")
- for t in all_sm7ok:
- r = parse_frame(t)
- if r and r["cmd"] == "0x0207":
- print(f" {r['detail']} CRC={'✅' if r['crc_ok'] else '❌'} RAW={t.split(':')[1].strip().split()}")
- print(f"\n=== 0x0209 压力查询回复 (所有) ===")
- for t in all_sm7ok:
- r = parse_frame(t)
- if r and r["cmd"] == "0x0209":
- print(f" {r['detail']} CRC={'✅' if r['crc_ok'] else '❌'}")
- print(f"\n=== JSON 最新值 ===")
- if all_json:
- last = all_json[-1]
- print(f" {last}")
- import json
- try:
- j = json.loads(last)
- print(f" → pl2(疲劳)={j.get('pl2','?')} qx2(压力)={j.get('qx2','?')} sm2={j.get('sm2','?')} xl2(心率)={j.get('xl2','?')} hx2(呼吸)={j.get('hx2','?')}")
- except:
- pass
- print("\nDone!")
|