history-project/SCLP/auto_callback.py
2024-10-24 09:23:39 +08:00

52 lines
1.5 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.

# -*- coding:utf-8 -*-
"""
@Author : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc : 用于自动回复mqtt用于测试模拟设备下发请求成功
"""
import json
import time
import paho.mqtt.client as mqtt
from utils import logger
from config import BROKER_HOST, BROKER_PORT, BROKER_USERNAME, BROKER_PASSWD
def on_connect(client, userdata, flags, rc):
logger.Logger.debug(f"\033[1;32mAUTO CALLBACK\033[0m 🔗 Mqtt connection! {{rc: {rc}}} 🔗")
client.subscribe("/jmlink/+/tml/service/call")
def on_disconnect(client, userdata, rc):
logger.Logger.debug(f"\033[1;31mAUTO CALLBACK\033[0m 🔌 Break mqtt connection! {{rc: {rc}}} 🔌")
def on_message(client, userdata, message):
logger.Logger.debug("\033[1;36mAUTO CALLBACK\033[0m <- 💡 接收到新数据,执行 on_message 中 ...")
msg = json.loads(message.payload.decode().replace("\x00", ""))
print(f"msg: {msg}")
if "messageId" in msg.keys():
topic = f"{message.topic}_resp"
print(topic)
auto_callback = {
"messageId": msg["messageId"],
"code": 0,
"data": {
"code": 0
}
}
client.publish(topic, json.dumps(auto_callback))
print(auto_callback)
client = mqtt.Client(client_id="auto_callback@python")
client.on_connect = on_connect
client.on_disconnect = on_disconnect
client.on_message = on_message
client.username_pw_set(BROKER_USERNAME, BROKER_PASSWD)
client.connect(BROKER_HOST, BROKER_PORT)
client.loop_start()
while True:
time.sleep(86400)