ESPHome 2026.3.0-dev
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_ESP8266
134 // On ESP8266, ESPHOME_F() returns __FlashStringHelper* (PROGMEM pointer).
135 // Store as const char* — populate_service_map copies from PROGMEM at play() time.
136 template<typename V> void add_data(const __FlashStringHelper *key, V &&value) {
137 this->add_kv_(this->data_, reinterpret_cast<const char *>(key), std::forward<V>(value));
138 }
139 template<typename V> void add_data_template(const __FlashStringHelper *key, V &&value) {
140 this->add_kv_(this->data_template_, reinterpret_cast<const char *>(key), std::forward<V>(value));
141 }
142 template<typename V> void add_variable(const __FlashStringHelper *key, V &&value) {
143 this->add_kv_(this->variables_, reinterpret_cast<const char *>(key), std::forward<V>(value));
144 }
145#endif
146
147#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
148 template<typename T> void set_response_template(T response_template) {
149 this->response_template_ = response_template;
150 this->flags_.has_response_template = true;
151 }
152
153 void set_wants_status() { this->flags_.wants_status = true; }
154 void set_wants_response() { this->flags_.wants_response = true; }
155
156#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
157 Trigger<JsonObjectConst, Ts...> *get_success_trigger_with_response() { return &this->success_trigger_with_response_; }
158#endif
159 Trigger<Ts...> *get_success_trigger() { return &this->success_trigger_; }
160 Trigger<std::string, Ts...> *get_error_trigger() { return &this->error_trigger_; }
161#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
162
163 void play(const Ts &...x) override {
165 std::string service_value = this->service_.value(x...);
166 resp.service = StringRef(service_value);
167 resp.is_event = this->flags_.is_event;
168
169 // Local storage for lambda-evaluated strings - lives until after send
170 FixedVector<std::string> data_storage;
171 FixedVector<std::string> data_template_storage;
172 FixedVector<std::string> variables_storage;
173
174 this->populate_service_map(resp.data, this->data_, data_storage, x...);
175 this->populate_service_map(resp.data_template, this->data_template_, data_template_storage, x...);
176 this->populate_service_map(resp.variables, this->variables_, variables_storage, x...);
177
178#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
179#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
180 // IMPORTANT: Declare at outer scope so it lives until send_homeassistant_action returns.
181 std::string response_template_value;
182#endif
183 if (this->flags_.wants_status) {
184 // Generate a unique call ID for this service call
185 static uint32_t call_id_counter = 1;
186 uint32_t call_id = call_id_counter++;
187 resp.call_id = call_id;
188#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
189 if (this->flags_.wants_response) {
190 resp.wants_response = true;
191 // Set response template if provided
192 if (this->flags_.has_response_template) {
193 response_template_value = this->response_template_.value(x...);
194 resp.response_template = StringRef(response_template_value);
195 }
196 }
197#endif
198
199 auto captured_args = std::make_tuple(x...);
200 this->parent_->register_action_response_callback(call_id, [this, captured_args](const ActionResponse &response) {
201 std::apply(
202 [this, &response](auto &&...args) {
203 if (response.is_success()) {
204#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
205 if (this->flags_.wants_response) {
206 this->success_trigger_with_response_.trigger(response.get_json(), args...);
207 } else
208#endif
209 {
210 this->success_trigger_.trigger(args...);
211 }
212 } else {
213 this->error_trigger_.trigger(response.get_error_message(), args...);
214 }
215 },
216 captured_args);
217 });
218 }
219#endif
220
221 this->parent_->send_homeassistant_action(resp);
222 }
223
224 protected:
225 // Helper to add key-value pairs to FixedVectors
226 // Keys are always string literals (const char*), values can be lambdas/templates
227 template<typename V> void add_kv_(FixedVector<TemplatableKeyValuePair<Ts...>> &vec, const char *key, V &&value) {
228 auto &kv = vec.emplace_back();
229 kv.key = key;
230 kv.value = std::forward<V>(value);
231 }
232
233 template<typename VectorType, typename SourceType>
234 static void populate_service_map(VectorType &dest, SourceType &source, FixedVector<std::string> &value_storage,
235 Ts... x) {
236 dest.init(source.size());
237
238#ifdef USE_ESP8266
239 // On ESP8266, all static strings from codegen are FLASH_STRING (PROGMEM),
240 // so is_static_string() is always false — the zero-copy STATIC_STRING fast
241 // path from the non-ESP8266 branch cannot trigger. We copy all keys and
242 // values unconditionally: keys via _P functions (may be in PROGMEM), values
243 // via value() which handles FLASH_STRING internally.
244 value_storage.init(source.size() * 2);
245
246 for (auto &it : source) {
247 auto &kv = dest.emplace_back();
248
249 // Key: copy from possible PROGMEM
250 {
251 size_t key_len = strlen_P(it.key);
252 value_storage.push_back(std::string(key_len, '\0'));
253 memcpy_P(value_storage.back().data(), it.key, key_len);
254 kv.key = StringRef(value_storage.back());
255 }
256
257 // Value: value() handles FLASH_STRING via _P functions internally
258 value_storage.push_back(it.value.value(x...));
259 kv.value = StringRef(value_storage.back());
260 }
261#else
262 // On non-ESP8266, strings are directly readable from flash-mapped memory.
263 // Count non-static strings to allocate exact storage needed.
264 size_t lambda_count = 0;
265 for (const auto &it : source) {
266 if (!it.value.is_static_string()) {
267 lambda_count++;
268 }
269 }
270 value_storage.init(lambda_count);
271
272 for (auto &it : source) {
273 auto &kv = dest.emplace_back();
274 kv.key = StringRef(it.key);
275
276 if (it.value.is_static_string()) {
277 // Static string — pointer directly readable, zero allocation
278 kv.value = StringRef(it.value.get_static_string());
279 } else {
280 // Lambda — evaluate and store result
281 value_storage.push_back(it.value.value(x...));
282 kv.value = StringRef(value_storage.back());
283 }
284 }
285#endif
286 }
287
289 TemplatableStringValue<Ts...> service_{};
293#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES
294#ifdef USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
295 TemplatableStringValue<Ts...> response_template_{""};
297#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES_JSON
299 Trigger<std::string, Ts...> error_trigger_;
300#endif // USE_API_HOMEASSISTANT_ACTION_RESPONSES
301
302 struct Flags {
303 uint8_t is_event : 1;
304 uint8_t wants_status : 1;
305 uint8_t wants_response : 1;
307 uint8_t reserved : 5;
308 } flags_{0};
309};
310
311} // namespace esphome::api
312
313#endif
314#endif
Fixed-capacity vector - allocates once at runtime, never reallocates This avoids std::vector template...
Definition helpers.h:299
T & back()
Access last element (no bounds checking - matches std::vector behavior) Caller must ensure vector is ...
Definition helpers.h:453
void push_back(const T &value)
Add element without bounds checking Caller must ensure sufficient capacity was allocated via init() S...
Definition helpers.h:416
void init(size_t n)
Definition helpers.h:389
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_
void add_variable(const __FlashStringHelper *key, V &&value)
HomeAssistantServiceCallAction(APIServer *parent, bool is_event)
FixedVector< TemplatableKeyValuePair< Ts... > > data_
void add_data(const __FlashStringHelper *key, V &&value)
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)
void add_data_template(const __FlashStringHelper *key, V &&value)
FixedVector< HomeassistantServiceMap > variables
Definition api_pb2.h:1031
FixedVector< HomeassistantServiceMap > data
Definition api_pb2.h:1029
FixedVector< HomeassistantServiceMap > data_template
Definition api_pb2.h:1030
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