同时运行两个互相调用函数的循环?

2024-10-03 09:15:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要运行两个循环,一个用于侦听语音命令,另一个用于保持与MQTT代理的连接,并侦听/发布MQTT主题,在发出语音命令时进行发布。问题是,我不知道最好的办法来设置这个。在MQTT等待语音命令执行函数的情况下,如何将这些设置为同时运行/从哪里开始研究解决方案?上课?多线程?不知道从哪里开始。在

另外-旁注-这种语音识别(pocketsphinx)是绝对可怕的。它有5%的时间会出现开/关的情况,每隔一段时间就会给出各种随机响应。如果你能用一个更好的模块,或者用pocketsphinx编码来更准确的话,你可以给我指出一个正确的方向(我已经注册了一个Google云语音API密钥,但是还没有收到)。在

这是密码

在语音.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公司名称:

^{pr2}$

Tags: pyimport命令名称sourceas情况公司
2条回答

根据hardillb的建议,我研究了线程并发现了一些问题,可以用类来解决这个问题。我以前的答案是:

Running infinite loops using threads in python

Thread issue while subscribing to MQTT in Python using Paho MQTT

下面是按预期工作的完整代码。它启动语音模块和Mqtt客户机,等待yes/no(这是我能让语音模块识别的唯一一致的单词…)并在收到相应命令时打开/关闭我的Aruidno指示灯。对于那些感兴趣的人,我也将包括Arduino代码。IP地址192.168.1.2指向我的Raspberry Pi,它正在运行一个Mosquitto代理来处理MQTT主题。在

在语音.py公司名称:

import pyaudio, os
from mqttPublisher import MqttHandler
import speech_recognition as sr
from threading import Thread

class Amy(Thread):
    def mainfunction(self, source):
        audio = self.r.listen(source)
        user = self.r.recognize_sphinx(audio)
        print(user)
        if user == 'yes':
            mqtt.led_on()
        elif user == 'no':
            mqtt.led_off()
        elif user == 'get':
            mqtt.get_status()

    def __init__(self):
        Thread.__init__(self)
        self.daemon = True
        self.start()

    def run(self):
        self.r = sr.Recognizer()
        with sr.Microphone() as source:
            while True:
                self.mainfunction(source)

amy = Amy()
mqtt = MqttHandler()

amy
mqtt

while True:
    pass

在mqttPublisher.py公司名称:

^{pr2}$

Arduino代码:

#include <PubSubClient.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[]    = {0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xEF };
byte ip[] = { 192, 168, 1, 6 };
byte localserver[] = { 192, 168, 1, 2 };

const char clientID[8] = "Arduino";
const char topicName[8] = "IoT/LED";
const char on[3] = "On";
const char off[4] = "Off";
const int led = 9;

int status;

EthernetClient ethClient;
PubSubClient client(localserver, 1883, callback, ethClient);

void callback(char* topic, byte* payload, unsigned int length) {
  int load = atoi ((const char*) payload);
  if (load != 0) {
    Serial.print("\n");
    Serial.print("Payload= ");
    Serial.println(load);
    switch(load) {
      case 1:
        digitalWrite(led, HIGH);
        client.publish(topicName, on);
        Serial.print("Light turned on");
        break;
      case 2:
        digitalWrite(led, LOW);
        client.publish(topicName, off);
        Serial.print("Light turned off");
        break;
      case 3:
        status = digitalRead(led);
        if (status == 0) {
          client.publish(topicName, off);
          Serial.print("Light status: ");
          Serial.println(off);
          break;
        }
        else if (status == 1) {
          client.publish(topicName, on);
          Serial.print("Light status: ");
          Serial.println(on);
          break;
        }
      default:
        break;
    }
  }
}

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
  Ethernet.begin(mac, ip);

  if (!client.connected()) {
    Serial. print("Trying to connect...");
    client.connect(clientID);
  }
  if (client.connected()) {
    Serial.print("Connected");
    client.subscribe(topicName);
  }
}

void loop() {
  client.loop();
}

paho.mqtt.client.loop_start()启动一个线程来处理它的网络循环。打一次电话就可以了。在

相关问题 更多 >