3 #ifdef USE_VOICE_ASSISTANT 10 namespace voice_assistant {
12 static const char *
const TAG =
"voice_assistant";
18 static const size_t SAMPLE_RATE_HZ = 16000;
19 static const size_t INPUT_BUFFER_SIZE = 32 * SAMPLE_RATE_HZ / 1000;
20 static const size_t BUFFER_SIZE = 1024 * SAMPLE_RATE_HZ / 1000;
21 static const size_t SEND_BUFFER_SIZE = INPUT_BUFFER_SIZE *
sizeof(int16_t);
22 static const size_t RECEIVE_SIZE = 1024;
23 static const size_t SPEAKER_BUFFER_SIZE = 16 * RECEIVE_SIZE;
30 ESP_LOGE(TAG,
"Could not create socket");
35 int err = this->
socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable,
sizeof(
int));
37 ESP_LOGW(TAG,
"Socket unable to set reuseaddr: errno %d", err);
40 err = this->
socket_->setblocking(
false);
42 ESP_LOGE(TAG,
"Socket unable to set nonblocking mode: errno %d", err);
53 ESP_LOGE(TAG,
"Socket unable to set sockaddr: errno %d", errno);
60 ESP_LOGE(TAG,
"Socket unable to bind: errno %d", errno);
71 ESP_LOGCONFIG(TAG,
"Setting up Voice Assistant...");
80 ESP_LOGW(TAG,
"Could not allocate speaker buffer");
90 ESP_LOGW(TAG,
"Could not allocate input buffer");
101 ESP_LOGW(TAG,
"Could not allocate ring buffer");
109 ESP_LOGW(TAG,
"Could not allocate send buffer");
116 size_t bytes_read = 0;
119 if (bytes_read == 0) {
120 memset(this->
input_buffer_, 0, INPUT_BUFFER_SIZE *
sizeof(int16_t));
126 ESP_LOGD(TAG,
"microphone not running");
163 ESP_LOGD(TAG,
"Starting Microphone");
165 memset(this->
input_buffer_, 0, INPUT_BUFFER_SIZE *
sizeof(int16_t));
180 ESP_LOGD(TAG,
"Waiting for speech...");
186 if (bytes_read > 0) {
187 vad_state_t vad_state =
189 if (vad_state == VAD_SPEECH) {
193 ESP_LOGD(TAG,
"VAD detected speech");
210 ESP_LOGD(TAG,
"Requesting start...");
230 ESP_LOGW(TAG,
"Could not request start");
247 while (available >= SEND_BUFFER_SIZE) {
251 msg.
data.assign((
char *) this->send_buffer_, read_bytes);
261 sizeof(this->dest_addr_));
287 bool playing =
false;
290 ssize_t received_len = 0;
294 if (received_len > 0) {
300 ESP_LOGD(TAG,
"Receive buffer full");
310 ESP_LOGD(TAG,
"End of audio stream received");
319 #ifdef USE_MEDIA_PLAYER 342 ESP_LOGD(TAG,
"Speaker has finished outputting all audio");
374 ESP_LOGD(TAG,
"Speaker buffer full, trying again next loop");
383 ESP_LOGE(TAG,
"Client attempting to unsubscribe that is not the current API Client");
392 ESP_LOGE(TAG,
"Multiple API Clients attempting to connect to Voice Assistant");
402 static const LogString *voice_assistant_state_to_string(
State state) {
405 return LOG_STR(
"IDLE");
407 return LOG_STR(
"START_MICROPHONE");
409 return LOG_STR(
"STARTING_MICROPHONE");
411 return LOG_STR(
"WAIT_FOR_VAD");
413 return LOG_STR(
"WAITING_FOR_VAD");
415 return LOG_STR(
"START_PIPELINE");
417 return LOG_STR(
"STARTING_PIPELINE");
419 return LOG_STR(
"STREAMING_MICROPHONE");
421 return LOG_STR(
"STOP_MICROPHONE");
423 return LOG_STR(
"STOPPING_MICROPHONE");
425 return LOG_STR(
"AWAITING_RESPONSE");
427 return LOG_STR(
"STREAMING_RESPONSE");
429 return LOG_STR(
"RESPONSE_FINISHED");
431 return LOG_STR(
"UNKNOWN");
438 ESP_LOGD(TAG,
"State changed from %s to %s", LOG_STR_ARG(voice_assistant_state_to_string(old_state)),
439 LOG_STR_ARG(voice_assistant_state_to_string(state)));
445 ESP_LOGD(TAG,
"Desired state set to %s", LOG_STR_ARG(voice_assistant_state_to_string(desired_state)));
449 ESP_LOGE(TAG,
"Failed to start server. See Home Assistant logs for more details.");
450 this->
error_trigger_->
trigger(
"failed-to-start",
"Failed to start server. See Home Assistant logs for more details.");
460 ESP_LOGD(TAG,
"Client started, streaming microphone");
476 ESP_LOGD(TAG,
"Client started, streaming microphone");
502 ESP_LOGE(TAG,
"No API client connected");
556 ESP_LOGD(TAG,
"Signaling stop...");
563 ESP_LOGD(TAG,
"Event Type: %d", msg.
event_type);
566 ESP_LOGD(TAG,
"Assist Pipeline running");
572 ESP_LOGD(TAG,
"Wake word detected");
577 ESP_LOGD(TAG,
"STT started");
582 for (
auto arg : msg.
data) {
583 if (arg.name ==
"text") {
584 text = std::move(arg.value);
588 ESP_LOGW(TAG,
"No text in STT_END event");
591 ESP_LOGD(TAG,
"Speech recognised as: \"%s\"", text.c_str());
596 ESP_LOGD(TAG,
"Intent started");
600 for (
auto arg : msg.
data) {
601 if (arg.name ==
"conversation_id") {
610 for (
auto arg : msg.
data) {
611 if (arg.name ==
"text") {
612 text = std::move(arg.value);
616 ESP_LOGW(TAG,
"No text in TTS_START event");
619 ESP_LOGD(TAG,
"Response: \"%s\"", text.c_str());
620 this->
defer([
this, text]() {
630 for (
auto arg : msg.
data) {
631 if (arg.name ==
"url") {
632 url = std::move(arg.value);
636 ESP_LOGW(TAG,
"No url in TTS_END event");
639 ESP_LOGD(TAG,
"Response URL: \"%s\"", url.c_str());
640 this->
defer([
this, url]() {
641 #ifdef USE_MEDIA_PLAYER 653 ESP_LOGD(TAG,
"Assist Pipeline ended");
673 std::string code =
"";
674 std::string message =
"";
675 for (
auto arg : msg.
data) {
676 if (arg.name ==
"code") {
677 code = std::move(arg.value);
678 }
else if (arg.name ==
"message") {
679 message = std::move(arg.value);
682 if (code ==
"wake-word-timeout" || code ==
"wake_word_detection_aborted") {
685 }
else if (code ==
"wake-provider-missing" || code ==
"wake-engine-missing") {
687 this->
defer([
this, code, message]() {
693 ESP_LOGE(TAG,
"Error: %s - %s", code.c_str(), message.c_str());
704 ESP_LOGD(TAG,
"TTS stream start");
712 ESP_LOGD(TAG,
"TTS stream end");
717 ESP_LOGD(TAG,
"Starting STT by VAD");
721 ESP_LOGD(TAG,
"STT by VAD end");
726 ESP_LOGD(TAG,
"Unhandled event type: %d", msg.
event_type);
732 #ifdef USE_SPEAKER // We should never get to this function if there is no speaker anyway 739 ESP_LOGE(TAG,
"Cannot receive audio, buffer is full");
749 #endif // USE_VOICE_ASSISTANT Trigger * tts_stream_start_trigger_
virtual size_t play(const uint8_t *data, size_t length)=0
std::string wake_word_phrase
bool wait_for_stream_end_
const float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
bool cancel_timeout(const std::string &name)
Cancel a timeout function.
Trigger * intent_end_trigger_
HighFrequencyLoopRequester high_freq_
VoiceAssistant * global_voice_assistant
std::string conversation_id_
socklen_t set_sockaddr_any(struct sockaddr *addr, socklen_t addrlen, uint16_t port)
Set a sockaddr to the any address and specified port for the IP version used by socket_ip().
std::string conversation_id
api::APIConnection * api_client_
float get_setup_priority() const override
vad_handle_t vad_instance_
std::unique_ptr< socket::Socket > socket_
uint32_t noise_suppression_level
Trigger< std::string > * tts_start_trigger_
void set_timeout(const std::string &name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a unique name.
An STL allocator that uses SPI RAM.
void defer(const std::string &name, std::function< void()> &&f)
Defer a callback to the next loop() call.
Trigger< std::string > * tts_end_trigger_
VoiceAssistantAudioSettings audio_settings
microphone::Microphone * mic_
enums::VoiceAssistantEvent event_type
void client_subscription(api::APIConnection *client, bool subscribe)
virtual bool has_buffered_data() const =0
std::vector< VoiceAssistantEventData > data
std::string get_client_combined_info() const
size_t speaker_bytes_received_
uint8_t * speaker_buffer_
uint8_t noise_suppression_level_
void trigger(Ts... x)
Inform the parent automation that the event has triggered.
Trigger * listening_trigger_
media_player::MediaPlayer * media_player_
void start()
Start running the loop continuously.
Trigger * client_connected_trigger_
bool send_voice_assistant_request(const VoiceAssistantRequest &msg)
speaker::Speaker * speaker_
void stop()
Stop running the loop continuously.
void set_state_(State state)
Trigger * stt_vad_start_trigger_
std::unique_ptr< RingBuffer > ring_buffer_
bool send_voice_assistant_audio(const VoiceAssistantAudio &msg)
void on_audio(const api::VoiceAssistantAudio &msg)
Trigger * client_disconnected_trigger_
Trigger * stt_vad_end_trigger_
struct sockaddr_storage dest_addr_
virtual size_t read(int16_t *buf, size_t len)=0
Trigger * wake_word_detected_trigger_
Trigger * tts_stream_end_trigger_
virtual void mark_failed()
Mark this component as failed.
This is a workaround until we can figure out a way to get the tflite-micro idf component code availab...
size_t speaker_buffer_size_
Trigger * intent_start_trigger_
static std::unique_ptr< RingBuffer > create(size_t len)
size_t speaker_buffer_index_
void on_event(const api::VoiceAssistantEventResponse &msg)
Trigger< std::string > * stt_end_trigger_
void request_start(bool continuous, bool silence_detection)
Trigger< std::string, std::string > * error_trigger_
std::unique_ptr< Socket > socket(int domain, int type, int protocol)
Create a socket of the given domain, type and protocol.