diff --git a/esphome/codegen.py b/esphome/codegen.py index b552490129..6b000b53a1 100644 --- a/esphome/codegen.py +++ b/esphome/codegen.py @@ -60,6 +60,7 @@ from esphome.cpp_types import ( # noqa std_ns, std_shared_ptr, std_string, + std_string_ref, std_vector, uint8, uint16, diff --git a/esphome/components/http_request/__init__.py b/esphome/components/http_request/__init__.py index 37487ec9a7..ade7024bed 100644 --- a/esphome/components/http_request/__init__.py +++ b/esphome/components/http_request/__init__.py @@ -257,7 +257,7 @@ async def http_request_action_to_code(config, action_id, template_arg, args): trigger, [ (cg.std_shared_ptr.template(HttpContainer), "response"), - (cg.std_string, "body"), + (cg.std_string_ref, "body"), ], conf, ) diff --git a/esphome/components/http_request/http_request.h b/esphome/components/http_request/http_request.h index 6281adddb6..82b7392648 100644 --- a/esphome/components/http_request/http_request.h +++ b/esphome/components/http_request/http_request.h @@ -43,10 +43,10 @@ class HttpContainer : public Parented { bool secure_{false}; }; -class HttpRequestResponseTrigger : public Trigger, std::string> { +class HttpRequestResponseTrigger : public Trigger, std::string &> { public: - void process(std::shared_ptr container, std::string response_body) { - this->trigger(std::move(container), std::move(response_body)); + void process(std::shared_ptr container, std::string &response_body) { + this->trigger(std::move(container), response_body); } }; @@ -153,8 +153,17 @@ template class HttpRequestSendAction : public Action { } } - for (auto *trigger : this->response_triggers_) { - trigger->process(container, response_body); + if (this->response_triggers_.size() == 1) { + // if there is only one trigger, no need to copy the response body + this->response_triggers_[0]->process(container, response_body); + } else { + for (auto *trigger : this->response_triggers_) { + // with multiple triggers, pass a copy of the response body to each + // one so that modifications made in one trigger are not visible to + // the others + auto response_body_copy = std::string(response_body); + trigger->process(container, response_body_copy); + } } container->end(); } diff --git a/esphome/cpp_types.py b/esphome/cpp_types.py index bd79d3b2f9..dab993f87f 100644 --- a/esphome/cpp_types.py +++ b/esphome/cpp_types.py @@ -10,6 +10,7 @@ int_ = global_ns.namespace("int") std_ns = global_ns.namespace("std") std_shared_ptr = std_ns.class_("shared_ptr") std_string = std_ns.class_("string") +std_string_ref = std_ns.namespace("string &") std_vector = std_ns.class_("vector") uint8 = global_ns.namespace("uint8_t") uint16 = global_ns.namespace("uint16_t")