MQTT客户端实现 Python

Reads: 1031 Edit

Python MQTT客户端实现

使用Python Package Index (PyPi)

pip install paho-mqtt

发布数据

# -*- coding: utf-8 -*-

import paho.mqtt.publish as publish
import time

HOST = "192.168.11.10"
PORT = 1883

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("wang")

def on_message(client, userdata, msg):
    print(msg.topic + " " + msg.payload.decode("utf-8"))


if __name__ == '__main__':
    client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    # client = mqtt.Client(client_id)    # ClientId不能重复,所以使用当前时间
    # client.username_pw_set("admin", "123456")  # 必须设置,否则会返回「Connected with result code 4」
    # client.on_connect = on_connect
    # client.on_message = on_message
    # client.connect(HOST, PORT, 60)
    # client.publish("test", "你好 MQTT", qos=0, retain=False)  # 发布消息

    publish.single("wang", "你好 MQTT", qos=1, hostname=HOST, port=PORT, client_id=client_id,
                   auth={'username': "admin", 'password': "public"})

接受数据

# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import time

HOST = "192.168.11.10"
PORT = 1883

def client_loop():
    client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
    client = mqtt.Client(client_id)  # ClientId不能重复,所以使用当前时间
    client.username_pw_set("admin", "public")  # 必须设置,否则会返回「Connected with result code 4」
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(HOST, PORT, 60)
    client.loop_forever()

def on_connect(client, userdata, flags, rc):
    print("Connected with result code " + str(rc))
    client.subscribe("wang")

def on_message(client, userdata, msg):
    print(msg.topic + " " + msg.payload.decode("utf-8"))

if __name__ == '__main__':
    client_loop()

关于作者

王硕,网名信平,十多年软件开发经验,业余架构师,精通Java/Python/Go等,喜欢研究技术,著有《PyQt 5 快速开发与实战》《Python 3.* 全栈开发》,多个业余开源项目托管在GitHub上,欢迎微博交流。


Comments

Make a comment

www.ultrapower.com ,王硕的博客,专注于研究互联网产品和技术,提供中文精品教程。 本网站与其它任何公司及/或商标无任何形式关联或合作。