ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
rtttl.cpp
Go to the documentation of this file.
1#include "rtttl.h"
2#include <cmath>
3#include "esphome/core/hal.h"
4#include "esphome/core/log.h"
5
6namespace esphome {
7namespace rtttl {
8
9static const char *const TAG = "rtttl";
10
11static const uint32_t DOUBLE_NOTE_GAP_MS = 10;
12
13// These values can also be found as constants in the Tone library (Tone.h)
14static const uint16_t NOTES[] = {0, 262, 277, 294, 311, 330, 349, 370, 392, 415, 440, 466, 494,
15 523, 554, 587, 622, 659, 698, 740, 784, 831, 880, 932, 988, 1047,
16 1109, 1175, 1245, 1319, 1397, 1480, 1568, 1661, 1760, 1865, 1976, 2093, 2217,
17 2349, 2489, 2637, 2794, 2960, 3136, 3322, 3520, 3729, 3951};
18
19static const uint16_t I2S_SPEED = 1000;
20
21#undef HALF_PI
22static const double HALF_PI = 1.5707963267948966192313216916398;
23
24inline double deg2rad(double degrees) {
25 static const double PI_ON_180 = 4.0 * atan(1.0) / 180.0;
26 return degrees * PI_ON_180;
27}
28
30 ESP_LOGCONFIG(TAG,
31 "Rtttl:\n"
32 " Gain: %f",
33 this->gain_);
34}
35
36void Rtttl::play(std::string rtttl) {
38 int pos = this->rtttl_.find(':');
39 auto name = this->rtttl_.substr(0, pos);
40 ESP_LOGW(TAG, "Already playing: %s", name.c_str());
41 return;
42 }
43
44 this->rtttl_ = std::move(rtttl);
45
46 this->default_duration_ = 4;
47 this->default_octave_ = 6;
48 this->note_duration_ = 0;
49
50 int bpm = 63;
51 uint8_t num;
52
53 // Get name
54 this->position_ = this->rtttl_.find(':');
55
56 // it's somewhat documented to be up to 10 characters but let's be a bit flexible here
57 if (this->position_ == std::string::npos || this->position_ > 15) {
58 ESP_LOGE(TAG, "Unable to determine name; missing ':'");
59 return;
60 }
61
62 auto name = this->rtttl_.substr(0, this->position_);
63 ESP_LOGD(TAG, "Playing song %s", name.c_str());
64
65 // get default duration
66 this->position_ = this->rtttl_.find("d=", this->position_);
67 if (this->position_ == std::string::npos) {
68 ESP_LOGE(TAG, "Missing 'd='");
69 return;
70 }
71 this->position_ += 2;
72 num = this->get_integer_();
73 if (num > 0)
74 this->default_duration_ = num;
75
76 // get default octave
77 this->position_ = this->rtttl_.find("o=", this->position_);
78 if (this->position_ == std::string::npos) {
79 ESP_LOGE(TAG, "Missing 'o=");
80 return;
81 }
82 this->position_ += 2;
83 num = get_integer_();
84 if (num >= 3 && num <= 7)
85 this->default_octave_ = num;
86
87 // get BPM
88 this->position_ = this->rtttl_.find("b=", this->position_);
89 if (this->position_ == std::string::npos) {
90 ESP_LOGE(TAG, "Missing b=");
91 return;
92 }
93 this->position_ += 2;
94 num = get_integer_();
95 if (num != 0)
96 bpm = num;
97
98 this->position_ = this->rtttl_.find(':', this->position_);
99 if (this->position_ == std::string::npos) {
100 ESP_LOGE(TAG, "Missing second ':'");
101 return;
102 }
103 this->position_++;
104
105 // BPM usually expresses the number of quarter notes per minute
106 this->wholenote_ = 60 * 1000L * 4 / bpm; // this is the time for whole note (in milliseconds)
107
108 this->output_freq_ = 0;
109 this->last_note_ = millis();
110 this->note_duration_ = 1;
111
112#ifdef USE_SPEAKER
113 if (this->speaker_ != nullptr) {
115 this->samples_sent_ = 0;
116 this->samples_count_ = 0;
117 }
118#endif
119#ifdef USE_OUTPUT
120 if (this->output_ != nullptr) {
122 }
123#endif
124}
125
127#ifdef USE_OUTPUT
128 if (this->output_ != nullptr) {
129 this->output_->set_level(0.0);
131 }
132#endif
133#ifdef USE_SPEAKER
134 if (this->speaker_ != nullptr) {
135 if (this->speaker_->is_running()) {
136 this->speaker_->stop();
137 }
139 }
140#endif
141 this->note_duration_ = 0;
142}
143
145 if (this->note_duration_ == 0 || this->state_ == State::STATE_STOPPED) {
146 this->disable_loop();
147 return;
148 }
149
150#ifdef USE_SPEAKER
151 if (this->speaker_ != nullptr) {
152 if (this->state_ == State::STATE_STOPPING) {
153 if (this->speaker_->is_stopped()) {
155 }
156 } else if (this->state_ == State::STATE_INIT) {
157 if (this->speaker_->is_stopped()) {
158 this->speaker_->start();
160 }
161 } else if (this->state_ == State::STATE_STARTING) {
162 if (this->speaker_->is_running()) {
164 }
165 }
166 if (!this->speaker_->is_running()) {
167 return;
168 }
169 if (this->samples_sent_ != this->samples_count_) {
170 SpeakerSample sample[SAMPLE_BUFFER_SIZE + 2];
171 int x = 0;
172 double rem = 0.0;
173
174 while (true) {
175 // Try and send out the remainder of the existing note, one per loop()
176
177 if (this->samples_per_wave_ != 0 && this->samples_sent_ >= this->samples_gap_) { // Play note//
178 rem = ((this->samples_sent_ << 10) % this->samples_per_wave_) * (360.0 / this->samples_per_wave_);
179
180 int16_t val = (127 * this->gain_) * sin(deg2rad(rem)); // 16bit = 49152
181
182 sample[x].left = val;
183 sample[x].right = val;
184
185 } else {
186 sample[x].left = 0;
187 sample[x].right = 0;
188 }
189
190 if (x >= SAMPLE_BUFFER_SIZE || this->samples_sent_ >= this->samples_count_) {
191 break;
192 }
193 this->samples_sent_++;
194 x++;
195 }
196 if (x > 0) {
197 int send = this->speaker_->play((uint8_t *) (&sample), x * 2);
198 if (send != x * 4) {
199 this->samples_sent_ -= (x - (send / 2));
200 }
201 return;
202 }
203 }
204 }
205#endif
206#ifdef USE_OUTPUT
207 if (this->output_ != nullptr && millis() - this->last_note_ < this->note_duration_)
208 return;
209#endif
210 if (!this->rtttl_[this->position_]) {
211 this->finish_();
212 return;
213 }
214
215 // align to note: most rtttl's out there does not add and space after the ',' separator but just in case...
216 while (this->rtttl_[this->position_] == ',' || this->rtttl_[this->position_] == ' ')
217 this->position_++;
218
219 // first, get note duration, if available
220 uint8_t num = this->get_integer_();
221
222 if (num) {
223 this->note_duration_ = this->wholenote_ / num;
224 } else {
225 this->note_duration_ =
226 this->wholenote_ / this->default_duration_; // we will need to check if we are a dotted note after
227 }
228
229 uint8_t note;
230
231 switch (this->rtttl_[this->position_]) {
232 case 'c':
233 note = 1;
234 break;
235 case 'd':
236 note = 3;
237 break;
238 case 'e':
239 note = 5;
240 break;
241 case 'f':
242 note = 6;
243 break;
244 case 'g':
245 note = 8;
246 break;
247 case 'a':
248 note = 10;
249 break;
250 case 'h':
251 case 'b':
252 note = 12;
253 break;
254 case 'p':
255 default:
256 note = 0;
257 }
258 this->position_++;
259
260 // now, get optional '#' sharp
261 if (this->rtttl_[this->position_] == '#') {
262 note++;
263 this->position_++;
264 }
265
266 // now, get optional '.' dotted note
267 if (this->rtttl_[this->position_] == '.') {
268 this->note_duration_ += this->note_duration_ / 2;
269 this->position_++;
270 }
271
272 // now, get scale
273 uint8_t scale = get_integer_();
274 if (scale == 0)
275 scale = this->default_octave_;
276
277 if (scale < 4 || scale > 7) {
278 ESP_LOGE(TAG, "Octave must be between 4 and 7 (it is %d)", scale);
279 this->finish_();
280 return;
281 }
282 bool need_note_gap = false;
283
284 // Now play the note
285 if (note) {
286 auto note_index = (scale - 4) * 12 + note;
287 if (note_index < 0 || note_index >= (int) sizeof(NOTES)) {
288 ESP_LOGE(TAG, "Note out of range (note: %d, scale: %d, index: %d, max: %d)", note, scale, note_index,
289 (int) sizeof(NOTES));
290 this->finish_();
291 return;
292 }
293 auto freq = NOTES[note_index];
294 need_note_gap = freq == this->output_freq_;
295
296 // Add small silence gap between same note
297 this->output_freq_ = freq;
298
299 ESP_LOGVV(TAG, "playing note: %d for %dms", note, this->note_duration_);
300 } else {
301 ESP_LOGVV(TAG, "waiting: %dms", this->note_duration_);
302 this->output_freq_ = 0;
303 }
304
305#ifdef USE_OUTPUT
306 if (this->output_ != nullptr) {
307 if (need_note_gap) {
308 this->output_->set_level(0.0);
309 delay(DOUBLE_NOTE_GAP_MS);
310 this->note_duration_ -= DOUBLE_NOTE_GAP_MS;
311 }
312 if (this->output_freq_ != 0) {
314 this->output_->set_level(this->gain_);
315 } else {
316 this->output_->set_level(0.0);
317 }
318 }
319#endif
320#ifdef USE_SPEAKER
321 if (this->speaker_ != nullptr) {
322 this->samples_sent_ = 0;
323 this->samples_gap_ = 0;
324 this->samples_per_wave_ = 0;
325 this->samples_count_ = (this->sample_rate_ * this->note_duration_) / 1600; //(ms);
326 if (need_note_gap) {
327 this->samples_gap_ = (this->sample_rate_ * DOUBLE_NOTE_GAP_MS) / 1600; //(ms);
328 }
329 if (this->output_freq_ != 0) {
330 // make sure there is enough samples to add a full last sinus.
331
332 uint16_t samples_wish = this->samples_count_;
333 this->samples_per_wave_ = (this->sample_rate_ << 10) / this->output_freq_;
334
335 uint16_t division = ((this->samples_count_ << 10) / this->samples_per_wave_) + 1;
336
337 this->samples_count_ = (division * this->samples_per_wave_);
338 this->samples_count_ = this->samples_count_ >> 10;
339 ESP_LOGVV(TAG, "- Calc play time: wish: %d gets: %d (div: %d spw: %d)", samples_wish, this->samples_count_,
340 division, this->samples_per_wave_);
341 }
342 // Convert from frequency in Hz to high and low samples in fixed point
343 }
344#endif
345
346 this->last_note_ = millis();
347}
348
350#ifdef USE_OUTPUT
351 if (this->output_ != nullptr) {
352 this->output_->set_level(0.0);
354 }
355#endif
356#ifdef USE_SPEAKER
357 if (this->speaker_ != nullptr) {
358 SpeakerSample sample[2];
359 sample[0].left = 0;
360 sample[0].right = 0;
361 sample[1].left = 0;
362 sample[1].right = 0;
363 this->speaker_->play((uint8_t *) (&sample), 8);
364
365 this->speaker_->finish();
367 }
368#endif
369 this->note_duration_ = 0;
371 ESP_LOGD(TAG, "Playback finished");
372}
373
374#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_DEBUG
375static const LogString *state_to_string(State state) {
376 switch (state) {
377 case STATE_STOPPED:
378 return LOG_STR("STATE_STOPPED");
379 case STATE_STARTING:
380 return LOG_STR("STATE_STARTING");
381 case STATE_RUNNING:
382 return LOG_STR("STATE_RUNNING");
383 case STATE_STOPPING:
384 return LOG_STR("STATE_STOPPING");
385 case STATE_INIT:
386 return LOG_STR("STATE_INIT");
387 default:
388 return LOG_STR("UNKNOWN");
389 }
390};
391#endif
392
394 State old_state = this->state_;
395 this->state_ = state;
396 ESP_LOGV(TAG, "State changed from %s to %s", LOG_STR_ARG(state_to_string(old_state)),
397 LOG_STR_ARG(state_to_string(state)));
398
399 // Clear loop_done when transitioning from STOPPED to any other state
400 if (old_state == State::STATE_STOPPED && state != State::STATE_STOPPED) {
401 this->enable_loop();
402 }
403}
404
405} // namespace rtttl
406} // namespace esphome
void enable_loop()
Enable this component's loop.
void disable_loop()
Disable this component's loop.
void set_level(float state)
Set the level of this float output, this is called from the front-end.
virtual void update_frequency(float frequency)
Set the frequency of the output for PWM outputs.
uint16_t wholenote_
Definition rtttl.h:68
uint32_t last_note_
Definition rtttl.h:71
uint16_t note_duration_
Definition rtttl.h:72
output::FloatOutput * output_
Definition rtttl.h:79
void dump_config() override
Definition rtttl.cpp:29
void set_state_(State state)
Definition rtttl.cpp:393
uint32_t output_freq_
Definition rtttl.h:74
void loop() override
Definition rtttl.cpp:144
uint8_t get_integer_()
Definition rtttl.h:56
uint16_t default_duration_
Definition rtttl.h:69
uint16_t default_octave_
Definition rtttl.h:70
speaker::Speaker * speaker_
Definition rtttl.h:83
CallbackManager< void()> on_finished_playback_callback_
Definition rtttl.h:92
void play(std::string rtttl)
Definition rtttl.cpp:36
std::string rtttl_
Definition rtttl.h:66
virtual size_t play(const uint8_t *data, size_t length)=0
Plays the provided audio data.
bool is_running() const
Definition speaker.h:66
virtual void start()=0
virtual void finish()
Definition speaker.h:58
bool is_stopped() const
Definition speaker.h:67
virtual void stop()=0
bool state
Definition fan.h:0
mopeka_std_values val[4]
double deg2rad(double degrees)
Definition rtttl.cpp:24
@ STATE_STOPPING
Definition rtttl.h:22
@ STATE_RUNNING
Definition rtttl.h:21
@ STATE_STOPPED
Definition rtttl.h:18
@ STATE_STARTING
Definition rtttl.h:20
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
void IRAM_ATTR HOT delay(uint32_t ms)
Definition core.cpp:29
uint32_t IRAM_ATTR HOT millis()
Definition core.cpp:28
uint16_t x
Definition tt21100.cpp:5