xy1_test.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import serial, time, json
  2. s = serial.Serial('COM9', 115200, timeout=0.1)
  3. print('COM9 opened')
  4. # 先清积压,等 5 秒抓当前状态
  5. time.sleep(2)
  6. print('\n=== 当前状态(先看 5 秒)===')
  7. cnt = 0
  8. last_json = None
  9. line = b''
  10. end = time.time() + 5
  11. while time.time() < end:
  12. data = s.read(256)
  13. for b in data:
  14. if b in (13, 10):
  15. if not line: continue
  16. t = line.decode('ascii', errors='replace')
  17. line = b''
  18. if t.startswith('{'):
  19. last_json = json.loads(t)
  20. cnt += 1
  21. else:
  22. line += bytes([b])
  23. if last_json:
  24. print(f" 收到 {cnt} 帧,最新:")
  25. for k in ['xl1','xy1','sm2','pl2','zy2','xl2','hx2']:
  26. v = last_json.get(k, '')
  27. print(f" {k}={v or '(空)'}")
  28. else:
  29. print(" ❌ 5 秒内没收到任何 JSON!")
  30. s.close()
  31. exit(1)
  32. # 发 xy1,01
  33. print('\n=== TX: {"zt":"xy1","neirong":"01"} ===')
  34. s.write(b'{"zt":"xy1","neirong":"01"}\n')
  35. s.flush()
  36. # 等 25 秒观察
  37. print('\n=== 等 25 秒,看血氧能不能上来 ===')
  38. end = time.time() + 25
  39. found = False
  40. frame_idx = 0
  41. while time.time() < end:
  42. data = s.read(256)
  43. for b in data:
  44. if b in (13, 10):
  45. if not line: continue
  46. t = line.decode('ascii', errors='replace')
  47. line = b''
  48. if t.startswith('{'):
  49. d = json.loads(t)
  50. frame_idx += 1
  51. xl1 = d.get('xl1', '')
  52. xy1 = d.get('xy1', '')
  53. sm2 = d.get('sm2', '')
  54. xl2 = d.get('xl2', '')
  55. hx2 = d.get('hx2', '')
  56. flag = ''
  57. if xl1 and xy1:
  58. flag = ' ✅ 血氧正常!'
  59. found = True
  60. elif xl1 == '' and xy1 == '':
  61. flag = ' ⚠️ 血氧空'
  62. print(f" JSON#{frame_idx:>2} xl1={xl1 or '(空)':<6} xy1={xy1 or '(空)':<6} sm2={sm2 or '(空)':<5} xl2={xl2 or '(空)':<6} hx2={hx2 or '(空)':<6}{flag}")
  63. else:
  64. line += bytes([b])
  65. s.close()
  66. print(f"\n=== 结论 ===")
  67. print(f" 血氧有没有上来: {'✅ YES' if found else '❌ NO'}")
  68. print(f" 总共收到 {frame_idx} 帧 JSON")