| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405 |
- """轮椅客户端「任务指令接收 + 任务状态反馈」模拟(MQTT)。
- 对应《MQTT 交互协议设计文档》第 5、6.2、6.3、6.5 章:
- 下行(服务端 → 设备,QoS 1):
- server/device/{deviceCode}/task/command 任务指令下发
- server/device/{deviceCode}/task/finish 结束指令
- 上行(设备 → 服务端,QoS 1):
- device/{deviceCode}/task/status 任务状态反馈
- 载荷统一为安全信封(A256GCM-HS256),deviceSecret 只用于消息层加解密/验签,
- 连接层只使用 EMQX 接入账号密码(--username/--password,可留空匿名)。
- 行为:
- 1. 订阅上述两个下行主题;收到报文后验签解密、打印明文;
- 2. 默认自动回执:收到 command → 回 `accepted`;收到 finish → 回 `ended`(--no-auto-ack 可关闭);
- 3. --task 且 --interval>0 时,按间隔周期性上报当前任务状态(可配合 --status/--current-site 等参数)。
- 用法(pyhkdf 目录下执行):
- # 1) 只打印上行报文参数,不连 broker(便于 mosquitto_pub / EMQX 控制台手工发布)
- python task_client.py --device Wheelchair-4502 --secret <deviceSecret> \
- --task TASK-20261112-000123 --status navigating --current-site S2 \
- --finished-sites S1 --params-only
- # 2) 真实连接:订阅指令 + 自动回执(Ctrl+C 退出)
- python task_client.py --device Wheelchair-4502 --secret <deviceSecret> \
- --base ws://host:8083/mqtt --username <账号> --password <密码>
- # 3) 连接并每 10s 上报一次进度(最多 6 次)
- python task_client.py --device X --secret Y --base tcp://127.0.0.1:1883 \
- --task TASK-001 --status navigating --current-site S2 --interval 10 --count 6
- """
- from __future__ import annotations
- import argparse
- import json
- import os
- import sys
- import time
- from typing import Any, Callable, Dict, List, Optional, Tuple
- from wheelchair_crypto import open_envelope, seal_envelope
- # 主题(第 5 章)
- COMMAND_TOPIC_TEMPLATE = "server/device/{deviceCode}/task/command"
- FINISH_TOPIC_TEMPLATE = "server/device/{deviceCode}/task/finish"
- STATUS_TOPIC_TEMPLATE = "device/{deviceCode}/task/status"
- QOS = 1
- # 6.5 单车反馈子状态
- STATUS_VALUES = ("accepted", "navigating", "paused", "resumed",
- "suspended", "arrived", "completed", "failed", "ended")
- # --------------------------------------------------------------------------- #
- # 上行:任务状态反馈
- # --------------------------------------------------------------------------- #
- def build_status_plaintext(device_code: str, task_id: str, status: str,
- current_site: str, finished_sites: List[str],
- x: str, y: str, remark: str) -> Dict[str, Any]:
- """构造 6.5 任务状态反馈明文(timestamp 为毫秒整数,服务端按 int64 解析)。"""
- return {
- "taskId": task_id,
- "deviceCode": device_code,
- "status": status,
- "currentSite": current_site,
- "finishedSites": finished_sites,
- "locationX": x,
- "locationY": y,
- "timestamp": int(time.time() * 1000),
- "remark": remark,
- }
- def build_envelope_message(device_secret: str, device_code: str,
- plaintext: Dict[str, Any]) -> str:
- """加密签名后返回 JSON 信封字符串(字段顺序同文档 4.2)。"""
- raw = json.dumps(plaintext, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
- env = seal_envelope(device_secret, device_code, raw)
- ordered = {
- "alg": env["alg"],
- "deviceCode": env["deviceCode"],
- "timestamp": env["timestamp"],
- "nonce": env["nonce"],
- "iv": env["iv"],
- "payload": env["payload"],
- "tag": env["tag"],
- "sign": env["sign"],
- }
- return json.dumps(ordered, ensure_ascii=False, separators=(",", ":"))
- def print_uplink_params(topic: str, message: str, plaintext: Dict[str, Any],
- broker: str, username: str, password: str) -> None:
- """打印上行状态反馈报文与手工发布命令。"""
- print("— 上行明文(6.5 任务状态反馈,加密前)—")
- print(json.dumps(plaintext, ensure_ascii=False, indent=2))
- print()
- print("— 发布主题与账号 —")
- print(f" topic = {topic} qos = {QOS} broker = {broker}")
- print(f" username = {username or '(匿名)'}"
- f" password = {'(未设置)' if not password else '******(长度 %d)' % len(password)}")
- print()
- print("— 信封载荷(单行 JSON)—")
- print(message)
- print()
- print("— 手工发布命令示例 —")
- cred = f" -u {username}" if username else ""
- if username and password:
- cred += " -P '******'"
- print(" # bash / Linux / macOS")
- print(f" mosquitto_pub -h {broker_host(broker)} -p {broker_port(broker)} "
- f"-t {topic} -q {QOS}{cred} -m '{message}'")
- print(" # Windows:把单行 JSON 存成 status.json 后用文件方式发布")
- print(f" mosquitto_pub -h {broker_host(broker)} -p {broker_port(broker)} "
- f"-t {topic} -q {QOS}{cred} -f status.json")
- print(f" # EMQX 控制台:Topics → Publish,Topic 填 {topic},QoS 选 1")
- print()
- print("— 下行订阅主题(设备需订阅,服务端发到这里)—")
- print(f" {COMMAND_TOPIC_TEMPLATE.format(deviceCode='<deviceCode>')}")
- print(f" {FINISH_TOPIC_TEMPLATE.format(deviceCode='<deviceCode>')}")
- print()
- print("提示:timestamp ±60s 防重放、nonce 一次性;参数仅打印,未连接 broker。")
- # --------------------------------------------------------------------------- #
- # MQTT 客户端
- # --------------------------------------------------------------------------- #
- def _import_paho():
- try:
- import paho.mqtt.client as mqtt # noqa: F401
- return mqtt
- except ImportError:
- raise SystemExit("缺少 paho-mqtt:请执行 pip install -r requirements.txt 后再运行。")
- def _client_id(device_code: str) -> str:
- return f"wheelchair-task-{device_code}-{os.getpid()}"
- def broker_host(broker: str) -> str:
- return broker.split("://", 1)[-1].split("/", 1)[0].split(":", 1)[0] or "127.0.0.1"
- def broker_port(broker: str) -> int:
- tail = broker.split("://", 1)[-1].split("/", 1)[0]
- if ":" in tail:
- try:
- return int(tail.split(":", 1)[1])
- except ValueError:
- pass
- return 1883
- def broker_ws(broker: str) -> Tuple[bool, str]:
- scheme = broker.split("://", 1)[0].lower() if "://" in broker else "tcp"
- if scheme not in ("ws", "wss"):
- return False, ""
- tail = broker.split("://", 1)[-1]
- path = "/" + tail.split("/", 1)[1] if "/" in tail else ""
- return True, path or "/mqtt"
- def run_client(broker: str, device_code: str, device_secret: str,
- report_args: Dict[str, Any], interval: int, count: int,
- connect_timeout: int, username: str, password: str,
- auto_ack: bool) -> int:
- mqtt = _import_paho()
- ws, ws_path = broker_ws(broker)
- client = mqtt.Client(
- client_id=_client_id(device_code),
- clean_session=False,
- protocol=mqtt.MQTTv311,
- transport="websockets" if ws else "tcp",
- )
- if ws:
- client.ws_set_options(path=ws_path)
- if username:
- client.username_pw_set(username, password or None)
- state = {"connected": False, "last_rc": 0, "sent": 0}
- def publish_status(status: str, current_site: str, finished_sites: List[str],
- remark: str = "", task_id: Optional[str] = None) -> None:
- args = dict(report_args)
- args.update({
- "status": status,
- "current_site": current_site,
- "finished_sites": finished_sites,
- "remark": remark,
- })
- # 回执用下行报文里的 taskId;周期上报才用 --task
- tid = task_id or args["task"]
- plaintext = build_status_plaintext(
- device_code, tid, args["status"], args["current_site"],
- args["finished_sites"], args["x"], args["y"], args["remark"],
- )
- topic = STATUS_TOPIC_TEMPLATE.format(deviceCode=device_code)
- message = build_envelope_message(device_secret, device_code, plaintext)
- info = client.publish(topic, payload=message, qos=QOS)
- if info.rc != 0:
- print(f"[反馈失败] status={plaintext['status']} rc={info.rc}")
- return
- state["sent"] += 1
- print(f"[反馈] taskId={plaintext['taskId']} status={plaintext['status']} "
- f"currentSite={plaintext['currentSite'] or '-'} "
- f"finished={','.join(plaintext['finishedSites']) or '-'} "
- f"pos=({plaintext['locationX']},{plaintext['locationY']})")
- def on_connect(c, userdata, flags, rc, *extra):
- if rc != 0:
- state["last_rc"] = rc
- print(f"[连接失败] rc={rc}(4=账号密码错误, 5=无权限)")
- return
- state["connected"] = True
- print(f"[已连接] broker={broker} clientId={_client_id(device_code)}")
- for topic in (COMMAND_TOPIC_TEMPLATE.format(deviceCode=device_code),
- FINISH_TOPIC_TEMPLATE.format(deviceCode=device_code)):
- c.subscribe(topic, qos=QOS)
- print(f"[订阅] {topic} QoS {QOS}")
- def on_disconnect(c, userdata, rc, *extra):
- state["connected"] = False
- if rc != 0:
- print(f"[断线] rc={rc},自动重连中")
- def on_subscribe(c, userdata, mid, granted_qos, *extra):
- print(f"[订阅成功] mid={mid} granted={granted_qos}")
- def on_message(c, userdata, msg):
- print(f"\n[收到] topic={msg.topic} bytes={len(msg.payload)}")
- try:
- env = json.loads(msg.payload.decode("utf-8"))
- plain = open_envelope(env, device_secret, device_code)
- payload = json.loads(plain.decode("utf-8"))
- except Exception as exc: # noqa: BLE001
- print(f"[解析失败] {type(exc).__name__}: {exc}")
- return
- print("[下行明文] " + json.dumps(payload, ensure_ascii=False, indent=2))
- task_id = str(payload.get("taskId") or "")
- if msg.topic.endswith("/task/command"):
- route = payload.get("route") or []
- print(f"[任务] taskId={task_id} mapCode={payload.get('mapCode')} 站点 {len(route)} 个")
- for p in route:
- print(f" seq={p.get('seq')} code={p.get('stationCode')} "
- f"name={p.get('stationName')} pos=({p.get('x')},{p.get('y')})")
- if auto_ack and task_id:
- # 8.4:收到指令先回 accepted,再按行进进度回 navigating
- first = str(route[0].get("stationCode") or "") if route else ""
- publish_status("accepted", first, [], "已接收任务", task_id=task_id)
- publish_status("navigating", first, [], "", task_id=task_id)
- elif not auto_ack:
- print("[提示] --no-auto-ack,未回执 accepted")
- elif msg.topic.endswith("/task/finish"):
- reason = payload.get("reason") or ""
- print(f"[结束] taskId={task_id} reason={reason or '-'}")
- if auto_ack and task_id:
- publish_status("ended", report_args.get("current_site", ""),
- report_args.get("finished_sites", []),
- reason or "收到结束指令", task_id=task_id)
- elif not auto_ack:
- print("[提示] --no-auto-ack,未回执 ended")
- print()
- client.on_connect = on_connect
- client.on_disconnect = on_disconnect
- client.on_subscribe = on_subscribe
- client.on_message = on_message
- client.reconnect_delay_set(min_delay=1, max_delay=30)
- print(f"===== 连接 MQTT broker {broker} =====")
- print(f" deviceCode = {device_code}")
- print(f" mqtt 账号 = {username or '(匿名)'}"
- f" 密码 = {'已设置(长度 %d)' % len(password) if password else '未设置'}")
- print(f" 自动回执 = {'开' if auto_ack else '关'}"
- f" 周期上报 = {'关' if not (report_args.get('task') and interval > 0) else '%ds/次' % interval}")
- print()
- try:
- client.connect_async(broker_host(broker), broker_port(broker), keepalive=60)
- client.loop_start()
- except Exception as exc: # noqa: BLE001
- print(f"连接异常: {exc}")
- return 1
- deadline = time.time() + max(connect_timeout, 1)
- while time.time() < deadline and not state["connected"]:
- time.sleep(0.2)
- if not state["connected"]:
- client.loop_stop()
- if state["last_rc"] in (4, 5):
- print(f"broker 拒绝连接(rc={state['last_rc']}):"
- f"{'账号或密码错误' if state['last_rc'] == 4 else '无访问权限'};"
- f"请核对 --username/--password(服务端同类配置 MQTT_USERNAME / MQTT_PASSWORD)。")
- else:
- print(f"连接超时({connect_timeout}s 内未连上 {broker}):请确认 broker 已启动、"
- f"端口/路径(ws 默认 /mqtt)正确、防火墙放行。")
- return 1
- try:
- if report_args.get("task") and interval > 0:
- print(f"[开始] 每 {interval}s 上报一次任务状态(--count 0 表示持续,Ctrl+C 退出)")
- while True:
- time.sleep(interval)
- if count != 0 and state["sent"] >= count:
- break
- if not state["connected"]:
- print("[等待重连] 暂不上报")
- continue
- publish_status(report_args["status"], report_args.get("current_site", ""),
- report_args.get("finished_sites", []), report_args.get("remark", ""))
- else:
- print("等待下行指令(Ctrl+C 退出)…")
- while True:
- time.sleep(1)
- except KeyboardInterrupt:
- print("\n[停止] 收到 Ctrl+C")
- finally:
- client.loop_stop()
- try:
- client.disconnect()
- except Exception: # noqa: BLE001
- pass
- print(f"[汇总] 共上报 {state['sent']} 次任务状态")
- return 0
- # --------------------------------------------------------------------------- #
- # 入口
- # --------------------------------------------------------------------------- #
- def main() -> int:
- parser = argparse.ArgumentParser(
- description="模拟轮椅客户端:接收任务指令/结束指令并上报任务状态")
- parser.add_argument("--base", default="tcp://127.0.0.1:1883",
- help="broker 地址:tcp://host:1883 或 ws://host:8083/mqtt")
- parser.add_argument("--device", required=True, help="设备编码 deviceCode")
- parser.add_argument("--secret", required=True, help="设备 deviceSecret")
- parser.add_argument("--username", default="", help="MQTT 连接账号")
- parser.add_argument("--password", default="", help="MQTT 连接密码")
- parser.add_argument("--task", default="", help="任务编码 taskId(周期上报时必填)")
- parser.add_argument("--status", default="navigating", choices=STATUS_VALUES,
- help="周期上报的状态(默认 navigating)")
- parser.add_argument("--current-site", default="", help="当前站点编码 currentSite")
- parser.add_argument("--finished-sites", default="",
- help="已完成站点,逗号分隔(如 S1,S2)")
- parser.add_argument("--x", default="0", help="位置 locationX(默认 0)")
- parser.add_argument("--y", default="0", help="位置 locationY(默认 0)")
- parser.add_argument("--remark", default="", help="备注 remark")
- parser.add_argument("--interval", type=int, default=0,
- help="周期上报间隔秒(0=只靠下行指令回执,默认 0)")
- parser.add_argument("--count", type=int, default=0, help="上报次数,0=持续")
- parser.add_argument("--connect-timeout", type=int, default=10, help="连接等待秒数")
- parser.add_argument("--no-auto-ack", action="store_true",
- help="收到指令后不回执 accepted/ended")
- parser.add_argument("--params-only", action="store_true",
- help="只打印上行报文参数,不连接 broker")
- args = parser.parse_args()
- device_code = args.device.strip()
- if not device_code:
- raise SystemExit("deviceCode 不能为空")
- finished = [s.strip() for s in args.finished_sites.split(",") if s.strip()]
- report_args: Dict[str, Any] = {
- "task": args.task.strip(),
- "status": args.status,
- "current_site": args.current_site.strip(),
- "finished_sites": finished,
- "x": str(args.x),
- "y": str(args.y),
- "remark": args.remark,
- }
- if args.params_only:
- if not report_args["task"]:
- print("提示:--params-only 需要 --task 才能生成状态反馈报文;"
- "下行订阅主题见下方。")
- print(f" {COMMAND_TOPIC_TEMPLATE.format(deviceCode=device_code)}")
- print(f" {FINISH_TOPIC_TEMPLATE.format(deviceCode=device_code)}")
- return 0
- print("===== 1. 生成任务状态反馈报文 =====")
- print(f" deviceCode = {device_code}")
- print(f" deviceSecret = {args.secret[:6]}…(长度 {len(args.secret)})")
- print()
- plaintext = build_status_plaintext(
- device_code, report_args["task"], report_args["status"],
- report_args["current_site"], report_args["finished_sites"],
- report_args["x"], report_args["y"], report_args["remark"],
- )
- topic = STATUS_TOPIC_TEMPLATE.format(deviceCode=device_code)
- message = build_envelope_message(args.secret, device_code, plaintext)
- print_uplink_params(topic, message, plaintext, args.base, args.username, args.password)
- return 0
- return run_client(args.base, device_code, args.secret, report_args,
- args.interval, args.count, args.connect_timeout,
- args.username, args.password, not args.no_auto_ack)
- if __name__ == "__main__":
- sys.exit(main())
|