Compare commits

...
1 Commits
Author SHA1 Message Date
J. Nick Koston 6ca7614820 [core] Add bit_at, the read side of assign_bits 2026-10-22 09:31:48 -10:00
3 changed files with 30 additions and 3 deletions
+4 -3
View File
@@ -212,9 +212,10 @@ file does, and it is the authority when they disagree. The most useful starting
logged with `get_log_str` and `LOG_STR_ARG`, copied out with `ESPHOME_strncpy_P` before `publish_state`.
A `dump_config` helper that picks a name returns `const LogString *` from `LOG_STR(...)`.
* **CRCs and bit tricks** come from `esphome/core/helpers.h` (`crc8`, `crc16`, `xor_bytes`, `sum16_bytes`,
`reverse_bits`, `encode_uint16`, `encode_value_le`, `sign_extend<BITS>`, `bcd_to_uint8`, `assign_bits`); pick
the helper's arguments instead of writing a loop. 7-byte BCD RTC calendars use `time::decode_bcd_calendar<LAYOUT>`
and `encode_bcd_calendar<LAYOUT>` with `EPSON_BCD_CALENDAR`, `DS_BCD_CALENDAR` or `PCF_BCD_CALENDAR`.
`reverse_bits`, `encode_uint16`, `encode_value_le`, `sign_extend<BITS>`, `bcd_to_uint8`, `assign_bits`,
`bit_at`); pick the helper's arguments instead of writing a loop. 7-byte BCD RTC calendars use
`time::decode_bcd_calendar<LAYOUT>` and `encode_bcd_calendar<LAYOUT>` with `EPSON_BCD_CALENDAR`,
`DS_BCD_CALENDAR` or `PCF_BCD_CALENDAR`.
* **Bus helpers:** UART drains with `read_available(on_byte)` and `discard_available()`, text lines with
`LineReader<N>`; I2C has `update_register`, `write_registers` (PROGMEM `I2CRegValue` table), `check_chip_id`
and `read_bytes_16_le`. `if (!this->status_comm_result(ok)) return;` sets or clears the warning.
+3
View File
@@ -1077,6 +1077,9 @@ template<typename T> ESPHOME_ALWAYS_INLINE constexpr void assign_bits(T &value,
}
}
/// Whether bit \p bit (0 is the LSB) of \p value is set; the read side of assign_bits().
template<typename T> ESPHOME_ALWAYS_INLINE constexpr bool bit_at(T value, unsigned bit) { return (value >> bit) & 1; }
/// Reverse the order of 8 bits.
inline uint8_t reverse_bits(uint8_t x) {
x = ((x & 0xAA) >> 1) | ((x & 0x55) << 1);
+23
View File
@@ -0,0 +1,23 @@
#include <gtest/gtest.h>
#include "esphome/core/helpers.h"
namespace esphome::core::testing {
static_assert(bit_at(uint8_t{0b1010'0001}, 0));
static_assert(!bit_at(uint8_t{0b1010'0001}, 1));
static_assert(bit_at(uint8_t{0b1010'0001}, 7));
static_assert(bit_at(uint64_t{1} << 63, 63));
static_assert(!bit_at(uint64_t{1} << 63, 62));
static_assert(bit_at(int32_t{-1}, 31));
static_assert(!bit_at(int32_t{0x7FFF'FFFF}, 31));
TEST(BitAt, IsTheReadSideOfAssignBits) {
uint16_t reg = 0;
assign_bits(reg, 1 << 9, true);
EXPECT_TRUE(bit_at(reg, 9));
assign_bits(reg, 1 << 9, false);
EXPECT_FALSE(bit_at(reg, 9));
}
} // namespace esphome::core::testing