ESPHome 2026.2.4
Loading...
Searching...
No Matches
homeassistant_service.h
Go to the documentation of this file.
1#pragma once
2
3#include "api_server.h"
4#ifdef USE_API
5#ifdef USE_API_HOMEASSISTANT_SERVICES
6#include <functional>
7#include <utility>
8#include <vector>
9#include "api_pb2.h"
10#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
12#endif
16
17namespace esphome::api {
18
19template<typename... X> class TemplatableStringValue : public TemplatableValue<std::string, X...> {
20 // Verify that const char* uses the base class STATIC_STRING optimization (no heap allocation)
21 // rather than being wrapped in a lambda. The base class constructor for const char* is more
22 // specialized than the templated constructor here, so it should be selected.
23 static_assert(std::is_constructible_v<TemplatableValue<std::string, X...>, const char *>,
24 "Base class must have const char* constructor for STATIC_STRING optimization");
25
26 private:
27 // Helper to convert value to string - handles the case where value is already a string
28 template<typename T> static std::string value_to_string(T &&val) {
29 return to_string(std::forward<T>(val)); // NOLINT
30 }
31
32 // Overloads for string types - needed because std::to_string doesn't support them
33 static std::string value_to_string(char *val) {
34 return val ? std::string(val) : std::string();
35 } // For lambdas returning char* (e.g., itoa)
36 static std::string value_to_string(const char *val) { return std::string(val); } // For lambdas returning .c_str()
37 static std::string value_to_string(const std::string &val) { return val; }
38 static std::string value_to_string(std::string &&val) { return std::move(val); }
39 static std::string value_to_string(const StringRef &val) { return val.str(); }
40 static std::string value_to_string(StringRef &&val) { return val.str(); }
41
42 public:
43 TemplatableStringValue() : TemplatableValue<std::string, X...>() {}
44
45 template<typename F, enable_if_t<!is_invocable<F, X...>::value, int> = 0>
47
48 template<typename F, enable_if_t<is_invocable<F, X...>::value, int> = 0>
50 : TemplatableValue<std::string, X...>([f](X... x) -> std::string { return value_to_string(f(x...)); }) {}
51};
52
53template<typename... Ts> class TemplatableKeyValuePair {
54 public:
55 // Default constructor needed for FixedVector::emplace_back()
57
58 // Keys are always string literals from YAML dictionary keys (e.g., "code", "event")
59 // and never templatable values or lambdas. Only the value parameter can be a lambda/template.
60 // Using const char* avoids std::string heap allocation - keys remain in flash.
61 template<typename T> TemplatableKeyValuePair(const char *key, T value) : key(key), value(value) {}
62
63 const char *key{nullptr};
65};
66
67#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
68// Represents the response data from a Home Assistant action
69// Note: This class holds a StringRef to the error_message from the protobuf message.
70// The protobuf message must outlive the ActionResponse (which is guaranteed since
71// the callback is invoked synchronously while the message is on the stack).
73 public:
74 ActionResponse(bool success, StringRef error_message) : success_(success), error_message_(error_message) {}
75
76#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
77 ActionResponse(bool success, StringRef error_message, const uint8_t *data, size_t data_len)
78 : success_(success), error_message_(error_message) {
79 if (data == nullptr || data_len == 0)
80 return;
81 this->json_document_ = json::parse_json(data, data_len);
82 }
83#endif
84
85 bool is_success() const { return this->success_; }
86 // Returns reference to error message - can be implicitly converted to std::string if needed
87 const StringRef &get_error_message() const { return this->error_message_; }
88
89#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
90 // Get data as parsed JSON object (const version returns read-only view)
91 JsonObjectConst get_json() const { return this->json_document_.as<JsonObjectConst>(); }
92#endif
93
94 protected:
97#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
98 JsonDocument json_document_;
99#endif
100};
101
102// Callback type for action responses
103template<typename... Ts> using ActionResponseCallback = std::function<void(const ActionResponse &, Ts...)>;
104#endif
105
106template<typename... Ts> class HomeAssistantServiceCallAction : public Action<Ts...> {
107 public:
108 explicit HomeAssistantServiceCallAction(APIServer *parent, bool is_event) : parent_(parent) {
109 this->flags_.is_event = is_event;
110 }
111
112 template<typename T> void set_service(T service) { this->service_ = service; }
113
114 // Initialize FixedVector members - called from Python codegen with compile-time known sizes.
115 // Must be called before any add_* methods; capacity must match the number of subsequent add_* calls.
116 void init_data(size_t count) { this->data_.init(count); }
117 void init_data_template(size_t count) { this->data_template_.init(count); }
118 void init_variables(size_t count) { this->variables_.init(count); }
119
120 // Keys are always string literals from the Python code generation (e.g., cg.add(var.add_data("tag_id", templ))).
121 // The value parameter can be a lambda/template, but keys are never templatable.
122 // Using const char* for keys avoids std::string heap allocation - keys remain in flash.
123 template<typename V> void add_data(const char *key, V &&value) {
124 this->add_kv_(this->data_, key, std::forward<V>(value));
125 }
126 template<typename V> void add_data_template(const char *key, V &&value) {
127 this->add_kv_(this->data_template_, key, std::forward<V>(value));
128 }
129 template<typename V> void add_variable(const char *key, V &&value) {
130 this->add_kv_(this->variables_, key, std::forward<V>(value));
131 }
132
133#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
134 template<typename T> void set_response_template(T response_template) {
135 this->response_template_ = response_template;
136 this->flags_.has_response_template = true;
137 }
138
139 void set_wants_status() { this->flags_.wants_status = true; }
140 void set_wants_response() { this->flags_.wants_response = true; }
141
142#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
143 Trigger<JsonObjectConst, Ts...> *get_success_trigger_with_response() { return &this->success_trigger_with_response_; }
144#endif
145 Trigger<Ts...> *get_success_trigger() { return &this->success_trigger_; }
146 Trigger<std::string, Ts...> *get_error_trigger() { return &this->error_trigger_; }
147#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
148
149 void play(const Ts &...x) override {
151 std::string service_value = this->service_.value(x...);
152 resp.service = StringRef(service_value);
153 resp.is_event = this->flags_.is_event;
154
155 // Local storage for lambda-evaluated strings - lives until after send
156 FixedVector<std::string> data_storage;
157 FixedVector<std::string> data_template_storage;
158 FixedVector<std::string> variables_storage;
159
160 this->populate_service_map(resp.data, this->data_, data_storage, x...);
161 this->populate_service_map(resp.data_template, this->data_template_, data_template_storage, x...);
162 this->populate_service_map(resp.variables, this->variables_, variables_storage, x...);
163
164#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
165#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
166 // IMPORTANT: Declare at outer scope so it lives until send_homeassistant_action returns.
167 std::string response_template_value;
168#endif
169 if (this->flags_.wants_status) {
170 // Generate a unique call ID for this service call
171 static uint32_t call_id_counter = 1;
172 uint32_t call_id = call_id_counter++;
173 resp.call_id = call_id;
174#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
175 if (this->flags_.wants_response) {
176 resp.wants_response = true;
177 // Set response template if provided
178 if (this->flags_.has_response_template) {
179 response_template_value = this->response_template_.value(x...);
180 resp.response_template = StringRef(response_template_value);
181 }
182 }
183#endif
184
185 auto captured_args = std::make_tuple(x...);
186 this->parent_->register_action_response_callback(call_id, [this, captured_args](const ActionResponse &response) {
187 std::apply(
188 [this, &response](auto &&...args) {
189 if (response.is_success()) {
190#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
191 if (this->flags_.wants_response) {
192 this->success_trigger_with_response_.trigger(response.get_json(), args...);
193 } else
194#endif
195 {
196 this->success_trigger_.trigger(args...);
197 }
198 } else {
199 this->error_trigger_.trigger(response.get_error_message(), args...);
200 }
201 },
202 captured_args);
203 });
204 }
205#endif
206
207 this->parent_->send_homeassistant_action(resp);
208 }
209
210 protected:
211 // Helper to add key-value pairs to FixedVectors
212 // Keys are always string literals (const char*), values can be lambdas/templates
213 template<typename V> void add_kv_(FixedVector<TemplatableKeyValuePair<Ts...>> &vec, const char *key, V &&value) {
214 auto &kv = vec.emplace_back();
215 kv.key = key;
216 kv.value = std::forward<V>(value);
217 }
218
219 template<typename VectorType, typename SourceType>
220 static void populate_service_map(VectorType &dest, SourceType &source, FixedVector<std::string> &value_storage,
221 Ts... x) {
222 dest.init(source.size());
223
224 // Count non-static strings to allocate exact storage needed
225 size_t lambda_count = 0;
226 for (const auto &it : source) {
227 if (!it.value.is_static_string()) {
228 lambda_count++;
229 }
230 }
231 value_storage.init(lambda_count);
232
233 for (auto &it : source) {
234 auto &kv = dest.emplace_back();
235 kv.key = StringRef(it.key);
236
237 if (it.value.is_static_string()) {
238 // Static string from YAML - zero allocation
239 kv.value = StringRef(it.value.get_static_string());
240 } else {
241 // Lambda evaluation - store result, reference it
242 value_storage.push_back(it.value.value(x...));
243 kv.value = StringRef(value_storage.back());
244 }
245 }
246 }
247
249 TemplatableStringValue<Ts...> service_{};
253#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
254#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
255 TemplatableStringValue<Ts...> response_template_{""};
257#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
259 Trigger<std::string, Ts...> error_trigger_;
260#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
261
262 struct Flags {
263 uint8_t is_event : 1;
264 uint8_t wants_status : 1;
265 uint8_t wants_response : 1;
267 uint8_t reserved : 5;
268 } flags_{0};
269};
270
271} // namespace esphome::api
272
273#endif
274#endif
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:227
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:381
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:344
void init(size_t n)
Definition helpers.h:317
StringRef is a reference to a string owned by something else.
Definition string_ref.h:26
ActionResponse(bool success, StringRef error_message)
const StringRef & get_error_message() const
JsonObjectConst get_json() const
ActionResponse(bool success, StringRef error_message, const uint8_t *data, size_t data_len)
Trigger< JsonObjectConst, Ts... > success_trigger_with_response_
HomeAssistantServiceCallAction(APIServer *parent, bool is_event)
FixedVector< TemplatableKeyValuePair< Ts... > > data_
Trigger< std::string, Ts... > * get_error_trigger()
void add_kv_(FixedVector< TemplatableKeyValuePair< Ts... > > &vec, const char *key, V &&value)
FixedVector< TemplatableKeyValuePair< Ts... > > variables_
Trigger< JsonObjectConst, Ts... > * get_success_trigger_with_response()
FixedVector< TemplatableKeyValuePair< Ts... > > data_template_
void add_data_template(const char *key, V &&value)
static void populate_service_map(VectorType &dest, SourceType &source, FixedVector< std::string > &value_storage, Ts... x)
FixedVector< HomeassistantServiceMap > variables
Definition api_pb2.h:1025
FixedVector< HomeassistantServiceMap > data
Definition api_pb2.h:1023
FixedVector< HomeassistantServiceMap > data_template
Definition api_pb2.h:1024
TemplatableStringValue< Ts... > value
TemplatableKeyValuePair(const char *key, T value)
mopeka_std_values val[4]
std::function< void(const ActionResponse &, Ts...)> ActionResponseCallback
uint16_t x
Definition tt21100.cpp:5