#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ MQTT 上报/下发验证脚本(对齐当前工程底座) ========================================== 用途: 1) 订阅上行 /senan/001/+,确认能否收到指定 IMEI 的上报消息; 2) 校验上行内容是否为标准 JSON(当前工程底座用逗号分隔); 3) 校验 zt=001~006 各组的字段是否与 main.c 中 Net_SendPublish 定义一致; 4) 订阅下行 /senan_server/+,按 main.c 的 Host_ParseCmd 规范校验下发命令。 当前工程字段定义: 001: sbh qd jg 002: sbh xl1 xy1 wxh1 pl1 ss1 sz1 003: sbh qx2 zy2 pl2 bq2 xl2 hx2 sm2 004: sbh ID0~ID9 005: sbh ID10 ID12 ID14 ID15 ID16 ID17 ID18 006: sbh ID60 ID61 ID62 ID63 ID70 ID71 ID72 ID73 ID74 用法: python mqtt_verify.py python mqtt_verify.py --imei 869663076785935 --seconds 180 python mqtt_verify.py --host 59.110.125.164 --user zkb --password 123456 \ --imei 869663076785935 --send-detection --seconds 100 """ import argparse import json import threading import time from datetime import datetime import paho.mqtt.client as mqtt # 有数据时必须落在这些范围内的字段(0/空表示本次无数据,不校验) VALUE_RANGES = { "xl1": (30, 220), # 血氧模块心率 "xy1": (50, 100), # 血氧饱和度 "ss1": (60, 220), # 收缩压 "sz1": (40, 160), # 舒张压 "xl2": (30, 220), # 睡眠带心率 "hx2": (5, 60), # 呼吸率 } EXPECTED_FIELDS = { "001": ["sbh", "qd", "jg"], "002": ["sbh", "xl1", "xy1", "wxh1", "pl1", "ss1", "sz1"], "003": ["sbh", "qx2", "zy2", "pl2", "bq2", "xl2", "hx2", "sm2"], "004": ["sbh"] + ["ID%d" % i for i in range(10)], "005": ["sbh", "ID10", "ID12", "ID14", "ID15", "ID16", "ID17", "ID18"], "006": ["sbh", "ID60", "ID61", "ID62", "ID63", "ID70", "ID71", "ID72", "ID73", "ID74"], } # 当前工程底座的下行命令定义(Host_ParseCmd): # {"zt":"xy1"|"sm2","neirong":"01"/"02"} # {"zt":"jiange","neirong":"10"~"65000"} # {"zt":"tz2","neirong":"01","gender":1,"bodyHeight":1800,"bodyWeight":600,"age":30,"type":1}(1=男 2=女) # {"zt":"rt3","neirong":"01","weizhi":"00001","xingbie":"00001","shengao":"01750","tizhong":"00700","nianling":"00025"} DOWN_FIELDS = { "xy1": ["zt", "neirong"], "sm2": ["zt", "neirong"], "jiange": ["zt", "neirong"], "tz2": ["zt", "neirong", "gender", "bodyHeight", "bodyWeight", "age"], } def now(): return datetime.now().strftime("%H:%M:%S") class Verifier: def __init__(self, args): self.args = args self.lock = threading.Lock() self.total = 0 self.other_imeis = set() self.stats = {} # zt -> {count, json_ok, field_ok} self.issues = [] # (时间, 描述, 原文) self.samples = {} # zt -> 首条原文 self.last_samples = {} # zt -> 末条原文 self._fmt_reported = set() self.down_total = 0 self.down_ok = 0 self.down_issues = [] # (时间, 描述, 原文) self.down_samples = [] self.connected = threading.Event() self.client = self._build_client() def _build_client(self): try: client = mqtt.Client( mqtt.CallbackAPIVersion.VERSION2, client_id="verify_%d" % int(time.time()), protocol=mqtt.MQTTv311, ) except AttributeError: # paho-mqtt 1.x client = mqtt.Client(client_id="verify_%d" % int(time.time()), protocol=mqtt.MQTTv311) client.username_pw_set(self.args.user, self.args.password) client.on_connect = self._on_connect client.on_message = self._on_message client.on_disconnect = self._on_disconnect return client def _on_connect(self, client, userdata, flags, rc, properties=None): code = getattr(rc, "value", rc) if code != 0: print("[%s] 连接失败 rc=%s,请检查地址/账号/密码" % (now(), rc), flush=True) return # 上行:通配订阅并按 IMEI 过滤,避免精确主题+通配主题重复投递 client.subscribe("/senan/001/+", qos=2) # 下行:当前工程订阅的命令主题,顺便校验下发给任意设备的命令格式 client.subscribe("/senan_server/+", qos=2) print("[%s] 已连接 %s:%d,订阅 上行 /senan/001/+、下行 /senan_server/+ (QoS2),目标 IMEI=%s" % ( now(), self.args.host, self.args.port, self.args.imei), flush=True) self.connected.set() def _on_disconnect(self, client, userdata, *args): self.connected.clear() print("[%s] 连接断开" % now(), flush=True) def publish_detection(self, start=True): """向目标设备下发三路检测的启动/停止指令""" topic = "/senan_server/%s" % self.args.imei if start: cmds = [ '{"zt":"xy1","neirong":"01"}', '{"zt":"sm2","neirong":"01"}', '{"zt":"tz2","neirong":"01","gender":1,"bodyHeight":1800,"bodyWeight":600,"age":30,"type":1}', ] else: cmds = [ '{"zt":"xy1","neirong":"02"}', '{"zt":"sm2","neirong":"02"}', '{"zt":"tz2","neirong":"02"}', ] for c in cmds: info = self.client.publish(topic, c, qos=2) print("[%s] >> 下发%s %s" % (now(), "启动" if start else "停止", c), flush=True) if info.rc != mqtt.MQTT_ERR_SUCCESS: print(" 发布失败 rc=%s" % info.rc, flush=True) time.sleep(0.6) def _on_message(self, client, userdata, msg): text = msg.payload.decode("utf-8", errors="replace") topic = msg.topic topic_imei = topic.rsplit("/", 1)[-1] if "/" in topic else "" with self.lock: if topic.startswith("/senan_server/"): self.down_total += 1 self._check_down(topic_imei, text) elif topic_imei != self.args.imei: self.other_imeis.add(topic_imei) else: self.total += 1 self._check(topic_imei, text) def _check(self, topic_imei, text): raw = text.strip() # 1) 标准 JSON 校验(逗号分隔);失败后兼容分号分隔再解析一遍用于字段比对 fmt = "标准JSON" try: data = json.loads(raw) json_ok = isinstance(data, dict) json_err = "" if json_ok else "顶层不是对象" except Exception as e: json_ok = False json_err = str(e) try: data = json.loads(raw.replace(";", ",")) fmt = "分号分隔(非标准JSON)" except Exception: data = {} fmt = "无法解析" if not isinstance(data, dict): pass if not isinstance(data, dict): data = {} zt = str(data.get("zt", "")).strip() st = self.stats.setdefault(zt or "?", {"count": 0, "json_ok": 0, "field_ok": 0, "fmts": {}}) st["count"] += 1 st["fmts"][fmt] = st["fmts"].get(fmt, 0) + 1 if json_ok: st["json_ok"] += 1 if zt and zt not in self.samples: self.samples[zt] = raw if zt: self.last_samples[zt] = raw if getattr(self.args, "print_uplink", False): print(" RAW %s" % raw[:300]) # 2) 字段一致性校验(分号分隔时也按解析出的字段比对) field_ok = False if data: expected = EXPECTED_FIELDS.get(zt) if expected is None: if "unknown-zt" not in self._fmt_reported: self._fmt_reported.add("unknown-zt") self.issues.append((now(), "未知 zt=%r" % zt, raw)) else: keys = [k for k in data.keys() if k != "zt"] missing = [k for k in expected if k not in keys] extra = [k for k in keys if k not in expected] field_ok = not missing and not extra if missing: self.issues.append((now(), "zt=%s 缺少字段 %s" % (zt, missing), raw)) if extra: self.issues.append((now(), "zt=%s 多余字段 %s" % (zt, extra), raw)) if field_ok: st["field_ok"] += 1 # 3) sbh 与主题 IMEI 一致性 if str(data.get("sbh", "")) != topic_imei: self.issues.append((now(), "sbh=%r 与主题 IMEI=%s 不一致" % (data.get("sbh"), topic_imei), raw)) # 值含义:底座约定除 zt/sbh 外都是数字字符串,空串表示本帧无有效数据 bad = [k for k, val in data.items() if k not in ("zt", "sbh") and not (isinstance(val, str) and (val == "" or val.isdigit()))] if bad and ("valtype:" + zt) not in self._fmt_reported: self._fmt_reported.add("valtype:" + zt) self.issues.append((now(), "zt=%s 存在非数字字符串值 %s" % (zt, bad), raw)) # 值范围:0/空表示本次无数据,不校验 for k, (lo, hi) in VALUE_RANGES.items(): if k not in data: continue s = str(data.get(k)).strip() if s.isdigit() and int(s) != 0 and not (lo <= int(s) <= hi): key = "range:" + zt + ":" + k if key not in self._fmt_reported: self._fmt_reported.add(key) self.issues.append((now(), "zt=%s %s=%s 超出合理范围 %d~%d" % (zt, k, s, lo, hi), raw)) # 4) 非标准 JSON 只按“首次出现”记录,避免刷屏 if not json_ok and fmt != "标准JSON": key = "fmt:" + zt if key not in self._fmt_reported: self._fmt_reported.add(key) self.issues.append((now(), "zt=%s 不是标准 JSON:%s(%s)" % (zt or "?", fmt, json_err), raw)) print("[%s] << %s zt=%s 格式=%s 字段=%s" % ( now(), topic_imei, zt or "-", fmt, "OK" if field_ok else "FAIL"), flush=True) def _check_down(self, topic_imei, text): """按当前工程底座的 Host_ParseCmd 规范校验下行命令""" raw = text.strip() try: data = json.loads(raw) if not isinstance(data, dict): raise ValueError("顶层不是对象") except Exception as e: self.down_issues.append((now(), "下行不是标准 JSON: %s" % e, raw)) print("[%s] >> %s 下行 格式=FAIL 字段=FAIL" % (now(), topic_imei), flush=True) return zt = str(data.get("zt", "")).strip() reasons = [] nr = str(data.get("neirong", "")).strip() # 停止指令只需要 zt+neirong;启动指令才要求完整参数 is_stop = zt in ("xy1", "sm2", "tz2") and nr == "02" expected = ["zt", "neirong"] if is_stop else DOWN_FIELDS.get(zt) if expected is None: reasons.append("未知 zt=%r(支持 %s)" % (zt, "/".join(DOWN_FIELDS))) else: missing = [k for k in expected if k not in data] extra = [k for k in data if k not in expected and not (zt == "tz2" and k == "type")] if missing: reasons.append("缺少字段 %s" % missing) if extra: reasons.append("多余字段 %s" % extra) if zt in ("xy1", "sm2"): if nr not in ("01", "02"): reasons.append("neirong=%r(应为 01/02)" % nr) elif zt == "jiange": if not nr.isdigit() or not (10 <= int(nr) <= 65000): reasons.append("neirong=%r(应为 10~65000 秒)" % nr) elif zt == "tz2" and not is_stop: g = str(data.get("gender", "")).strip().lower() if g not in ("1", "2"): reasons.append("gender=%r(应为 1=男 / 2=女)" % g) for name, lo, hi in (("bodyHeight", 500, 2500), ("bodyWeight", 200, 3000), ("age", 1, 120)): try: val = int(data.get(name)) except Exception: reasons.append("%s=%r 不是整数" % (name, data.get(name))) continue if not (lo <= val <= hi): reasons.append("%s=%d 超出合理范围 %d~%d" % (name, val, lo, hi)) if reasons: self.down_issues.append((now(), "; ".join(reasons), raw)) print("[%s] >> %s 下行 zt=%s 格式=FAIL 字段=FAIL" % (now(), topic_imei, zt or "-"), flush=True) else: self.down_ok += 1 print("[%s] >> %s 下行 zt=%s 格式=OK 字段=OK" % (now(), topic_imei, zt), flush=True) if len(self.down_samples) < 5: self.down_samples.append((topic_imei, raw)) def summary(self): print("\n================ 验证结果 ================") print("目标 IMEI: %s" % self.args.imei) print("\n---- 上行 /senan/001/ ----") print("收到目标设备消息: %d 条" % self.total) all_ok = self.total > 0 if self.total == 0: print("未收到该 IMEI 的上报(检查设备供电/4G 联网/订阅权限)") else: print("%-6s %-6s %-8s %-8s %s" % ("zt", "条数", "标准JSON", "字段一致", "实际格式")) for zt in sorted(self.stats): st = self.stats[zt] fmts = ", ".join("%s×%d" % (k, v) for k, v in st["fmts"].items()) print("%-6s %-6d %-8d %-8d %s" % (zt, st["count"], st["json_ok"], st["field_ok"], fmts)) if st["json_ok"] != st["count"] or st["field_ok"] != st["count"]: all_ok = False missing_groups = [zt for zt in EXPECTED_FIELDS if zt not in self.stats] if missing_groups: print("未上报的分组: %s(无对应传感器数据时属正常)" % ", ".join(missing_groups)) if self.issues: all_ok = False print("\n上行问题明细(最多显示 10 条):") for t, desc, raw in self.issues[:10]: print(" [%s] %s" % (t, desc)) print(" %s" % raw[:300]) elif self.total: print("未发现上行 JSON / 字段问题") if self.samples: print("\n首条样本:") for zt in sorted(self.samples): print(" zt=%s: %s" % (zt, self.samples[zt][:300])) if self.last_samples: print("\n末条样本:") for zt in sorted(self.last_samples): print(" zt=%s: %s" % (zt, self.last_samples[zt][:300])) # ---- 下行 ---- print("\n---- 下行 /senan_server/ ----") print("收到下行消息: %d 条,符合底座规范: %d 条" % (self.down_total, self.down_ok)) if self.down_total == 0: print("本次监听期间没有观察到下行命令(仅能验证上行;下行格式见 main.c Host_ParseCmd)") else: if self.down_issues: all_ok = False print("下行问题明细(最多显示 10 条):") for t, desc, raw in self.down_issues[:10]: print(" [%s] %s" % (t, desc)) print(" %s" % raw[:300]) if self.down_samples: print("下行样本:") for imei, raw in self.down_samples: print(" %s: %s" % (imei, raw[:300])) if self.other_imeis: print("\n同 broker 上其它 IMEI: %s" % ", ".join(sorted(self.other_imeis))) format_ok = bool(self.stats) and all(st["json_ok"] == st["count"] for st in self.stats.values()) fields_ok = bool(self.stats) and all(st["field_ok"] == st["count"] for st in self.stats.values()) print("\n结论:") print(" 能收到上行消息: %s" % ("是(%d 条)" % self.total if self.total else "否")) print(" 上行内容是标准 JSON: %s" % ("是" if format_ok else "否(见上方实际格式)")) print(" 上行字段与当前工程一致: %s" % ("是" if fields_ok else "否(见问题明细)")) if self.down_total: print(" 下行格式与当前工程一致: %s(%d/%d 条)" % ( "是" if self.down_ok == self.down_total else "否", self.down_ok, self.down_total)) else: print(" 下行格式与当前工程一致: 无法验证(未观察到下行消息)") return all_ok def parse_args(): p = argparse.ArgumentParser(description="验证设备 MQTT 上报的 JSON 与字段") p.add_argument("--host", default="124.221.1.174") p.add_argument("--port", type=int, default=1883) p.add_argument("--user", default="sadewin") p.add_argument("--password", default="sadewin") p.add_argument("--imei", default="869663076785935") p.add_argument("--seconds", type=float, default=120, help="监听时长(秒),默认 120") p.add_argument("--send-detection", action="store_true", help="连接后下发 xy1/sm2/tz2 启动指令") p.add_argument("--stop-after", type=float, default=0, help="启动后多少秒下发停止指令,之后继续纯监听") p.add_argument("--print-uplink", action="store_true", help="打印每条上行原文") p.add_argument("--keep", action="store_true", help="结束时不下发停止指令") return p.parse_args() def main(): args = parse_args() v = Verifier(args) try: v.client.connect(args.host, args.port, keepalive=60) except Exception as e: print("无法连接 broker: %s" % e) return v.client.loop_start() if not v.connected.wait(10): print("连接 broker 超时(10s),请检查地址/账号/密码/网络") v.client.loop_stop() return if args.send_detection: time.sleep(1.5) v.publish_detection(True) start_ts = time.time() stop_sent = False deadline = time.time() + args.seconds try: while time.time() < deadline: if args.send_detection and args.stop_after > 0 and not stop_sent and time.time() - start_ts >= args.stop_after: v.publish_detection(False) stop_sent = True print("[%s] 已下发停止指令,继续纯监听,观察是否还有上报" % now(), flush=True) time.sleep(0.5) except KeyboardInterrupt: pass finally: if args.send_detection and not args.keep and not stop_sent: v.publish_detection(False) time.sleep(0.8) v.client.loop_stop() v.client.disconnect() v.summary() if __name__ == "__main__": main()