Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import paho.mqtt.client as mqtt
- from subprocess import Popen
- import os
- import sys
- import subprocess
- import time
- # Don't forget to change the variables for the MQTT broker!
- #mqtt_topic = "button"
- mqtt_topic = "test"
- mqtt_topic = "test1"
- mqtt_username = "username"
- mqtt_password = "qwerty"
- mqtt_broker_ip = "192.168.43.207"
- client = mqtt.Client()
- # These functions handle what happens when the MQTT client connectsmqtt_username = "MQTT Username"
- # to the broker, and what happens then the topic receives a messageesponse_path = '/home/pi/auto_response/gas_alert.wav'
- def on_connect(client, userdata, flags, rc):
- # rc is the error code returned when connecting to the brokeresponse_path = '/home/pi/auto_response/gas_alert.wav'
- print "Connected!", str(rc)
- # Once the client has connected to the broker, subscribe to the topic
- client.subscribe(mqtt_topic)
- def on_message(client, userdata, msg):
- # This function is called everytime the topic is published to.
- # If you want to check each message, and do something depending on
- # the content, the code to do this should be run in this function
- os.system('aplay -d {} {}'.format(duration_time, response_path))
- print "Topic: ", msg.topic + "\nMessage: " + str(msg.payload)
- # The message itself is stored in the msg variable
- # and details about who sent it are stored in userdata
- # Here, we are telling the client which functions are to be run
- # on connecting, and on receiving a message
- client.on_connect = on_connect
- client.on_message = on_message
- # Once everything has been set up, we can (finally) connect to the broker
- # 1883 is the listener port that the MQTT broker is using
- client.connect(mqtt_broker_ip, 1883)
- # Once we have told the client to connect, let the client object run itself
- client.loop_forever()
- client.disconnect()
Add Comment
Please, Sign In to add comment