ESPHome 2026.6.0-dev
Loading...
Searching...
No Matches
api_connection_buffer.h
Go to the documentation of this file.
1#pragma once
2
4#ifdef USE_API
5
6// Inline APIConnection methods that need APIServer complete. Include this
7// instead of api_connection.h when calling encode_to_buffer or get_batch_delay_ms_.
8
9#include "api_connection.h"
10#include "api_server.h"
11
12namespace esphome::api {
13
14inline uint16_t ESPHOME_ALWAYS_INLINE APIConnection::encode_to_buffer(uint32_t calculated_size,
15 MessageEncodeFn encode_fn, const void *msg,
16 APIConnection *conn, uint32_t remaining_size) {
17#ifdef HAS_PROTO_MESSAGE_DUMP
18 if (conn->flags_.log_only_mode) {
19 auto *proto_msg = static_cast<const ProtoMessage *>(msg);
20 DumpBuffer dump_buf;
21 conn->log_send_message_(proto_msg->message_name(), proto_msg->dump_to(dump_buf));
22 return 1;
23 }
24#endif
25 const uint8_t footer_size = conn->helper_->frame_footer_size();
26
27 // First message uses max padding (already in buffer), subsequent use exact header size
28 size_t to_add;
29 if (conn->flags_.batch_first_message) {
30 conn->flags_.batch_first_message = false;
31 conn->batch_header_size_ = conn->helper_->frame_header_padding();
32 to_add = calculated_size;
33 } else {
34 conn->batch_header_size_ = conn->helper_->frame_header_size(calculated_size, conn->batch_message_type_);
35 to_add = calculated_size + conn->batch_header_size_ + footer_size;
36 }
37
38 // Check if it fits (using actual header size, not max padding)
39 uint16_t total_calculated_size = calculated_size + conn->batch_header_size_ + footer_size;
40 if (total_calculated_size > remaining_size)
41 return 0;
42
43 auto &shared_buf = conn->parent_->get_shared_buffer_ref();
44 shared_buf.resize(shared_buf.size() + to_add);
45 ProtoWriteBuffer buffer{&shared_buf, shared_buf.size() - calculated_size};
46 encode_fn(msg, buffer PROTO_ENCODE_DEBUG_INIT(&shared_buf));
47
48 return total_calculated_size;
49}
50
52
53} // namespace esphome::api
54#endif
void resize(size_t n) ESPHOME_ALWAYS_INLINE
Definition api_buffer.h:43
struct esphome::api::APIConnection::APIFlags flags_
std::unique_ptr< APIFrameHelper > helper_
uint8_t *(*)(const void *, ProtoWriteBuffer &PROTO_ENCODE_DEBUG_PARAM) MessageEncodeFn
static uint16_t ESPHOME_ALWAYS_INLINE encode_to_buffer(uint32_t calculated_size, MessageEncodeFn encode_fn, const void *msg, APIConnection *conn, uint32_t remaining_size)
void log_send_message_(const LogString *name, const char *dump)
uint16_t get_batch_delay() const
Definition api_server.h:66
APIBuffer & get_shared_buffer_ref()
Definition api_server.h:70
Fixed-size buffer for message dumps - avoids heap allocation.
Definition proto.h:543
static void uint32_t