mirror of
https://github.com/esphome/esphome.git
synced 2024-12-25 15:04:54 +01:00
online_image: allow setting templatable headers on http request
This commit is contained in:
parent
e819185de1
commit
e89f7fe385
3 changed files with 23 additions and 1 deletions
|
@ -28,6 +28,7 @@ MULTI_CONF = True
|
|||
|
||||
CONF_ON_DOWNLOAD_FINISHED = "on_download_finished"
|
||||
CONF_PLACEHOLDER = "placeholder"
|
||||
CONF_HTTP_REQUEST_HEADERS = "http_request_headers"
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
@ -86,6 +87,9 @@ ONLINE_IMAGE_SCHEMA = cv.Schema(
|
|||
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(DownloadErrorTrigger),
|
||||
}
|
||||
),
|
||||
cv.Optional(CONF_HTTP_REQUEST_HEADERS): cv.All(
|
||||
cv.Schema({cv.string: cv.templatable(cv.string)})
|
||||
),
|
||||
}
|
||||
).extend(cv.polling_component_schema("never"))
|
||||
|
||||
|
@ -154,6 +158,12 @@ async def to_code(config):
|
|||
|
||||
cg.add(var.set_transparency(transparent))
|
||||
|
||||
for key in config.get(CONF_HTTP_REQUEST_HEADERS, []):
|
||||
template_ = await cg.templatable(
|
||||
config[CONF_HTTP_REQUEST_HEADERS][key], [], cg.optional.template(cg.const_char_ptr)
|
||||
)
|
||||
cg.add(var.add_header(key, template_))
|
||||
|
||||
if placeholder_id := config.get(CONF_PLACEHOLDER):
|
||||
placeholder = await cg.get_variable(placeholder_id)
|
||||
cg.add(var.set_placeholder(placeholder))
|
||||
|
|
|
@ -103,7 +103,16 @@ void OnlineImage::update() {
|
|||
ESP_LOGI(TAG, "Updating image");
|
||||
}
|
||||
|
||||
this->downloader_ = this->parent_->get(this->url_);
|
||||
|
||||
std::list<http_request::Header> headers;
|
||||
for (const auto &item : this->headers_) {
|
||||
auto val = item.second();
|
||||
if (val.has_value()) {
|
||||
headers.push_back(http_request::Header{item.first, *val});
|
||||
}
|
||||
}
|
||||
|
||||
this->downloader_ = this->parent_->get(this->url_, headers);
|
||||
|
||||
if (this->downloader_ == nullptr) {
|
||||
ESP_LOGE(TAG, "Download failed.");
|
||||
|
|
|
@ -62,6 +62,8 @@ class OnlineImage : public PollingComponent,
|
|||
}
|
||||
}
|
||||
|
||||
void add_header(const char *key, std::function<optional<const char*>()> &&f) { this->headers_.insert({key, f}); }
|
||||
|
||||
/**
|
||||
* @brief Set the image that needs to be shown as long as the downloaded image
|
||||
* is not available.
|
||||
|
@ -122,6 +124,7 @@ class OnlineImage : public PollingComponent,
|
|||
image::Image *placeholder_{nullptr};
|
||||
|
||||
std::string url_{""};
|
||||
std::map<const char *, std::function<optional<const char*>()>> headers_{};
|
||||
|
||||
/** width requested on configuration, or 0 if non specified. */
|
||||
const int fixed_width_;
|
||||
|
|
Loading…
Reference in a new issue