Guest User

Ambuje

a guest
Aug 19th, 2018
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. import paho.mqtt.client as mqtt
  2.  
  3. # Don't forget to change the variables for the MQTT broker!
  4. mqtt_username = "username"
  5. mqtt_password = "qwerty"
  6. mqtt_topic = "test1"
  7. mqtt_broker_ip = "192.168.43.207"
  8.  
  9. client = mqtt.Client()
  10. # Set the username and password for the MQTT client
  11. client.username_pw_set(mqtt_username, mqtt_password)
  12.  
  13. # These functions handle what happens when the MQTT client connects
  14. # to the broker, and what happens then the topic receives a message
  15. def on_connect(client, userdata,flags,rc):
  16. # rc is the error code returned when connecting to the broker
  17. print "Connected!", str(rc)
  18.  
  19. # Once the client has connected to the broker, subscribe to the topic
  20. client.subscribe(mqtt_topic)
  21.  
  22. def on_message(client, userdata, msg):
  23. # This function is called everytime the topic is published to.
  24. # If you want to check each message, and do something depending on
  25. # the content, the code to do this should be run in this function
  26.  
  27. print "Topic: ", msg.topic + "\nMessage: " + str(msg.payload)
  28.  
  29. # The message itself is stored in the msg variable
  30. # and details about who sent it are stored in userdata
  31.  
  32. # Here, we are telling the client which functions are to be run
  33. # on connecting, and on receiving a message
  34. client.on_connect = on_connect
  35. client.on_message = on_message
  36.  
  37. # Once everything has been set up, we can (finally) connect to the broker
  38. # 1883 is the listener port that the MQTT broker is using
  39. client.connect(mqtt_broker_ip, 1883)
  40.  
  41. # Once we have told the client to connect, let the client object run itself
  42. client.loop_forever()
  43. client.disconnect()
  44.  
  45. Topic: ", msg.topic + "\nMessage: " + str(msg.payload)
  46.  
  47. # The message itself is stored in the msg variable
  48. # and details about who sent it are stored in userdata
  49.  
  50. # Here, we are telling the client which functions are to be run
  51. # on connecting, and on receiving a message
  52. client.on_connect = on_connect
  53. client.on_message = on_message
  54.  
  55. # Once everything has been set up, we can (finally) connect to the broker
  56. # 1883 is the listener port that the MQTT broker is using
  57. client.connect(mqtt_broker_ip, 1883)
  58.  
  59. # Once we have told the client to connect, let the client object run itself
  60. client.loop_forever()
  61. client.disconnect()
Add Comment
Please, Sign In to add comment