У меня есть скрипт на Python, который прослушивает входящие полезные нагрузки mqtt и должен воспроизводить звуковой файл с Sox os.system('play --no-show-progress %s --channels 2 synth %s' % (sound1, duration))
в зависимости от публикации от клиента, но это не так.
При дальнейшем исследовании я обнаружилчто, когда я помещаю вызов для инициализации звукового файла непосредственно под функцией on_message
, звуковой файл воспроизводится.Но если я сделаю это заявление условным, оно не сможет сделать это без каких-либо ошибок.
Вот мой полный код.
import paho.mqtt.client as mqtt
from subprocess import Popen
import os
import sys
import subprocess
import time
duration = 5 # second
sound1 = "/home/pi/auto_response/laser_alert.wav"
sound2 = "/home/pi/auto_response/online.wav"
sound3 = "<path>.mp3"
sound4 = "<path>.mp3"
sound5 = "<path>.mp3"
mqtt_topics = ["laser", "motion", "cam", "temp"] # Change to multiple topics that suits your needs.
mqtt_broker_ip = "xxx.xxx.x.xx"
client = mqtt.Client()
# These functions handle what happens when the MQTT client connects
# to the broker, and what happens then the topic receives a message
def on_connect(client, userdata, flags, rc):
print "Connected!", str(rc) # rc is the error code returned when connecting to the broker
for topic in mqtt_topics:
client.subscribe(topic) # Once the client has connected to the broker, subscribe to the topic
# 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
def on_message(client, userdata, msg):
#os.system('aplay -d {} {}'.format(duration_time, response_path))
if msg.payload == "close":
os.system('play --no-show-progress %s --channels 2 synth %s' % (sound1, duration))
elif msg.payload == "open":
os.system('play --no-show-progress %s --channels 2 synth %s' % (sound1, duration))
elif msg.payload == "on":
os.system('play --no-show-progress %s --channels 2 synth %s' % (sound3, duration))
elif msg.payload == "off":
os.system('play --no-show-progress %s --channels 2 synth %s' % (sound4, duration))
elif msg.payload == "motion":
os.system('play --no-show-progress %s --channels 2 synth %s' % (sound5, duration))
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()