ESPHome 2026.11.0-dev
Loading...
Searching...
No Matches
m5stack_4relay.cpp
Go to the documentation of this file.
1#include "m5stack_4relay.h"
3#include "esphome/core/log.h"
4
6
7ESPHOME_LOG_TAG(TAG, "m5stack_4relay");
8
9static constexpr uint8_t REG_MODE = 0x10;
10static constexpr uint8_t REG_RELAY = 0x11;
11static constexpr uint8_t MODE_SYNC = 1;
12
14 if (!this->write_byte(REG_MODE, MODE_SYNC) || !this->read_byte(REG_RELAY, &this->relays_)) {
15 this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
16 return;
17 }
18#ifdef USE_SWITCH
19 for (size_t channel = 0; channel < this->switches_.size(); channel++) {
20 switch_::Switch *sw = this->switches_[channel];
21 if (sw == nullptr)
22 continue;
23 // The chip keeps the relays across an ESP reboot, so a switch with restore mode DISABLED keeps what it
24 // holds. Every mode goes through control(), so inverted: applies and the first publish is the saved one.
25 sw->restore(((this->relays_ >> channel) & 1) != sw->is_inverted());
26 }
27#endif
28}
29
31 ESP_LOGCONFIG(TAG, "M5Stack 4 Relay:");
32 LOG_I2C_DEVICE(this);
33}
34
35bool M5Stack4Relay::set_relay(uint8_t channel, bool on) {
36 if (this->is_failed())
37 return false;
38 uint8_t value = this->relays_;
39 assign_bits(value, 1 << channel, on);
40 if (!this->status_comm_result(this->write_byte(REG_RELAY, value)))
41 return false;
42 this->relays_ = value;
43#ifdef USE_SWITCH
44 if (this->switches_[channel] != nullptr)
45 this->switches_[channel]->publish_state(on);
46#endif
47 return true;
48}
49
50} // namespace esphome::m5stack_4relay
void mark_failed()
Mark this component as failed.
bool is_failed() const
Definition component.h:274
bool status_comm_result(bool ok)
Clears the warning when ok, else sets it with message (default "Communication failed"); returns ok.
bool write_byte(uint8_t a_register, uint8_t data) const
Definition i2c.h:312
bool read_byte(uint8_t a_register, uint8_t *data)
Definition i2c.h:272
std::array< switch_::Switch *, 4 > switches_
bool set_relay(uint8_t channel, bool on)
Switch relay channel (0-3) on or off; returns false when the write failed.
Base class for all switches.
Definition switch.h:43
void restore()
Drive the switch to the state its restore mode yields, through control(), so inversion and write_stat...
Definition switch.cpp:63
bool is_inverted() const
Definition switch.h:130
ESPHOME_LOG_TAG(TAG, "m5stack_4relay")
ESPHOME_ALWAYS_INLINE constexpr void assign_bits(T &value, std::type_identity_t< T > mask, bool on)
Set the bits of mask in value when on is true, clear them otherwise.
Definition helpers.h:1072