paho-mqtt 通讯测试代码

该代码示例展示了如何使用paho-mqtt库在Python中建立MQTT客户端,连接到服务器(127.0.0.1),订阅和发布消息。客户端订阅主题/test/sx789,并处理接收到的消息。同时,程序创建多个线程发送不同消息到服务器,并演示了错误处理和消息确认机制。
import random
import paho.mqtt.client as mqtt
import paho.mqtt.publish as mqttpublish
import time, threading

HOST = "127.0.0.1"  # "broker.emqx.io"  #
PORT = 1883
TOPIC = "/test/sx789"
USER, PASSWORD = "", ""  #  "admin", "123456"


def connect_mqtt():
    client_id = f"C{int(time.time() * 1000)}_{random.randint(0, 1000)}"
    client = mqtt.Client(client_id)
    if USER:
        client.username_pw_set(USER, PASSWORD)
    client.connect(HOST, PORT, 60)
    return client


def client_sub():
    def on_connect(client, userdata, flags, rc):
        if rc:
            print("Connected ERROR with code " + str(rc))
        client.subscribe(TOPIC)

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

    client = connect_mqtt()
    client.on_connect = on_connect
    client.on_message = on_message
    client.loop_forever()


def publish(client, msg):
    result = client.publish(TOPIC, msg, qos=1, retain=False)
    if result[0]:
        print(f"Failed to send message to topic {TOPIC}")
    else:
        pass  # print(f"Send `{msg}` to topic `{TOPIC}`")
    # time.sleep(1)


def sendmsg(msg):
    mqttpublish.single(
        TOPIC,
        msg,
        qos=1,
        hostname=HOST,
        port=PORT,
        client_id=f"temp{random.randint(0, 1000)}",
        auth={"username": USER, "password": PASSWORD} if USER else {},
    )


if __name__ == "__main__":
    for i in range(1, 15):
        threading.Timer(
            1 + i * 0.1,
            sendmsg,
            (f"你好,MQTT! {i} {time.strftime('%Y%m%d_%H%M%S', time.localtime())}",),
        ).start()
    s = connect_mqtt()
    for i in range(1, 15):
        threading.Timer(1 + i * 0.1, publish, (s, f"传输:{i}")).start()

    t = threading.Thread(target=client_sub)
    t.daemon = True
    t.start()

    print("ok")


# pip install paho-mqtt
# "D:\Program Files\mosquitto\mosquitto.exe" -v
# mosquitto -p 10086 -v
# mosquitto_sub -t test -v  -u admin -P 123456
# mosquitto_pub -t 'test/topic' -m "'hello world 中国"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值