当前位置:   article > 正文

ubuntu安装mqtt,python发布订阅_ubuntu mqtt python

ubuntu mqtt python

1、安装MQTT

  1. #要安装最新版本的MQTT服务器,需配置 Mosquitto 源
  2. apt-add-repository ppa:mosquitto-dev/mosquitto-ppa
  3. apt-get update
  4. #安装
  5. apt install mosquitto
  6. #安装 mosquitto-clients 才会有 mosquitto_sub 和 mosquitto_pub 命令
  7. apt install mosquitto mosquitto-clients
  8. #安装 MQTT 开发库
  9. apt install mosquitto-dev
  10. #启动
  11. mosquitto -v -d -c /etc/mosquitto/mosquitto.conf

2、启动 MQTT 服务

  1. #启动
  2. osquitto -v
  3. #启动
  4. mosquitto -v -d -c /etc/mosquitto/mosquitto.conf
  5. #重启
  6. /etc/init.d/mosquitto restart

订阅一个消息:
>>mosquitto_sub -t 'myopic' -v -d

发布一个消息:
>>mosquitto_pub -t 'mytopic' -m 'hello world' -d

3、设置密码

 1、创建用户

  1. #方式1
  2. #这里是创建一个新的 mqtt 用户 scott,接下来就会问密码与确认密码,目前是设置为 123456
  3. mosquitto_passwd -c /etc/mosquitto/passwd scott
  4. #方式2
  5. #这里是创建一个新的 mqtt 用户 zhangsan ,设置为 123456
  6. mosquitto_passwd -b /etc/mosquitto/passwd zhangsan 123456

 2、修改配置文件

  1. #添加配置,禁止匿名用户以及指定密码文件
  2. vim /etc/mosquitto/conf.d/default.conf

allow_anonymous false
password_file /etc/mosquitto/passwd

 3、重启 MQTT 服务

/etc/init.d/mosquitto restart

4、测试

 发布

  1. mosquitto_pub -t 'mytopic' -m 'hello world2' -d -u scott -P 123456 -q 2
  2. Client null sending CONNECT
  3. Client null received CONNACK (0)
  4. Client null sending PUBLISH (d0, q2, r0, m1, 'mytopic', ... (12 bytes))
  5. Client null received PUBREC (Mid: 1)
  6. Client null sending PUBREL (m1)
  7. Client null received PUBCOMP (Mid: 1, RC:0)
  8. Client null sending DISCONNECT

 订阅

  1. /etc/mosquitto# mosquitto_sub -t 'mytopic' -v -d -u scott -P 123456 -q 2
  2. Client null sending CONNECT
  3. Client null received CONNACK (0)
  4. Client null sending SUBSCRIBE (Mid: 1, Topic: mytopic, QoS: 2, Options: 0x00)
  5. Client null received SUBACK
  6. Subscribed (mid: 1): 2
  7. Client null received PUBLISH (d0, q2, r0, m1, 'mytopic', ... (12 bytes))
  8. Client null sending PUBREC (m1, rc0)
  9. Client null received PUBREL (Mid: 1)
  10. Client null sending PUBCOMP (m1)
  11. mytopic hello world2

python代码

首先,先修改配置文件,增加ip和端口号,否则只能用127.0.0.1.

bind_address 192.168.31.129
port 1883

 然后重启。

python代码如下

publish.py
  1. import random
  2. import time
  3. from paho.mqtt import client as mqtt_client
  4. broker = '192.168.31.129'
  5. port = 1883
  6. topic = "mytopic"
  7. user = "scott"
  8. password = "123456"
  9. # generate client ID with pub prefix randomly
  10. client_id = f'python-mqtt-{random.randint(0, 1000)}'
  11. def connect_mqtt():
  12. def on_connect(client, userdata, flags, rc):
  13. if rc == 0:
  14. print("Connected to MQTT Broker!")
  15. else:
  16. print("Failed to connect, return code %d\n", rc)
  17. client = mqtt_client.Client(client_id, transport='tcp')
  18. client.username_pw_set(user, password=password)
  19. client.on_connect = on_connect
  20. client.connect(broker, port)
  21. return client
  22. def publish(client):
  23. msg_count = 0
  24. while True:
  25. time.sleep(1)
  26. msg = f"messages: {msg_count}"
  27. result = client.publish(topic, msg,qos=2)
  28. # result: [0, 1]
  29. status = result[0]
  30. if status == 0:
  31. print(f"Send `{msg}` to topic `{topic}`")
  32. else:
  33. print(f"Failed to send message to topic {topic}")
  34. msg_count += 1
  35. def run():
  36. client = connect_mqtt()
  37. client.loop_start()
  38. publish(client)
  39. if __name__ == '__main__':
  40. run()
subscribe.py
  1. import random
  2. from paho.mqtt import client as mqtt_client
  3. broker = '192.168.31.129'
  4. port = 1883
  5. user = "scott"
  6. password = "123456"
  7. topic = "mytopic"
  8. # generate client ID with pub prefix randomly
  9. client_id = f'python-mqtt-{random.randint(0, 100)}'
  10. def connect_mqtt() -> mqtt_client:
  11. def on_connect(client, userdata, flags, rc):
  12. if rc == 0:
  13. print("Connected to MQTT Broker!")
  14. else:
  15. print("Failed to connect, return code %d\n", rc)
  16. client = mqtt_client.Client(client_id, transport='tcp')
  17. client.username_pw_set(user, password=password)
  18. client.on_connect = on_connect
  19. client.connect(broker, port)
  20. return client
  21. def subscribe(client: mqtt_client):
  22. def on_message(client, userdata, msg):
  23. print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
  24. client.subscribe(topic)
  25. client.on_message = on_message
  26. def run():
  27. client = connect_mqtt()
  28. subscribe(client)
  29. client.loop_forever()
  30. if __name__ == '__main__':
  31. run()

运行效果

 

 命令订阅

 命令发布

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/543211
推荐阅读
相关标签
  

闽ICP备14008679号