14static const uint32_t MAX_FILL_DURATION_MS = 30;
15static const uint32_t RING_BUFFER_DURATION_MS = 120;
18static const double MAX_SAMPLE_SQUARED_DENOMINATOR = INT16_MIN * INT16_MIN;
22 "Sound Level Component:\n"
23 " Measurement Duration: %" PRIu32
" ms",
25 LOG_SENSOR(
" ",
"Peak:", this->peak_sensor_);
27 LOG_SENSOR(
" ",
"RMS:", this->rms_sensor_);
30void SoundLevelComponent::setup() {
32 std::shared_ptr<ring_buffer::RingBuffer> temp_ring_buffer = this->
ring_buffer_.lock();
33 if (temp_ring_buffer !=
nullptr) {
34 temp_ring_buffer->write((
void *) capture.
data.data(), capture.
data.size());
44void SoundLevelComponent::loop() {
45 if ((this->peak_sensor_ ==
nullptr) && (this->rms_sensor_ ==
nullptr)) {
57 this->
status_set_warning(LOG_STR(
"Microphone isn't running, can't compute statistics"));
63 PUBLISH_STATE(this->peak_sensor_, NAN);
64 PUBLISH_STATE(this->rms_sensor_, NAN);
89 const uint32_t samples_available_to_process =
91 const uint32_t samples_to_process = std::min(samples_in_window - this->
sample_count_, samples_available_to_process);
94 const int16_t *audio_data =
reinterpret_cast<const int16_t *
>(this->
audio_source_->data());
97 for (
uint32_t i = 0; i < samples_to_process; ++i) {
99 int32_t squared_sample =
static_cast<int32_t
>(audio_data[i]) *
static_cast<int32_t
>(audio_data[i]);
101 if (this->peak_sensor_ !=
nullptr) {
105 if (this->rms_sensor_ !=
nullptr) {
118 if (this->peak_sensor_ !=
nullptr) {
119 const float peak_db = 10.0f * log10f(
static_cast<float>(this->
squared_peak_) / MAX_SAMPLE_SQUARED_DENOMINATOR);
120 this->peak_sensor_->publish_state(peak_db);
125 if (this->rms_sensor_ !=
nullptr) {
127 const double rms_db = 10.0 * log10((this->
squared_samples_sum_ / MAX_SAMPLE_SQUARED_DENOMINATOR) /
128 static_cast<double>(samples_in_window));
129 this->rms_sensor_->publish_state(rms_db);
138void SoundLevelComponent::start() {
140 ESP_LOGW(TAG,
"Can't start the microphone in passive mode");
146void SoundLevelComponent::stop() {
148 ESP_LOGW(TAG,
"Can't stop microphone in passive mode");
154bool SoundLevelComponent::start_() {
165 const size_t ring_buffer_size =
166 (stream_info.ms_to_bytes(RING_BUFFER_DURATION_MS) / bytes_per_frame) * bytes_per_frame;
168 if (temp_ring_buffer ==
nullptr) {
176 temp_ring_buffer, stream_info.ms_to_bytes(MAX_FILL_DURATION_MS),
static_cast<uint8_t
>(bytes_per_frame));
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.