modify: 测试

This commit is contained in:
2026-08-23 05:10:27 +08:00
parent a1be33376e
commit eeffc06841
24 changed files with 2 additions and 2 deletions
+51
View File
@@ -0,0 +1,51 @@
"""
MQTT Publisher — 向 chongming Worker 发送 MQTT 请求
用法:
python publisher.py <worker_type> <operation> [json_payload]
示例(信封协议,meta 可选):
python publisher.py example add '{"meta": {"method": "GET"}, "data": {"a": 3, "b": 5}}'
python publisher.py example add '{"a": 3, "b": 5}' # 扁平载荷自动包装(method=GET)
python publisher.py example add '{"meta": {"method": "MQTT"}, "data": {"a": 3, "b": 5}}'
"""
import asyncio
import sys
import json
import logging
from amqtt.client import MQTTClient
from amqtt.mqtt.constants import QOS_1
logging.basicConfig(level=logging.INFO)
# MQTT 主题前缀(与 mqtt_bridge.py 保持一致)
PREFIX = "chongming"
# 默认参数
DEFAULT_WORKER = "example"
DEFAULT_OP = "add"
DEFAULT_PAYLOAD = {"meta": {"method": "GET"}, "data": {"a": 3, "b": 5}}
async def main():
worker_type = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_WORKER
operation = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_OP
payload_str = sys.argv[3] if len(sys.argv) > 3 else json.dumps(DEFAULT_PAYLOAD)
topic = f"{PREFIX}/{worker_type}/{operation}"
payload = json.loads(payload_str)
# 扁平载荷自动包装为信封(method 默认 GET),已含 meta/data 则原样使用
if not (isinstance(payload, dict) and ("meta" in payload or "data" in payload)):
payload = {"meta": {"method": "GET"}, "data": payload}
client = MQTTClient()
await client.connect("mqtt://localhost:1883/")
await client.publish(topic, json.dumps(payload).encode("utf-8"), QOS_1)
print(f"[Publisher] Sent to '{topic}': {payload}")
await client.disconnect()
print("[Publisher] Disconnected")
if __name__ == "__main__":
asyncio.run(main())