ESPHome 2026.5.0-dev
Loading...
Searching...
No Matches
cached_gpio.h
Go to the documentation of this file.
1#pragma once
2
3#include <array>
4#include <cstdint>
5#include <cstring>
6#include <limits>
7#include <type_traits>
8#include "esphome/core/hal.h"
9
11
28template<typename T, uint16_t N, typename P = typename std::conditional<(N > 256), uint16_t, uint8_t>::type>
30 public:
37 bool digital_read(P pin) {
38 const P bank = pin / BANK_SIZE;
39 const T pin_mask = (1 << (pin % BANK_SIZE));
40 // Check if specific pin cache is valid
41 if (this->read_cache_valid_[bank] & pin_mask) {
42 if (this->invalidate_on_read_) {
43 // Invalidate pin so next read triggers hardware read
44 this->read_cache_valid_[bank] &= ~pin_mask;
45 }
46 } else {
47 // Read whole bank from hardware
48 if (!this->digital_read_hw(pin))
49 return false;
50 // Mark bank cache as valid except the pin that is being returned now
51 // (when not invalidating on read, mark all pins including this one as valid)
52 this->read_cache_valid_[bank] = std::numeric_limits<T>::max() & ~(this->invalidate_on_read_ ? pin_mask : 0);
53 }
54 return this->digital_read_cache(pin);
55 }
56
57 void digital_write(P pin, bool value) { this->digital_write_hw(pin, value); }
58
59 protected:
65 virtual bool digital_read_hw(P pin) = 0;
66
70 virtual bool digital_read_cache(P pin) = 0;
71
75 virtual void digital_write_hw(P pin, bool value) = 0;
76
78 void reset_pin_cache_() { memset(this->read_cache_valid_, 0x00, CACHE_SIZE_BYTES); }
79
83 void set_invalidate_on_read_(bool invalidate) { this->invalidate_on_read_ = invalidate; }
84
85 static constexpr uint16_t BITS_PER_BYTE = 8;
86 static constexpr uint16_t BANK_SIZE = sizeof(T) * BITS_PER_BYTE;
87 static constexpr size_t BANKS = N / BANK_SIZE;
88 static constexpr size_t CACHE_SIZE_BYTES = BANKS * sizeof(T);
89
92};
93
94} // namespace esphome::gpio_expander
A class to cache the read state of a GPIO expander.
Definition cached_gpio.h:29
void reset_pin_cache_()
Invalidate cache. This function should be called in component loop().
Definition cached_gpio.h:78
static constexpr uint16_t BANK_SIZE
Definition cached_gpio.h:86
static constexpr uint16_t BITS_PER_BYTE
Definition cached_gpio.h:85
void set_invalidate_on_read_(bool invalidate)
Control whether digital_read() invalidates the pin's cache entry after reading.
Definition cached_gpio.h:83
virtual void digital_write_hw(P pin, bool value)=0
Write GPIO state to hardware.
virtual bool digital_read_cache(P pin)=0
Get cached pin value from internal state.
bool digital_read(P pin)
Read the state of the given pin.
Definition cached_gpio.h:37
virtual bool digital_read_hw(P pin)=0
Read GPIO bank from hardware into internal state.
static constexpr size_t CACHE_SIZE_BYTES
Definition cached_gpio.h:88
uint16_t type