# python 3.6
import random
import time
from paho.mqtt import client as mqtt_client
broker = '192.168.1.88'
port = 1883
topic = "zigbee2mqtt/0x54ef44100035e399/set"
# generate client ID with pub prefix randomly
client_id = f'python-mqtt-{random.randint(0, 1000)}'
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.username_pw_set("autozq","39176430") # 必须设置,否则会返回「Connected with result code 4
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
msg_count = 0
while True:
time.sleep(1)
msg = "{\"state\": \"TOGGLE\"}"#f"messages: {msg_count}"
result = client.publish(topic, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
msg_count += 1
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
run()
没有合适的资源?快使用搜索试试~ 我知道了~
Python的paho-mqtt客户端库使用例程
共4个文件
py:4个
11 下载量 73 浏览量
2022-12-15
14:32:24
上传
评论
收藏 3KB RAR 举报
温馨提示
Python的paho-mqtt客户端库使用例程,通过paho-mqtt客户端库实现了订阅主题和发布主题,快速上手MQTT
资源推荐
资源详情
资源评论
收起资源包目录
Python的paho-mqtt客户端库使用.rar (4个子文件)
Python的paho-mqtt客户端库使用
paho-mqtt客户端消息发布完整代码.py 1KB
客户端订阅消息测试.py 1KB
paho-mqtt客户端消息订阅完整代码.py 1KB
客户端发布消息测试.py 1KB
共 4 条
- 1
资源评论
豪哥追求卓越
- 粉丝: 82
- 资源: 26
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功