You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
'''
|
|
# Filename: mqtt_sub.py
|
|
# Author: Cai Gui Lin
|
|
# Created on: 2024-09-2
|
|
# Modified on: 2024-09-2
|
|
# Version: 2.0
|
|
# Copyright (c) 2024 Cai Gui Lin
|
|
# License: MIT
|
|
# Description: mqtt subscriber
|
|
# Contact: 18166451309@163.com
|
|
|
|
'''
|
|
import random
|
|
from paho.mqtt import client as mqtt_client
|
|
import re
|
|
client_id = f'python-mqtt-{random.randint(0, 100)}'
|
|
def connect_mqtt(username, password, broker, port) -> mqtt_client:
|
|
def on_connect(client, userdata, flags, rc):
|
|
if rc == 0:
|
|
print("Mqtt ok, Ready to subscribe.")
|
|
else:
|
|
print("Failed to connect mqtt, return code %d\n", rc)
|
|
|
|
client = mqtt_client.Client(client_id)
|
|
client.username_pw_set(username=username,password=password)
|
|
client.on_connect = on_connect
|
|
client.connect(broker, port)
|
|
return client
|
|
|
|
|
|
def subscribe(queue, client, sub_topic):
|
|
queue = queue
|
|
def on_message(client, userdata, msg):
|
|
# 解码消息负载为字符串
|
|
payload_str = msg.payload.decode()
|
|
# pattern = r'"channelId": (\d+)|"time": (\d+)'
|
|
# matches = re.findall(pattern, payload_str)
|
|
# print(payload_str)
|
|
queue.put(payload_str)
|
|
client.subscribe(sub_topic)
|
|
client.on_message = on_message
|
|
|
|
def sub_run(queue, username, password, broker, port, sub_topic):
|
|
client = connect_mqtt(username, password, broker, port)
|
|
subscribe(queue, client, sub_topic)
|
|
client.loop_forever()
|
|
|
|
if __name__ == '__main__':
|
|
username = "stark"
|
|
password = "12345678"
|
|
broker = "47.120.70.16"
|
|
port = 1883
|
|
sub_topic = "/smell/cmd"
|
|
sub_run(username, password, broker, port, sub_topic)
|
|
|