ESPHome 2026.10.2
Loading...
Searching...
No Matches
homeassistant_switch.cpp
Go to the documentation of this file.
3#include "esphome/core/log.h"
5
7
8static const char *const TAG = "homeassistant.switch";
9
10using namespace esphome::switch_;
11
14 auto val = parse_on_off(state.c_str());
15 switch (val) {
16 case PARSE_NONE:
17 case PARSE_TOGGLE:
18 ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
19 break;
20 case PARSE_ON:
21 case PARSE_OFF:
22 bool new_state = val == PARSE_ON;
23 ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
24 this->publish_state(new_state);
25 break;
26 }
27 });
28}
29
31 LOG_SWITCH("", "Homeassistant Switch", this);
32 ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
33}
34
36
38 if (!api::global_api_server->is_connected()) {
39 ESP_LOGE(TAG, "No clients connected to API server");
40 return;
41 }
42
43#ifdef USE_API_WIZARD_LINKED_INPUTS
44 if (this->entity_id_[0] == '\0') {
45 ESP_LOGW(TAG, "'%s': No entity ID set yet", this->get_name().c_str());
46 return;
47 }
48#endif
49
50 static constexpr auto SERVICE_ON = StringRef::from_lit("homeassistant.turn_on");
51 static constexpr auto SERVICE_OFF = StringRef::from_lit("homeassistant.turn_off");
52 static constexpr auto ENTITY_ID_KEY = StringRef::from_lit("entity_id");
53
55 if (state) {
56 resp.service = SERVICE_ON;
57 } else {
58 resp.service = SERVICE_OFF;
59 }
60
61 resp.data.init(1);
62 auto &entity_id_kv = resp.data.emplace_back();
63 entity_id_kv.key = ENTITY_ID_KEY;
64 entity_id_kv.value = StringRef(this->entity_id_);
65
67}
68
69} // namespace esphome::homeassistant
const StringRef & get_name() const
Definition entity_base.h:71
StringRef is a reference to a string owned by something else.
Definition string_ref.h:30
static constexpr StringRef from_lit(const CharT(&s)[N])
Definition string_ref.h:54
void send_homeassistant_action(const HomeassistantActionRequest &call)
void subscribe_home_assistant_state(const char *entity_id, const char *attribute, std::function< void(StringRef)> &&f)
FixedVector< HomeassistantServiceMap > data
Definition api_pb2.h:1414
bool state
The current reported state of the binary sensor.
Definition switch.h:55
void publish_state(bool state)
Publish a state to the front-end from the back-end.
Definition switch.cpp:56
bool state
Definition fan.h:2
mopeka_std_values val[3]
APIServer * global_api_server
constexpr float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
Definition component.h:57
ParseOnOffState parse_on_off(const char *str, const char *on, const char *off)
Parse a string that contains either on, off or toggle.
Definition helpers.cpp:493
@ PARSE_ON
Definition helpers.h:1699
@ PARSE_TOGGLE
Definition helpers.h:1701
@ PARSE_OFF
Definition helpers.h:1700
@ PARSE_NONE
Definition helpers.h:1698