ESPHome 2025.9.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 "esphome/core/hal.h"
8
10
19template<typename T, T N> class CachedGpioExpander {
20 public:
24 bool digital_read(T pin) {
25 const uint8_t bank = pin / BANK_SIZE;
26 const T pin_mask = (1 << (pin % BANK_SIZE));
27 // Check if specific pin cache is valid
28 if (this->read_cache_valid_[bank] & pin_mask) {
29 // Invalidate pin
30 this->read_cache_valid_[bank] &= ~pin_mask;
31 } else {
32 // Read whole bank from hardware
33 if (!this->digital_read_hw(pin))
34 return false;
35 // Mark bank cache as valid except the pin that is being returned now
36 this->read_cache_valid_[bank] = std::numeric_limits<T>::max() & ~pin_mask;
37 }
38 return this->digital_read_cache(pin);
39 }
40
41 void digital_write(T pin, bool value) { this->digital_write_hw(pin, value); }
42
43 protected:
45 virtual bool digital_read_hw(T pin) = 0;
47 virtual bool digital_read_cache(T pin) = 0;
49 virtual void digital_write_hw(T pin, bool value) = 0;
50
52 void reset_pin_cache_() { memset(this->read_cache_valid_, 0x00, CACHE_SIZE_BYTES); }
53
54 static constexpr uint8_t BITS_PER_BYTE = 8;
55 static constexpr uint8_t BANK_SIZE = sizeof(T) * BITS_PER_BYTE;
56 static constexpr size_t BANKS = N / BANK_SIZE;
57 static constexpr size_t CACHE_SIZE_BYTES = BANKS * sizeof(T);
58
60};
61
62} // namespace esphome::gpio_expander
A class to cache the read state of a GPIO expander.
Definition cached_gpio.h:19
static constexpr uint8_t BITS_PER_BYTE
Definition cached_gpio.h:54
virtual void digital_write_hw(T pin, bool value)=0
Call component low level function to write GPIO state to device.
bool digital_read(T pin)
Read the state of the given pin.
Definition cached_gpio.h:24
virtual bool digital_read_cache(T pin)=0
Call component read function from internal cache.
static constexpr size_t CACHE_SIZE_BYTES
Definition cached_gpio.h:57
void reset_pin_cache_()
Invalidate cache. This function should be called in component loop().
Definition cached_gpio.h:52
virtual bool digital_read_hw(T pin)=0
Call component low level function to read GPIO state from device.