python对mqtt进行封装成类函数
时间: 2023-10-13 21:22:19 浏览: 156
下面是一个简单的Python类函数,用于封装MQTT:
```python
import paho.mqtt.client as mqtt
class MQTT:
def __init__(self, broker_address, username=None, password=None):
self.client = mqtt.Client()
if username and password:
self.client.username_pw_set(username, password)
self.client.connect(broker_address)
def publish(self, topic, payload, qos=0, retain=False):
self.client.publish(topic, payload, qos, retain)
def subscribe(self, topic, qos=0):
self.client.subscribe(topic, qos)
def on_message(self, callback):
self.client.on_message = callback
def loop_forever(self):
self.client.loop_forever()
```
使用示例:
```python
def on_message(client, userdata, message):
print(message.topic + " " + str(message.payload))
mqtt = MQTT("localhost")
mqtt.subscribe("test/topic")
mqtt.on_message(on_message)
mqtt.loop_forever()
```
这个类函数封装了MQTT的连接、发布、订阅和消息处理等功能,可以方便地在Python中使用MQTT。
阅读全文