I have 2 loops I need to run, one to listen for voice commands and the other to stay connected to an MQTT broker and listen for/post to an MQTT topic, posting when a voice command is issued. Problem is, I'm not sure of the best way to set this up. How would I set these up to both run, with MQTT waiting for a voice command to execute functions/where would I start researching the solution? Classes? Multithreading? Not real sure where to begin.
Also - side note - this voice recognition(pocketsphinx) is absolutely horrible. It picks up on/off maybe 5% of the time, giving all kinds of random response every other time. Bonus bro points if you can point me in the right direction to fix that by using a better module or possible coding pocketsphinx to be more accurate (I've already signed up for a Google Cloud-Speech API key but have not yet received it).
Here's the code
voice.py:
import pyaudio, os
import mqttPublisher
import speech_recognition as sr
def mainfunction(source):
audio = r.listen(source)
user = r.recognize_sphinx(audio)
print(user)
if user == 'on':
mqttPublisher.led_on()
elif user == 'off':
mqttPublisher.led_off()
if __name__ == '__main__':
r = sr.Recognizer()
with sr.Microphone() as source:
while 1:
mainfunction(source)
mqttPublisher.py:
import paho.mqtt.client as mqtt
def led_on():
mqttc.publish("IoT/LED", payload="1")
print("LED is ON")
def led_off():
mqttc.publish("IoT/LED", payload="2")
print("LED is OFF")
def get_status():
mqttc.publish("IoT/LED", payload="3")
def on_connect(client, userdata, flags, rc):
mqttc.publish("IoT/LED", "connected")
print("connected")
def on_subscribe(client, userdata, mid, granted_qos):
mqttc.publish("IoT/LED", payload="3")
print("subscribed")
def on_publish(client, userdata, mid):
print("message published")
def on_message(client, userdata, message):
print("message printed to topic")
def on_disconnect(client, userdata, rc):
print("Client Disconnected")
mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_subscribe = on_subscribe
mqttc.on_message = on_message
mqttc.on_publish = on_publish
mqttc.on_disconnect = on_disconnect
mqttc.connect("192.168.1.3", 1883)
mqttc.subscribe("IoT/LED", 1)
run = True
while run:
mqttc.loop_start()