ESPHome 2025.9.0-dev
Loading...
Searching...
No Matches
homeassistant_switch.cpp
Go to the documentation of this file.
3#include "esphome/core/log.h"
4
5namespace esphome {
6namespace homeassistant {
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_.c_str(), 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_.c_str());
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 static constexpr auto SERVICE_ON = StringRef::from_lit("homeassistant.turn_on");
44 static constexpr auto SERVICE_OFF = StringRef::from_lit("homeassistant.turn_off");
45 static constexpr auto ENTITY_ID_KEY = StringRef::from_lit("entity_id");
46
48 if (state) {
49 resp.set_service(SERVICE_ON);
50 } else {
51 resp.set_service(SERVICE_OFF);
52 }
53
54 resp.data.emplace_back();
55 auto &entity_id_kv = resp.data.back();
56 entity_id_kv.set_key(ENTITY_ID_KEY);
57 entity_id_kv.value = this->entity_id_;
58
60}
61
62} // namespace homeassistant
63} // namespace esphome
static constexpr StringRef from_lit(const CharT(&s)[N])
Definition string_ref.h:46
void send_homeassistant_service_call(const HomeassistantServiceResponse &call)
void subscribe_home_assistant_state(std::string entity_id, optional< std::string > attribute, std::function< void(std::string)> f)
void set_service(const StringRef &ref)
Definition api_pb2.h:1095
std::vector< HomeassistantServiceMap > data
Definition api_pb2.h:1096
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:55
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:58
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:324
@ PARSE_ON
Definition helpers.h:553
@ PARSE_TOGGLE
Definition helpers.h:555
@ PARSE_OFF
Definition helpers.h:554
@ PARSE_NONE
Definition helpers.h:552
const nullopt_t nullopt((nullopt_t::init()))