ESPHome 2025.6.3
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 return;
147
148#ifdef USE_SPEAKER
149 if (this->speaker_ != nullptr) {
150 if (this->state_ == State::STATE_STOPPING) {
151 if (this->speaker_->is_stopped()) {
153 }
154 } else if (this->state_ == State::STATE_INIT) {
155 if (this->speaker_->is_stopped()) {
156 this->speaker_->start();
158 }
159 } else if (this->state_ == State::STATE_STARTING) {
160 if (this->speaker_->is_running()) {
162 }
163 }
164 if (!this->speaker_->is_running()) {
165 return;
166 }
167 if (this->samples_sent_ != this->samples_count_) {
168 SpeakerSample sample[SAMPLE_BUFFER_SIZE + 2];
169 int x = 0;
170 double rem = 0.0;
171
172 while (true) {
173 // Try and send out the remainder of the existing note, one per loop()
174
175 if (this->samples_per_wave_ != 0 && this->samples_sent_ >= this->samples_gap_) { // Play note//
176 rem = ((this->samples_sent_ << 10) % this->samples_per_wave_) * (360.0 / this->samples_per_wave_);
177
178 int16_t val = (127 * this->gain_) * sin(deg2rad(rem)); // 16bit = 49152
179
180 sample[x].left = val;
181 sample[x].right = val;
182
183 } else {
184 sample[x].left = 0;
185 sample[x].right = 0;
186 }
187
188 if (x >= SAMPLE_BUFFER_SIZE || this->samples_sent_ >= this->samples_count_) {
189 break;
190 }
191 this->samples_sent_++;
192 x++;
193 }
194 if (x > 0) {
195 int send = this->speaker_->play((uint8_t *) (&sample), x * 2);
196 if (send != x * 4) {
197 this->samples_sent_ -= (x - (send / 2));
198 }
199 return;
200 }
201 }
202 }
203#endif
204#ifdef USE_OUTPUT
205 if (this->output_ != nullptr && millis() - this->last_note_ < this->note_duration_)
206 return;
207#endif
208 if (!this->rtttl_[this->position_]) {
209 this->finish_();
210 return;
211 }
212
213 // align to note: most rtttl's out there does not add and space after the ',' separator but just in case...
214 while (this->rtttl_[this->position_] == ',' || this->rtttl_[this->position_] == ' ')
215 this->position_++;
216
217 // first, get note duration, if available
218 uint8_t num = this->get_integer_();
219
220 if (num) {
221 this->note_duration_ = this->wholenote_ / num;
222 } else {
223 this->note_duration_ =
224 this->wholenote_ / this->default_duration_; // we will need to check if we are a dotted note after
225 }
226
227 uint8_t note;
228
229 switch (this->rtttl_[this->position_]) {
230 case 'c':
231 note = 1;
232 break;
233 case 'd':
234 note = 3;
235 break;
236 case 'e':
237 note = 5;
238 break;
239 case 'f':
240 note = 6;
241 break;
242 case 'g':
243 note = 8;
244 break;
245 case 'a':
246 note = 10;
247 break;
248 case 'h':
249 case 'b':
250 note = 12;
251 break;
252 case 'p':
253 default:
254 note = 0;
255 }
256 this->position_++;
257
258 // now, get optional '#' sharp
259 if (this->rtttl_[this->position_] == '#') {
260 note++;
261 this->position_++;
262 }
263
264 // now, get optional '.' dotted note
265 if (this->rtttl_[this->position_] == '.') {
266 this->note_duration_ += this->note_duration_ / 2;
267 this->position_++;
268 }
269
270 // now, get scale
271 uint8_t scale = get_integer_();
272 if (scale == 0)
273 scale = this->default_octave_;
274
275 if (scale < 4 || scale > 7) {
276 ESP_LOGE(TAG, "Octave must be between 4 and 7 (it is %d)", scale);
277 this->finish_();
278 return;
279 }
280 bool need_note_gap = false;
281
282 // Now play the note
283 if (note) {
284 auto note_index = (scale - 4) * 12 + note;
285 if (note_index < 0 || note_index >= (int) sizeof(NOTES)) {
286 ESP_LOGE(TAG, "Note out of range (note: %d, scale: %d, index: %d, max: %d)", note, scale, note_index,
287 (int) sizeof(NOTES));
288 this->finish_();
289 return;
290 }
291 auto freq = NOTES[note_index];
292 need_note_gap = freq == this->output_freq_;
293
294 // Add small silence gap between same note
295 this->output_freq_ = freq;
296
297 ESP_LOGVV(TAG, "playing note: %d for %dms", note, this->note_duration_);
298 } else {
299 ESP_LOGVV(TAG, "waiting: %dms", this->note_duration_);
300 this->output_freq_ = 0;
301 }
302
303#ifdef USE_OUTPUT
304 if (this->output_ != nullptr) {
305 if (need_note_gap) {
306 this->output_->set_level(0.0);
307 delay(DOUBLE_NOTE_GAP_MS);
308 this->note_duration_ -= DOUBLE_NOTE_GAP_MS;
309 }
310 if (this->output_freq_ != 0) {
312 this->output_->set_level(this->gain_);
313 } else {
314 this->output_->set_level(0.0);
315 }
316 }
317#endif
318#ifdef USE_SPEAKER
319 if (this->speaker_ != nullptr) {
320 this->samples_sent_ = 0;
321 this->samples_gap_ = 0;
322 this->samples_per_wave_ = 0;
323 this->samples_count_ = (this->sample_rate_ * this->note_duration_) / 1600; //(ms);
324 if (need_note_gap) {
325 this->samples_gap_ = (this->sample_rate_ * DOUBLE_NOTE_GAP_MS) / 1600; //(ms);
326 }
327 if (this->output_freq_ != 0) {
328 // make sure there is enough samples to add a full last sinus.
329
330 uint16_t samples_wish = this->samples_count_;
331 this->samples_per_wave_ = (this->sample_rate_ << 10) / this->output_freq_;
332
333 uint16_t division = ((this->samples_count_ << 10) / this->samples_per_wave_) + 1;
334
335 this->samples_count_ = (division * this->samples_per_wave_);
336 this->samples_count_ = this->samples_count_ >> 10;
337 ESP_LOGVV(TAG, "- Calc play time: wish: %d gets: %d (div: %d spw: %d)", samples_wish, this->samples_count_,
338 division, this->samples_per_wave_);
339 }
340 // Convert from frequency in Hz to high and low samples in fixed point
341 }
342#endif
343
344 this->last_note_ = millis();
345}
346
348#ifdef USE_OUTPUT
349 if (this->output_ != nullptr) {
350 this->output_->set_level(0.0);
352 }
353#endif
354#ifdef USE_SPEAKER
355 if (this->speaker_ != nullptr) {
356 SpeakerSample sample[2];
357 sample[0].left = 0;
358 sample[0].right = 0;
359 sample[1].left = 0;
360 sample[1].right = 0;
361 this->speaker_->play((uint8_t *) (&sample), 8);
362
363 this->speaker_->finish();
365 }
366#endif
367 this->note_duration_ = 0;
369 ESP_LOGD(TAG, "Playback finished");
370}
371
372static const LogString *state_to_string(State state) {
373 switch (state) {
374 case STATE_STOPPED:
375 return LOG_STR("STATE_STOPPED");
376 case STATE_STARTING:
377 return LOG_STR("STATE_STARTING");
378 case STATE_RUNNING:
379 return LOG_STR("STATE_RUNNING");
380 case STATE_STOPPING:
381 return LOG_STR("STATE_STOPPING");
382 case STATE_INIT:
383 return LOG_STR("STATE_INIT");
384 default:
385 return LOG_STR("UNKNOWN");
386 }
387};
388
390 State old_state = this->state_;
391 this->state_ = state;
392 ESP_LOGV(TAG, "State changed from %s to %s", LOG_STR_ARG(state_to_string(old_state)),
393 LOG_STR_ARG(state_to_string(state)));
394}
395
396} // namespace rtttl
397} // namespace esphome
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:389
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