Python MQTT introduce essay

灰太狼 2023-06-07 12:24 91阅读 0赞

2019-10-15

MQTT in Python

  • MQTT(Message Queuing Telemetry Transport)
  • IoT(Internet of Things) protocol,
  • supports Python 2.7.9+ or 3.4+
  • include server,client(pub and sub)
  • message include

    • topic——message type,after subscriber subscribe the topic,it will receive the message content of the topic(payload)
    • payload——message content
  • Architecture diagram
    007X8olVly1g7yp2t4rulj30ua08z74c.jpg
  • install

    pip install paho-mqtt

 or with virtualenv

  1. virtualenv paho-mqtt
  2. source paho-mqtt/bin/activate
  3. pip install paho-mqtt

 full code

  1. git clone git://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.python.git
  • import

    import paho.mqtt.client as mqtt

  • example
    pub.py

    -- coding: utf-8 --

    import paho.mqtt.client as mqtt

    MQTTHOST = “127.0.0.1”
    MQTTPORT = 1883
    client = mqtt.Client()

  1. def connnect():
  2. client.connect(MQTTHOST,MQTTPORT,60)
  3. def pub(topic,message,qos):
  4. client.publish(topic,message,qos)
  5. print('pub success!')
  6. def main():
  7. connnect()
  8. text=input('please input text:')
  9. while text:
  10. #send a message which topic is 'test'
  11. pub("test",text,2)
  12. client.loop_start()
  13. text=input('please input text:')
  14. if __name__=="__main__":
  15. main()

  sub.py

  1. # -*- coding: utf-8 -*-
  2. import paho.mqtt.client as mqtt
  3. MQTTHOST = "127.0.0.1"
  4. MQTTPORT = 1883
  5. client = mqtt.Client()
  6. def connnect():
  7. client.connect(MQTTHOST,MQTTPORT,60)
  8. client.loop_start()
  9. def on_message(client,user,msg):
  10. # msg.payload's type is bytes,so we must decode it
  11. print("get message:topic=%s content=%s"%(msg.topic,msg.payload.decode()))
  12. def sub():
  13. client.subscribe('test',2)
  14. client.on_message=on_message #function to receive messages
  15. def main():
  16. connnect()
  17. sub()
  18. while True:
  19. pass
  20. # client.loop_forever()
  21. if __name__=="__main__":
  22. main()
  • runserver–mosquitto
    install
    https://mosquitto.org/download/

    notice:article’s example is for windows.

    run demo

    • terminal 1 for server

      mosquitto -d -v

    • terminal 2 for sub

      mosquitto_sub -t test

    • terminal 3 for pub

      mosquitto_pub -t test -m “haloha”

    while you excute the terminal 3’s command,the terminal 2 will display the message ‘haloha’.

  • run Python demo
    start mosquitto server

    1. mosquitto -d -v

    then run sub.py to to subscribe topic and run pub.py to send message.

  run sub.py

  result

  1. D:\PythonProject>python .\sub.py
  2. get message:topic=test content=hello
  3. get message:topic=test content=how are you

  run pub.py

  result

  1. D:\PythonProject> python .\pub.py
  2. please input text:hello
  3. pub success!
  4. please input text:how are you
  5. pub success!

发表评论

表情:
评论列表 (有 0 条评论,91人围观)

还没有评论,来说两句吧...

相关阅读