ESPHome 2026.1.5
Loading...
Searching...
No Matches
homeassistant_switch.cpp
Go to the documentation of this file.
3#include "esphome/core/log.h"
5
6namespace esphome {
7namespace homeassistant {
8
9static const char *const TAG = "homeassistant.switch";
10
11using namespace esphome::switch_;
12
15 auto val = parse_on_off(state.c_str());
16 switch (val) {
17 case PARSE_NONE:
18 case PARSE_TOGGLE:
19 ESP_LOGW(TAG, "Can't convert '%s' to binary state!", state.c_str());
20 break;
21 case PARSE_ON:
22 case PARSE_OFF:
23 bool new_state = val == PARSE_ON;
24 ESP_LOGD(TAG, "'%s': Got state %s", this->entity_id_, ONOFF(new_state));
25 this->publish_state(new_state);
26 break;
27 }
28 });
29}
30
32 LOG_SWITCH("", "Homeassistant Switch", this);
33 ESP_LOGCONFIG(TAG, " Entity ID: '%s'", this->entity_id_);
34}
35
37
39 if (!api::global_api_server->is_connected()) {
40 ESP_LOGE(TAG, "No clients connected to API server");
41 return;
42 }
43
44 static constexpr auto SERVICE_ON = StringRef::from_lit("homeassistant.turn_on");
45 static constexpr auto SERVICE_OFF = StringRef::from_lit("homeassistant.turn_off");
46 static constexpr auto ENTITY_ID_KEY = StringRef::from_lit("entity_id");
47
49 if (state) {
50 resp.service = SERVICE_ON;
51 } else {
52 resp.service = SERVICE_OFF;
53 }
54
55 resp.data.init(1);
56 auto &entity_id_kv = resp.data.emplace_back();
57 entity_id_kv.key = ENTITY_ID_KEY;
58 entity_id_kv.value = StringRef(this->entity_id_);
59
61}
62
63} // namespace homeassistant
64} // namespace esphome
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
static constexpr StringRef from_lit(const CharT(&s)[N])
Definition string_ref.h:50
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:1073
bool state
The current reported state of the binary sensor.
Definition switch.h:56
void publish_state(bool state)
Publish a state to the front-end from the back-end.
Definition switch.cpp:57
bool state
Definition fan.h:0
mopeka_std_values val[4]
APIServer * global_api_server
const float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
Definition component.cpp:89
Providing packet encoding functions for exchanging data with a remote host.
Definition a01nyub.cpp:7
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:419
@ PARSE_ON
Definition helpers.h:1088
@ PARSE_TOGGLE
Definition helpers.h:1090
@ PARSE_OFF
Definition helpers.h:1089
@ PARSE_NONE
Definition helpers.h:1087