#pragma once #include "api_server.h" #ifdef USE_API #include "api_pb2.h" #include "esphome/core/automation.h" #include "esphome/core/helpers.h" #include namespace esphome { namespace api { template class TemplatableStringValue : public TemplatableValue { public: TemplatableStringValue() : TemplatableValue() {} template::value, int> = 0> TemplatableStringValue(F value) : TemplatableValue(value) {} template::value, int> = 0> TemplatableStringValue(F f) : TemplatableValue([f](X... x) -> std::string { return to_string(f(x...)); }) {} }; template class TemplatableKeyValuePair { public: template TemplatableKeyValuePair(std::string key, T value) : key(std::move(key)), value(value) {} std::string key; TemplatableStringValue value; }; template class HomeAssistantServiceCallAction : public Action { public: explicit HomeAssistantServiceCallAction(APIServer *parent, bool is_event) : parent_(parent), is_event_(is_event) {} template void set_service(T service) { this->service_ = service; } template void add_data(std::string key, T value) { this->data_.push_back(TemplatableKeyValuePair(key, value)); } template void add_data_template(std::string key, T value) { this->data_template_.push_back(TemplatableKeyValuePair(key, value)); } template void add_variable(std::string key, T value) { this->variables_.push_back(TemplatableKeyValuePair(key, value)); } void play(Ts... x) override { HomeassistantServiceResponse resp; resp.service = this->service_.value(x...); resp.is_event = this->is_event_; for (auto &it : this->data_) { HomeassistantServiceMap kv; kv.key = it.key; kv.value = it.value.value(x...); resp.data.push_back(kv); } for (auto &it : this->data_template_) { HomeassistantServiceMap kv; kv.key = it.key; kv.value = it.value.value(x...); resp.data_template.push_back(kv); } for (auto &it : this->variables_) { HomeassistantServiceMap kv; kv.key = it.key; kv.value = it.value.value(x...); resp.variables.push_back(kv); } this->parent_->send_homeassistant_service_call(resp); } protected: APIServer *parent_; bool is_event_; TemplatableStringValue service_{}; std::vector> data_; std::vector> data_template_; std::vector> variables_; }; } // namespace api } // namespace esphome #endif