# wget http://file.ofs.com/hv/script/umqtt/mqtt.py script/umqtt/mqtt.py # mqtt_client.py 测试 from script.umqtt.simple import MQTTClient from binascii import hexlify import machine import _thread import time, sys class MQTTClientThread: def __init__(self, server, client_id): self.server = server self.client_id = client_id self.running = False self.send_list = [] self.receive_list = [] self.lock = _thread.allocate_lock() self.client = MQTTClient(client_id, server) def sub_cb(self, topic, msg): with self.lock: self.receive_list.append((topic, msg)) # 将接收到的消息添加到接收列表 print("Received: {}".format((topic, msg))) def run(self): try: self.client.set_callback(self.sub_cb) self.client.connect() print("Connected to {}".format(self.server)) for topic in self.sub_list: self.client.subscribe(topic) self.running = True while self.running: self.client.check_msg() self.process_messages() print("mqtt exit") except Exception as e: sys.print_exception(e) finally: _thread.exit() self.client.disconnect() print("mqtt stop") def process_messages(self): with self.lock: while self.send_list: topic, msg, qos = self.send_list.pop(0) # 从发送列表中取出第一个消息 self.client.publish(topic, msg, qos) # print("Sent: {} to topic: {} with QoS: {}".format(msg, topic, qos)) def start(self): if not self.running: _thread.stack_size(18192) _thread.start_new_thread(self.run, ()) def stop(self): self.running = False def send_message(self, topic, message, qos=0): with self.lock: self.send_list.append((topic, message, qos)) # 将消息添加到发送列表 # print("Queued for sending: {}".format((topic, message, qos))) def take_message(self): with self.lock: if self.receive_list: return self.receive_list.pop(0) # 返回并移除接收列表的第一个消息 else: return None # 如果没有消息,返回 None def start_mqtt_client(params={}): server = params['broker']['ip'] client_id = params['broker']['clientid'] + hexlify(machine.unique_id()).decode()[0:8] mqtt_client = MQTTClientThread(server, client_id) mqtt_client.client.port = params['broker']['port'] mqtt_client.client.user = params['broker']['user'] mqtt_client.client.pswd = params['broker']['passwd'] mqtt_client.sub_list = params['topic']['sub'] mqtt_client.start() return mqtt_client