Files
chongming-core/test/publisher.py
T
2026-08-23 05:10:27 +08:00

51 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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())