post_flash_test.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. import serial, time, zlib
  2. def calc_crc32(data):
  3. crc = 0xFFFFFFFF
  4. for b in data:
  5. crc ^= b
  6. for _ in range(8):
  7. if crc & 1: crc = (crc >> 1) ^ 0xEDB88320
  8. else: crc >>= 1
  9. return (crc ^ 0xFFFFFFFF) & 0xFFFFFFFF
  10. s = serial.Serial('COM9', 115200, timeout=0.3)
  11. print(f"[{time.strftime('%H:%M:%S')}] COM9 打开")
  12. # 先让板子启动 sm2
  13. s.write(b'{"zt":"sm2","neirong":"01"}\n')
  14. s.flush()
  15. print(f"[{time.strftime('%H:%M:%S')}] 已发 sm2,01")
  16. # 等 30 秒抓数据
  17. print("\n=== 抓 30 秒 SM7OK 帧 ===\n")
  18. end = time.time() + 30
  19. buf = b''
  20. all_sm7ok = []
  21. all_json = []
  22. while time.time() < end:
  23. data = s.read(2048)
  24. if data:
  25. buf += data
  26. while b'\n' in buf:
  27. line, buf = buf.split(b'\n', 1)
  28. try:
  29. t = line.decode('ascii', errors='replace').strip()
  30. except:
  31. continue
  32. if t.startswith('SM7OK'):
  33. all_sm7ok.append(t)
  34. print(f" [{t.split(':')[1].strip().split()[11] if ':' in t and len(t.split(':')[1].strip().split())>11 else '??'}] {t[:120]}")
  35. elif t.startswith('{') and ('pl2' in t or 'qx2' in t or 'sm2' in t):
  36. all_json.append(t)
  37. s.close()
  38. # 统计
  39. counts = {}
  40. for t in all_sm7ok:
  41. if ':' in t:
  42. parts = t.split(':')[1].strip().split()
  43. if len(parts) >= 13:
  44. cmd = f"0x{parts[11].upper()}{parts[12].upper()}"
  45. else:
  46. cmd = "short"
  47. counts[cmd] = counts.get(cmd, 0) + 1
  48. print(f"\n=== 帧类型统计 ({len(all_sm7ok)} 帧) ===")
  49. for k, v in sorted(counts.items()):
  50. print(f" {k}: {v}")
  51. # 详细分析每个 Command
  52. def parse_frame(t):
  53. if ':' not in t: return None
  54. parts = t.split(':')[1].strip().split()
  55. if len(parts) < 15: return None
  56. cmd = f"0x{parts[11].upper()}{parts[12].upper()}"
  57. # parts: [0]=EF [1]=AA [2]=55 [3]=LenH [4]=LenL [5]=Ver [6]=TypeH [7]=TypeL
  58. # [8]=SeqH [9]=SeqL [10]=Ch [11]=CmdH [12]=CmdL [13]=DataField[0] [14]=DataField[1] ...
  59. result = {"cmd": cmd, "parts": parts, "len": len(parts)}
  60. # 验证 CRC32
  61. crc_input = bytes([int(p,16) for p in parts[1:-5]]) # 去掉 EF 头 + CRC32 + FE
  62. recv_crc = (int(parts[-5],16) << 24) | (int(parts[-4],16) << 16) | (int(parts[-3],16) << 8) | int(parts[-2],16)
  63. calc_crc = calc_crc32(crc_input)
  64. result["crc_ok"] = calc_crc == recv_crc
  65. # DataField 解析
  66. if cmd == "0x0202": # HR/RR
  67. result["detail"] = f"Res={parts[13]} HR={parts[14]} RR={parts[15]} state={parts[16]}"
  68. elif cmd == "0x0206": # 睡眠查询回复
  69. result["detail"] = f"Err={parts[13]} sleep={parts[14]} (0=觉醒,1=浅睡,2=深睡,3=REM,4=离床)"
  70. elif cmd == "0x0207": # 疲劳查询回复
  71. result["detail"] = f"Err={parts[13]} fatigue={parts[14]} (0=离床,10-60=疲劳)"
  72. elif cmd == "0x0208": # 憋气查询回复
  73. result["detail"] = f"Err={parts[13]} breath_hold={parts[14]} (0=正常,1=憋气,4=离床)"
  74. elif cmd == "0x0209": # 压力查询回复
  75. if len(parts) >= 17:
  76. result["detail"] = f"Err={parts[13]} s1={parts[14]} s2={parts[15]} bed={parts[16]}"
  77. elif cmd == "0x020B": # 组数据上报 ★ 最关注!
  78. if len(parts) >= 20:
  79. result["detail"] = f"Res={parts[13]} sleep={parts[14]} fatigue={parts[15]} breath={parts[16]} s1={parts[17]} s2={parts[18]} bed={parts[19]}"
  80. else:
  81. result["detail"] = f"DataField: {' '.join(parts[13:-5])}"
  82. elif cmd == "0x0201" and parts[6] == "0x02".upper(): # 开关设置回复
  83. if len(parts) >= 15:
  84. result["detail"] = f"Err={parts[13]}"
  85. if len(parts) >= 16: result["detail"] += f" state={parts[14]}"
  86. elif cmd == "0x020A" and parts[6] == "0x02".upper(): # 组开关设置回复
  87. if len(parts) >= 16:
  88. result["detail"] = f"Err={parts[13]} state={parts[14]}"
  89. return result
  90. print(f"\n=== Enable 开关设置回复 ===")
  91. found_enable_reply = False
  92. for t in all_sm7ok:
  93. r = parse_frame(t)
  94. if r and r["cmd"] in ("0x0201", "0x020A") and r["crc_ok"]:
  95. print(f" ✅ {r['cmd']}: {r['detail']}")
  96. found_enable_reply = True
  97. if not found_enable_reply:
  98. print(" ❌ 没有收到开关设置回复帧!")
  99. print(f"\n=== ★ 0x020B 组数据主动上报 (关键!) ===")
  100. found_020b = False
  101. for t in all_sm7ok:
  102. r = parse_frame(t)
  103. if r and r["cmd"] == "0x020B":
  104. print(f" ✅ 收到 0x020B 帧: {r['detail']} CRC={'✅' if r['crc_ok'] else '❌'}")
  105. found_020b = True
  106. if not found_020b:
  107. print(" ❌ 还是没有 0x020B 帧...")
  108. print(f"\n=== 0x0207 疲劳查询回复 (所有) ===")
  109. for t in all_sm7ok:
  110. r = parse_frame(t)
  111. if r and r["cmd"] == "0x0207":
  112. print(f" {r['detail']} CRC={'✅' if r['crc_ok'] else '❌'} RAW={t.split(':')[1].strip().split()}")
  113. print(f"\n=== 0x0209 压力查询回复 (所有) ===")
  114. for t in all_sm7ok:
  115. r = parse_frame(t)
  116. if r and r["cmd"] == "0x0209":
  117. print(f" {r['detail']} CRC={'✅' if r['crc_ok'] else '❌'}")
  118. print(f"\n=== JSON 最新值 ===")
  119. if all_json:
  120. last = all_json[-1]
  121. print(f" {last}")
  122. import json
  123. try:
  124. j = json.loads(last)
  125. print(f" → pl2(疲劳)={j.get('pl2','?')} qx2(压力)={j.get('qx2','?')} sm2={j.get('sm2','?')} xl2(心率)={j.get('xl2','?')} hx2(呼吸)={j.get('hx2','?')}")
  126. except:
  127. pass
  128. print("\nDone!")