ESPHome  2024.11.3
homeassistant_switch.cpp
Go to the documentation of this file.
1 #include "homeassistant_switch.h"
3 #include "esphome/core/log.h"
4 
5 namespace esphome {
6 namespace homeassistant {
7 
8 static const char *const TAG = "homeassistant.switch";
9 
10 using namespace esphome::switch_;
11 
13  api::global_api_server->subscribe_home_assistant_state(this->entity_id_, nullopt, [this](const std::string &state) {
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 
39  ESP_LOGE(TAG, "No clients connected to API server");
40  return;
41  }
42 
44  if (state) {
45  resp.service = "homeassistant.turn_on";
46  } else {
47  resp.service = "homeassistant.turn_off";
48  }
49 
50  api::HomeassistantServiceMap entity_id_kv;
51  entity_id_kv.key = "entity_id";
52  entity_id_kv.value = this->entity_id_;
53  resp.data.push_back(entity_id_kv);
54 
56 }
57 
58 } // namespace homeassistant
59 } // namespace esphome
const float AFTER_CONNECTION
For components that should be initialized after a data connection (API/MQTT) is connected.
Definition: component.cpp:27
void send_homeassistant_service_call(const HomeassistantServiceResponse &call)
Definition: api_server.cpp:350
mopeka_std_values val[4]
bool is_connected()
Return whether the node is connected to the network (through wifi, eth, ...)
Definition: util.cpp:15
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:412
const nullopt_t nullopt((nullopt_t::init()))
Implementation of SPI Controller mode.
Definition: a01nyub.cpp:7
void subscribe_home_assistant_state(std::string entity_id, optional< std::string > attribute, std::function< void(std::string)> f)
Definition: api_server.cpp:357
std::vector< HomeassistantServiceMap > data
Definition: api_pb2.h:817
APIServer * global_api_server
Definition: api_server.cpp:347
bool state
Definition: fan.h:34