From 70dfd64b581ef774945971e238fbfe2cc711fb39 Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Mon, 3 Jun 2024 20:46:34 +0200 Subject: [PATCH] Simplify _write_row_packet by precomputing header and lengths --- src/WebSerial.cpp | 51 +++++++++++++++++++++-------------------------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/src/WebSerial.cpp b/src/WebSerial.cpp index 65fdc42..79126d5 100644 --- a/src/WebSerial.cpp +++ b/src/WebSerial.cpp @@ -18,6 +18,24 @@ typedef enum { static const uint8_t WSL_PONG[] = {WSL_MAGIC_BYTE_1, WSL_MAGIC_BYTE_2, WSLPacketType::WSL_PONG}; static const size_t WSL_PONG_LEN = sizeof(WSL_PONG) / sizeof(WSL_PONG[0]); +static const uint8_t WSL_HEAD[] = { + WSL_MAGIC_BYTE_1, // Magic Bytes + WSL_MAGIC_BYTE_2, // Magic Bytes + WSLPacketType::WSL_WRITE_ROW, // Packet Type (1 byte) + 0x00, // Reserved + 0x00, // Reserved + 0x00, // Reserved + 0x00, // Reserved + 0x00, // Padding + 0x00, // Padding + 0x00, // Padding + 0x00, // Padding + 0x00 // Reserved +}; +static const size_t WSL_HEAD_LEN = sizeof(WSL_HEAD) / sizeof(WSL_HEAD[0]); + +static const size_t WSL_MSG_SIZE_LEN = sizeof(uint16_t); + void WebSerialClass::setAuthentication(const String& username, const String& password){ _username = username; _password = password; @@ -142,37 +160,14 @@ bool WebSerialClass::_has_enough_space(size_t size) { } size_t WebSerialClass::_write_row_packet(__unused uint64_t reserved1, __unused uint8_t reserved2, const uint8_t *payload, const size_t payload_size) { - size_t header_size = 0; - - // Write Magic Bytes - _buffer[_buffer_offset + header_size++] = WSL_MAGIC_BYTE_1; - _buffer[_buffer_offset + header_size++] = WSL_MAGIC_BYTE_2; - - // Packet Type (1 byte) - _buffer[_buffer_offset + header_size++] = WSLPacketType::WSL_WRITE_ROW; - - // Reserved (8 bytes) - _buffer[_buffer_offset + header_size++] = 0x00; - _buffer[_buffer_offset + header_size++] = 0x00; - _buffer[_buffer_offset + header_size++] = 0x00; - _buffer[_buffer_offset + header_size++] = 0x00; - _buffer[_buffer_offset + header_size++] = 0x00; - _buffer[_buffer_offset + header_size++] = 0x00; - _buffer[_buffer_offset + header_size++] = 0x00; - _buffer[_buffer_offset + header_size++] = 0x00; - - // Reserved (1 byte) - _buffer[_buffer_offset + header_size++] = 0x00; - + // Write header + memmove(_buffer, WSL_HEAD, WSL_HEAD_LEN); // Message Length (2 bytes) - memset(_buffer + _buffer_offset + header_size, (uint16_t)payload_size, sizeof((uint16_t)payload_size)); - header_size += sizeof((uint16_t)payload_size); - + memset(_buffer + WSL_HEAD_LEN, static_cast(payload_size), WSL_MSG_SIZE_LEN); // Set Message - memcpy(_buffer + _buffer_offset + header_size, payload, payload_size); - + memmove(_buffer + WSL_HEAD_LEN + WSL_MSG_SIZE_LEN, payload, payload_size); // Return total packet size - return header_size + payload_size; + return WSL_HEAD_LEN + WSL_MSG_SIZE_LEN + payload_size; } size_t WebSerialClass::_write_row(uint8_t *data, size_t len) {