Guest User

Ambuje

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