ESPHome 2026.8.0b4
Loading...
Searching...
No Matches
sendspin_text_sensor.cpp
Go to the documentation of this file.
2
3#if defined(USE_ESP32) && defined(USE_SENDSPIN_METADATA) && defined(USE_TEXT_SENSOR)
4
5#include <sendspin/metadata_role.h>
6
7#include <string>
8
9namespace esphome::sendspin_ {
10
11static const char *const TAG = "sendspin.text_sensor";
12
13void SendspinTextSensor::dump_config() { LOG_TEXT_SENSOR("", "Sendspin", this); }
14
15// A field is nullopt when the server has not provided it or has explicitly cleared it. Both mean there is nothing to
16// show, so return the empty string and let the caller publish it; returning early would leave the previous track's
17// value on display.
18//
19// The empty string is not the same as unknown. A text sensor reports unknown through the API's missing_state flag,
20// which follows has_state(), and has_state() is only ever set, never cleared. Once a real value has been published,
21// an empty state is the closest we can get. The numeric sensors publish NAN, which does read as unknown.
22const char *SendspinTextSensor::extract_value_(const sendspin::ServerMetadataStateObject &metadata) const {
23 switch (this->metadata_type_) {
25 return metadata.title.has_value() ? metadata.title.value().c_str() : "";
27 return metadata.artist.has_value() ? metadata.artist.value().c_str() : "";
29 return metadata.album.has_value() ? metadata.album.value().c_str() : "";
31 return metadata.album_artist.has_value() ? metadata.album_artist.value().c_str() : "";
32 }
33 return "";
34}
35
36// THREAD CONTEXT: Main loop. The registered metadata callback also fires on the main loop
37// (SendspinHub dispatches metadata from client_->loop()).
39 this->parent_->add_metadata_update_callback([this](const sendspin::ServerMetadataStateObject &metadata) {
40 this->publish_if_changed_(this->extract_value_(metadata));
41 });
42}
43
44// Dedup to avoid frontend churn; TextSensor::publish_state already dedups the string assign but still notifies.
46 // The state starts empty, so a field that is already cleared when the first update arrives is suppressed here: the
47 // entity stays unknown rather than being dropped out of it for good by an empty publish. Later clears do publish the
48 // empty string and fire on_value with it.
49 if (this->get_raw_state() != value) {
50 this->publish_state(value);
51 }
52}
53
54} // namespace esphome::sendspin_
55
56#endif
const char * extract_value_(const sendspin::ServerMetadataStateObject &metadata) const
const std::string & get_raw_state() const
Returns the raw (pre-filter) state.
void publish_state(const std::string &state)