ESPHome 2026.12.0-dev
Loading...
Searching...
No Matches
sendspin_hub.cpp
Go to the documentation of this file.
1#include "sendspin_hub.h"
2
3#ifdef USE_ESP_IDF
4
6#ifdef USE_ETHERNET
8#endif
9#ifdef USE_WIFI
11#endif
12
15#include "esphome/core/log.h"
17
18#include <esp_log.h>
19
20#include <memory>
21#include <string>
22
23namespace esphome::sendspin_ {
24
25ESPHOME_LOG_TAG(TAG, "sendspin.hub");
26
27namespace {
28
29// The reason passed to on_pairing_failed automations, in the protocol's own spelling.
30StringRef pair_abort_reason_to_string(sendspin::SendspinPairAbortReason reason) {
31 using sendspin::SendspinPairAbortReason;
32 switch (reason) {
33 case SendspinPairAbortReason::ATTEMPT_TIMEOUT:
34 return StringRef::from_lit("attempt_timeout");
35 case SendspinPairAbortReason::CONCURRENT_ATTEMPT:
36 return StringRef::from_lit("concurrent_attempt");
37 case SendspinPairAbortReason::METHOD_NOT_SUPPORTED:
38 return StringRef::from_lit("method_not_supported");
39 case SendspinPairAbortReason::PAIRING_CODE_MISMATCH:
40 return StringRef::from_lit("pairing_code_mismatch");
41 case SendspinPairAbortReason::USER_CANCELLED:
42 return StringRef::from_lit("user_cancelled");
43 case SendspinPairAbortReason::UNKNOWN:
44 break;
45 }
46 return StringRef::from_lit("unknown");
47}
48
49// Zeroes through a volatile pointer so dead-store elimination cannot drop it.
50void secure_wipe(void *data, size_t len) {
51 volatile auto *p = static_cast<volatile uint8_t *>(data);
52 for (size_t i = 0; i < len; ++i) {
53 p[i] = 0;
54 }
55}
56
57// Call once per key, from setup().
58ESPPreferenceObject make_blob_pref(const std::string &name, size_t size) {
59 return global_preferences->make_preference(size, fnv1a_hash("sendspin_" + name));
60}
61
62// Loads straight into the library's buffer, which it wipes after use. A failed load can leave part
63// of a stored private key or PSK behind, so that path wipes it here. This only covers this buffer:
64// the preference backend keeps its own copy of a pending write until it syncs.
65std::optional<size_t> load_pref(ESPPreferenceObject &pref, size_t size, std::span<uint8_t> out) {
66 if (out.size() < size) {
67 return std::nullopt;
68 }
69 if (!pref.load(out.data(), size)) {
70 secure_wipe(out.data(), size);
71 return std::nullopt;
72 }
73 return size;
74}
75
76// The library always writes a key's fixed size; any other length is misuse and is not stored.
77bool save_pref(ESPPreferenceObject &pref, StringRef key, size_t size, std::span<const uint8_t> data) {
78 if (data.size() != size) {
79 ESP_LOGW(TAG, "\"%.*s\" blob of %zu bytes does not match its size of %zu; rejecting write",
80 static_cast<int>(key.size()), key.c_str(), data.size(), size);
81 return false;
82 }
83 if (!pref.save(data.data(), data.size())) {
84 ESP_LOGW(TAG, "Failed to persist \"%.*s\" blob (%zu bytes)", static_cast<int>(key.size()), key.c_str(),
85 data.size());
86 return false;
87 }
88 return true;
89}
90
91// "rec_<n>" to n; nullopt for any other key or a slot with no storage here.
92std::optional<size_t> parse_record_slot(StringRef key) {
93 const StringRef prefix(sendspin::persistence_keys::RECORD_SLOT_PREFIX);
94 if (key.size() <= prefix.size() || !key.starts_with(prefix)) {
95 return std::nullopt;
96 }
97 size_t slot = 0;
98 for (const char c : StringRef(key.begin() + prefix.size(), key.end())) {
99 if (c < '0' || c > '9') {
100 return std::nullopt;
101 }
102 slot = slot * 10 + static_cast<size_t>(c - '0');
103 if (slot >= SENDSPIN_RECORD_SLOTS) {
104 return std::nullopt;
105 }
106 }
107 return slot;
108}
109
110} // namespace
111
112#ifdef USE_SENDSPIN_ARTWORK
113// Indexed by the library enums, which start at zero and are contiguous.
114static const char *const IMAGE_SOURCE_NAMES[] = {"ALBUM", "ARTIST", "NONE"};
115static const char *const IMAGE_FORMAT_NAMES[] = {"JPEG", "PNG"};
116#endif
117
118SendspinHub *global_sendspin_hub = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
119
121
123 auto config = this->build_client_config_();
124 this->client_ = std::make_unique<sendspin::SendspinClient>(std::move(config));
125
126 // Set up persistence (preferences must be initialized before providers are added to the client). These key names
127 // are frozen; see PREFERENCE KEYS in sendspin_hub.h.
128 namespace keys = sendspin::persistence_keys;
129 this->keypair_pref_ = make_blob_pref("keypair", keys::KEYPAIR_SIZE);
130 this->pairing_psk_pref_ = make_blob_pref("pair_psk", keys::PAIRING_PSK_SIZE);
131 this->last_played_pref_ = make_blob_pref("last_played", keys::LAST_PLAYED_SIZE);
132 // Released firmware's name, so a calibrated delay survives.
133 this->output_delay_pref_ = make_blob_pref("static_delay", keys::OUTPUT_DELAY_SIZE);
134 for (size_t slot = 0; slot < SENDSPIN_RECORD_SLOTS; slot++) {
135 this->record_slot_prefs_[slot] =
136 make_blob_pref(std::string(keys::RecordSlotKey(slot).view()), keys::RECORD_SLOT_SIZE);
137 }
138 this->record_order_pref_ = make_blob_pref(keys::RECORD_ORDER, SENDSPIN_RECORD_SLOTS);
139
140 // Wire providers and client listener
141 this->client_->set_listener(this);
142 this->client_->set_network_provider(this);
143 this->client_->set_persistence_provider(this);
144
145#ifdef USE_SENDSPIN_ARTWORK
146 this->artwork_role_ = &this->client_->add_artwork(this->artwork_config_);
147 this->artwork_role_->set_listener(this);
148#endif
149
150#ifdef USE_SENDSPIN_COLOR
151 this->client_->add_color().set_listener(this);
152#endif
153
154#ifdef USE_SENDSPIN_CONTROLLER
155 this->controller_role_ = &this->client_->add_controller();
156 this->controller_role_->set_listener(this);
157#endif
158
159#ifdef USE_SENDSPIN_METADATA
160 this->metadata_role_ = &this->client_->add_metadata(this->metadata_config_);
161 this->metadata_role_->set_listener(this);
162#endif
163
164#ifdef USE_SENDSPIN_PLAYER
165 this->client_->add_player(this->player_config_).set_listener(this->player_listener_);
166#endif
167
168#ifdef USE_SENDSPIN_SOURCE
169 // Every source reports its signal (Sendspin/spec#335); sendspin-cpp (as of 0.10.0) does so only with line sense,
170 // so the signal is always applied below. Remove both once sendspin-cpp follows the spec change.
171 this->source_config_.line_sense = true;
172 this->source_role_ = &this->client_->add_source(this->source_config_);
173 this->source_role_->set_listener(this);
174 // THREAD CONTEXT: Microphone task, the role's single producer. A capture time of 0 (unknown) makes the library
175 // stamp the buffer as ending now.
177 // A failed microphone read can publish an empty buffer, which the library rejects with a warning
178 if (!capture.data.empty()) {
179 this->source_role_->write_audio(capture.data.data(), capture.data.size(), capture.capture_time_us);
180 }
181 });
182 // A sensor that reports its state at boot can run the set_signal action before this setup()
184#endif
185
186#ifdef USE_SENDSPIN_VISUALIZER
187 if (this->visualizer_config_ != nullptr) {
188 this->client_->add_visualizer(*this->visualizer_config_).set_listener(this->visualizer_listener_);
189 }
190#endif
191
192 // Set before setup() by codegen; an unpaired access switch sets it later, from its own setup().
193 if (this->unpaired_access_.has_value()) {
194 this->client_->set_unpaired_access_enabled(*this->unpaired_access_);
195 }
196
197#ifdef USE_SENDSPIN_ENABLED_SWITCH
198 // loop() waits for this, so a restore mode without a state still has to answer.
199 this->enabled_switch_->restore(true);
200#endif
201}
202
204 if (this->enabled_.has_value() && this->unpaired_access_.has_value() &&
205 this->enabled_.value() != this->client_->is_started() && !this->status_has_error()) {
206 if (!this->enabled_.value()) {
207 this->client_->stop();
208 } else if (!this->client_->start()) {
209 this->status_set_error(LOG_STR("Failed to start Sendspin client"));
210 }
211 }
212 this->client_->loop();
213
214#ifdef USE_MDNS_SUPPORTS_ENABLE_DISABLE
215 this->update_mdns_service_();
216#endif
217}
218
219// Sends each server a goodbye and writes what the client still owed its provider. Wi-Fi sets up
220// before this hub, so it shuts down after it and the goodbyes can still go out.
222 // Keeps loop() from starting the client again.
223 this->enabled_ = false;
224 if (this->is_client_running()) {
225 this->client_->stop();
226 }
227}
228
230 // client_id exists only once start() has run.
231 const char *client_id = "(unavailable)";
232 if (this->client_ != nullptr && !this->client_->client_id().empty()) {
233 client_id = this->client_->client_id().c_str();
234 }
235 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
236 ESP_LOGCONFIG(TAG,
237 "Sendspin Hub:\n"
238 " Client ID: %s\n"
239 " MAC address: %s\n"
240 " Manufacturer: %s\n"
241 " Model: %s\n"
242 " Firmware version: %s\n"
243 " Task stack in PSRAM: %s\n"
244 " Unpaired access: %s\n"
245 " Pairing code method: %s",
246 client_id, get_mac_address_into_buffer(mac_buf), this->manufacturer_, this->get_product_name_(),
247 this->firmware_version_, YESNO(this->task_stack_in_psram_),
248 YESNO(this->client_ != nullptr && this->client_->is_unpaired_access_enabled()),
249 this->pairing_code_method_());
250#ifdef USE_SENDSPIN_ENABLED_SWITCH
251 LOG_SWITCH(" ", "Enabled switch", this->enabled_switch_);
252#endif
253
254#ifdef USE_SENDSPIN_ARTWORK
255 // Slot indices come from the order the image platform entries were declared, so the log is the
256 // only place the mapping from a slot to the artwork it asked for can be read back.
257 uint8_t slot = 0;
258 for (const auto &preference : this->artwork_config_.preferred_formats) {
259 ESP_LOGCONFIG(TAG, " Artwork slot %u: %s as %s, %ux%u, display offset %" PRId32 " ms", slot++,
260 IMAGE_SOURCE_NAMES[static_cast<uint8_t>(preference.source)],
261 IMAGE_FORMAT_NAMES[static_cast<uint8_t>(preference.format)], preference.width, preference.height,
262 preference.display_offset_ms);
263 }
264#endif
265
266#ifdef USE_SENDSPIN_SOURCE
267 ESP_LOGCONFIG(TAG,
268 " Source:\n"
269 " Sample rate: %" PRIu32 " Hz\n"
270 " Channels: %u\n"
271 " Bits per sample: %u\n"
272 " Task stack in PSRAM: %s",
273 this->source_config_.sample_rate, this->source_config_.channels, this->source_config_.bit_depth,
274 YESNO(this->source_config_.psram_stack));
275#endif
276}
277
278// THREAD CONTEXT: Main loop (invoked from codegen before setup(), or from Sendspin components)
279void SendspinHub::set_enabled(bool enabled) {
280 if (this->status_has_error()) {
281 ESP_LOGE(TAG, "Cannot %s: Sendspin failed to start, reboot to retry",
282 enabled ? LOG_STR_LITERAL("enable") : LOG_STR_LITERAL("disable"));
283 return;
284 }
285 this->enabled_ = enabled;
286}
287
288// THREAD CONTEXT: Main loop
289std::optional<SendspinHub::PairingToken> SendspinHub::get_pairing_token() const {
290 if (this->client_ == nullptr) {
291 return std::nullopt;
292 }
293 return this->client_->client_pairing_token();
294}
295
296// THREAD CONTEXT: Main loop
298 if (this->client_ == nullptr) {
299 return StringRef();
300 }
301 return StringRef(this->client_->client_id());
302}
303
304// THREAD CONTEXT: Main loop (invoked from codegen before setup(), or from Sendspin components)
305void SendspinHub::set_unpaired_access_enabled(bool enabled) {
306 this->unpaired_access_ = enabled;
307 // Before setup() there is no client yet; setup() applies the stored value.
308 if (this->client_ != nullptr) {
309 this->client_->set_unpaired_access_enabled(enabled);
310 }
311}
312
313#ifdef USE_MDNS_SUPPORTS_ENABLE_DISABLE
314// THREAD CONTEXT: Main loop
316 // Synced from loop() because mdns sets up after this hub and only builds its service list then.
317 if (!this->mdns_->is_ready()) {
318 return;
319 }
320 bool advertise = this->client_->is_started();
321 if (advertise == this->mdns_advertised_) {
322 return;
323 }
324 // One attempt per change
325 this->mdns_advertised_ = advertise;
326 if (!this->mdns_->set_service_enabled("_sendspin", "_tcp", advertise)) {
327 ESP_LOGE(TAG, "Failed to %s mDNS service", advertise ? LOG_STR_LITERAL("enable") : LOG_STR_LITERAL("disable"));
328 }
329}
330#endif
331
332// --- Delegating methods ---
333
334// THREAD CONTEXT: Main loop (invoked from Sendspin components)
335void SendspinHub::connect_to_server(const std::string &url) {
336 if (this->is_client_running()) {
337 this->client_->connect_to(url);
338 }
339}
340
341// THREAD CONTEXT: Main loop (invoked from Sendspin components)
342void SendspinHub::disconnect_from_server(sendspin::SendspinGoodbyeReason reason) {
343 if (this->is_client_running()) {
344 this->client_->disconnect(reason);
345 }
346}
347
348// THREAD CONTEXT: Main loop (invoked from Sendspin components)
350 if (this->is_client_running() &&
351 this->client_->group_state().playback_state == sendspin::SendspinPlaybackState::PLAYING) {
352 this->client_->leave();
353 }
354}
355
356// THREAD CONTEXT: Main loop (invoked from the sendspin.confirm_pairing_window action)
358 if (this->is_client_running()) {
359 this->client_->confirm_pairing_window();
360 }
361}
362
363// THREAD CONTEXT: Main loop (invoked from the sendspin.cancel_pairing_window action)
365 if (this->is_client_running()) {
366 this->client_->cancel_pairing_window();
367 }
368}
369
370const char *SendspinHub::get_mac_address_into_buffer(std::span<char, MAC_ADDRESS_PRETTY_BUFFER_SIZE> buf) {
371 // The server matches this MAC against the L2 source MAC of the device's multicast traffic.
372 // ESP-IDF derives the ethernet MAC as base+3 by default on ESP32-S3, so we cannot use the
373 // eFuse base MAC when ethernet is the active interface.
374#ifdef USE_ETHERNET
375 if (ethernet::global_eth_component != nullptr) {
377 } else {
379 }
380#else
382#endif
383 // The pretty format is uppercase, but SendspinClientConfig::mac_address must be lowercase.
384 for (char &c : buf) {
385 if (c >= 'A' && c <= 'F') {
386 c += 'a' - 'A';
387 }
388 }
389 return buf.data();
390}
391
392// Validation rejects a static code together with the dynamic code, so at most one is set.
395 return LOG_STR_LITERAL("dynamic");
396 }
397 if (this->static_pairing_code_ != nullptr) {
398 return LOG_STR_LITERAL("static");
399 }
400 return LOG_STR_LITERAL("none");
401}
402
404 return this->model_ != nullptr ? this->model_ : App.get_name().c_str();
405}
406
407sendspin::SendspinClientConfig SendspinHub::build_client_config_() {
408 sendspin::SendspinClientConfig config;
409
410 char mac_buf[MAC_ADDRESS_PRETTY_BUFFER_SIZE];
411 config.mac_address = SendspinHub::get_mac_address_into_buffer(mac_buf);
412 config.name = App.get_friendly_name();
413 config.product_name = this->get_product_name_();
414 config.manufacturer = this->manufacturer_;
415 config.software_version = this->firmware_version_;
416 config.httpd_psram_stack = this->task_stack_in_psram_;
417 config.protocol_task_psram_stack = this->task_stack_in_psram_;
418 config.max_pairing_records = SENDSPIN_RECORD_SLOTS;
419
420 // The dynamic code needs a channel and a format. Only digits, since automations get the bare string and could not
421 // tell a QR code token apart.
423 config.pairing_code_out_channels = {sendspin::SendspinPairingCodeChannel::DISPLAY};
424 config.pairing_code_formats = {sendspin::SendspinPairingCodeFormat::DIGITS};
425 }
426
427 if (this->static_pairing_code_ != nullptr) {
428 config.static_pairing_code_locations = {"operator"};
429 config.static_pairing_code = this->static_pairing_code_;
430 }
431
432 return config;
433}
434
435// --- SendspinClientListener overrides ---
436// THREAD CONTEXT: Main loop (fired from client_->loop())
437
438void SendspinHub::on_group_state(const sendspin::GroupState &changes) { this->group_state_callbacks_.call(changes); }
439
448
457
459
461
462// Only digits are offered, and the library refuses an activation in any other format. The automations get copies,
463// since a delayed action outlives the library's view.
464void SendspinHub::on_pairing_code(std::string_view code, // NOLINT
465 sendspin::SendspinPairingCodeFormat /*format*/) {
466 this->display_pairing_code_callbacks_.call(std::string(code));
467}
468
470
471void SendspinHub::on_paired(std::string_view server_id) { // NOLINT
472 this->pairing_succeeded_callbacks_.call(std::string(server_id));
473}
474
475void SendspinHub::on_pairing_aborted(std::string_view server_id, // NOLINT
476 sendspin::SendspinPairAbortReason reason) {
477 this->pairing_failed_callbacks_.call(std::string(server_id), pair_abort_reason_to_string(reason));
478}
479
480// --- SendspinNetworkProvider override ---
481
482// THREAD CONTEXT: Main loop (polled by start() and client_->loop())
484
485// --- SendspinPersistenceProvider overrides ---
486// THREAD CONTEXT: Main loop (the library makes every provider call there, including from start() and stop())
487
488std::pair<ESPPreferenceObject *, size_t> SendspinHub::pref_for_key_(StringRef key) {
489 namespace keys = sendspin::persistence_keys;
490 if (auto slot = parse_record_slot(key); slot.has_value()) {
491 return {&this->record_slot_prefs_[*slot], keys::RECORD_SLOT_SIZE};
492 }
493 if (key == keys::RECORD_ORDER) {
495 }
496 if (key == keys::KEYPAIR) {
497 return {&this->keypair_pref_, keys::KEYPAIR_SIZE};
498 }
499 if (key == keys::PAIRING_PSK) {
500 return {&this->pairing_psk_pref_, keys::PAIRING_PSK_SIZE};
501 }
502 if (key == keys::LAST_PLAYED) {
503 return {&this->last_played_pref_, keys::LAST_PLAYED_SIZE};
504 }
505 if (key == keys::OUTPUT_DELAY) {
506 return {&this->output_delay_pref_, keys::OUTPUT_DELAY_SIZE};
507 }
508 return {nullptr, 0};
509}
510
511std::optional<size_t> SendspinHub::read_blob(std::string_view key_view, std::span<uint8_t> out) { // NOLINT
512 const StringRef key(key_view.data(), key_view.size());
513 auto [pref, size] = this->pref_for_key_(key);
514 if (pref == nullptr) {
515 ESP_LOGW(TAG, "read_blob: unknown key \"%.*s\"", static_cast<int>(key.size()), key.c_str());
516 return std::nullopt;
517 }
518 return load_pref(*pref, size, out);
519}
520
521bool SendspinHub::write_blob(std::string_view key_view, std::span<const uint8_t> data) { // NOLINT
522 const StringRef key(key_view.data(), key_view.size());
523 auto [pref, size] = this->pref_for_key_(key);
524 if (pref == nullptr) {
525 ESP_LOGW(TAG, "write_blob: unknown key \"%.*s\"", static_cast<int>(key.size()), key.c_str());
526 return false;
527 }
528 return save_pref(*pref, key, size, data);
529}
530
531// Writes every component's queued preferences, so a failure may belong to another component.
533
534// --- Sendspin role specific methods/overrides ---
535
536#ifdef USE_SENDSPIN_ARTWORK
537// THREAD CONTEXT: Dedicated artwork decode thread; downstream callbacks run here too
538void SendspinHub::on_image_decode(uint8_t slot, const uint8_t *data, size_t length,
539 sendspin::SendspinImageFormat format) {
540 this->artwork_image_decode_callbacks_.call(slot, data, length, format);
541}
542
543// THREAD CONTEXT: Main loop (fired from client_->loop() once the slot's offset-shifted display
544// deadline is reached; lateness_ms reports how far past the deadline the display slipped)
545void SendspinHub::on_image_display(uint8_t slot, uint32_t lateness_ms) {
546 this->artwork_image_display_callbacks_.call(slot, lateness_ms);
547}
548
549// THREAD CONTEXT: Main loop (fired from client_->loop())
550void SendspinHub::on_image_clear(uint8_t slot) { this->artwork_image_clear_callbacks_.call(slot); }
551
552// THREAD CONTEXT: Main loop (invoked from SendspinImageSlot once a delivery is fully presented)
554 if (this->artwork_role_ != nullptr) {
555 this->artwork_role_->frame_done(slot);
556 }
557}
558#endif
559
560#ifdef USE_SENDSPIN_COLOR
561// THREAD CONTEXT: Main loop (ColorRoleListener override, fired from client_->loop())
562void SendspinHub::on_color(const sendspin::ServerColorStateObject &color) { this->color_callbacks_.call(color); }
563
564// THREAD CONTEXT: Main loop (ColorRoleListener override, fired from client_->loop())
565// Palette dropped (disconnect or role deactivated): fan out an all-nullopt state, as on_metadata_clear() does.
566void SendspinHub::on_color_clear() { this->color_callbacks_.call(sendspin::ServerColorStateObject{}); }
567#endif
568
569#ifdef USE_SENDSPIN_CONTROLLER
570// THREAD CONTEXT: Main loop (invoked from ESPHome actions / other components)
571void SendspinHub::send_client_command(sendspin::SendspinControllerCommand command, std::optional<uint8_t> volume,
572 std::optional<bool> mute) {
573 if (this->is_client_running()) {
574 sendspin::ClientCommandControllerObject obj = {
575 .command = command,
576 .volume = volume,
577 .muted = mute,
578 };
579 this->controller_role_->send_command(obj);
580 }
581}
582
583// THREAD CONTEXT: Main loop (invoked from the sendspin.switch action)
584void SendspinHub::switch_client() { this->send_client_command(sendspin::SendspinControllerCommand::SWITCH); }
585
586// THREAD CONTEXT: Main loop (ControllerRoleListener override, fired from client_->loop())
587void SendspinHub::on_controller_state(const sendspin::ServerStateControllerObject &state) {
588 this->controller_state_callbacks_.call(state);
589}
590
591// THREAD CONTEXT: Main loop (ControllerRoleListener override, fired from client_->loop())
592// Unlike metadata, this cannot be fanned out as a default-constructed state object: volume and muted are plain values
593// rather than optionals, so children would read a real-looking 0% volume where we mean no value at all. A separate
594// callback lets each child clear only what it can represent.
596#endif
597
598#ifdef USE_SENDSPIN_METADATA
599// THREAD CONTEXT: Main loop (MetadataRoleListener override, fired from client_->loop())
600void SendspinHub::on_track_metadata(const sendspin::TrackMetadata &metadata) {
601 this->metadata_update_callbacks_.call(metadata);
602}
603
604// THREAD CONTEXT: Main loop (MetadataRoleListener override, fired from client_->loop())
605// The cached metadata was dropped because the connection to the server was lost, so what the children now mirror is
606// the empty state. Fanning that out as a default-constructed state object rather than through a separate callback
607// keeps one code path in the children: every field is nullopt, which they already publish as empty/unknown.
608void SendspinHub::on_metadata_clear() { this->metadata_update_callbacks_.call(sendspin::TrackMetadata{}); }
609
610// THREAD CONTEXT: Main loop (invoked from Sendspin components)
612 if (this->is_ready()) {
613 return this->metadata_role_->get_track_progress_ms();
614 }
615 return 0;
616}
617#endif
618
619#ifdef USE_SENDSPIN_PLAYER
620// THREAD CONTEXT: Main loop, called from child component setup() after player role is created and configured
621sendspin::PlayerRole *SendspinHub::get_player_role() {
622 if (this->is_ready()) {
623 return this->client_->player();
624 }
625 return nullptr;
626}
627#endif
628
629#ifdef USE_SENDSPIN_SOURCE
630// THREAD CONTEXT: Main loop (invoked from the sendspin.source.set_signal action)
632 if (this->source_role_ == nullptr) {
633 this->source_signal_ = present; // Applied in setup()
634 return;
635 }
636 this->source_role_->set_signal(present ? sendspin::SourceSignal::PRESENT : sendspin::SourceSignal::ABSENT);
637}
638
639// THREAD CONTEXT: Main loop (SourceRoleListener override, fired from client_->loop())
644
645// THREAD CONTEXT: Main loop (SourceRoleListener override, fired from client_->loop())
650#endif
651
652} // namespace esphome::sendspin_
653
654#endif // USE_ESP_IDF
const StringRef & get_name() const
Get the name of this Application set by pre_setup().
const StringRef & get_friendly_name() const
Get the friendly name of this Application set by pre_setup().
bool is_ready() const
bool status_has_error() const
Definition component.h:296
StringRef is a reference to a string owned by something else.
Definition string_ref.h:31
constexpr const char * c_str() const
Definition string_ref.h:78
static constexpr StringRef from_lit(const CharT(&s)[N])
Definition string_ref.h:55
const char * get_eth_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
bool set_service_enabled(const char *service_type, const char *proto, bool enabled)
Enable or disable a compiled-in service, matched by type and proto (e.g.
void add_data_callback(F &&data_callback)
Same callbacks as Microphone::add_data_callback; stream_info is the processed format.
Thin adapter over sendspin::SendspinClient.
ESPPreferenceObject output_delay_pref_
sendspin::SourceRole * source_role_
CallbackManager< void(uint8_t, const uint8_t *, size_t, sendspin::SendspinImageFormat)> artwork_image_decode_callbacks_
CallbackManager< void(uint8_t, uint32_t)> artwork_image_display_callbacks_
sendspin::PlayerRoleListener * player_listener_
CallbackManager< void(const sendspin::ServerColorStateObject &)> color_callbacks_
sendspin::MetadataRoleConfig metadata_config_
const char * get_product_name_() const
Returns the product name reported to the server: the configured model, or the device name.
std::optional< bool > unpaired_access_
void on_controller_state_clear() override
void confirm_pairing_window()
Confirms a pairing attempt on the device.
ESPPreferenceObject record_order_pref_
microphone::MicrophoneSource * microphone_source_
LazyCallbackManager< void(const std::string &, StringRef)> pairing_failed_callbacks_
void on_track_metadata(const sendspin::TrackMetadata &metadata) override
LazyCallbackManager< void(const sendspin::ServerStateControllerObject &)> controller_state_callbacks_
std::optional< PairingToken > get_pairing_token() const
Returns the pairing token a Sendspin server uses to pair with this device.
void on_release_high_performance() override
LazyCallbackManager< void()> clear_pairing_code_callbacks_
void on_pairing_code(std::string_view code, sendspin::SendspinPairingCodeFormat format) override
sendspin::MetadataRole * metadata_role_
bool is_client_running() const
Returns whether the Sendspin client is running.
std::pair< ESPPreferenceObject *, size_t > pref_for_key_(StringRef key)
The preference a library key is stored in and its blob size, or {nullptr, 0} for a key with no storag...
const char * pairing_code_method_() const
LazyCallbackManager< void(const std::string &)> display_pairing_code_callbacks_
void switch_client()
Sends the SWITCH controller command; exposed as the sendspin.switch action.
void leave_group()
Leaves the current group so another source can use the speaker.
sendspin::PlayerRoleConfig player_config_
void cancel_pairing_window()
Closes an open pairing window, so a waiting pairing attempt is not confirmed.
ESPPreferenceObject last_played_pref_
LazyCallbackManager< void(const std::string &)> pairing_succeeded_callbacks_
static const char * get_mac_address_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Writes the active network interface's MAC, in lowercase, into buf and returns its data pointer.
sendspin::PlayerRole * get_player_role()
Child components call this to get the PlayerRole instance after setup, so they can push updates to it...
void on_image_clear(uint8_t slot) override
void on_paired(std::string_view server_id) override
void disconnect_from_server(sendspin::SendspinGoodbyeReason reason)
Disconnects the underlying client from the current server.
CallbackManager< void(const sendspin::GroupState &)> group_state_callbacks_
std::unique_ptr< sendspin::SendspinClient > client_
sendspin::ArtworkRoleConfig artwork_config_
void update_mdns_service_()
Keeps the _sendspin mDNS service advertised while the client is running.
LazyCallbackManager< void()> source_streaming_started_callbacks_
sendspin::VisualizerRoleListener * visualizer_listener_
LazyCallbackManager< void()> source_streaming_stopped_callbacks_
sendspin::SendspinClientConfig build_client_config_()
Builds the SendspinClientConfig from ESPHome configuration and platform info.
mdns::MDNSComponent * mdns_
sendspin::ControllerRole * controller_role_
void on_pairing_aborted(std::string_view server_id, sendspin::SendspinPairAbortReason reason) override
void on_group_state(const sendspin::GroupState &changes) override
uint32_t get_track_progress_ms() const
Returns the interpolated track progress in milliseconds, or 0 if the hub is not yet ready.
const sendspin::VisualizerRoleConfig * visualizer_config_
std::optional< size_t > read_blob(std::string_view key_view, std::span< uint8_t > out) override
std::optional< bool > enabled_
StringRef get_client_id() const
Returns the Sendspin client_id: base64url of the client's static public key.
void send_client_command(sendspin::SendspinControllerCommand command, std::optional< uint8_t > volume=std::nullopt, std::optional< bool > mute=std::nullopt)
LazyCallbackManager< void()> controller_state_clear_callbacks_
sendspin::SourceRoleConfig source_config_
CallbackManager< void(uint8_t)> artwork_image_clear_callbacks_
ESPPreferenceObject keypair_pref_
CallbackManager< void(const sendspin::TrackMetadata &)> metadata_update_callbacks_
LazyCallbackManager< void()> open_pairing_window_callbacks_
sendspin::ArtworkRole * artwork_role_
void on_request_high_performance() override
bool write_blob(std::string_view key_view, std::span< const uint8_t > data) override
void set_enabled(bool enabled)
Requests the Sendspin client, including the server, the roles and the mDNS advertisement,...
std::array< ESPPreferenceObject, SENDSPIN_RECORD_SLOTS > record_slot_prefs_
void on_image_display(uint8_t slot, uint32_t lateness_ms) override
void on_image_decode(uint8_t slot, const uint8_t *data, size_t length, sendspin::SendspinImageFormat format) override
ESPPreferenceObject pairing_psk_pref_
void on_controller_state(const sendspin::ServerStateControllerObject &state) override
LazyCallbackManager< void()> close_pairing_window_callbacks_
void connect_to_server(const std::string &url)
Connects the underlying client to the given Sendspin server.
void on_color(const sendspin::ServerColorStateObject &color) override
void set_source_signal(bool present)
Reports whether the source has audio to offer; exposed as the sendspin.source.set_signal action.
void artwork_frame_done(uint8_t slot)
Acknowledges the most recent artwork delivery (display or clear) for a slot.
bool request_high_performance()
Request high-performance mode (no power saving) for improved WiFi latency.
void release_roaming_suppression()
Same as set_roaming_suppressed(false); must be paired with a prior request.
void request_roaming_suppression()
Same as set_roaming_suppressed(true).
bool release_high_performance()
Release a high-performance mode request.
const char * key
bool state
Definition fan.h:2
std::vector< uint8_t > & out
Definition gif.cpp:49
EthernetComponent * global_eth_component
std::span< const uint8_t > data
ESPHOME_ALWAYS_INLINE bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition util.h:36
constexpr size_t SENDSPIN_RECORD_SLOTS
Pairing-record slots, handed to the client as max_pairing_records.
SendspinHub * global_sendspin_hub
ESPHOME_LOG_TAG(TAG, "sendspin.image")
WiFiComponent * global_wifi_component
const void size_t len
Definition hal.h:68
uint16_t size
Definition helpers.cpp:44
ESPPreferences * global_preferences
const char * get_mac_address_pretty_into_buffer(std::span< char, MAC_ADDRESS_PRETTY_BUFFER_SIZE > buf)
Get the device MAC address into the given buffer, in colon-separated uppercase hex notation.
Definition helpers.cpp:876
void const char int const char * format
Definition log.h:110
Application App
Global storage of Application pointer - only one Application can exist.
constexpr uint32_t fnv1a_hash(const char *str)
Calculate a FNV-1a hash of str.
Definition helpers.h:1192
static void uint32_t
ESPPreferenceObject make_preference(size_t, uint32_t, bool)
Definition preferences.h:24
bool sync()
Commit pending writes to flash.
Definition preferences.h:33
int64_t capture_time_us
esp_timer_get_time() of the first frame, or 0 if unknown
Definition microphone.h:29
std::span< const uint8_t > data
Only valid during the callback.
Definition microphone.h:25
uint16_t length
Definition tt21100.cpp:0