ESPHome 2025.10.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:
34 bool digital_read(P pin) {
35 const P bank = pin / BANK_SIZE;
36 const T pin_mask = (1 << (pin % BANK_SIZE));
37 // Check if specific pin cache is valid
38 if (this->read_cache_valid_[bank] & pin_mask) {
39 // Invalidate pin
40 this->read_cache_valid_[bank] &= ~pin_mask;
41 } else {
42 // Read whole bank from hardware
43 if (!this->digital_read_hw(pin))
44 return false;
45 // Mark bank cache as valid except the pin that is being returned now
46 this->read_cache_valid_[bank] = std::numeric_limits<T>::max() & ~pin_mask;
47 }
48 return this->digital_read_cache(pin);
49 }
50
51 void digital_write(P pin, bool value) { this->digital_write_hw(pin, value); }
52
53 protected:
59 virtual bool digital_read_hw(P pin) = 0;
60
64 virtual bool digital_read_cache(P pin) = 0;
65
69 virtual void digital_write_hw(P pin, bool value) = 0;
70
72 void reset_pin_cache_() { memset(this->read_cache_valid_, 0x00, CACHE_SIZE_BYTES); }
73
74 static constexpr uint16_t BITS_PER_BYTE = 8;
75 static constexpr uint16_t BANK_SIZE = sizeof(T) * BITS_PER_BYTE;
76 static constexpr size_t BANKS = N / BANK_SIZE;
77 static constexpr size_t CACHE_SIZE_BYTES = BANKS * sizeof(T);
78
80};
81
82} // 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:72
static constexpr uint16_t BANK_SIZE
Definition cached_gpio.h:75
static constexpr uint16_t BITS_PER_BYTE
Definition cached_gpio.h:74
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:34
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:77
uint16_t type