mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-25 04:29:51 +01:00
71 lines
2.1 KiB
Python
71 lines
2.1 KiB
Python
import logging
|
||
from typing import Protocol
|
||
|
||
from ..config import RuntimeConfig
|
||
from ..plugins import AudioPlugin, PluginManager, WakeWordPlugin
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
class EventPublisher(Protocol):
|
||
def publish_service_ready(self) -> None:
|
||
...
|
||
|
||
def publish_service_stopping(self) -> None:
|
||
...
|
||
|
||
def publish_detected(self, wake_word: str) -> None:
|
||
...
|
||
|
||
|
||
class TestRuntimeApplication:
|
||
def __init__(self, config: RuntimeConfig, event_publisher: EventPublisher) -> None:
|
||
self.config = config
|
||
self.event_bridge = event_publisher
|
||
self.plugins = PluginManager()
|
||
self.audio_source = None
|
||
self._is_setup = False
|
||
self._is_running = False
|
||
|
||
def setup(self) -> None:
|
||
if self._is_setup:
|
||
return
|
||
|
||
if self.config.wakeword_enabled:
|
||
self.plugins.register(
|
||
AudioPlugin(),
|
||
WakeWordPlugin(),
|
||
)
|
||
self.plugins.setup_all(self)
|
||
self._is_setup = True
|
||
|
||
def start(self) -> None:
|
||
if self._is_running:
|
||
return
|
||
|
||
self.setup()
|
||
self.plugins.start_all()
|
||
if self.config.wakeword_enabled:
|
||
self.event_bridge.publish_service_ready()
|
||
self._is_running = True
|
||
logger.info("test runtime application started")
|
||
|
||
def stop(self) -> None:
|
||
was_running = self._is_running
|
||
self._is_running = False
|
||
if was_running:
|
||
self.event_bridge.publish_service_stopping()
|
||
logger.info("test runtime application stopped")
|
||
# 启动中途失败时 _is_running 还是 False,但插件可能已经开过采集流,
|
||
# 这里不提前返回,保证采集流一定被关掉
|
||
self.plugins.stop_all()
|
||
|
||
def shutdown(self) -> None:
|
||
self.stop()
|
||
if self._is_setup:
|
||
self.plugins.shutdown_all()
|
||
|
||
def handle_wake_word_detected(self, wake_word: str, full_text: str) -> None:
|
||
_ = full_text
|
||
logger.info("wake word detected: %s", wake_word)
|
||
self.event_bridge.publish_detected(wake_word)
|