python mqtt 指令
时间: 2024-10-06 12:05:04 浏览: 32
mqtt网关python代码
Python MQTT(Message Queuing Telemetry Transport)指令主要用于客户端与MQTT服务器之间的通信,它是轻量级的发布/订阅消息协议。在Python中,你可以使用paho-mqtt库来操作MQTT。基本的指令包括:
1. **连接到Broker**:
```python
import paho.mqtt.client as mqtt
client = mqtt.Client()
client.connect("broker.example.com", 1883) # 连接到MQTT服务器
```
2. **订阅主题(Subscription)**:
```python
client.subscribe("topic/test") # 订阅名为"test"的主题
```
3. **发布消息(Publishing a message)**:
```python
client.publish("topic/test", "Hello World") # 发布消息到"test"主题
```
4. **处理消息(On_message callback)**:
```python
def on_message(client, userdata, msg):
print(f"Received message: {msg.payload.decode()}")
client.on_message = on_message # 设置消息接收回调函数
```
5. **断开连接(Disconnect)**:
```python
client.disconnect() # 断开与Broker的连接
```
阅读全文