mqtt_verify.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. MQTT 上报/下发验证脚本(对齐当前工程底座)
  5. ==========================================
  6. 用途:
  7. 1) 订阅上行 /senan/001/+,确认能否收到指定 IMEI 的上报消息;
  8. 2) 校验上行内容是否为标准 JSON(当前工程底座用逗号分隔);
  9. 3) 校验 zt=001~006 各组的字段是否与 main.c 中 Net_SendPublish 定义一致;
  10. 4) 订阅下行 /senan_server/+,按 main.c 的 Host_ParseCmd 规范校验下发命令。
  11. 当前工程字段定义:
  12. 001: sbh qd jg
  13. 002: sbh xl1 xy1 wxh1 pl1 ss1 sz1
  14. 003: sbh qx2 zy2 pl2 bq2 xl2 hx2 sm2
  15. 004: sbh ID0~ID9
  16. 005: sbh ID10 ID12 ID14 ID15 ID16 ID17 ID18
  17. 006: sbh ID60 ID61 ID62 ID63 ID70 ID71 ID72 ID73 ID74
  18. 用法:
  19. python mqtt_verify.py
  20. python mqtt_verify.py --imei 869663076785935 --seconds 180
  21. python mqtt_verify.py --host 59.110.125.164 --user zkb --password 123456 \
  22. --imei 869663076785935 --send-detection --seconds 100
  23. """
  24. import argparse
  25. import json
  26. import threading
  27. import time
  28. from datetime import datetime
  29. import paho.mqtt.client as mqtt
  30. # 有数据时必须落在这些范围内的字段(0/空表示本次无数据,不校验)
  31. VALUE_RANGES = {
  32. "xl1": (30, 220), # 血氧模块心率
  33. "xy1": (50, 100), # 血氧饱和度
  34. "ss1": (60, 220), # 收缩压
  35. "sz1": (40, 160), # 舒张压
  36. "xl2": (30, 220), # 睡眠带心率
  37. "hx2": (5, 60), # 呼吸率
  38. }
  39. EXPECTED_FIELDS = {
  40. "001": ["sbh", "qd", "jg"],
  41. "002": ["sbh", "xl1", "xy1", "wxh1", "pl1", "ss1", "sz1"],
  42. "003": ["sbh", "qx2", "zy2", "pl2", "bq2", "xl2", "hx2", "sm2"],
  43. "004": ["sbh"] + ["ID%d" % i for i in range(10)],
  44. "005": ["sbh", "ID10", "ID12", "ID14", "ID15", "ID16", "ID17", "ID18"],
  45. "006": ["sbh", "ID60", "ID61", "ID62", "ID63", "ID70", "ID71", "ID72", "ID73", "ID74"],
  46. }
  47. # 当前工程底座的下行命令定义(Host_ParseCmd):
  48. # {"zt":"xy1"|"sm2","neirong":"01"/"02"}
  49. # {"zt":"jiange","neirong":"10"~"65000"}
  50. # {"zt":"tz2","neirong":"01","gender":1,"bodyHeight":1800,"bodyWeight":600,"age":30,"type":1}(1=男 2=女)
  51. # {"zt":"rt3","neirong":"01","weizhi":"00001","xingbie":"00001","shengao":"01750","tizhong":"00700","nianling":"00025"}
  52. DOWN_FIELDS = {
  53. "xy1": ["zt", "neirong"],
  54. "sm2": ["zt", "neirong"],
  55. "jiange": ["zt", "neirong"],
  56. "tz2": ["zt", "neirong", "gender", "bodyHeight", "bodyWeight", "age"],
  57. }
  58. def now():
  59. return datetime.now().strftime("%H:%M:%S")
  60. class Verifier:
  61. def __init__(self, args):
  62. self.args = args
  63. self.lock = threading.Lock()
  64. self.total = 0
  65. self.other_imeis = set()
  66. self.stats = {} # zt -> {count, json_ok, field_ok}
  67. self.issues = [] # (时间, 描述, 原文)
  68. self.samples = {} # zt -> 首条原文
  69. self.last_samples = {} # zt -> 末条原文
  70. self._fmt_reported = set()
  71. self.down_total = 0
  72. self.down_ok = 0
  73. self.down_issues = [] # (时间, 描述, 原文)
  74. self.down_samples = []
  75. self.connected = threading.Event()
  76. self.client = self._build_client()
  77. def _build_client(self):
  78. try:
  79. client = mqtt.Client(
  80. mqtt.CallbackAPIVersion.VERSION2,
  81. client_id="verify_%d" % int(time.time()),
  82. protocol=mqtt.MQTTv311,
  83. )
  84. except AttributeError: # paho-mqtt 1.x
  85. client = mqtt.Client(client_id="verify_%d" % int(time.time()), protocol=mqtt.MQTTv311)
  86. client.username_pw_set(self.args.user, self.args.password)
  87. client.on_connect = self._on_connect
  88. client.on_message = self._on_message
  89. client.on_disconnect = self._on_disconnect
  90. return client
  91. def _on_connect(self, client, userdata, flags, rc, properties=None):
  92. code = getattr(rc, "value", rc)
  93. if code != 0:
  94. print("[%s] 连接失败 rc=%s,请检查地址/账号/密码" % (now(), rc), flush=True)
  95. return
  96. # 上行:通配订阅并按 IMEI 过滤,避免精确主题+通配主题重复投递
  97. client.subscribe("/senan/001/+", qos=2)
  98. # 下行:当前工程订阅的命令主题,顺便校验下发给任意设备的命令格式
  99. client.subscribe("/senan_server/+", qos=2)
  100. print("[%s] 已连接 %s:%d,订阅 上行 /senan/001/+、下行 /senan_server/+ (QoS2),目标 IMEI=%s" % (
  101. now(), self.args.host, self.args.port, self.args.imei), flush=True)
  102. self.connected.set()
  103. def _on_disconnect(self, client, userdata, *args):
  104. self.connected.clear()
  105. print("[%s] 连接断开" % now(), flush=True)
  106. def publish_detection(self, start=True):
  107. """向目标设备下发三路检测的启动/停止指令"""
  108. topic = "/senan_server/%s" % self.args.imei
  109. if start:
  110. cmds = [
  111. '{"zt":"xy1","neirong":"01"}',
  112. '{"zt":"sm2","neirong":"01"}',
  113. '{"zt":"tz2","neirong":"01","gender":1,"bodyHeight":1800,"bodyWeight":600,"age":30,"type":1}',
  114. ]
  115. else:
  116. cmds = [
  117. '{"zt":"xy1","neirong":"02"}',
  118. '{"zt":"sm2","neirong":"02"}',
  119. '{"zt":"tz2","neirong":"02"}',
  120. ]
  121. for c in cmds:
  122. info = self.client.publish(topic, c, qos=2)
  123. print("[%s] >> 下发%s %s" % (now(), "启动" if start else "停止", c), flush=True)
  124. if info.rc != mqtt.MQTT_ERR_SUCCESS:
  125. print(" 发布失败 rc=%s" % info.rc, flush=True)
  126. time.sleep(0.6)
  127. def _on_message(self, client, userdata, msg):
  128. text = msg.payload.decode("utf-8", errors="replace")
  129. topic = msg.topic
  130. topic_imei = topic.rsplit("/", 1)[-1] if "/" in topic else ""
  131. with self.lock:
  132. if topic.startswith("/senan_server/"):
  133. self.down_total += 1
  134. self._check_down(topic_imei, text)
  135. elif topic_imei != self.args.imei:
  136. self.other_imeis.add(topic_imei)
  137. else:
  138. self.total += 1
  139. self._check(topic_imei, text)
  140. def _check(self, topic_imei, text):
  141. raw = text.strip()
  142. # 1) 标准 JSON 校验(逗号分隔);失败后兼容分号分隔再解析一遍用于字段比对
  143. fmt = "标准JSON"
  144. try:
  145. data = json.loads(raw)
  146. json_ok = isinstance(data, dict)
  147. json_err = "" if json_ok else "顶层不是对象"
  148. except Exception as e:
  149. json_ok = False
  150. json_err = str(e)
  151. try:
  152. data = json.loads(raw.replace(";", ","))
  153. fmt = "分号分隔(非标准JSON)"
  154. except Exception:
  155. data = {}
  156. fmt = "无法解析"
  157. if not isinstance(data, dict):
  158. pass
  159. if not isinstance(data, dict):
  160. data = {}
  161. zt = str(data.get("zt", "")).strip()
  162. st = self.stats.setdefault(zt or "?", {"count": 0, "json_ok": 0, "field_ok": 0, "fmts": {}})
  163. st["count"] += 1
  164. st["fmts"][fmt] = st["fmts"].get(fmt, 0) + 1
  165. if json_ok:
  166. st["json_ok"] += 1
  167. if zt and zt not in self.samples:
  168. self.samples[zt] = raw
  169. if zt:
  170. self.last_samples[zt] = raw
  171. if getattr(self.args, "print_uplink", False):
  172. print(" RAW %s" % raw[:300])
  173. # 2) 字段一致性校验(分号分隔时也按解析出的字段比对)
  174. field_ok = False
  175. if data:
  176. expected = EXPECTED_FIELDS.get(zt)
  177. if expected is None:
  178. if "unknown-zt" not in self._fmt_reported:
  179. self._fmt_reported.add("unknown-zt")
  180. self.issues.append((now(), "未知 zt=%r" % zt, raw))
  181. else:
  182. keys = [k for k in data.keys() if k != "zt"]
  183. missing = [k for k in expected if k not in keys]
  184. extra = [k for k in keys if k not in expected]
  185. field_ok = not missing and not extra
  186. if missing:
  187. self.issues.append((now(), "zt=%s 缺少字段 %s" % (zt, missing), raw))
  188. if extra:
  189. self.issues.append((now(), "zt=%s 多余字段 %s" % (zt, extra), raw))
  190. if field_ok:
  191. st["field_ok"] += 1
  192. # 3) sbh 与主题 IMEI 一致性
  193. if str(data.get("sbh", "")) != topic_imei:
  194. self.issues.append((now(), "sbh=%r 与主题 IMEI=%s 不一致" % (data.get("sbh"), topic_imei), raw))
  195. # 值含义:底座约定除 zt/sbh 外都是数字字符串,空串表示本帧无有效数据
  196. bad = [k for k, val in data.items()
  197. if k not in ("zt", "sbh")
  198. and not (isinstance(val, str) and (val == "" or val.isdigit()))]
  199. if bad and ("valtype:" + zt) not in self._fmt_reported:
  200. self._fmt_reported.add("valtype:" + zt)
  201. self.issues.append((now(), "zt=%s 存在非数字字符串值 %s" % (zt, bad), raw))
  202. # 值范围:0/空表示本次无数据,不校验
  203. for k, (lo, hi) in VALUE_RANGES.items():
  204. if k not in data:
  205. continue
  206. s = str(data.get(k)).strip()
  207. if s.isdigit() and int(s) != 0 and not (lo <= int(s) <= hi):
  208. key = "range:" + zt + ":" + k
  209. if key not in self._fmt_reported:
  210. self._fmt_reported.add(key)
  211. self.issues.append((now(), "zt=%s %s=%s 超出合理范围 %d~%d" % (zt, k, s, lo, hi), raw))
  212. # 4) 非标准 JSON 只按“首次出现”记录,避免刷屏
  213. if not json_ok and fmt != "标准JSON":
  214. key = "fmt:" + zt
  215. if key not in self._fmt_reported:
  216. self._fmt_reported.add(key)
  217. self.issues.append((now(), "zt=%s 不是标准 JSON:%s(%s)" % (zt or "?", fmt, json_err), raw))
  218. print("[%s] << %s zt=%s 格式=%s 字段=%s" % (
  219. now(), topic_imei, zt or "-", fmt, "OK" if field_ok else "FAIL"), flush=True)
  220. def _check_down(self, topic_imei, text):
  221. """按当前工程底座的 Host_ParseCmd 规范校验下行命令"""
  222. raw = text.strip()
  223. try:
  224. data = json.loads(raw)
  225. if not isinstance(data, dict):
  226. raise ValueError("顶层不是对象")
  227. except Exception as e:
  228. self.down_issues.append((now(), "下行不是标准 JSON: %s" % e, raw))
  229. print("[%s] >> %s 下行 格式=FAIL 字段=FAIL" % (now(), topic_imei), flush=True)
  230. return
  231. zt = str(data.get("zt", "")).strip()
  232. reasons = []
  233. nr = str(data.get("neirong", "")).strip()
  234. # 停止指令只需要 zt+neirong;启动指令才要求完整参数
  235. is_stop = zt in ("xy1", "sm2", "tz2") and nr == "02"
  236. expected = ["zt", "neirong"] if is_stop else DOWN_FIELDS.get(zt)
  237. if expected is None:
  238. reasons.append("未知 zt=%r(支持 %s)" % (zt, "/".join(DOWN_FIELDS)))
  239. else:
  240. missing = [k for k in expected if k not in data]
  241. extra = [k for k in data if k not in expected and not (zt == "tz2" and k == "type")]
  242. if missing:
  243. reasons.append("缺少字段 %s" % missing)
  244. if extra:
  245. reasons.append("多余字段 %s" % extra)
  246. if zt in ("xy1", "sm2"):
  247. if nr not in ("01", "02"):
  248. reasons.append("neirong=%r(应为 01/02)" % nr)
  249. elif zt == "jiange":
  250. if not nr.isdigit() or not (10 <= int(nr) <= 65000):
  251. reasons.append("neirong=%r(应为 10~65000 秒)" % nr)
  252. elif zt == "tz2" and not is_stop:
  253. g = str(data.get("gender", "")).strip().lower()
  254. if g not in ("1", "2"):
  255. reasons.append("gender=%r(应为 1=男 / 2=女)" % g)
  256. for name, lo, hi in (("bodyHeight", 500, 2500),
  257. ("bodyWeight", 200, 3000),
  258. ("age", 1, 120)):
  259. try:
  260. val = int(data.get(name))
  261. except Exception:
  262. reasons.append("%s=%r 不是整数" % (name, data.get(name)))
  263. continue
  264. if not (lo <= val <= hi):
  265. reasons.append("%s=%d 超出合理范围 %d~%d" % (name, val, lo, hi))
  266. if reasons:
  267. self.down_issues.append((now(), "; ".join(reasons), raw))
  268. print("[%s] >> %s 下行 zt=%s 格式=FAIL 字段=FAIL" % (now(), topic_imei, zt or "-"), flush=True)
  269. else:
  270. self.down_ok += 1
  271. print("[%s] >> %s 下行 zt=%s 格式=OK 字段=OK" % (now(), topic_imei, zt), flush=True)
  272. if len(self.down_samples) < 5:
  273. self.down_samples.append((topic_imei, raw))
  274. def summary(self):
  275. print("\n================ 验证结果 ================")
  276. print("目标 IMEI: %s" % self.args.imei)
  277. print("\n---- 上行 /senan/001/<IMEI> ----")
  278. print("收到目标设备消息: %d 条" % self.total)
  279. all_ok = self.total > 0
  280. if self.total == 0:
  281. print("未收到该 IMEI 的上报(检查设备供电/4G 联网/订阅权限)")
  282. else:
  283. print("%-6s %-6s %-8s %-8s %s" % ("zt", "条数", "标准JSON", "字段一致", "实际格式"))
  284. for zt in sorted(self.stats):
  285. st = self.stats[zt]
  286. fmts = ", ".join("%s×%d" % (k, v) for k, v in st["fmts"].items())
  287. print("%-6s %-6d %-8d %-8d %s" % (zt, st["count"], st["json_ok"], st["field_ok"], fmts))
  288. if st["json_ok"] != st["count"] or st["field_ok"] != st["count"]:
  289. all_ok = False
  290. missing_groups = [zt for zt in EXPECTED_FIELDS if zt not in self.stats]
  291. if missing_groups:
  292. print("未上报的分组: %s(无对应传感器数据时属正常)" % ", ".join(missing_groups))
  293. if self.issues:
  294. all_ok = False
  295. print("\n上行问题明细(最多显示 10 条):")
  296. for t, desc, raw in self.issues[:10]:
  297. print(" [%s] %s" % (t, desc))
  298. print(" %s" % raw[:300])
  299. elif self.total:
  300. print("未发现上行 JSON / 字段问题")
  301. if self.samples:
  302. print("\n首条样本:")
  303. for zt in sorted(self.samples):
  304. print(" zt=%s: %s" % (zt, self.samples[zt][:300]))
  305. if self.last_samples:
  306. print("\n末条样本:")
  307. for zt in sorted(self.last_samples):
  308. print(" zt=%s: %s" % (zt, self.last_samples[zt][:300]))
  309. # ---- 下行 ----
  310. print("\n---- 下行 /senan_server/<IMEI> ----")
  311. print("收到下行消息: %d 条,符合底座规范: %d 条" % (self.down_total, self.down_ok))
  312. if self.down_total == 0:
  313. print("本次监听期间没有观察到下行命令(仅能验证上行;下行格式见 main.c Host_ParseCmd)")
  314. else:
  315. if self.down_issues:
  316. all_ok = False
  317. print("下行问题明细(最多显示 10 条):")
  318. for t, desc, raw in self.down_issues[:10]:
  319. print(" [%s] %s" % (t, desc))
  320. print(" %s" % raw[:300])
  321. if self.down_samples:
  322. print("下行样本:")
  323. for imei, raw in self.down_samples:
  324. print(" %s: %s" % (imei, raw[:300]))
  325. if self.other_imeis:
  326. print("\n同 broker 上其它 IMEI: %s" % ", ".join(sorted(self.other_imeis)))
  327. format_ok = bool(self.stats) and all(st["json_ok"] == st["count"] for st in self.stats.values())
  328. fields_ok = bool(self.stats) and all(st["field_ok"] == st["count"] for st in self.stats.values())
  329. print("\n结论:")
  330. print(" 能收到上行消息: %s" % ("是(%d 条)" % self.total if self.total else "否"))
  331. print(" 上行内容是标准 JSON: %s" % ("是" if format_ok else "否(见上方实际格式)"))
  332. print(" 上行字段与当前工程一致: %s" % ("是" if fields_ok else "否(见问题明细)"))
  333. if self.down_total:
  334. print(" 下行格式与当前工程一致: %s(%d/%d 条)" % (
  335. "是" if self.down_ok == self.down_total else "否", self.down_ok, self.down_total))
  336. else:
  337. print(" 下行格式与当前工程一致: 无法验证(未观察到下行消息)")
  338. return all_ok
  339. def parse_args():
  340. p = argparse.ArgumentParser(description="验证设备 MQTT 上报的 JSON 与字段")
  341. p.add_argument("--host", default="124.221.1.174")
  342. p.add_argument("--port", type=int, default=1883)
  343. p.add_argument("--user", default="sadewin")
  344. p.add_argument("--password", default="sadewin")
  345. p.add_argument("--imei", default="869663076785935")
  346. p.add_argument("--seconds", type=float, default=120, help="监听时长(秒),默认 120")
  347. p.add_argument("--send-detection", action="store_true", help="连接后下发 xy1/sm2/tz2 启动指令")
  348. p.add_argument("--stop-after", type=float, default=0, help="启动后多少秒下发停止指令,之后继续纯监听")
  349. p.add_argument("--print-uplink", action="store_true", help="打印每条上行原文")
  350. p.add_argument("--keep", action="store_true", help="结束时不下发停止指令")
  351. return p.parse_args()
  352. def main():
  353. args = parse_args()
  354. v = Verifier(args)
  355. try:
  356. v.client.connect(args.host, args.port, keepalive=60)
  357. except Exception as e:
  358. print("无法连接 broker: %s" % e)
  359. return
  360. v.client.loop_start()
  361. if not v.connected.wait(10):
  362. print("连接 broker 超时(10s),请检查地址/账号/密码/网络")
  363. v.client.loop_stop()
  364. return
  365. if args.send_detection:
  366. time.sleep(1.5)
  367. v.publish_detection(True)
  368. start_ts = time.time()
  369. stop_sent = False
  370. deadline = time.time() + args.seconds
  371. try:
  372. while time.time() < deadline:
  373. if args.send_detection and args.stop_after > 0 and not stop_sent and time.time() - start_ts >= args.stop_after:
  374. v.publish_detection(False)
  375. stop_sent = True
  376. print("[%s] 已下发停止指令,继续纯监听,观察是否还有上报" % now(), flush=True)
  377. time.sleep(0.5)
  378. except KeyboardInterrupt:
  379. pass
  380. finally:
  381. if args.send_detection and not args.keep and not stop_sent:
  382. v.publish_detection(False)
  383. time.sleep(0.8)
  384. v.client.loop_stop()
  385. v.client.disconnect()
  386. v.summary()
  387. if __name__ == "__main__":
  388. main()