ESPHome 2026.10.0-dev
Loading...
Searching...
No Matches
voice_assistant.cpp
Go to the documentation of this file.
1#include "voice_assistant.h"
3
4#ifdef USE_VOICE_ASSISTANT
5
8#include "esphome/core/log.h"
9
10#include <cinttypes>
11#include <cstdio>
12
14
15static const char *const TAG = "voice_assistant";
16
17#ifdef SAMPLE_RATE_HZ
18#undef SAMPLE_RATE_HZ
19#endif
20
21static const size_t SAMPLE_RATE_HZ = 16000;
22
23static const size_t RING_BUFFER_SAMPLES = 512 * SAMPLE_RATE_HZ / 1000; // 512 ms * 16 kHz/ 1000 ms
24static const size_t RING_BUFFER_SIZE = RING_BUFFER_SAMPLES * sizeof(int16_t);
25static const size_t SEND_BUFFER_SAMPLES = 32 * SAMPLE_RATE_HZ / 1000; // 32ms * 16kHz / 1000ms
26static const size_t SEND_BUFFER_SIZE = SEND_BUFFER_SAMPLES * sizeof(int16_t);
27static const size_t RECEIVE_SIZE = 1024;
28static const size_t SPEAKER_BUFFER_SIZE = 16 * RECEIVE_SIZE;
29
30// If one microphone channel keeps producing audio while another configured channel produces none for this
31// long, treat the silent channel as failed and stop the stream. A working microphone exposes a chunk every
32// SEND_BUFFER_SAMPLES (32 ms), so this is far longer than any legitimate gap between chunks.
33static const uint32_t AUDIO_CHANNEL_STALL_TIMEOUT_MS = 2000;
34
36
38 this->mic_source_->add_data_callback([this](const std::vector<uint8_t> &data) {
39 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->ring_buffer_.lock();
40 if (temp_ring_buffer != nullptr) {
41 temp_ring_buffer->write((void *) data.data(), data.size());
42 }
43 });
44
45 // Second microphone channel
46 if (this->mic_source2_ != nullptr) {
47 this->mic_source2_->add_data_callback([this](const std::vector<uint8_t> &data) {
48 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->ring_buffer2_.lock();
49 if (temp_ring_buffer != nullptr) {
50 temp_ring_buffer->write((void *) data.data(), data.size());
51 }
52 });
53 }
54
55#ifdef USE_MEDIA_PLAYER
56 if (this->media_player_ != nullptr) {
58 switch (state) {
61 // State changed to announcing after receiving the url
63 }
64 break;
65 default:
67 // No longer announcing the TTS response
69 }
70 break;
71 }
72 });
73 }
74#endif
75}
76
78
80 this->socket_ = socket::socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
81 if (this->socket_ == nullptr) {
82 ESP_LOGE(TAG, "Could not create socket");
83 this->mark_failed();
84 return false;
85 }
86 int enable = 1;
87 int err = this->socket_->setsockopt(SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
88 if (err != 0) {
89 ESP_LOGW(TAG, "Socket unable to set reuseaddr: errno %d", err);
90 // we can still continue
91 }
92 err = this->socket_->setblocking(false);
93 if (err != 0) {
94 ESP_LOGE(TAG, "Socket unable to set nonblocking mode: errno %d", err);
95 this->mark_failed();
96 return false;
97 }
98
99#ifdef USE_SPEAKER
100 if (this->speaker_ != nullptr) {
101 struct sockaddr_storage server;
102
103 socklen_t sl = socket::set_sockaddr_any((struct sockaddr *) &server, sizeof(server), 6055);
104 if (sl == 0) {
105 ESP_LOGE(TAG, "Socket unable to set sockaddr: errno %d", errno);
106 this->mark_failed();
107 return false;
108 }
109
110 err = this->socket_->bind((struct sockaddr *) &server, sizeof(server));
111 if (err != 0) {
112 ESP_LOGE(TAG, "Socket unable to bind: errno %d", errno);
113 this->mark_failed();
114 return false;
115 }
116 }
117#endif
118 this->udp_socket_running_ = true;
119 return true;
120}
121
123#ifdef USE_SPEAKER
124 if ((this->speaker_ != nullptr) && (this->speaker_buffer_ == nullptr)) {
125 RAMAllocator<uint8_t> speaker_allocator;
126 this->speaker_buffer_ = speaker_allocator.allocate(SPEAKER_BUFFER_SIZE);
127 if (this->speaker_buffer_ == nullptr) {
128 ESP_LOGW(TAG, "Could not allocate speaker buffer");
129 return false;
130 }
131 }
132#endif
133
134 if (this->audio_source_ == nullptr) {
135 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = ring_buffer::RingBuffer::create(RING_BUFFER_SIZE);
136 if (temp_ring_buffer == nullptr) {
137 ESP_LOGE(TAG, "Could not allocate ring buffer");
138 return false;
139 }
140 // Zero-copy source that reads directly from the ring buffer; frame-aligned to never split an int16 sample.
141 this->audio_source_ = audio::RingBufferAudioSource::create(temp_ring_buffer, SEND_BUFFER_SIZE, sizeof(int16_t));
142 if (this->audio_source_ == nullptr) {
143 ESP_LOGE(TAG, "Could not allocate audio source");
144 return false;
145 }
146 this->ring_buffer_ = temp_ring_buffer;
147 }
148
149 // Second microphone channel
150 if ((this->mic_source2_ != nullptr) && (this->audio_source2_ == nullptr)) {
151 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = ring_buffer::RingBuffer::create(RING_BUFFER_SIZE);
152 if (temp_ring_buffer == nullptr) {
153 ESP_LOGE(TAG, "Could not allocate second ring buffer");
154 return false;
155 }
156 this->audio_source2_ = audio::RingBufferAudioSource::create(temp_ring_buffer, SEND_BUFFER_SIZE, sizeof(int16_t));
157 if (this->audio_source2_ == nullptr) {
158 ESP_LOGE(TAG, "Could not allocate second audio source");
159 return false;
160 }
161 this->ring_buffer2_ = temp_ring_buffer;
162 }
163
164 return true;
165}
166
168 if (this->audio_source_ != nullptr) {
169 this->audio_source_->clear_buffered_data();
170 }
171
172 // Second microphone channel
173 if (this->audio_source2_ != nullptr) {
174 this->audio_source2_->clear_buffered_data();
175 }
176
177 // Reset the multi-channel stall watchdog (see audio_channel_stall_start_).
179
180#ifdef USE_SPEAKER
181 if ((this->speaker_ != nullptr) && (this->speaker_buffer_ != nullptr)) {
182 memset(this->speaker_buffer_, 0, SPEAKER_BUFFER_SIZE);
183
184 this->speaker_buffer_size_ = 0;
185 this->speaker_buffer_index_ = 0;
186 this->speaker_bytes_received_ = 0;
187 }
188#endif
189}
190
192 // Destroying each source releases its ring buffer; the matching weak_ptr then expires automatically.
193 this->audio_source_.reset();
194
195 // Second microphone channel
196 this->audio_source2_.reset();
197
198#ifdef USE_SPEAKER
199 if ((this->speaker_ != nullptr) && (this->speaker_buffer_ != nullptr)) {
200 RAMAllocator<uint8_t> speaker_deallocator;
201 speaker_deallocator.deallocate(this->speaker_buffer_, SPEAKER_BUFFER_SIZE);
202 this->speaker_buffer_ = nullptr;
203 }
204#endif
205}
206
208 this->conversation_id_ = "";
209 ESP_LOGD(TAG, "reset conversation ID");
210}
211
213 // Both microphone channels are sent together, if configured. Home Assistant feeds one of the
214 // channels to its speech-to-text stream and treats an empty payload on that channel as
215 // end-of-stream, and the device cannot know which channel it picked, so only send once every
216 // configured channel has audio exposed, and always send them together. We don't target any
217 // particular message size: Home Assistant re-chunks the audio, and each fill() exposes at most
218 // SEND_BUFFER_SIZE bytes.
219 while (true) {
220 // fill() exposes a new chunk, or returns 0 if a previous chunk is still exposed; available()
221 // reports the currently exposed bytes either way.
222 this->audio_source_->fill(0, false);
223 size_t available = this->audio_source_->available();
224 size_t available2 = 0;
225 if (this->audio_source2_ != nullptr) {
226 this->audio_source2_->fill(0, false);
227 available2 = this->audio_source2_->available();
228 }
229
230 const bool channel_empty = (available == 0);
231 const bool channel2_empty = (this->audio_source2_ != nullptr) && (available2 == 0);
232 if (channel_empty || channel2_empty) {
233 // A configured channel has no audio yet, so keep any chunk exposed on the other channel for the
234 // next pass rather than sending an empty payload.
235 this->handle_channel_stall_(available, available2);
236 break;
237 }
238
239 // Both channels have audio exposed; clear any in-progress stall timer.
241
243 // Zero-copy: send_message() copies the data out before we consume it.
244 msg.data = this->audio_source_->data();
245 msg.data_len = available;
246 if (this->audio_source2_ != nullptr) {
247 msg.data2 = this->audio_source2_->data();
248 msg.data2_len = available2;
249 }
250
251 if (!this->api_client_->send_message(msg)) {
252 // Keep the chunk exposed and retry next pass, the same shape as
253 // APIConnection::try_send_camera_image_(): the slice is only lost if
254 // the ring buffer overflows before the TCP buffer clears, instead of
255 // on every refusal. The api layer already reports the refusal at V.
256 return;
257 }
258
259 this->audio_source_->consume(available);
260 if (this->audio_source2_ != nullptr) {
261 this->audio_source2_->consume(available2);
262 }
263 }
264}
265
266void VoiceAssistant::handle_channel_stall_(size_t available, size_t available2) {
267 // Called when at least one configured channel has no audio exposed. When one channel has data and the
268 // other does not, watch how long the empty channel stays starved: Home Assistant has no stream timeout
269 // and would never tell us to stop, so a channel that fails outright would otherwise hang streaming
270 // forever with the live channel's chunk held. Stop the stream with an error after a prolonged imbalance.
271 if ((available == 0) && (available2 == 0)) {
272 // Both channels are idle (no audio buffered yet); normal, not a stalled channel.
274 return;
275 }
276
278 if (this->audio_channel_stall_start_ == 0) {
279 this->audio_channel_stall_start_ = now;
280 } else if ((now - this->audio_channel_stall_start_) >= AUDIO_CHANNEL_STALL_TIMEOUT_MS) {
281 ESP_LOGW(TAG, "Mic channel %d stalled, stopping stream", (available == 0) ? 0 : 1);
283 this->signal_stop_();
285 this->defer([this]() {
286 this->error_trigger_.trigger("mic-channel-stalled", "A microphone channel stopped producing audio");
287 });
288 }
289}
290
292 if (this->api_client_ == nullptr && this->state_ != State::IDLE && this->state_ != State::STOP_MICROPHONE &&
294 if (this->mic_source_->is_running() || (this->mic_source2_ && this->mic_source2_->is_running()) ||
295 this->state_ == State::STARTING_MICROPHONE) {
297 } else {
299 }
300 this->continuous_ = false;
301 this->signal_stop_();
302 this->clear_buffers_();
303 return;
304 }
305 switch (this->state_) {
306 case State::IDLE: {
307 if (this->continuous_ && this->desired_state_ == State::IDLE) {
308 this->idle_trigger_.trigger();
310 } else {
311 this->deallocate_buffers_();
312 }
313 break;
314 }
316 ESP_LOGD(TAG, "Starting Microphone");
317 if (!this->allocate_buffers_()) {
318 this->status_set_error(LOG_STR("Failed to allocate buffers"));
319 return;
320 }
321 if (this->status_has_error()) {
322 this->status_clear_error();
323 }
324 this->clear_buffers_();
325
326 this->mic_source_->start();
327 if (this->mic_source2_) {
328 this->mic_source2_->start();
329 }
331 break;
332 }
334 if (this->mic_source_->is_running() && (!this->mic_source2_ || this->mic_source2_->is_running())) {
335 this->set_state_(this->desired_state_);
336 }
337 break;
338 }
340 ESP_LOGD(TAG, "Requesting start");
341 uint32_t flags = 0;
342 if (!this->continue_conversation_ && this->use_wake_word_)
344 if (this->silence_detection_)
348 audio_settings.auto_gain = this->auto_gain_;
349 audio_settings.volume_multiplier = this->volume_multiplier_;
350
352 msg.start = true;
354 msg.flags = flags;
355 msg.audio_settings = audio_settings;
357
358 // Reset media player state tracking
359#ifdef USE_MEDIA_PLAYER
360 if (this->media_player_ != nullptr) {
362 }
363#endif
364
365 if (this->api_client_ == nullptr || !this->api_client_->send_message(msg)) {
366 ESP_LOGW(TAG, "Could not request start");
367 this->error_trigger_.trigger("not-connected", "Could not request start");
368 this->continuous_ = false;
370 break;
371 }
373 this->set_timeout("reset-conversation_id", this->conversation_timeout_,
374 [this]() { this->reset_conversation_id(); });
375 break;
376 }
378 break; // State changed when udp server port received
379 }
381 // pre_shift is ignored by RingBufferAudioSource (no intermediate transfer buffer to compact).
382 if (this->audio_mode_ == AUDIO_MODE_API) {
383 this->stream_api_audio_();
384 } else {
385 // UDP (will eventually be deprecated)
386 // Only the primary microphone channel is used
387 while (true) {
388 this->audio_source_->fill(0, false);
389 size_t available = this->audio_source_->available();
390 if (available == 0) {
391 break;
392 }
393 if (!this->udp_socket_running_) {
394 if (!this->start_udp_socket_()) {
396 break;
397 }
398 }
399 this->socket_->sendto(this->audio_source_->data(), available, 0, (struct sockaddr *) &this->dest_addr_,
400 sizeof(this->dest_addr_));
401 this->audio_source_->consume(available);
402 }
403 } // audio mode
404 break;
405 }
407 // Check both microphone channels
408 bool is_running = this->mic_source_->is_running();
409 bool is_running2 = false;
410 if (this->mic_source2_) {
411 is_running2 = this->mic_source2_->is_running();
412 }
413 if (is_running || is_running2) {
414 if (is_running) {
415 this->mic_source_->stop();
416 }
417 if (is_running2) {
418 this->mic_source2_->stop();
419 }
421 } else {
422 this->set_state_(this->desired_state_);
423 }
424 break;
425 }
427 // Check both microphone channels
428 bool is_stopped = this->mic_source_->is_stopped();
429 bool is_stopped2 = true;
430 if (this->mic_source2_) {
431 is_stopped2 = this->mic_source2_->is_stopped();
432 }
433 if (is_stopped && is_stopped2) {
434 this->set_state_(this->desired_state_);
435 }
436 break;
437 }
439 break; // State changed by events
440 }
442 bool playing = false;
443#ifdef USE_SPEAKER
444 if (this->speaker_ != nullptr) {
445 ssize_t received_len = 0;
446 if (this->audio_mode_ == AUDIO_MODE_UDP) {
447 if (this->speaker_buffer_index_ + RECEIVE_SIZE < SPEAKER_BUFFER_SIZE) {
448 received_len = this->socket_->read(this->speaker_buffer_ + this->speaker_buffer_index_, RECEIVE_SIZE);
449 if (received_len > 0) {
450 this->speaker_buffer_index_ += received_len;
451 this->speaker_buffer_size_ += received_len;
452 this->speaker_bytes_received_ += received_len;
453 }
454 } else {
455 ESP_LOGD(TAG, "Receive buffer full");
456 }
457 }
458 // Build a small buffer of audio before sending to the speaker
459 bool end_of_stream = this->stream_ended_ && (this->audio_mode_ == AUDIO_MODE_API || received_len < 0);
460 if (this->speaker_bytes_received_ > RECEIVE_SIZE * 4 || end_of_stream)
461 this->write_speaker_();
462 if (this->wait_for_stream_end_) {
463 this->cancel_timeout("playing");
464 if (end_of_stream) {
465 ESP_LOGD(TAG, "End of audio stream received");
466 this->cancel_timeout("speaker-timeout");
468 }
469 break; // We dont want to timeout here as the STREAM_END event will take care of that.
470 }
471 playing = this->speaker_->is_running();
472 }
473#endif
474#ifdef USE_MEDIA_PLAYER
475 if (this->media_player_ != nullptr) {
477
480 this->cancel_timeout("playing");
481 ESP_LOGD(TAG, "Announcement finished playing");
483
485 msg.success = true;
486 if (!this->api_client_->send_message(msg)) {
487 API_LOG_MSG_DROPPED(TAG, "Announce-finished");
488 }
489 break;
490 }
491 }
492#endif
493 if (playing) {
495 }
496 break;
497 }
499#ifdef USE_SPEAKER
500 if (this->speaker_ != nullptr) {
501 if (this->speaker_buffer_size_ > 0) {
502 this->write_speaker_();
503 break;
504 }
505 if (this->speaker_->has_buffered_data() || this->speaker_->is_running()) {
506 break;
507 }
508 ESP_LOGD(TAG, "Speaker has finished outputting all audio");
509 this->speaker_->stop();
510 this->cancel_timeout("speaker-timeout");
511 this->cancel_timeout("playing");
512
513 this->clear_buffers_();
514
515 this->wait_for_stream_end_ = false;
516 this->stream_ended_ = false;
517
519 }
520#endif
521 if (this->continue_conversation_) {
523 } else {
525 }
526 break;
527 }
528 default:
529 break;
530 }
531}
532
533#ifdef USE_SPEAKER
535 if ((this->speaker_ != nullptr) && (this->speaker_buffer_ != nullptr)) {
536 if (this->speaker_buffer_size_ > 0) {
537 size_t write_chunk = std::min<size_t>(this->speaker_buffer_size_, 4 * 1024);
538 size_t written = this->speaker_->play(this->speaker_buffer_, write_chunk);
539 if (written > 0) {
540 memmove(this->speaker_buffer_, this->speaker_buffer_ + written, this->speaker_buffer_size_ - written);
543 this->set_timeout("speaker-timeout", 5000, [this]() { this->speaker_->stop(); });
544 } else {
545 ESP_LOGV(TAG, "Speaker buffer full, trying again next loop");
546 }
547 }
548 }
549}
550#endif
551
553 if (!subscribe) {
554 if (this->api_client_ == nullptr || client != this->api_client_) {
555 ESP_LOGE(TAG, "Client attempting to unsubscribe that is not the current API Client");
556 return;
557 }
558 this->api_client_ = nullptr;
560 return;
561 }
562
563 if (this->api_client_ != nullptr) {
564 char current_peername[socket::SOCKADDR_STR_LEN];
565 char new_peername[socket::SOCKADDR_STR_LEN];
566 ESP_LOGE(TAG,
567 "Multiple API Clients attempting to connect to Voice Assistant\n"
568 " Current client: %s (%s)\n"
569 " New client: %s (%s)",
570 this->api_client_->get_name(), this->api_client_->get_peername_to(current_peername), client->get_name(),
571 client->get_peername_to(new_peername));
572 return;
573 }
574
575 this->api_client_ = client;
577}
578
579static const LogString *voice_assistant_state_to_string(State state) {
580 switch (state) {
581 case State::IDLE:
582 return LOG_STR("IDLE");
584 return LOG_STR("START_MICROPHONE");
586 return LOG_STR("STARTING_MICROPHONE");
588 return LOG_STR("WAIT_FOR_VAD");
590 return LOG_STR("WAITING_FOR_VAD");
592 return LOG_STR("START_PIPELINE");
594 return LOG_STR("STARTING_PIPELINE");
596 return LOG_STR("STREAMING_MICROPHONE");
598 return LOG_STR("STOP_MICROPHONE");
600 return LOG_STR("STOPPING_MICROPHONE");
602 return LOG_STR("AWAITING_RESPONSE");
604 return LOG_STR("STREAMING_RESPONSE");
606 return LOG_STR("RESPONSE_FINISHED");
607 default:
608 return LOG_STR("UNKNOWN");
609 }
610};
611
613 State old_state = this->state_;
614 this->state_ = state;
615 ESP_LOGD(TAG, "State changed from %s to %s", LOG_STR_ARG(voice_assistant_state_to_string(old_state)),
616 LOG_STR_ARG(voice_assistant_state_to_string(state)));
617}
618
620 this->set_state_(state);
621 this->desired_state_ = desired_state;
622 ESP_LOGD(TAG, "Desired state set to %s", LOG_STR_ARG(voice_assistant_state_to_string(desired_state)));
623}
624
626 ESP_LOGE(TAG, "Failed to start server. See Home Assistant logs for more details.");
627 this->error_trigger_.trigger("failed-to-start", "Failed to start server. See Home Assistant logs for more details.");
629}
630
632 if (this->state_ != State::STARTING_PIPELINE) {
633 this->signal_stop_();
634 return;
635 }
636
637 ESP_LOGD(TAG, "Client started, streaming microphone");
639
640 // Both microphone channels
641 if (this->mic_source_->is_running() && (!this->mic_source2_ || this->mic_source2_->is_running())) {
643 } else {
645 }
646}
647
648void VoiceAssistant::start_streaming(struct sockaddr_storage *addr, uint16_t port) {
649 if (this->state_ != State::STARTING_PIPELINE) {
650 this->signal_stop_();
651 return;
652 }
653
654 ESP_LOGD(TAG, "Client started, streaming microphone");
656
657 if (this->mic_source2_ != nullptr) {
658 ESP_LOGW(TAG, "UDP audio mode does not support a second microphone channel; only the primary will be streamed");
659 }
660
661 memcpy(&this->dest_addr_, addr, sizeof(this->dest_addr_));
662 if (this->dest_addr_.ss_family == AF_INET) {
663 ((struct sockaddr_in *) &this->dest_addr_)->sin_port = htons(port);
664 }
665#if LWIP_IPV6
666 else if (this->dest_addr_.ss_family == AF_INET6) {
667 ((struct sockaddr_in6 *) &this->dest_addr_)->sin6_port = htons(port);
668 }
669#endif
670 else {
671 ESP_LOGW(TAG, "Unknown address family: %d", this->dest_addr_.ss_family);
672 return;
673 }
674
675 // Only primary microphone channel over UDP
676 if (this->mic_source_->is_running()) {
678 } else {
680 }
681}
682
683void VoiceAssistant::request_start(bool continuous, bool silence_detection) {
684 if (this->api_client_ == nullptr) {
685 ESP_LOGE(TAG, "No API client connected");
687 this->continuous_ = false;
688 return;
689 }
690 if (this->state_ == State::IDLE) {
691 this->continuous_ = continuous;
692 this->silence_detection_ = silence_detection;
693
695 }
696}
697
699 this->continuous_ = false;
700 this->continue_conversation_ = false;
701
702 switch (this->state_) {
703 case State::IDLE:
704 break;
711 break;
714 this->signal_stop_();
716 break;
720 break;
722 this->signal_stop_();
723 break;
725#ifdef USE_MEDIA_PLAYER
726 // Stop any ongoing media player announcement
727 if (this->media_player_ != nullptr) {
728 this->media_player_->make_call()
730 .set_announcement(true)
731 .perform();
732 }
733 if (this->started_streaming_tts_) {
734 // Haven't reached the TTS_END stage, so send the stop signal to HA.
735 this->signal_stop_();
736 }
737#endif
738 break;
740 break; // Let the incoming audio stream finish then it will go to idle.
741 }
742}
743
745 memset(&this->dest_addr_, 0, sizeof(this->dest_addr_));
746 if (this->api_client_ == nullptr) {
747 return;
748 }
749 ESP_LOGD(TAG, "Signaling stop");
751 msg.start = false;
752 if (!this->api_client_->send_message(msg)) {
753 API_LOG_MSG_DROPPED(TAG, "Stop request");
754 }
755}
756
758 this->set_timeout("playing", 2000, [this]() {
759 this->cancel_timeout("speaker-timeout");
761
762 if (this->api_client_ == nullptr)
763 return;
765 msg.success = true;
766 if (!this->api_client_->send_message(msg)) {
767 API_LOG_MSG_DROPPED(TAG, "Announce-finished");
768 }
769 });
770}
771
773 ESP_LOGD(TAG, "Event Type: %" PRId32, msg.event_type);
774 switch (msg.event_type) {
776 ESP_LOGD(TAG, "Assist Pipeline running");
777#ifdef USE_MEDIA_PLAYER
778 this->started_streaming_tts_ = false;
779 for (const auto &arg : msg.data) {
780 if (arg.name == "url") {
781 this->tts_response_url_ = arg.value;
782 }
783 }
784#endif
785 this->defer([this]() { this->start_trigger_.trigger(); });
786 break;
788 break;
790 ESP_LOGD(TAG, "Wake word detected");
791 this->defer([this]() { this->wake_word_detected_trigger_.trigger(); });
792 break;
793 }
795 ESP_LOGD(TAG, "STT started");
796 this->defer([this]() { this->listening_trigger_.trigger(); });
797 break;
799 std::string text;
800 for (const auto &arg : msg.data) {
801 if (arg.name == "text") {
802 text = arg.value;
803 }
804 }
805 if (text.empty()) {
806 ESP_LOGW(TAG, "No text in STT_END event");
807 return;
808 } else if (text.length() > 500) {
809 text.resize(497);
810 text += "...";
811 }
812 ESP_LOGD(TAG, "Speech recognised as: \"%s\"", text.c_str());
813 this->defer([this, text]() { this->stt_end_trigger_.trigger(text); });
814 break;
815 }
817 ESP_LOGD(TAG, "Intent started");
818 this->defer([this]() { this->intent_start_trigger_.trigger(); });
819 break;
821 ESP_LOGD(TAG, "Intent progress");
822 std::string tts_url_for_trigger;
823#ifdef USE_MEDIA_PLAYER
824 if (this->media_player_ != nullptr) {
825 for (const auto &arg : msg.data) {
826 if ((arg.name == "tts_start_streaming") && (arg.value == "1") && !this->tts_response_url_.empty()) {
828
830
831 this->started_streaming_tts_ = true;
833
834 tts_url_for_trigger = this->tts_response_url_;
835 this->tts_response_url_.clear(); // Reset streaming URL
837 }
838 }
839 }
840#endif
841 this->defer([this, tts_url_for_trigger]() { this->intent_progress_trigger_.trigger(tts_url_for_trigger); });
842 break;
843 }
845 for (const auto &arg : msg.data) {
846 if (arg.name == "conversation_id") {
847 this->conversation_id_ = arg.value;
848 } else if (arg.name == "continue_conversation") {
849 this->continue_conversation_ = (arg.value == "1");
850 }
851 }
852 this->defer([this]() { this->intent_end_trigger_.trigger(); });
853 break;
854 }
856 std::string text;
857 for (const auto &arg : msg.data) {
858 if (arg.name == "text") {
859 text = arg.value;
860 }
861 }
862 if (text.empty()) {
863 ESP_LOGW(TAG, "No text in TTS_START event");
864 return;
865 }
866 if (text.length() > 500) {
867 text.resize(497);
868 text += "...";
869 }
870 ESP_LOGD(TAG, "Response: \"%s\"", text.c_str());
871 this->defer([this, text]() {
872 this->tts_start_trigger_.trigger(text);
873#ifdef USE_SPEAKER
874 if (this->speaker_ != nullptr) {
875 this->speaker_->start();
876 }
877#endif
878 });
879 break;
880 }
882 std::string url;
883 for (const auto &arg : msg.data) {
884 if (arg.name == "url") {
885 url = arg.value;
886 }
887 }
888 if (url.empty()) {
889 ESP_LOGW(TAG, "No url in TTS_END event");
890 return;
891 }
892 ESP_LOGD(TAG, "Response URL: \"%s\"", url.c_str());
893 this->defer([this, url]() {
894#ifdef USE_MEDIA_PLAYER
895 if ((this->media_player_ != nullptr) && (!this->started_streaming_tts_)) {
897
899
901 }
902 this->started_streaming_tts_ = false; // Helps indicate reaching the TTS_END stage
903#endif
904 this->tts_end_trigger_.trigger(url);
905 });
907 if (new_state != this->state_) {
908 // Don't needlessly change the state. The intent progress stage may have already changed the state to
909 // streaming response.
910 this->set_state_(new_state, new_state);
911 }
912 break;
913 }
915 ESP_LOGD(TAG, "Assist Pipeline ended");
916 if ((this->state_ == State::START_PIPELINE) || (this->state_ == State::STARTING_PIPELINE) ||
918 // Microphone is running, stop it
920 } else if (this->state_ == State::AWAITING_RESPONSE) {
921 // No TTS start event ("nevermind")
923 }
924 this->defer([this]() { this->end_trigger_.trigger(); });
925 break;
926 }
928 std::string code;
929 std::string message;
930 for (const auto &arg : msg.data) {
931 if (arg.name == "code") {
932 code = arg.value;
933 } else if (arg.name == "message") {
934 message = arg.value;
935 }
936 }
937 if (code == "wake-word-timeout" || code == "wake_word_detection_aborted" || code == "no_wake_word") {
938 // Don't change state here since either the "tts-end" or "run-end" events will do it.
939 return;
940 } else if (code == "wake-provider-missing" || code == "wake-engine-missing") {
941 // Wake word is not set up or not ready on Home Assistant so stop and do not retry until user starts again.
942 this->defer([this, code, message]() {
943 this->request_stop();
944 this->error_trigger_.trigger(code, message);
945 });
946 return;
947 }
948 ESP_LOGE(TAG, "Error: %s - %s", code.c_str(), message.c_str());
949 if (this->state_ != State::IDLE) {
950 this->signal_stop_();
952 }
953 this->defer([this, code, message]() { this->error_trigger_.trigger(code, message); });
954 break;
955 }
957#ifdef USE_SPEAKER
958 if (this->speaker_ != nullptr) {
959 this->wait_for_stream_end_ = true;
960 ESP_LOGD(TAG, "TTS stream start");
961 this->defer([this] { this->tts_stream_start_trigger_.trigger(); });
962 }
963#endif
964 break;
965 }
967#ifdef USE_SPEAKER
968 if (this->speaker_ != nullptr) {
969 this->stream_ended_ = true;
970 ESP_LOGD(TAG, "TTS stream end");
971 }
972#endif
973 break;
974 }
976 ESP_LOGD(TAG, "Starting STT by VAD");
977 this->defer([this]() { this->stt_vad_start_trigger_.trigger(); });
978 break;
980 ESP_LOGD(TAG, "STT by VAD end");
982 this->defer([this]() { this->stt_vad_end_trigger_.trigger(); });
983 break;
984 default:
985 ESP_LOGD(TAG, "Unhandled event type: %" PRId32, msg.event_type);
986 break;
987 }
988}
989
991#ifdef USE_SPEAKER // We should never get to this function if there is no speaker anyway
992 if ((this->speaker_ != nullptr) && (this->speaker_buffer_ != nullptr)) {
993 if (this->speaker_buffer_index_ + msg.data_len <= SPEAKER_BUFFER_SIZE) {
994 memcpy(this->speaker_buffer_ + this->speaker_buffer_index_, msg.data, msg.data_len);
995 this->speaker_buffer_index_ += msg.data_len;
996 this->speaker_buffer_size_ += msg.data_len;
998 this->write_speaker_();
999 ESP_LOGV(TAG, "Received audio: %u bytes from API", msg.data_len);
1000 } else {
1001 ESP_LOGE(TAG, "Cannot receive audio, buffer is full");
1002 }
1003 }
1004#endif
1005}
1006
1008 // Find existing timer or add a new one
1009 auto it = this->timers_.begin();
1010 for (; it != this->timers_.end(); ++it) {
1011 if (it->id == msg.timer_id)
1012 break;
1013 }
1014 if (it == this->timers_.end()) {
1015 this->timers_.push_back({});
1016 it = this->timers_.end() - 1;
1017 }
1018 it->id = msg.timer_id;
1019 it->name = msg.name;
1020 it->total_seconds = msg.total_seconds;
1021 it->seconds_left = msg.seconds_left;
1022 it->is_active = msg.is_active;
1023
1024 char timer_buf[Timer::TO_STR_BUFFER_SIZE];
1025 ESP_LOGD(TAG,
1026 "Timer Event\n"
1027 " Type: %" PRId32 "\n"
1028 " %s",
1029 msg.event_type, it->to_str(timer_buf));
1030
1031 switch (msg.event_type) {
1033 this->timer_started_trigger_.trigger(*it);
1034 break;
1036 this->timer_updated_trigger_.trigger(*it);
1037 break;
1039 this->timer_cancelled_trigger_.trigger(*it);
1040 this->timers_.erase(it);
1041 break;
1043 this->timer_finished_trigger_.trigger(*it);
1044 this->timers_.erase(it);
1045 break;
1046 }
1047
1048 if (this->timers_.empty()) {
1049 this->cancel_interval("timer-event");
1050 this->timer_tick_running_ = false;
1051 } else if (!this->timer_tick_running_) {
1052 this->set_interval("timer-event", 1000, [this]() { this->timer_tick_(); });
1053 this->timer_tick_running_ = true;
1054 }
1055}
1056
1058 for (auto &timer : this->timers_) {
1059 if (timer.is_active && timer.seconds_left > 0) {
1060 timer.seconds_left--;
1061 }
1062 }
1063 this->timer_tick_trigger_.trigger(this->timers_);
1064}
1065
1067#ifdef USE_MEDIA_PLAYER
1068 if (this->media_player_ != nullptr) {
1069 this->tts_start_trigger_.trigger(msg.text);
1070
1072
1073 if (!msg.preannounce_media_id.empty()) {
1075 }
1076 // Enqueueing a URL with an empty playlist will still play the file immediately
1077 this->media_player_->make_call()
1080 .set_announcement(true)
1081 .perform();
1083
1085
1086 if (this->continuous_) {
1088 } else {
1090 }
1091
1093 this->end_trigger_.trigger();
1094 }
1095#endif
1096}
1097
1098void VoiceAssistant::on_set_configuration(const std::vector<std::string> &active_wake_words) {
1099#ifdef USE_MICRO_WAKE_WORD
1100 if (this->micro_wake_word_) {
1101 // Disable all wake words first
1102 for (auto &model : this->micro_wake_word_->get_wake_words()) {
1103 model->disable();
1104 }
1105
1106 // Enable only active wake words
1107 for (const auto &ww_id : active_wake_words) {
1108 for (auto &model : this->micro_wake_word_->get_wake_words()) {
1109 if (model->get_id() == ww_id) {
1110 model->enable();
1111 ESP_LOGD(TAG, "Enabled wake word: %s (id=%s)", model->get_wake_word().c_str(), model->get_id().c_str());
1112 }
1113 }
1114 }
1115 }
1116#endif
1117};
1118
1120 this->config_.available_wake_words.clear();
1121 this->config_.active_wake_words.clear();
1122
1123#ifdef USE_MICRO_WAKE_WORD
1124 if (this->micro_wake_word_) {
1126
1127 for (auto &model : this->micro_wake_word_->get_wake_words()) {
1128 if (model->is_enabled()) {
1129 this->config_.active_wake_words.push_back(model->get_id());
1130 }
1131
1132 WakeWord wake_word;
1133 wake_word.id = model->get_id();
1134 wake_word.wake_word = model->get_wake_word();
1135 for (const auto &lang : model->get_trained_languages()) {
1136 wake_word.trained_languages.push_back(lang);
1137 }
1138 this->config_.available_wake_words.push_back(std::move(wake_word));
1139 }
1140 } else {
1141#endif
1142 // No microWakeWord
1144#ifdef USE_MICRO_WAKE_WORD
1145 }
1146#endif
1147
1148 return this->config_;
1149};
1150
1151VoiceAssistant *global_voice_assistant = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
1152
1153} // namespace esphome::voice_assistant
1154
1155#endif // USE_VOICE_ASSISTANT
uint32_t IRAM_ATTR HOT get_loop_component_start_time() const
Get the cached time in milliseconds from when the current component started its loop execution.
void mark_failed()
Mark this component as failed.
bool cancel_interval(const char *name)
Cancel an interval function.
Definition component.cpp:92
void status_clear_error()
Definition component.h:295
bool cancel_timeout(const char *name)
Cancel a timeout function.
void set_timeout(const char *name, uint32_t timeout, std::function< void()> &&f)
Set a timeout function with a const char* name.
Definition component.cpp:96
void defer(const char *name, std::function< void()> &&f)
Defer a callback to the next loop() call with a const char* name.
bool status_has_error() const
Definition component.h:280
void set_interval(const char *name, uint32_t interval, std::function< void()> &&f)
Set an interval function with a const char* name.
Definition component.cpp:88
An STL allocator that uses SPI or internal RAM.
Definition helpers.h:2107
void deallocate(T *p, size_t n)
Definition helpers.h:2164
T * allocate(size_t n)
Definition helpers.h:2134
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
constexpr bool empty() const
Definition string_ref.h:76
void trigger(const Ts &...x) ESPHOME_ALWAYS_INLINE
Inform the parent automation that the event has triggered.
Definition automation.h:461
const char * get_peername_to(std::span< char, socket::SOCKADDR_STR_LEN > buf) const
Get peer name (IP address) into caller-provided buffer, returns buf for convenience.
const char * get_name() const
bool send_message(const T &msg)
Returns false as soon as the TCP buffer is full.
enums::VoiceAssistantEvent event_type
Definition api_pb2.h:2533
std::vector< VoiceAssistantEventData > data
Definition api_pb2.h:2534
VoiceAssistantAudioSettings audio_settings
Definition api_pb2.h:2489
enums::VoiceAssistantTimerEvent event_type
Definition api_pb2.h:2572
static std::unique_ptr< RingBufferAudioSource > create(std::shared_ptr< ring_buffer::RingBuffer > ring_buffer, size_t max_fill_bytes, uint8_t alignment_bytes=1)
Creates a new ring-buffer-backed audio source after validating its parameters.
MediaPlayerCall & set_media_url(const std::string &url)
MediaPlayerCall & set_announcement(bool announce)
MediaPlayerCall & set_command(MediaPlayerCommand command)
void add_on_state_callback(F &&callback)
std::vector< WakeWordModel * > get_wake_words()
void add_data_callback(F &&data_callback)
static std::unique_ptr< RingBuffer > create(size_t len, MemoryPreference preference=MemoryPreference::EXTERNAL_FIRST)
virtual size_t play(const uint8_t *data, size_t length)=0
Plays the provided audio data.
bool is_running() const
Definition speaker.h:65
virtual bool has_buffered_data() const =0
virtual void start()=0
virtual void stop()=0
std::unique_ptr< socket::Socket > socket_
microphone::MicrophoneSource * mic_source2_
void on_timer_event(const api::VoiceAssistantTimerEventResponse &msg)
void on_audio(const api::VoiceAssistantAudio &msg)
std::unique_ptr< audio::RingBufferAudioSource > audio_source_
std::weak_ptr< ring_buffer::RingBuffer > ring_buffer2_
std::weak_ptr< ring_buffer::RingBuffer > ring_buffer_
media_player::MediaPlayer * media_player_
void client_subscription(api::APIConnection *client, bool subscribe)
MediaPlayerResponseState media_player_response_state_
void on_event(const api::VoiceAssistantEventResponse &msg)
Trigger< std::string, std::string > error_trigger_
Trigger< const std::vector< Timer > & > timer_tick_trigger_
Trigger< std::string > intent_progress_trigger_
void on_announce(const api::VoiceAssistantAnnounceRequest &msg)
void request_start(bool continuous, bool silence_detection)
void handle_channel_stall_(size_t available, size_t available2)
std::unique_ptr< audio::RingBufferAudioSource > audio_source2_
microphone::MicrophoneSource * mic_source_
micro_wake_word::MicroWakeWord * micro_wake_word_
void on_set_configuration(const std::vector< std::string > &active_wake_words)
const LogString * message
Definition component.cpp:35
uint16_t flags
bool state
Definition fan.h:2
uint32_t socklen_t
Definition headers.h:99
__int64 ssize_t
Definition httplib.h:178
@ VOICE_ASSISTANT_REQUEST_USE_WAKE_WORD
Definition api_pb2.h:264
@ VOICE_ASSISTANT_REQUEST_USE_VAD
Definition api_pb2.h:263
@ VOICE_ASSISTANT_TIMER_UPDATED
Definition api_pb2.h:287
@ VOICE_ASSISTANT_TIMER_STARTED
Definition api_pb2.h:286
@ VOICE_ASSISTANT_TIMER_FINISHED
Definition api_pb2.h:289
@ VOICE_ASSISTANT_TIMER_CANCELLED
Definition api_pb2.h:288
@ VOICE_ASSISTANT_WAKE_WORD_START
Definition api_pb2.h:277
@ VOICE_ASSISTANT_TTS_STREAM_END
Definition api_pb2.h:282
@ VOICE_ASSISTANT_STT_VAD_START
Definition api_pb2.h:279
@ VOICE_ASSISTANT_INTENT_PROGRESS
Definition api_pb2.h:283
@ VOICE_ASSISTANT_TTS_STREAM_START
Definition api_pb2.h:281
@ VOICE_ASSISTANT_WAKE_WORD_END
Definition api_pb2.h:278
constexpr float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
Definition component.h:57
std::unique_ptr< Socket > socket(int domain, int type, int protocol)
Create a socket of the given domain, type and protocol.
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().
Definition socket.cpp:194
VoiceAssistant * global_voice_assistant
int written
Definition helpers.h:1099
Application App
Global storage of Application pointer - only one Application can exist.
static void uint32_t
std::vector< WakeWord > available_wake_words
std::vector< std::string > active_wake_words
static constexpr size_t TO_STR_BUFFER_SIZE
Buffer size for to_str() - sufficient for typical timer names.
std::vector< std::string > trained_languages
sa_family_t ss_family
Definition headers.h:94