Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
WHW/Xiong
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
52 lines (42 sloc)
1.68 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import paho.mqtt.client as mqtt | |
import logging | |
# 配置日志 | |
logging.basicConfig(level=logging.INFO, | |
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', | |
handlers=[logging.FileHandler("mqtt_client.log"), logging.StreamHandler()]) | |
# 创建一个logger对象 | |
logger = logging.getLogger(__name__) | |
# 设置遗嘱消息 | |
LWT_TOPIC = "client" | |
LWT_MESSAGE = "offline" | |
LWT_QOS = 0 | |
LWT_RETAIN = True | |
# 提示用户输入用户名和密码 | |
USERNAME = input("请输入MQTT用户名: ") | |
PASSWORD = input("请输入MQTT密码: ") | |
BROKER_ADDRESS = '127.0.0.1' | |
BROKER_PORT = 1883 | |
CLIENT_ID = 'mqttx_809f42de' # 客户端 ID | |
# 订阅的主题 | |
#TOPICS = [("examinfo", 0), ("activityinfo", 0)] | |
# 从用户获取要订阅的主题和QoS | |
topics_input = input("请输入要订阅的主题(以逗号分隔,可选后跟空格和QoS值,例如:topic1 1,topic2):") | |
topics_list = [] | |
for topic_input in topics_input.split(','): | |
topic_parts = topic_input.split() | |
topic = topic_parts[0] | |
qos = 0 if len(topic_parts) == 1 else int(topic_parts[1]) | |
topics_list.append((topic, qos)) | |
def on_connect(client, userdata, flags, rc): | |
logger.info(f"Connected with result code {rc}") | |
print(f"Connected with result code {rc}") | |
# 检查连接是否成功 | |
if rc == 0: | |
for topic, qos in topics_list: | |
client.subscribe(topic, qos) | |
else: | |
print(f"Failed to connect, result code {rc}") | |
# 回调函数,当接收到订阅的主题消息时触发 | |
def on_message(client, userdata, msg): | |
logger.info(f"Received message on topic {msg.topic}: {str(msg.payload)}") | |
print(f"Received message on topic {msg.topic}: {str(msg.payload)}") |