task_client.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. """轮椅客户端「任务指令接收 + 任务状态反馈」模拟(MQTT)。
  2. 对应《MQTT 交互协议设计文档》第 5、6.2、6.3、6.5 章:
  3. 下行(服务端 → 设备,QoS 1):
  4. server/device/{deviceCode}/task/command 任务指令下发
  5. server/device/{deviceCode}/task/finish 结束指令
  6. 上行(设备 → 服务端,QoS 1):
  7. device/{deviceCode}/task/status 任务状态反馈
  8. 载荷统一为安全信封(A256GCM-HS256),deviceSecret 只用于消息层加解密/验签,
  9. 连接层只使用 EMQX 接入账号密码(--username/--password,可留空匿名)。
  10. 行为:
  11. 1. 订阅上述两个下行主题;收到报文后验签解密、打印明文;
  12. 2. 默认自动回执:收到 command → 回 `accepted`;收到 finish → 回 `ended`(--no-auto-ack 可关闭);
  13. 3. --task 且 --interval>0 时,按间隔周期性上报当前任务状态(可配合 --status/--current-site 等参数)。
  14. 用法(pyhkdf 目录下执行):
  15. # 1) 只打印上行报文参数,不连 broker(便于 mosquitto_pub / EMQX 控制台手工发布)
  16. python task_client.py --device Wheelchair-4502 --secret <deviceSecret> \
  17. --task TASK-20261112-000123 --status navigating --current-site S2 \
  18. --finished-sites S1 --params-only
  19. # 2) 真实连接:订阅指令 + 自动回执(Ctrl+C 退出)
  20. python task_client.py --device Wheelchair-4502 --secret <deviceSecret> \
  21. --base ws://host:8083/mqtt --username <账号> --password <密码>
  22. # 3) 连接并每 10s 上报一次进度(最多 6 次)
  23. python task_client.py --device X --secret Y --base tcp://127.0.0.1:1883 \
  24. --task TASK-001 --status navigating --current-site S2 --interval 10 --count 6
  25. """
  26. from __future__ import annotations
  27. import argparse
  28. import json
  29. import os
  30. import sys
  31. import time
  32. from typing import Any, Callable, Dict, List, Optional, Tuple
  33. from wheelchair_crypto import open_envelope, seal_envelope
  34. # 主题(第 5 章)
  35. COMMAND_TOPIC_TEMPLATE = "server/device/{deviceCode}/task/command"
  36. FINISH_TOPIC_TEMPLATE = "server/device/{deviceCode}/task/finish"
  37. STATUS_TOPIC_TEMPLATE = "device/{deviceCode}/task/status"
  38. QOS = 1
  39. # 6.5 单车反馈子状态
  40. STATUS_VALUES = ("accepted", "navigating", "paused", "resumed",
  41. "suspended", "arrived", "completed", "failed", "ended")
  42. # --------------------------------------------------------------------------- #
  43. # 上行:任务状态反馈
  44. # --------------------------------------------------------------------------- #
  45. def build_status_plaintext(device_code: str, task_id: str, status: str,
  46. current_site: str, finished_sites: List[str],
  47. x: str, y: str, remark: str) -> Dict[str, Any]:
  48. """构造 6.5 任务状态反馈明文(timestamp 为毫秒整数,服务端按 int64 解析)。"""
  49. return {
  50. "taskId": task_id,
  51. "deviceCode": device_code,
  52. "status": status,
  53. "currentSite": current_site,
  54. "finishedSites": finished_sites,
  55. "locationX": x,
  56. "locationY": y,
  57. "timestamp": int(time.time() * 1000),
  58. "remark": remark,
  59. }
  60. def build_envelope_message(device_secret: str, device_code: str,
  61. plaintext: Dict[str, Any]) -> str:
  62. """加密签名后返回 JSON 信封字符串(字段顺序同文档 4.2)。"""
  63. raw = json.dumps(plaintext, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
  64. env = seal_envelope(device_secret, device_code, raw)
  65. ordered = {
  66. "alg": env["alg"],
  67. "deviceCode": env["deviceCode"],
  68. "timestamp": env["timestamp"],
  69. "nonce": env["nonce"],
  70. "iv": env["iv"],
  71. "payload": env["payload"],
  72. "tag": env["tag"],
  73. "sign": env["sign"],
  74. }
  75. return json.dumps(ordered, ensure_ascii=False, separators=(",", ":"))
  76. def print_uplink_params(topic: str, message: str, plaintext: Dict[str, Any],
  77. broker: str, username: str, password: str) -> None:
  78. """打印上行状态反馈报文与手工发布命令。"""
  79. print("— 上行明文(6.5 任务状态反馈,加密前)—")
  80. print(json.dumps(plaintext, ensure_ascii=False, indent=2))
  81. print()
  82. print("— 发布主题与账号 —")
  83. print(f" topic = {topic} qos = {QOS} broker = {broker}")
  84. print(f" username = {username or '(匿名)'}"
  85. f" password = {'(未设置)' if not password else '******(长度 %d)' % len(password)}")
  86. print()
  87. print("— 信封载荷(单行 JSON)—")
  88. print(message)
  89. print()
  90. print("— 手工发布命令示例 —")
  91. cred = f" -u {username}" if username else ""
  92. if username and password:
  93. cred += " -P '******'"
  94. print(" # bash / Linux / macOS")
  95. print(f" mosquitto_pub -h {broker_host(broker)} -p {broker_port(broker)} "
  96. f"-t {topic} -q {QOS}{cred} -m '{message}'")
  97. print(" # Windows:把单行 JSON 存成 status.json 后用文件方式发布")
  98. print(f" mosquitto_pub -h {broker_host(broker)} -p {broker_port(broker)} "
  99. f"-t {topic} -q {QOS}{cred} -f status.json")
  100. print(f" # EMQX 控制台:Topics → Publish,Topic 填 {topic},QoS 选 1")
  101. print()
  102. print("— 下行订阅主题(设备需订阅,服务端发到这里)—")
  103. print(f" {COMMAND_TOPIC_TEMPLATE.format(deviceCode='<deviceCode>')}")
  104. print(f" {FINISH_TOPIC_TEMPLATE.format(deviceCode='<deviceCode>')}")
  105. print()
  106. print("提示:timestamp ±60s 防重放、nonce 一次性;参数仅打印,未连接 broker。")
  107. # --------------------------------------------------------------------------- #
  108. # MQTT 客户端
  109. # --------------------------------------------------------------------------- #
  110. def _import_paho():
  111. try:
  112. import paho.mqtt.client as mqtt # noqa: F401
  113. return mqtt
  114. except ImportError:
  115. raise SystemExit("缺少 paho-mqtt:请执行 pip install -r requirements.txt 后再运行。")
  116. def _client_id(device_code: str) -> str:
  117. return f"wheelchair-task-{device_code}-{os.getpid()}"
  118. def broker_host(broker: str) -> str:
  119. return broker.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0] or "127.0.0.1"
  120. def broker_port(broker: str) -> int:
  121. tail = broker.split("://", 1)[-1].split("/", 1)[0]
  122. if ":" in tail:
  123. try:
  124. return int(tail.split(":", 1)[1])
  125. except ValueError:
  126. pass
  127. return 1883
  128. def broker_ws(broker: str) -> Tuple[bool, str]:
  129. scheme = broker.split("://", 1)[0].lower() if "://" in broker else "tcp"
  130. if scheme not in ("ws", "wss"):
  131. return False, ""
  132. tail = broker.split("://", 1)[-1]
  133. path = "/" + tail.split("/", 1)[1] if "/" in tail else ""
  134. return True, path or "/mqtt"
  135. def run_client(broker: str, device_code: str, device_secret: str,
  136. report_args: Dict[str, Any], interval: int, count: int,
  137. connect_timeout: int, username: str, password: str,
  138. auto_ack: bool) -> int:
  139. mqtt = _import_paho()
  140. ws, ws_path = broker_ws(broker)
  141. client = mqtt.Client(
  142. client_id=_client_id(device_code),
  143. clean_session=False,
  144. protocol=mqtt.MQTTv311,
  145. transport="websockets" if ws else "tcp",
  146. )
  147. if ws:
  148. client.ws_set_options(path=ws_path)
  149. if username:
  150. client.username_pw_set(username, password or None)
  151. state = {"connected": False, "last_rc": 0, "sent": 0}
  152. def publish_status(status: str, current_site: str, finished_sites: List[str],
  153. remark: str = "", task_id: Optional[str] = None) -> None:
  154. args = dict(report_args)
  155. args.update({
  156. "status": status,
  157. "current_site": current_site,
  158. "finished_sites": finished_sites,
  159. "remark": remark,
  160. })
  161. # 回执用下行报文里的 taskId;周期上报才用 --task
  162. tid = task_id or args["task"]
  163. plaintext = build_status_plaintext(
  164. device_code, tid, args["status"], args["current_site"],
  165. args["finished_sites"], args["x"], args["y"], args["remark"],
  166. )
  167. topic = STATUS_TOPIC_TEMPLATE.format(deviceCode=device_code)
  168. message = build_envelope_message(device_secret, device_code, plaintext)
  169. info = client.publish(topic, payload=message, qos=QOS)
  170. if info.rc != 0:
  171. print(f"[反馈失败] status={plaintext['status']} rc={info.rc}")
  172. return
  173. state["sent"] += 1
  174. print(f"[反馈] taskId={plaintext['taskId']} status={plaintext['status']} "
  175. f"currentSite={plaintext['currentSite'] or '-'} "
  176. f"finished={','.join(plaintext['finishedSites']) or '-'} "
  177. f"pos=({plaintext['locationX']},{plaintext['locationY']})")
  178. def on_connect(c, userdata, flags, rc, *extra):
  179. if rc != 0:
  180. state["last_rc"] = rc
  181. print(f"[连接失败] rc={rc}(4=账号密码错误, 5=无权限)")
  182. return
  183. state["connected"] = True
  184. print(f"[已连接] broker={broker} clientId={_client_id(device_code)}")
  185. for topic in (COMMAND_TOPIC_TEMPLATE.format(deviceCode=device_code),
  186. FINISH_TOPIC_TEMPLATE.format(deviceCode=device_code)):
  187. c.subscribe(topic, qos=QOS)
  188. print(f"[订阅] {topic} QoS {QOS}")
  189. def on_disconnect(c, userdata, rc, *extra):
  190. state["connected"] = False
  191. if rc != 0:
  192. print(f"[断线] rc={rc},自动重连中")
  193. def on_subscribe(c, userdata, mid, granted_qos, *extra):
  194. print(f"[订阅成功] mid={mid} granted={granted_qos}")
  195. def on_message(c, userdata, msg):
  196. print(f"\n[收到] topic={msg.topic} bytes={len(msg.payload)}")
  197. try:
  198. env = json.loads(msg.payload.decode("utf-8"))
  199. plain = open_envelope(env, device_secret, device_code)
  200. payload = json.loads(plain.decode("utf-8"))
  201. except Exception as exc: # noqa: BLE001
  202. print(f"[解析失败] {type(exc).__name__}: {exc}")
  203. return
  204. print("[下行明文] " + json.dumps(payload, ensure_ascii=False, indent=2))
  205. task_id = str(payload.get("taskId") or "")
  206. if msg.topic.endswith("/task/command"):
  207. route = payload.get("route") or []
  208. print(f"[任务] taskId={task_id} mapCode={payload.get('mapCode')} 站点 {len(route)} 个")
  209. for p in route:
  210. print(f" seq={p.get('seq')} code={p.get('stationCode')} "
  211. f"name={p.get('stationName')} pos=({p.get('x')},{p.get('y')})")
  212. if auto_ack and task_id:
  213. # 8.4:收到指令先回 accepted,再按行进进度回 navigating
  214. first = str(route[0].get("stationCode") or "") if route else ""
  215. publish_status("accepted", first, [], "已接收任务", task_id=task_id)
  216. publish_status("navigating", first, [], "", task_id=task_id)
  217. elif not auto_ack:
  218. print("[提示] --no-auto-ack,未回执 accepted")
  219. elif msg.topic.endswith("/task/finish"):
  220. reason = payload.get("reason") or ""
  221. print(f"[结束] taskId={task_id} reason={reason or '-'}")
  222. if auto_ack and task_id:
  223. publish_status("ended", report_args.get("current_site", ""),
  224. report_args.get("finished_sites", []),
  225. reason or "收到结束指令", task_id=task_id)
  226. elif not auto_ack:
  227. print("[提示] --no-auto-ack,未回执 ended")
  228. print()
  229. client.on_connect = on_connect
  230. client.on_disconnect = on_disconnect
  231. client.on_subscribe = on_subscribe
  232. client.on_message = on_message
  233. client.reconnect_delay_set(min_delay=1, max_delay=30)
  234. print(f"===== 连接 MQTT broker {broker} =====")
  235. print(f" deviceCode = {device_code}")
  236. print(f" mqtt 账号 = {username or '(匿名)'}"
  237. f" 密码 = {'已设置(长度 %d)' % len(password) if password else '未设置'}")
  238. print(f" 自动回执 = {'开' if auto_ack else '关'}"
  239. f" 周期上报 = {'关' if not (report_args.get('task') and interval > 0) else '%ds/次' % interval}")
  240. print()
  241. try:
  242. client.connect_async(broker_host(broker), broker_port(broker), keepalive=60)
  243. client.loop_start()
  244. except Exception as exc: # noqa: BLE001
  245. print(f"连接异常: {exc}")
  246. return 1
  247. deadline = time.time() + max(connect_timeout, 1)
  248. while time.time() < deadline and not state["connected"]:
  249. time.sleep(0.2)
  250. if not state["connected"]:
  251. client.loop_stop()
  252. if state["last_rc"] in (4, 5):
  253. print(f"broker 拒绝连接(rc={state['last_rc']}):"
  254. f"{'账号或密码错误' if state['last_rc'] == 4 else '无访问权限'};"
  255. f"请核对 --username/--password(服务端同类配置 MQTT_USERNAME / MQTT_PASSWORD)。")
  256. else:
  257. print(f"连接超时({connect_timeout}s 内未连上 {broker}):请确认 broker 已启动、"
  258. f"端口/路径(ws 默认 /mqtt)正确、防火墙放行。")
  259. return 1
  260. try:
  261. if report_args.get("task") and interval > 0:
  262. print(f"[开始] 每 {interval}s 上报一次任务状态(--count 0 表示持续,Ctrl+C 退出)")
  263. while True:
  264. time.sleep(interval)
  265. if count != 0 and state["sent"] >= count:
  266. break
  267. if not state["connected"]:
  268. print("[等待重连] 暂不上报")
  269. continue
  270. publish_status(report_args["status"], report_args.get("current_site", ""),
  271. report_args.get("finished_sites", []), report_args.get("remark", ""))
  272. else:
  273. print("等待下行指令(Ctrl+C 退出)…")
  274. while True:
  275. time.sleep(1)
  276. except KeyboardInterrupt:
  277. print("\n[停止] 收到 Ctrl+C")
  278. finally:
  279. client.loop_stop()
  280. try:
  281. client.disconnect()
  282. except Exception: # noqa: BLE001
  283. pass
  284. print(f"[汇总] 共上报 {state['sent']} 次任务状态")
  285. return 0
  286. # --------------------------------------------------------------------------- #
  287. # 入口
  288. # --------------------------------------------------------------------------- #
  289. def main() -> int:
  290. parser = argparse.ArgumentParser(
  291. description="模拟轮椅客户端:接收任务指令/结束指令并上报任务状态")
  292. parser.add_argument("--base", default="tcp://127.0.0.1:1883",
  293. help="broker 地址:tcp://host:1883 或 ws://host:8083/mqtt")
  294. parser.add_argument("--device", required=True, help="设备编码 deviceCode")
  295. parser.add_argument("--secret", required=True, help="设备 deviceSecret")
  296. parser.add_argument("--username", default="", help="MQTT 连接账号")
  297. parser.add_argument("--password", default="", help="MQTT 连接密码")
  298. parser.add_argument("--task", default="", help="任务编码 taskId(周期上报时必填)")
  299. parser.add_argument("--status", default="navigating", choices=STATUS_VALUES,
  300. help="周期上报的状态(默认 navigating)")
  301. parser.add_argument("--current-site", default="", help="当前站点编码 currentSite")
  302. parser.add_argument("--finished-sites", default="",
  303. help="已完成站点,逗号分隔(如 S1,S2)")
  304. parser.add_argument("--x", default="0", help="位置 locationX(默认 0)")
  305. parser.add_argument("--y", default="0", help="位置 locationY(默认 0)")
  306. parser.add_argument("--remark", default="", help="备注 remark")
  307. parser.add_argument("--interval", type=int, default=0,
  308. help="周期上报间隔秒(0=只靠下行指令回执,默认 0)")
  309. parser.add_argument("--count", type=int, default=0, help="上报次数,0=持续")
  310. parser.add_argument("--connect-timeout", type=int, default=10, help="连接等待秒数")
  311. parser.add_argument("--no-auto-ack", action="store_true",
  312. help="收到指令后不回执 accepted/ended")
  313. parser.add_argument("--params-only", action="store_true",
  314. help="只打印上行报文参数,不连接 broker")
  315. args = parser.parse_args()
  316. device_code = args.device.strip()
  317. if not device_code:
  318. raise SystemExit("deviceCode 不能为空")
  319. finished = [s.strip() for s in args.finished_sites.split(",") if s.strip()]
  320. report_args: Dict[str, Any] = {
  321. "task": args.task.strip(),
  322. "status": args.status,
  323. "current_site": args.current_site.strip(),
  324. "finished_sites": finished,
  325. "x": str(args.x),
  326. "y": str(args.y),
  327. "remark": args.remark,
  328. }
  329. if args.params_only:
  330. if not report_args["task"]:
  331. print("提示:--params-only 需要 --task 才能生成状态反馈报文;"
  332. "下行订阅主题见下方。")
  333. print(f" {COMMAND_TOPIC_TEMPLATE.format(deviceCode=device_code)}")
  334. print(f" {FINISH_TOPIC_TEMPLATE.format(deviceCode=device_code)}")
  335. return 0
  336. print("===== 1. 生成任务状态反馈报文 =====")
  337. print(f" deviceCode = {device_code}")
  338. print(f" deviceSecret = {args.secret[:6]}…(长度 {len(args.secret)})")
  339. print()
  340. plaintext = build_status_plaintext(
  341. device_code, report_args["task"], report_args["status"],
  342. report_args["current_site"], report_args["finished_sites"],
  343. report_args["x"], report_args["y"], report_args["remark"],
  344. )
  345. topic = STATUS_TOPIC_TEMPLATE.format(deviceCode=device_code)
  346. message = build_envelope_message(args.secret, device_code, plaintext)
  347. print_uplink_params(topic, message, plaintext, args.base, args.username, args.password)
  348. return 0
  349. return run_client(args.base, device_code, args.secret, report_args,
  350. args.interval, args.count, args.connect_timeout,
  351. args.username, args.password, not args.no_auto_ack)
  352. if __name__ == "__main__":
  353. sys.exit(main())