Format all files

This commit is contained in:
2026-07-12 12:56:02 +00:00
parent 7612987884
commit a5c5bf6c6b
56 changed files with 2372 additions and 2395 deletions
+7 -7
View File
@@ -8,22 +8,22 @@ esphome:
version: "1.0"
external_components:
- source: components
- source: components
packages:
device_base: !include templates/esp8266.yaml
sensor: !include templates/esp8266-vcc.yaml
one_wire:
- platform: gpio
- platform: gpio
pin: D1
sensor:
- platform: dallas_temp
- platform: dallas_temp
address: 0x0401212E565C7428
id: bathroom_heater_temperature
- platform: duty_time
- platform: duty_time
id: continuous_on_time
name: Continuous on time
accuracy_decimals: 0
@@ -34,7 +34,7 @@ remote_transmitter:
id: heater_ir_transmitter
climate:
- platform: zehnder
- platform: zehnder
name: None
id: bathroom_heater
transmitter_id: heater_ir_transmitter
@@ -42,7 +42,7 @@ climate:
on_state:
- if:
condition:
lambda: 'return x.mode == climate::CLIMATE_MODE_HEAT;'
lambda: "return x.mode == climate::CLIMATE_MODE_HEAT;"
then:
- sensor.duty_time.start: continuous_on_time
else:
@@ -50,7 +50,7 @@ climate:
- sensor.duty_time.reset: continuous_on_time
interval:
- interval: 1min
- interval: 1min
then:
- if:
condition:
+1 -1
View File
@@ -17,7 +17,7 @@ switch:
optimistic: true
time:
- platform: sntp
- platform: sntp
id: sntp_time
servers: !secret sntp_servers
timezone: Europe/Zurich
+3 -3
View File
@@ -14,7 +14,7 @@ packages:
psram:
i2c:
- id: camera_i2c
- id: camera_i2c
sda: GPIO26
scl: GPIO27
@@ -34,12 +34,12 @@ esp32_camera: # Ai-Thinker
idle_framerate: 0.1fps
output:
- platform: ledc
- platform: ledc
pin: GPIO4
channel: 2 # PWM channel 1 is used for esp32_camera.
id: led
light:
- platform: monochromatic
- platform: monochromatic
output: led
name: Flash
+3 -5
View File
@@ -8,12 +8,10 @@
namespace esphome::ratgdo {
class SyncFailed : public Trigger<> {
public:
explicit SyncFailed(RATGDOComponent* parent)
{
public:
explicit SyncFailed(RATGDOComponent* parent) {
parent->subscribe_sync_failed([this](optional<bool> state) {
if (state.value_or(false))
this->trigger();
if (state.value_or(false)) this->trigger();
});
}
};
+12 -12
View File
@@ -1,8 +1,9 @@
#pragma once
#include "observable.h"
#include <cstdint>
#include <utility>
#include "observable.h"
namespace esphome::ratgdo {
void log_once_callbacks_overflow(uint8_t max);
@@ -12,25 +13,24 @@ class OnceCallbacks;
template <typename... Ts>
class OnceCallbacks<void(Ts...)> {
public:
// Runtime max is 1 for all current usage (door_state waits, command_sent waits).
// Set to 2 for safety margin.
public:
// Runtime max is 1 for all current usage (door_state waits, command_sent
// waits). Set to 2 for safety margin.
static constexpr uint8_t MAX_CALLBACKS = 2;
template <typename F>
void operator()(F&& callback)
{
void operator()(F&& callback) {
if (this->count_ >= MAX_CALLBACKS) {
log_once_callbacks_overflow(MAX_CALLBACKS);
return;
}
this->callbacks_[this->count_++] = Callback<Ts...>::create(std::forward<F>(callback));
this->callbacks_[this->count_++] =
Callback<Ts...>::create(std::forward<F>(callback));
}
// Re-entrant safe: count_ is zeroed before invoking callbacks,
// so callbacks can queue new entries during trigger().
void trigger(Ts... args)
{
void trigger(Ts... args) {
uint8_t count = this->count_;
this->count_ = 0;
for (uint8_t i = 0; i < count; i++) {
@@ -41,9 +41,9 @@ public:
void clear() { this->count_ = 0; }
uint8_t count() const { return this->count_; }
protected:
Callback<Ts...> callbacks_[MAX_CALLBACKS] { };
uint8_t count_ { 0 };
protected:
Callback<Ts...> callbacks_[MAX_CALLBACKS]{};
uint8_t count_{0};
};
} // namespace esphome::ratgdo
+7 -12
View File
@@ -7,9 +7,8 @@
namespace esphome::ratgdo {
class CoverOpeningTrigger : public Trigger<> {
public:
CoverOpeningTrigger(cover::Cover* a_cover)
{
public:
CoverOpeningTrigger(cover::Cover* a_cover) {
a_cover->add_on_state_callback([this, a_cover]() {
if (a_cover->current_operation == cover::COVER_OPERATION_OPENING) {
this->trigger();
@@ -19,9 +18,8 @@ public:
};
class CoverClosingTrigger : public Trigger<> {
public:
CoverClosingTrigger(cover::Cover* a_cover)
{
public:
CoverClosingTrigger(cover::Cover* a_cover) {
a_cover->add_on_state_callback([this, a_cover]() {
if (a_cover->current_operation == cover::COVER_OPERATION_CLOSING) {
this->trigger();
@@ -31,12 +29,9 @@ public:
};
class CoverStateTrigger : public Trigger<> {
public:
CoverStateTrigger(cover::Cover* a_cover)
{
a_cover->add_on_state_callback([this, a_cover]() {
this->trigger();
});
public:
CoverStateTrigger(cover::Cover* a_cover) {
a_cover->add_on_state_callback([this, a_cover]() { this->trigger(); });
}
};
+6 -12
View File
@@ -1,4 +1,5 @@
#include "ratgdo_cover.h"
#include "../ratgdo_state.h"
#include "esphome/core/log.h"
@@ -8,13 +9,9 @@ using namespace esphome::cover;
static const char* const TAG = "ratgdo.cover";
void RATGDOCover::dump_config()
{
LOG_COVER("", "RATGDO Cover", this);
}
void RATGDOCover::dump_config() { LOG_COVER("", "RATGDO Cover", this); }
void RATGDOCover::setup()
{
void RATGDOCover::setup() {
auto state = this->restore_state_();
if (state.has_value()) {
this->parent_->set_door_position(state.value().position);
@@ -24,8 +21,7 @@ void RATGDOCover::setup()
});
}
void RATGDOCover::on_door_state(DoorState state, float position)
{
void RATGDOCover::on_door_state(DoorState state, float position) {
if (!*this->parent_->synced || state == DoorState::UNKNOWN) {
return;
}
@@ -64,8 +60,7 @@ void RATGDOCover::on_door_state(DoorState state, float position)
this->publish_state(save_to_flash);
}
CoverTraits RATGDOCover::get_traits()
{
CoverTraits RATGDOCover::get_traits() {
auto traits = CoverTraits();
traits.set_supports_stop(true);
traits.set_supports_toggle(true);
@@ -73,8 +68,7 @@ CoverTraits RATGDOCover::get_traits()
return traits;
}
void RATGDOCover::control(const CoverCall& call)
{
void RATGDOCover::control(const CoverCall& call) {
if (call.get_stop()) {
this->parent_->door_stop();
}
+2 -2
View File
@@ -8,14 +8,14 @@
namespace esphome::ratgdo {
class RATGDOCover : public cover::Cover, public RATGDOClient, public Component {
public:
public:
void dump_config() override;
void setup() override;
cover::CoverTraits get_traits() override;
void on_door_state(DoorState state, float position);
protected:
protected:
void control(const cover::CoverCall& call) override;
};
+13 -23
View File
@@ -1,4 +1,5 @@
#include "ratgdo_light_output.h"
#include "../ratgdo_state.h"
#include "esphome/core/log.h"
@@ -8,52 +9,41 @@ using namespace esphome::light;
static const char* const TAG = "ratgdo.light";
void RATGDOLightOutput::dump_config()
{
ESP_LOGCONFIG(TAG, "RATGDO Light");
void RATGDOLightOutput::dump_config() { ESP_LOGCONFIG(TAG, "RATGDO Light"); }
void RATGDOLightOutput::setup() {
this->parent_->subscribe_light_state(
[this](LightState state) { this->on_light_state(state); });
}
void RATGDOLightOutput::setup()
{
this->parent_->subscribe_light_state([this](LightState state) {
this->on_light_state(state);
});
}
void RATGDOLightOutput::on_light_state(esphome::ratgdo::LightState state)
{
void RATGDOLightOutput::on_light_state(esphome::ratgdo::LightState state) {
if (this->light_state_) {
this->has_initial_state_ = true;
set_state(state);
}
}
void RATGDOLightOutput::set_state(esphome::ratgdo::LightState state)
{
void RATGDOLightOutput::set_state(esphome::ratgdo::LightState state) {
bool is_on = state == LightState::ON;
this->light_state_->current_values.set_state(is_on);
this->light_state_->remote_values.set_state(is_on);
this->light_state_->publish_state();
}
void RATGDOLightOutput::setup_state(light::LightState* light_state)
{
void RATGDOLightOutput::setup_state(light::LightState* light_state) {
esphome::ratgdo::LightState state = this->parent_->get_light_state();
this->light_state_ = light_state;
this->set_state(state);
}
LightTraits RATGDOLightOutput::get_traits()
{
LightTraits RATGDOLightOutput::get_traits() {
auto traits = LightTraits();
traits.set_supported_color_modes({ light::ColorMode::ON_OFF });
traits.set_supported_color_modes({light::ColorMode::ON_OFF});
return traits;
}
void RATGDOLightOutput::write_state(light::LightState* state)
{
if (!this->has_initial_state_)
return;
void RATGDOLightOutput::write_state(light::LightState* state) {
if (!this->has_initial_state_) return;
bool binary;
state->current_values_as_binary(&binary);
if (binary) {
@@ -7,8 +7,10 @@
namespace esphome::ratgdo {
class RATGDOLightOutput : public light::LightOutput, public RATGDOClient, public Component {
public:
class RATGDOLightOutput : public light::LightOutput,
public RATGDOClient,
public Component {
public:
void dump_config() override;
void setup() override;
light::LightTraits get_traits() override;
@@ -19,7 +21,7 @@ public:
void on_light_state(esphome::ratgdo::LightState state);
protected:
protected:
light::LightState* light_state_;
bool has_initial_state_ = false;
};
+11 -13
View File
@@ -1,4 +1,5 @@
#include "ratgdo_lock.h"
#include "../ratgdo_state.h"
#include "esphome/core/log.h"
@@ -6,25 +7,23 @@ namespace esphome::ratgdo {
static const char* const TAG = "ratgdo.lock";
void RATGDOLock::dump_config()
{
void RATGDOLock::dump_config() {
LOG_LOCK("", "RATGDO Lock", this);
ESP_LOGCONFIG(TAG, " Type: Lock");
}
void RATGDOLock::setup()
{
this->parent_->subscribe_lock_state([this](LockState state) {
this->on_lock_state(state);
});
void RATGDOLock::setup() {
this->parent_->subscribe_lock_state(
[this](LockState state) { this->on_lock_state(state); });
}
void RATGDOLock::on_lock_state(LockState state)
{
if (state == LockState::LOCKED && this->state == lock::LockState::LOCK_STATE_LOCKED) {
void RATGDOLock::on_lock_state(LockState state) {
if (state == LockState::LOCKED &&
this->state == lock::LockState::LOCK_STATE_LOCKED) {
return;
}
if (state == LockState::UNLOCKED && this->state == lock::LockState::LOCK_STATE_UNLOCKED) {
if (state == LockState::UNLOCKED &&
this->state == lock::LockState::LOCK_STATE_UNLOCKED) {
return;
}
@@ -37,8 +36,7 @@ void RATGDOLock::on_lock_state(LockState state)
this->publish_state(*call.get_state());
}
void RATGDOLock::control(const lock::LockCall& call)
{
void RATGDOLock::control(const lock::LockCall& call) {
auto state = *call.get_state();
if (state == lock::LockState::LOCK_STATE_LOCKED) {
+1 -1
View File
@@ -8,7 +8,7 @@
namespace esphome::ratgdo {
class RATGDOLock : public lock::Lock, public RATGDOClient, public Component {
public:
public:
void dump_config() override;
void setup() override;
+10 -16
View File
@@ -1,4 +1,5 @@
#include "ratgdo_number.h"
#include "../ratgdo_state.h"
#include "esphome/core/log.h"
@@ -6,8 +7,7 @@ namespace esphome::ratgdo {
static const char* const TAG = "ratgdo.number";
void RATGDONumber::dump_config()
{
void RATGDONumber::dump_config() {
LOG_NUMBER("", "RATGDO Number", this);
switch (this->number_type_) {
case RATGDO_OPENING_DURATION:
@@ -21,8 +21,7 @@ void RATGDONumber::dump_config()
}
}
void RATGDONumber::setup()
{
void RATGDONumber::setup() {
float value;
this->pref_ = this->make_entity_preference<float>();
if (!this->pref_.load(&value)) {
@@ -32,22 +31,19 @@ void RATGDONumber::setup()
switch (this->number_type_) {
case RATGDO_OPENING_DURATION:
this->parent_->subscribe_opening_duration([this](float value) {
this->update_state(value);
});
this->parent_->subscribe_opening_duration(
[this](float value) { this->update_state(value); });
break;
case RATGDO_CLOSING_DURATION:
this->parent_->subscribe_closing_duration([this](float value) {
this->update_state(value);
});
this->parent_->subscribe_closing_duration(
[this](float value) { this->update_state(value); });
break;
default:
break;
}
}
void RATGDONumber::set_number_type(NumberType number_type_)
{
void RATGDONumber::set_number_type(NumberType number_type_) {
this->number_type_ = number_type_;
switch (this->number_type_) {
case RATGDO_OPENING_DURATION:
@@ -61,8 +57,7 @@ void RATGDONumber::set_number_type(NumberType number_type_)
}
}
void RATGDONumber::update_state(float value)
{
void RATGDONumber::update_state(float value) {
if (value == this->state) {
return;
}
@@ -70,8 +65,7 @@ void RATGDONumber::update_state(float value)
this->publish_state(value);
}
void RATGDONumber::control(float value)
{
void RATGDONumber::control(float value) {
switch (this->number_type_) {
case RATGDO_OPENING_DURATION:
this->parent_->set_opening_duration(value);
+11 -7
View File
@@ -13,20 +13,24 @@ enum NumberType {
RATGDO_CLOSING_DURATION,
};
class RATGDONumber : public number::Number, public RATGDOClient, public Component {
public:
class RATGDONumber : public number::Number,
public RATGDOClient,
public Component {
public:
void dump_config() override;
void setup() override;
void set_number_type(NumberType number_type);
// other esphome components that persist state in the flash have HARDWARE priority
// ensure we get initialized before them, so that the state doesn't get invalidated
// by components that might be added in the future
float get_setup_priority() const override { return setup_priority::HARDWARE + 1; }
// other esphome components that persist state in the flash have HARDWARE
// priority ensure we get initialized before them, so that the state doesn't
// get invalidated by components that might be added in the future
float get_setup_priority() const override {
return setup_priority::HARDWARE + 1;
}
void update_state(float value);
void control(float value) override;
protected:
protected:
NumberType number_type_;
ESPPreferenceObject pref_;
};
+11 -9
View File
@@ -1,4 +1,5 @@
#include "observable.h"
#include "callbacks.h"
#include "esphome/core/log.h"
@@ -6,19 +7,20 @@ namespace esphome::ratgdo {
static const char* const TAG = "ratgdo.observable";
void log_multiple_subscribers()
{
ESP_LOGE(TAG, "single_observable already has a subscriber! This will overwrite the existing subscriber.");
void log_multiple_subscribers() {
ESP_LOGE(TAG,
"single_observable already has a subscriber! This will overwrite "
"the existing subscriber.");
}
void log_observer_overflow()
{
ESP_LOGE(TAG, "observable has too many subscribers! Ignoring new subscriber.");
void log_observer_overflow() {
ESP_LOGE(TAG,
"observable has too many subscribers! Ignoring new subscriber.");
}
void log_once_callbacks_overflow(uint8_t max)
{
ESP_LOGE(TAG, "OnceCallbacks overflow (max %u)! Ignoring callback.", static_cast<unsigned>(max));
void log_once_callbacks_overflow(uint8_t max) {
ESP_LOGE(TAG, "OnceCallbacks overflow (max %u)! Ignoring callback.",
static_cast<unsigned>(max));
}
} // namespace esphome::ratgdo
+35 -48
View File
@@ -11,29 +11,32 @@ void log_multiple_subscribers();
void log_observer_overflow();
// Lightweight type-erased callback (16 bytes on 32-bit).
// For small trivially-copyable callables (like [this], [this, f], or [this, f, id] lambdas),
// stores the callable inline — zero heap allocation.
// Supports up to 3 * sizeof(void*) bytes (12 bytes on 32-bit, 24 on 64-bit).
// For small trivially-copyable callables (like [this], [this, f], or [this, f,
// id] lambdas), stores the callable inline — zero heap allocation. Supports up
// to 3 * sizeof(void*) bytes (12 bytes on 32-bit, 24 on 64-bit).
inline constexpr size_t CALLBACK_STORAGE_SIZE = 3 * sizeof(void*);
template <typename... Ts>
struct Callback {
using fn_t = void (*)(const void*, Ts...);
fn_t fn_ { nullptr };
alignas(void*) uint8_t storage_[CALLBACK_STORAGE_SIZE] { };
fn_t fn_{nullptr};
alignas(void*) uint8_t storage_[CALLBACK_STORAGE_SIZE]{};
void call(Ts... args) const { this->fn_(this->storage_, args...); }
explicit operator bool() const { return this->fn_ != nullptr; }
template <typename F>
static Callback create(F&& f)
{
static Callback create(F&& f) {
Callback cb;
using Decay = std::decay_t<F>;
static_assert(!std::is_function_v<std::remove_reference_t<F>>,
"Pass function pointers, not function references");
static_assert(std::is_trivially_copyable_v<Decay>, "Observable callbacks must be trivially copyable (e.g. [this] lambdas)");
static_assert(sizeof(Decay) <= CALLBACK_STORAGE_SIZE, "Observable callbacks must fit in storage (capture at most 3 pointers)");
static_assert(std::is_trivially_copyable_v<Decay>,
"Observable callbacks must be trivially copyable (e.g. "
"[this] lambdas)");
static_assert(sizeof(Decay) <= CALLBACK_STORAGE_SIZE,
"Observable callbacks must fit in storage (capture at most 3 "
"pointers)");
cb.fn_ = [](const void* storage, Ts... args) {
alignas(Decay) char buf[sizeof(Decay)];
__builtin_memcpy(buf, storage, sizeof(Decay));
@@ -47,15 +50,11 @@ struct Callback {
// Primary template for observable with subscribers.
template <typename T, uint8_t MaxObservers>
class observable {
public:
observable(const T& value)
: value_(value)
{
}
public:
observable(const T& value) : value_(value) {}
template <typename U>
observable& operator=(U value)
{
observable& operator=(U value) {
if (value != this->value_) {
this->value_ = value;
this->notify();
@@ -67,40 +66,35 @@ public:
T const& operator*() const { return this->value_; }
template <typename F>
void subscribe(F&& observer)
{
void subscribe(F&& observer) {
if (this->count_ >= MaxObservers) {
log_observer_overflow();
return;
}
this->observers_[this->count_++] = Callback<T>::create(std::forward<F>(observer));
this->observers_[this->count_++] =
Callback<T>::create(std::forward<F>(observer));
}
void notify() const
{
void notify() const {
for (uint8_t i = 0; i < this->count_; i++) {
this->observers_[i].call(this->value_);
}
}
private:
private:
T value_;
Callback<T> observers_[MaxObservers] { };
uint8_t count_ { 0 };
Callback<T> observers_[MaxObservers]{};
uint8_t count_{0};
};
// Specialization for zero subscribers — no array, no count, notify is a no-op.
template <typename T>
class observable<T, 0> {
public:
observable(const T& value)
: value_(value)
{
}
public:
observable(const T& value) : value_(value) {}
template <typename U>
observable& operator=(U value)
{
observable& operator=(U value) {
if (value != this->value_) {
this->value_ = value;
}
@@ -111,28 +105,23 @@ public:
T const& operator*() const { return this->value_; }
template <typename F>
void subscribe(F&&)
{
void subscribe(F&&) {
log_observer_overflow();
}
void notify() const { }
void notify() const {}
private:
private:
T value_;
};
template <typename T>
class single_observable {
public:
single_observable(const T& value)
: value_(value)
{
}
public:
single_observable(const T& value) : value_(value) {}
template <typename U>
single_observable& operator=(U value)
{
single_observable& operator=(U value) {
if (value != this->value_) {
this->value_ = value;
this->notify();
@@ -144,24 +133,22 @@ public:
T const& operator*() const { return this->value_; }
template <typename F>
void subscribe(F&& observer)
{
void subscribe(F&& observer) {
if (this->observer_) {
log_multiple_subscribers();
}
this->observer_ = Callback<T>::create(std::forward<F>(observer));
}
void notify() const
{
void notify() const {
if (this->observer_) {
this->observer_.call(this->value_);
}
}
private:
private:
T value_;
Callback<T> observer_ { };
Callback<T> observer_{};
};
} // namespace esphome::ratgdo
+86 -103
View File
@@ -5,19 +5,16 @@
************************************/
#include "ratgdo.h"
#include "common.h"
#include "ratgdo_state.h"
#include "secplus2.h"
#include "esphome/core/application.h"
#include "esphome/core/gpio.h"
#include "esphome/core/log.h"
#include "ratgdo_state.h"
#include "secplus2.h"
namespace esphome::ratgdo {
static const char* const TAG = "ratgdo";
static constexpr int SYNC_DELAY = 5000;
// Door state updates arrive over UART every ~200-400ms during movement.
@@ -28,14 +25,12 @@ static constexpr uint32_t DOOR_STATE_CALLBACK_TIMEOUT = 2000;
using namespace scheduler_ids;
void log_subscriber_overflow(const LogString* observable_name, uint32_t max)
{
void log_subscriber_overflow(const LogString* observable_name, uint32_t max) {
ESP_LOGE(TAG, "Too many subscribers for %s (max %d)",
LOG_STR_ARG(observable_name), (int)max);
}
void RATGDOComponent::setup()
{
void RATGDOComponent::setup() {
this->output_gdo_pin_->setup();
this->output_gdo_pin_->pin_mode(gpio::FLAG_OUTPUT);
@@ -55,39 +50,30 @@ void RATGDOComponent::setup()
this->lock_state.notify();
}
});
}
// initializing protocol, this gets called before setup() because
// its children components might require that
void RATGDOComponent::init_protocol()
{
void RATGDOComponent::init_protocol() {
this->protocol_ = new secplus2::Secplus2();
}
void RATGDOComponent::loop()
{
this->protocol_->loop();
}
void RATGDOComponent::loop() { this->protocol_->loop(); }
void RATGDOComponent::dump_config()
{
void RATGDOComponent::dump_config() {
ESP_LOGCONFIG(TAG, "Setting up RATGDO...");
LOG_PIN(" Output GDO Pin: ", this->output_gdo_pin_);
LOG_PIN(" Input GDO Pin: ", this->input_gdo_pin_);
this->protocol_->dump_config();
}
void RATGDOComponent::on_shutdown()
{
void RATGDOComponent::on_shutdown() {
if (this->protocol_ != nullptr) {
this->protocol_->on_shutdown();
}
}
void RATGDOComponent::received(const DoorState door_state)
{
void RATGDOComponent::received(const DoorState door_state) {
ESP_LOGD(TAG, "Door state=%s", LOG_STR_ARG(DoorState_to_string(door_state)));
auto prev_door_state = *this->door_state;
@@ -98,10 +84,12 @@ void RATGDOComponent::received(const DoorState door_state)
// opening duration calibration
if (*this->opening_duration == 0) {
if (door_state == DoorState::OPENING && prev_door_state == DoorState::CLOSED) {
if (door_state == DoorState::OPENING &&
prev_door_state == DoorState::CLOSED) {
this->start_opening = millis();
}
if (door_state == DoorState::OPEN && prev_door_state == DoorState::OPENING && this->start_opening > 0) {
if (door_state == DoorState::OPEN &&
prev_door_state == DoorState::OPENING && this->start_opening > 0) {
auto duration = (millis() - this->start_opening) / 1000;
this->set_opening_duration(round(duration * 10) / 10);
}
@@ -111,10 +99,12 @@ void RATGDOComponent::received(const DoorState door_state)
}
// closing duration calibration
if (*this->closing_duration == 0) {
if (door_state == DoorState::CLOSING && prev_door_state == DoorState::OPEN) {
if (door_state == DoorState::CLOSING &&
prev_door_state == DoorState::OPEN) {
this->start_closing = millis();
}
if (door_state == DoorState::CLOSED && prev_door_state == DoorState::CLOSING && this->start_closing > 0) {
if (door_state == DoorState::CLOSED &&
prev_door_state == DoorState::CLOSING && this->start_closing > 0) {
auto duration = (millis() - this->start_closing) / 1000;
this->set_closing_duration(round(duration * 10) / 10);
}
@@ -182,21 +172,18 @@ void RATGDOComponent::received(const DoorState door_state)
this->on_door_state_.trigger(door_state);
}
void RATGDOComponent::received(const LightState light_state)
{
void RATGDOComponent::received(const LightState light_state) {
ESP_LOGD(TAG, "Light state=%s",
LOG_STR_ARG(LightState_to_string(light_state)));
this->light_state = light_state;
}
void RATGDOComponent::received(const LockState lock_state)
{
void RATGDOComponent::received(const LockState lock_state) {
ESP_LOGD(TAG, "Lock state=%s", LOG_STR_ARG(LockState_to_string(lock_state)));
this->lock_state = lock_state;
}
void RATGDOComponent::received(const LightAction light_action)
{
void RATGDOComponent::received(const LightAction light_action) {
ESP_LOGD(TAG, "Light cmd=%s state=%s",
LOG_STR_ARG(LightAction_to_string(light_action)),
LOG_STR_ARG(LightState_to_string(*this->light_state)));
@@ -209,8 +196,7 @@ void RATGDOComponent::received(const LightAction light_action)
}
}
void RATGDOComponent::received(const Openings openings)
{
void RATGDOComponent::received(const Openings openings) {
if (openings.flag == 0 || *this->openings != 0) {
this->openings = openings.count;
ESP_LOGD(TAG, "Openings: %d", *this->openings);
@@ -219,8 +205,7 @@ void RATGDOComponent::received(const Openings openings)
}
}
void RATGDOComponent::schedule_door_position_sync(float update_period)
{
void RATGDOComponent::schedule_door_position_sync(float update_period) {
ESP_LOG1(
TAG,
"Schedule position sync: delta %f, start position: %f, start moving: %d",
@@ -231,7 +216,8 @@ void RATGDOComponent::schedule_door_position_sync(float update_period)
if (duration == 0) {
return;
}
this->position_sync_remaining_ = std::max(static_cast<uint16_t>(1000 * duration / update_period),
this->position_sync_remaining_ =
std::max(static_cast<uint16_t>(1000 * duration / update_period),
static_cast<uint16_t>(1));
set_interval(INTERVAL_POSITION_SYNC, static_cast<uint32_t>(update_period),
[this]() {
@@ -242,9 +228,10 @@ void RATGDOComponent::schedule_door_position_sync(float update_period)
});
}
void RATGDOComponent::door_position_update()
{
if (this->door_start_moving == 0 || this->door_start_position == DOOR_POSITION_UNKNOWN || this->door_move_delta == DOOR_DELTA_UNKNOWN) {
void RATGDOComponent::door_position_update() {
if (this->door_start_moving == 0 ||
this->door_start_position == DOOR_POSITION_UNKNOWN ||
this->door_move_delta == DOOR_DELTA_UNKNOWN) {
return;
}
auto now = millis();
@@ -253,22 +240,27 @@ void RATGDOComponent::door_position_update()
if (duration == 0) {
return;
}
auto position = this->door_start_position + (now - this->door_start_moving) / (1000 * duration);
auto position = this->door_start_position +
(now - this->door_start_moving) / (1000 * duration);
position = clamp(position, 0.0f, 1.0f);
ESP_LOG2(TAG, "[%d] Position update: %f", now, position);
this->door_position = position;
// Check if we reached our move-to-position target
if (this->target_position_ != DOOR_POSITION_UNKNOWN && this->target_direction_ != DoorAction::UNKNOWN) {
if (this->target_position_ != DOOR_POSITION_UNKNOWN &&
this->target_direction_ != DoorAction::UNKNOWN) {
bool reached = false;
if (this->target_direction_ == DoorAction::OPEN && position >= this->target_position_) {
if (this->target_direction_ == DoorAction::OPEN &&
position >= this->target_position_) {
reached = true;
} else if (this->target_direction_ == DoorAction::CLOSE && position <= this->target_position_) {
} else if (this->target_direction_ == DoorAction::CLOSE &&
position <= this->target_position_) {
reached = true;
}
if (reached) {
ESP_LOGD(TAG, "Reached target position %.2f, stopping door", this->target_position_);
ESP_LOGD(TAG, "Reached target position %.2f, stopping door",
this->target_position_);
this->door_stop();
this->target_position_ = DOOR_POSITION_UNKNOWN;
this->target_direction_ = DoorAction::UNKNOWN;
@@ -276,37 +268,27 @@ void RATGDOComponent::door_position_update()
}
}
void RATGDOComponent::set_opening_duration(float duration)
{
void RATGDOComponent::set_opening_duration(float duration) {
ESP_LOGD(TAG, "Set opening duration: %.1fs", duration);
this->opening_duration = duration;
}
void RATGDOComponent::set_closing_duration(float duration)
{
void RATGDOComponent::set_closing_duration(float duration) {
ESP_LOGD(TAG, "Set closing duration: %.1fs", duration);
this->closing_duration = duration;
}
void RATGDOComponent::set_distance_measurement(int16_t distance)
{
void RATGDOComponent::set_distance_measurement(int16_t distance) {
this->last_distance_measurement = distance;
}
void RATGDOComponent::query_status() { this->protocol_->query_status(); }
void RATGDOComponent::query_openings()
{
this->protocol_->query_openings();
}
void RATGDOComponent::query_openings() { this->protocol_->query_openings(); }
void RATGDOComponent::sync()
{
this->protocol_->sync();
}
void RATGDOComponent::sync() { this->protocol_->sync(); }
void RATGDOComponent::set_door_state_expiry()
{
void RATGDOComponent::set_door_state_expiry() {
this->set_timeout(TIMEOUT_DOOR_STATE_EXPIRY, DOOR_STATE_CALLBACK_TIMEOUT,
[this]() {
ESP_LOGW(TAG, "Door state callback expired, clearing");
@@ -314,29 +296,35 @@ void RATGDOComponent::set_door_state_expiry()
});
}
void RATGDOComponent::cancel_door_state_expiry()
{
void RATGDOComponent::cancel_door_state_expiry() {
this->cancel_timeout(TIMEOUT_DOOR_STATE_EXPIRY);
}
void RATGDOComponent::smart_door_action(DoorAction target_direction)
{
void RATGDOComponent::smart_door_action(DoorAction target_direction) {
// target_direction must be OPEN or CLOSE
if (target_direction != DoorAction::OPEN && target_direction != DoorAction::CLOSE) {
if (target_direction != DoorAction::OPEN &&
target_direction != DoorAction::CLOSE) {
return;
}
DoorState expected_state = (target_direction == DoorAction::OPEN) ? DoorState::OPENING : DoorState::CLOSING;
DoorState opposite_state = (target_direction == DoorAction::OPEN) ? DoorState::CLOSING : DoorState::OPENING;
DoorState expected_state = (target_direction == DoorAction::OPEN)
? DoorState::OPENING
: DoorState::CLOSING;
DoorState opposite_state = (target_direction == DoorAction::OPEN)
? DoorState::CLOSING
: DoorState::OPENING;
// 1. Try the discrete command first
this->door_action(target_direction);
// 2. Set a timeout to check if it worked
this->set_timeout(2000, [this, target_direction, expected_state, opposite_state]() {
this->set_timeout(
2000, [this, target_direction, expected_state, opposite_state]() {
if (*this->door_state == expected_state ||
(*this->door_state == DoorState::OPEN && target_direction == DoorAction::OPEN) ||
(*this->door_state == DoorState::CLOSED && target_direction == DoorAction::CLOSE)) {
(*this->door_state == DoorState::OPEN &&
target_direction == DoorAction::OPEN) ||
(*this->door_state == DoorState::CLOSED &&
target_direction == DoorAction::CLOSE)) {
// It worked (or is already at destination)
return;
}
@@ -348,7 +336,8 @@ void RATGDOComponent::smart_door_action(DoorAction target_direction)
this->door_action(DoorAction::TOGGLE);
// 4. Check what the toggle did
this->on_door_state([this, target_direction, expected_state, opposite_state](DoorState s) {
this->on_door_state([this, target_direction, expected_state,
opposite_state](DoorState s) {
if (s == opposite_state) {
// Wrong direction! Stop it.
ESP_LOGW(TAG, "Toggle went the wrong way. Stopping...");
@@ -366,8 +355,7 @@ void RATGDOComponent::smart_door_action(DoorAction target_direction)
});
}
void RATGDOComponent::door_open()
{
void RATGDOComponent::door_open() {
if (*this->door_state == DoorState::OPENING) {
return; // gets ignored by opener
}
@@ -379,17 +367,17 @@ void RATGDOComponent::door_open()
this->set_timeout(
TIMEOUT_DOOR_QUERY_STATE, (*this->opening_duration + 5) * 1000,
[this]() {
if (*this->door_state != DoorState::OPEN && *this->door_state != DoorState::STOPPED) {
this->received(DoorState::OPEN); // probably missed a status mesage,
// assume it's open
if (*this->door_state != DoorState::OPEN &&
*this->door_state != DoorState::STOPPED) {
this->received(DoorState::OPEN); // probably missed a status
// mesage, assume it's open
this->query_status(); // query in case we're wrong and it's stopped
}
});
}
}
void RATGDOComponent::door_close()
{
void RATGDOComponent::door_close() {
if (*this->door_state == DoorState::CLOSING) {
return; // gets ignored by opener
}
@@ -414,7 +402,8 @@ void RATGDOComponent::door_close()
this->set_timeout(
TIMEOUT_DOOR_QUERY_STATE, (*this->closing_duration + 5) * 1000,
[this]() {
if (*this->door_state != DoorState::CLOSED && *this->door_state != DoorState::STOPPED) {
if (*this->door_state != DoorState::CLOSED &&
*this->door_state != DoorState::STOPPED) {
this->received(DoorState::CLOSED); // probably missed a status
// mesage, assume it's closed
this->query_status(); // query in case we're wrong and it's stopped
@@ -423,9 +412,9 @@ void RATGDOComponent::door_close()
}
}
void RATGDOComponent::door_stop()
{
if (*this->door_state != DoorState::OPENING && *this->door_state != DoorState::CLOSING) {
void RATGDOComponent::door_stop() {
if (*this->door_state != DoorState::OPENING &&
*this->door_state != DoorState::CLOSING) {
return;
}
this->door_action(DoorAction::STOP);
@@ -433,14 +422,13 @@ void RATGDOComponent::door_stop()
void RATGDOComponent::door_toggle() { this->door_action(DoorAction::TOGGLE); }
void RATGDOComponent::door_action(DoorAction action)
{
void RATGDOComponent::door_action(DoorAction action) {
this->protocol_->door_action(action);
}
void RATGDOComponent::door_move_to_position(float position)
{
if (*this->door_state == DoorState::OPENING || *this->door_state == DoorState::CLOSING) {
void RATGDOComponent::door_move_to_position(float position) {
if (*this->door_state == DoorState::OPENING ||
*this->door_state == DoorState::CLOSING) {
this->door_action(DoorAction::STOP);
this->on_door_state([this, position](DoorState s) {
if (s == DoorState::STOPPED) {
@@ -456,7 +444,8 @@ void RATGDOComponent::door_move_to_position(float position)
return;
}
auto duration = delta > 0 ? *this->opening_duration : -*this->closing_duration;
auto duration =
delta > 0 ? *this->opening_duration : -*this->closing_duration;
if (duration == 0) {
ESP_LOGW(TAG, "I don't know duration, ignoring move to position");
return;
@@ -474,8 +463,7 @@ void RATGDOComponent::door_move_to_position(float position)
this->smart_door_action(this->target_direction_);
}
void RATGDOComponent::cancel_position_sync_callbacks()
{
void RATGDOComponent::cancel_position_sync_callbacks() {
if (this->door_start_moving != 0) {
ESP_LOGD(TAG, "Cancelling position callbacks");
this->cancel_timeout(TIMEOUT_MOVE_TO_POSITION);
@@ -487,32 +475,27 @@ void RATGDOComponent::cancel_position_sync_callbacks()
}
}
void RATGDOComponent::light_on()
{
void RATGDOComponent::light_on() {
this->light_state = LightState::ON;
this->protocol_->light_action(LightAction::ON);
}
void RATGDOComponent::light_off()
{
void RATGDOComponent::light_off() {
this->light_state = LightState::OFF;
this->protocol_->light_action(LightAction::OFF);
}
LightState RATGDOComponent::get_light_state() const
{
LightState RATGDOComponent::get_light_state() const {
return *this->light_state;
}
// Lock functions
void RATGDOComponent::lock()
{
void RATGDOComponent::lock() {
this->lock_state = LockState::LOCKED;
this->protocol_->lock_action(LockAction::LOCK);
}
void RATGDOComponent::unlock()
{
void RATGDOComponent::unlock() {
this->lock_state = LockState::UNLOCKED;
this->protocol_->lock_action(LockAction::UNLOCK);
}
+78 -76
View File
@@ -7,22 +7,22 @@
#pragma once
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/hal.h"
#include "esphome/core/preferences.h"
#include <type_traits>
#include <utility>
#include "callbacks.h"
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "esphome/core/hal.h"
#include "esphome/core/preferences.h"
#include "observable.h"
#include "ratgdo_state.h"
namespace esphome::ratgdo {
namespace secplus2 { class Secplus2; }
namespace secplus2 {
class Secplus2;
}
class RATGDOComponent;
typedef Parented<RATGDOComponent> RATGDOClient;
@@ -30,55 +30,55 @@ typedef Parented<RATGDOComponent> RATGDOClient;
const float DOOR_POSITION_UNKNOWN = -1.0;
const float DOOR_DELTA_UNKNOWN = -2.0;
class RATGDOComponent : public Component {
public:
RATGDOComponent()
{
}
public:
RATGDOComponent() {}
void setup() override;
void loop() override;
void dump_config() override;
void on_shutdown() override;
float get_setup_priority() const override { return setup_priority::AFTER_WIFI; }
float get_setup_priority() const override {
return setup_priority::AFTER_WIFI;
}
void init_protocol();
float start_opening { -1 };
single_observable<float> opening_duration { 0 };
float start_closing { -1 };
single_observable<float> closing_duration { 0 };
float start_opening{-1};
single_observable<float> opening_duration{0};
float start_closing{-1};
single_observable<float> closing_duration{0};
observable<int16_t, RATGDO_MAX_DISTANCE_SUBSCRIBERS> last_distance_measurement { 0 };
observable<int16_t, RATGDO_MAX_DISTANCE_SUBSCRIBERS>
last_distance_measurement{0};
single_observable<uint16_t> openings { 0 }; // number of times the door has been opened
single_observable<uint16_t> openings{
0}; // number of times the door has been opened
observable<DoorState, RATGDO_MAX_DOOR_STATE_SUBSCRIBERS> door_state { DoorState::UNKNOWN };
observable<float, RATGDO_MAX_DOOR_STATE_SUBSCRIBERS> door_position { DOOR_POSITION_UNKNOWN };
observable<DoorState, RATGDO_MAX_DOOR_STATE_SUBSCRIBERS> door_state{
DoorState::UNKNOWN};
observable<float, RATGDO_MAX_DOOR_STATE_SUBSCRIBERS> door_position{
DOOR_POSITION_UNKNOWN};
unsigned long door_start_moving { 0 };
float door_start_position { DOOR_POSITION_UNKNOWN };
float door_move_delta { DOOR_DELTA_UNKNOWN };
uint16_t position_sync_remaining_ { 0 };
float target_position_ { DOOR_POSITION_UNKNOWN };
DoorAction target_direction_ { DoorAction::UNKNOWN };
unsigned long door_start_moving{0};
float door_start_position{DOOR_POSITION_UNKNOWN};
float door_move_delta{DOOR_DELTA_UNKNOWN};
uint16_t position_sync_remaining_{0};
float target_position_{DOOR_POSITION_UNKNOWN};
DoorAction target_direction_{DoorAction::UNKNOWN};
single_observable<LightState> light_state { LightState::UNKNOWN };
single_observable<LockState> lock_state { LockState::UNKNOWN };
single_observable<LightState> light_state{LightState::UNKNOWN};
single_observable<LockState> lock_state{LockState::UNKNOWN};
OnceCallbacks<void(DoorState)> on_door_state_;
single_observable<bool> synced { false };
single_observable<optional<bool>> sync_failed { nullopt };
single_observable<bool> synced{false};
single_observable<optional<bool>> sync_failed{nullopt};
void set_output_gdo_pin(InternalGPIOPin* pin) { this->output_gdo_pin_ = pin; }
void set_input_gdo_pin(InternalGPIOPin* pin) { this->input_gdo_pin_ = pin; }
void received(const DoorState door_state);
void received(const LightState light_state);
void received(const LockState lock_state);
@@ -94,7 +94,9 @@ public:
void door_action(DoorAction action);
void smart_door_action(DoorAction target_direction);
void door_move_to_position(float position);
void set_door_position(float door_position) { this->door_position = door_position; }
void set_door_position(float door_position) {
this->door_position = door_position;
}
void set_opening_duration(float duration);
void set_closing_duration(float duration);
void schedule_door_position_sync(float update_period = 500);
@@ -145,10 +147,10 @@ public:
// meaning no new callback was queued — otherwise we'd cancel
// expiry B here and leave the inner callback without protection.
template <typename F>
void on_door_state(F&& callback)
{
void on_door_state(F&& callback) {
using Cb = std::decay_t<F>;
this->on_door_state_([this, cb = Cb(std::forward<F>(callback))](DoorState s) {
this->on_door_state_(
[this, cb = Cb(std::forward<F>(callback))](DoorState s) {
cb(s);
if (!this->on_door_state_.count()) {
this->cancel_door_state_expiry();
@@ -178,7 +180,7 @@ public:
template <typename F>
void subscribe_distance_measurement(F&& f);
protected:
protected:
// Pointers first (4-byte aligned)
secplus2::Secplus2* protocol_;
InternalGPIOPin* output_gdo_pin_;
@@ -187,24 +189,26 @@ protected:
// Bool members packed into bitfield
struct {
uint8_t reserved : 8; // Reserved for future use
} flags_ { 0 };
} flags_{0};
// Subscriber counters for defer name allocation
uint8_t door_state_sub_num_ { 0 };
uint8_t distance_sub_num_ { 0 };
uint8_t door_state_sub_num_{0};
uint8_t distance_sub_num_{0};
}; // RATGDOComponent
void log_subscriber_overflow(const LogString* observable_name, uint32_t max);
inline uint32_t get_scheduler_id(uint32_t base, uint32_t count, uint8_t& counter, const LogString* observable_name)
{
inline uint32_t get_scheduler_id(uint32_t base, uint32_t count,
uint8_t& counter,
const LogString* observable_name) {
if (count == 0) {
log_subscriber_overflow(observable_name, count);
return base;
}
if (counter >= count) {
log_subscriber_overflow(observable_name, count);
return base + count - 1; // reuse last ID to avoid collision with first subscriber
return base + count -
1; // reuse last ID to avoid collision with first subscriber
}
return base + counter++;
}
@@ -212,18 +216,22 @@ inline uint32_t get_scheduler_id(uint32_t base, uint32_t count, uint8_t& counter
// Scheduler IDs using uint32_t ranges to avoid heap allocations
// Bases are auto-generated from counts to prevent ID conflicts
namespace scheduler_ids {
inline constexpr uint32_t INTERVAL_POSITION_SYNC = 0;
inline constexpr uint32_t INTERVAL_POSITION_SYNC = 0;
// Multi-subscriber ranges — counts derived from codegen defines
inline constexpr uint32_t DEFER_DOOR_STATE_COUNT = RATGDO_MAX_DOOR_STATE_SUBSCRIBERS;
inline constexpr uint32_t DEFER_DOOR_STATE_BASE = INTERVAL_POSITION_SYNC + 1;
// Multi-subscriber ranges — counts derived from codegen defines
inline constexpr uint32_t DEFER_DOOR_STATE_COUNT =
RATGDO_MAX_DOOR_STATE_SUBSCRIBERS;
inline constexpr uint32_t DEFER_DOOR_STATE_BASE = INTERVAL_POSITION_SYNC + 1;
inline constexpr uint32_t DEFER_DISTANCE_COUNT = RATGDO_MAX_DISTANCE_SUBSCRIBERS;
inline constexpr uint32_t DEFER_DISTANCE_BASE = DEFER_DOOR_STATE_BASE + DEFER_DOOR_STATE_COUNT;
inline constexpr uint32_t DEFER_DISTANCE_END = DEFER_DISTANCE_BASE + DEFER_DISTANCE_COUNT;
inline constexpr uint32_t DEFER_DISTANCE_COUNT =
RATGDO_MAX_DISTANCE_SUBSCRIBERS;
inline constexpr uint32_t DEFER_DISTANCE_BASE =
DEFER_DOOR_STATE_BASE + DEFER_DOOR_STATE_COUNT;
inline constexpr uint32_t DEFER_DISTANCE_END =
DEFER_DISTANCE_BASE + DEFER_DISTANCE_COUNT;
// Single-subscriber IDs
enum : uint32_t {
// Single-subscriber IDs
enum : uint32_t {
DEFER_OPENING_DURATION = DEFER_DISTANCE_END,
DEFER_CLOSING_DURATION,
DEFER_OPENINGS,
@@ -236,7 +244,7 @@ namespace scheduler_ids {
TIMEOUT_MOVE_TO_POSITION,
TIMEOUT_DOOR_STATE_EXPIRY,
TIMEOUT_SYNC,
};
};
} // namespace scheduler_ids
// Template implementations for subscribe methods.
@@ -245,33 +253,31 @@ namespace scheduler_ids {
// is dispatched to the child component.
template <typename F>
void RATGDOComponent::subscribe_opening_duration(F&& f)
{
void RATGDOComponent::subscribe_opening_duration(F&& f) {
this->opening_duration.subscribe([this, f](float state) {
defer(scheduler_ids::DEFER_OPENING_DURATION, [f, state] { f(state); });
});
}
template <typename F>
void RATGDOComponent::subscribe_closing_duration(F&& f)
{
void RATGDOComponent::subscribe_closing_duration(F&& f) {
this->closing_duration.subscribe([this, f](float state) {
defer(scheduler_ids::DEFER_CLOSING_DURATION, [f, state] { f(state); });
});
}
template <typename F>
void RATGDOComponent::subscribe_openings(F&& f)
{
void RATGDOComponent::subscribe_openings(F&& f) {
this->openings.subscribe([this, f](uint16_t state) {
defer(scheduler_ids::DEFER_OPENINGS, [f, state] { f(state); });
});
}
template <typename F>
void RATGDOComponent::subscribe_door_state(F&& f)
{
uint32_t id = get_scheduler_id(scheduler_ids::DEFER_DOOR_STATE_BASE, scheduler_ids::DEFER_DOOR_STATE_COUNT,
void RATGDOComponent::subscribe_door_state(F&& f) {
uint32_t id =
get_scheduler_id(scheduler_ids::DEFER_DOOR_STATE_BASE,
scheduler_ids::DEFER_DOOR_STATE_COUNT,
this->door_state_sub_num_, LOG_STR("door_state"));
this->door_state.subscribe([this, f, id](DoorState state) {
defer(id, [this, f, state] { f(state, *this->door_position); });
@@ -282,35 +288,31 @@ void RATGDOComponent::subscribe_door_state(F&& f)
}
template <typename F>
void RATGDOComponent::subscribe_light_state(F&& f)
{
void RATGDOComponent::subscribe_light_state(F&& f) {
this->light_state.subscribe([this, f](LightState state) {
defer(scheduler_ids::DEFER_LIGHT_STATE, [f, state] { f(state); });
});
}
template <typename F>
void RATGDOComponent::subscribe_lock_state(F&& f)
{
void RATGDOComponent::subscribe_lock_state(F&& f) {
this->lock_state.subscribe([this, f](LockState state) {
defer(scheduler_ids::DEFER_LOCK_STATE, [f, state] { f(state); });
});
}
template <typename F>
void RATGDOComponent::subscribe_sync_failed(F&& f)
{
void RATGDOComponent::subscribe_sync_failed(F&& f) {
this->sync_failed.subscribe(std::forward<F>(f));
}
template <typename F>
void RATGDOComponent::subscribe_distance_measurement(F&& f)
{
uint32_t id = get_scheduler_id(scheduler_ids::DEFER_DISTANCE_BASE, scheduler_ids::DEFER_DISTANCE_COUNT,
void RATGDOComponent::subscribe_distance_measurement(F&& f) {
uint32_t id = get_scheduler_id(
scheduler_ids::DEFER_DISTANCE_BASE, scheduler_ids::DEFER_DISTANCE_COUNT,
this->distance_sub_num_, LOG_STR("distance_measurement"));
this->last_distance_measurement.subscribe([this, f, id](int16_t state) {
defer(id, [f, state] { f(state); });
});
this->last_distance_measurement.subscribe(
[this, f, id](int16_t state) { defer(id, [f, state] { f(state); }); });
}
} // namespace esphome::ratgdo
+1 -2
View File
@@ -2,8 +2,7 @@
namespace esphome::ratgdo {
LightState light_state_toggle(LightState state)
{
LightState light_state_toggle(LightState state) {
switch (state) {
case LightState::OFF:
return LightState::ON;
+38 -34
View File
@@ -6,9 +6,10 @@
************************************/
#pragma once
#include "esphome/core/defines.h"
#include <cstdint>
#include "esphome/core/defines.h"
namespace esphome::ratgdo {
enum class DoorState : uint8_t {
@@ -21,40 +22,38 @@ enum class DoorState : uint8_t {
};
inline const char* DoorState_to_string(DoorState e) {
static const char* const names[] = {"UNKNOWN", "OPEN", "CLOSED", "STOPPED", "OPENING", "CLOSING"};
static const char* const names[] = {"UNKNOWN", "OPEN", "CLOSED",
"STOPPED", "OPENING", "CLOSING"};
auto i = static_cast<uint8_t>(e);
return (i <= static_cast<uint8_t>(DoorState::CLOSING)) ? names[i] : "UNKNOWN";
}
inline DoorState to_DoorState(uint8_t t, DoorState unknown) {
return (t <= static_cast<uint8_t>(DoorState::CLOSING)) ? static_cast<DoorState>(t) : unknown;
return (t <= static_cast<uint8_t>(DoorState::CLOSING))
? static_cast<DoorState>(t)
: unknown;
}
/// Enum for all states a the light can be in.
enum class LightState : uint8_t {
OFF = 0,
ON = 1,
UNKNOWN = 2
};
enum class LightState : uint8_t { OFF = 0, ON = 1, UNKNOWN = 2 };
inline const char* LightState_to_string(LightState e) {
static const char* const names[] = {"OFF", "ON", "UNKNOWN"};
auto i = static_cast<uint8_t>(e);
return (i <= static_cast<uint8_t>(LightState::UNKNOWN)) ? names[i] : "UNKNOWN";
return (i <= static_cast<uint8_t>(LightState::UNKNOWN)) ? names[i]
: "UNKNOWN";
}
inline LightState to_LightState(uint8_t t, LightState unknown) {
return (t <= static_cast<uint8_t>(LightState::UNKNOWN)) ? static_cast<LightState>(t) : unknown;
return (t <= static_cast<uint8_t>(LightState::UNKNOWN))
? static_cast<LightState>(t)
: unknown;
}
LightState light_state_toggle(LightState state);
/// Enum for all states a the lock can be in.
enum class LockState : uint8_t {
UNLOCKED = 0,
LOCKED = 1,
UNKNOWN = 2
};
enum class LockState : uint8_t { UNLOCKED = 0, LOCKED = 1, UNKNOWN = 2 };
inline const char* LockState_to_string(LockState e) {
static const char* const names[] = {"UNLOCKED", "LOCKED", "UNKNOWN"};
@@ -63,41 +62,42 @@ inline const char* LockState_to_string(LockState e) {
}
inline LockState to_LockState(uint8_t t, LockState unknown) {
return (t <= static_cast<uint8_t>(LockState::UNKNOWN)) ? static_cast<LockState>(t) : unknown;
return (t <= static_cast<uint8_t>(LockState::UNKNOWN))
? static_cast<LockState>(t)
: unknown;
}
// actions
enum class LightAction : uint8_t {
OFF = 0,
ON = 1,
TOGGLE = 2,
UNKNOWN = 3
};
enum class LightAction : uint8_t { OFF = 0, ON = 1, TOGGLE = 2, UNKNOWN = 3 };
inline const char* LightAction_to_string(LightAction e) {
static const char* const names[] = {"OFF", "ON", "TOGGLE", "UNKNOWN"};
auto i = static_cast<uint8_t>(e);
return (i <= static_cast<uint8_t>(LightAction::UNKNOWN)) ? names[i] : "UNKNOWN";
return (i <= static_cast<uint8_t>(LightAction::UNKNOWN)) ? names[i]
: "UNKNOWN";
}
inline LightAction to_LightAction(uint8_t t, LightAction unknown) {
return (t <= static_cast<uint8_t>(LightAction::UNKNOWN)) ? static_cast<LightAction>(t) : unknown;
return (t <= static_cast<uint8_t>(LightAction::UNKNOWN))
? static_cast<LightAction>(t)
: unknown;
}
enum class LockAction : uint8_t {
UNLOCK = 0,
LOCK = 1,
UNKNOWN = 3
};
enum class LockAction : uint8_t { UNLOCK = 0, LOCK = 1, UNKNOWN = 3 };
inline const char* LockAction_to_string(LockAction e) {
static const char* const names[] = {"UNLOCK", "LOCK", "UNKNOWN", "UNKNOWN"};
auto i = static_cast<uint8_t>(e);
return (i <= static_cast<uint8_t>(LockAction::UNKNOWN)) ? names[i] : "UNKNOWN";
return (i <= static_cast<uint8_t>(LockAction::UNKNOWN)) ? names[i]
: "UNKNOWN";
}
inline LockAction to_LockAction(uint8_t t, LockAction unknown) {
return (t == static_cast<uint8_t>(LockAction::UNLOCK) || t == static_cast<uint8_t>(LockAction::LOCK) || t == static_cast<uint8_t>(LockAction::UNKNOWN)) ? static_cast<LockAction>(t) : unknown;
return (t == static_cast<uint8_t>(LockAction::UNLOCK) ||
t == static_cast<uint8_t>(LockAction::LOCK) ||
t == static_cast<uint8_t>(LockAction::UNKNOWN))
? static_cast<LockAction>(t)
: unknown;
}
enum class DoorAction : uint8_t {
@@ -109,13 +109,17 @@ enum class DoorAction : uint8_t {
};
inline const char* DoorAction_to_string(DoorAction e) {
static const char* const names[] = {"CLOSE", "OPEN", "TOGGLE", "STOP", "UNKNOWN"};
static const char* const names[] = {"CLOSE", "OPEN", "TOGGLE", "STOP",
"UNKNOWN"};
auto i = static_cast<uint8_t>(e);
return (i <= static_cast<uint8_t>(DoorAction::UNKNOWN)) ? names[i] : "UNKNOWN";
return (i <= static_cast<uint8_t>(DoorAction::UNKNOWN)) ? names[i]
: "UNKNOWN";
}
inline DoorAction to_DoorAction(uint8_t t, DoorAction unknown) {
return (t <= static_cast<uint8_t>(DoorAction::UNKNOWN)) ? static_cast<DoorAction>(t) : unknown;
return (t <= static_cast<uint8_t>(DoorAction::UNKNOWN))
? static_cast<DoorAction>(t)
: unknown;
}
struct Openings {
+33 -39
View File
@@ -1,17 +1,16 @@
#include "ratgdo_uart_esp32.h"
#include "esphome/core/log.h"
#include <driver/uart.h>
#include <driver/rmt_tx.h>
#include <esp_private/rmt.h> // for rmt_get_channel_id (used once during init)
#include <driver/gpio.h>
#include <driver/rmt_tx.h>
#include <driver/uart.h>
#include <esp_private/rmt.h> // for rmt_get_channel_id (used once during init)
#include <esp_rom_gpio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <soc/gpio_sig_map.h>
#include "esphome/core/log.h"
namespace esphome::ratgdo {
static const char* const TAG = "ratgdo_uart";
@@ -32,10 +31,9 @@ static constexpr size_t RMT_TRANS_QUEUE_DEPTH = 4;
static constexpr int UART_PORT = UART_NUM_1;
static constexpr int UART_TX_SIGNAL_IDX = U1TXD_OUT_IDX;
RatgdoUART::RatgdoUART() { }
RatgdoUART::RatgdoUART() {}
RatgdoUART::~RatgdoUART()
{
RatgdoUART::~RatgdoUART() {
if (this->is_initialized_) {
uart_driver_delete((uart_port_t)this->uart_num_);
if (this->rmt_copy_encoder_) {
@@ -51,8 +49,7 @@ RatgdoUART::~RatgdoUART()
}
void RatgdoUART::begin(int baud, RatgdoUARTConfig config, int rx_pin,
int tx_pin, bool invert)
{
int tx_pin, bool invert) {
this->tx_pin_ = tx_pin;
this->rx_pin_ = rx_pin;
this->baud_ = baud;
@@ -60,19 +57,21 @@ void RatgdoUART::begin(int baud, RatgdoUARTConfig config, int rx_pin,
this->uart_num_ = UART_PORT;
uart_config_t uart_config = { };
uart_config_t uart_config = {};
uart_config.baud_rate = baud;
uart_config.data_bits = UART_DATA_8_BITS;
uart_config.parity = (config == RATGDO_UART_8E1) ? UART_PARITY_EVEN : UART_PARITY_DISABLE;
uart_config.parity =
(config == RATGDO_UART_8E1) ? UART_PARITY_EVEN : UART_PARITY_DISABLE;
uart_config.stop_bits = UART_STOP_BITS_1;
uart_config.flow_ctrl = UART_HW_FLOWCTRL_DISABLE;
uart_config.source_clk = UART_SCLK_APB;
ESP_ERROR_CHECK(uart_driver_install((uart_port_t)this->uart_num_,
UART_RX_BUFFER_SIZE, 0, 0, NULL, 0));
ESP_ERROR_CHECK(
uart_driver_install((uart_port_t)this->uart_num_, UART_RX_BUFFER_SIZE, 0, 0, NULL, 0));
ESP_ERROR_CHECK(uart_param_config((uart_port_t)this->uart_num_, &uart_config));
uart_param_config((uart_port_t)this->uart_num_, &uart_config));
rmt_tx_channel_config_t tx_chan_config = { };
rmt_tx_channel_config_t tx_chan_config = {};
tx_chan_config.gpio_num = (gpio_num_t)tx_pin;
tx_chan_config.clk_src = RMT_CLK_SRC_DEFAULT;
tx_chan_config.resolution_hz = RMT_RESOLUTION_HZ;
@@ -81,7 +80,7 @@ void RatgdoUART::begin(int baud, RatgdoUARTConfig config, int rx_pin,
tx_chan_config.flags.invert_out = 0;
ESP_ERROR_CHECK(rmt_new_tx_channel(&tx_chan_config, &this->rmt_chan_handle_));
rmt_copy_encoder_config_t copy_encoder_config = { };
rmt_copy_encoder_config_t copy_encoder_config = {};
ESP_ERROR_CHECK(
rmt_new_copy_encoder(&copy_encoder_config, &this->rmt_copy_encoder_));
@@ -90,7 +89,8 @@ void RatgdoUART::begin(int baud, RatgdoUARTConfig config, int rx_pin,
// Cache the channel ID for GPIO matrix switching during preamble.
// The RMT driver allocates channels dynamically, so we query it once
// here rather than relying on the private esp_private/rmt.h API at runtime.
ESP_ERROR_CHECK(rmt_get_channel_id(this->rmt_chan_handle_, &this->rmt_channel_id_));
ESP_ERROR_CHECK(
rmt_get_channel_id(this->rmt_chan_handle_, &this->rmt_channel_id_));
ESP_ERROR_CHECK(uart_set_pin((uart_port_t)this->uart_num_, tx_pin, rx_pin,
UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
@@ -105,14 +105,12 @@ void RatgdoUART::begin(int baud, RatgdoUARTConfig config, int rx_pin,
rx_pin);
}
void RatgdoUART::transmit_secplus2_preamble()
{
if (!this->is_initialized_)
return;
void RatgdoUART::transmit_secplus2_preamble() {
if (!this->is_initialized_) return;
// Switch GPIO matrix from UART TX to RMT output
esp_rom_gpio_connect_out_signal(this->tx_pin_, RMT_SIG_OUT0_IDX + this->rmt_channel_id_,
false, false);
esp_rom_gpio_connect_out_signal(
this->tx_pin_, RMT_SIG_OUT0_IDX + this->rmt_channel_id_, false, false);
esp_rom_delay_us(SIGNAL_SETTLE_US);
@@ -127,19 +125,19 @@ void RatgdoUART::transmit_secplus2_preamble()
symbols[0].duration1 = PREAMBLE_MARK_US;
symbols[0].level1 = 0;
rmt_transmit_config_t transmit_config = { };
rmt_transmit_config_t transmit_config = {};
transmit_config.loop_count = 0;
rmt_transmit(this->rmt_chan_handle_, this->rmt_copy_encoder_, symbols,
sizeof(symbols), &transmit_config);
rmt_tx_wait_all_done(this->rmt_chan_handle_, -1);
// Switch GPIO matrix back to UART TX
esp_rom_gpio_connect_out_signal(this->tx_pin_, UART_TX_SIGNAL_IDX, false, false);
esp_rom_gpio_connect_out_signal(this->tx_pin_, UART_TX_SIGNAL_IDX, false,
false);
esp_rom_delay_us(SIGNAL_SETTLE_US);
}
void RatgdoUART::write(const uint8_t* data, size_t len)
{
void RatgdoUART::write(const uint8_t* data, size_t len) {
if (this->is_initialized_) {
uart_write_bytes((uart_port_t)this->uart_num_, (const char*)data, len);
uart_wait_tx_done((uart_port_t)this->uart_num_, portMAX_DELAY);
@@ -148,19 +146,15 @@ void RatgdoUART::write(const uint8_t* data, size_t len)
void RatgdoUART::write(uint8_t data) { write(&data, 1); }
int RatgdoUART::available()
{
if (!this->is_initialized_)
return 0;
int RatgdoUART::available() {
if (!this->is_initialized_) return 0;
size_t length = 0;
uart_get_buffered_data_len((uart_port_t)this->uart_num_, &length);
return length;
}
int RatgdoUART::read()
{
if (!this->is_initialized_)
return -1;
int RatgdoUART::read() {
if (!this->is_initialized_) return -1;
uint8_t data = 0;
int len = uart_read_bytes((uart_port_t)this->uart_num_, &data, 1, 0);
if (len > 0) {
@@ -169,12 +163,12 @@ int RatgdoUART::read()
return -1;
}
void RatgdoUART::on_shutdown()
{
void RatgdoUART::on_shutdown() {
if (this->is_initialized_) {
// Unmap the matrix output signal so that UART peripheral resets do not
// pull the hardware line dominant.
esp_rom_gpio_connect_out_signal(this->tx_pin_, SIG_GPIO_OUT_IDX, false, false);
esp_rom_gpio_connect_out_signal(this->tx_pin_, SIG_GPIO_OUT_IDX, false,
false);
gpio_set_direction((gpio_num_t)this->tx_pin_, GPIO_MODE_INPUT);
gpio_set_direction((gpio_num_t)this->rx_pin_, GPIO_MODE_INPUT);
}
+15 -15
View File
@@ -1,11 +1,11 @@
#pragma once
#include "esphome/core/defines.h"
#include <driver/rmt_tx.h>
#include <stddef.h>
#include <stdint.h>
#include "esphome/core/defines.h"
namespace esphome::ratgdo {
enum RatgdoUARTConfig {
@@ -14,7 +14,7 @@ enum RatgdoUARTConfig {
};
class RatgdoUART {
public:
public:
RatgdoUART();
~RatgdoUART();
@@ -24,8 +24,8 @@ public:
void write(uint8_t data);
int available();
int read();
void enableIntTx(bool enable) { }
void enableAutoBaud(bool enable) { }
void enableIntTx(bool enable) {}
void enableAutoBaud(bool enable) {}
int baudRate() { return this->baud_; }
// Sends the SecPlus 2.0 preamble using RMT
@@ -33,21 +33,21 @@ public:
void on_shutdown();
private:
private:
// Pointers (4 bytes on 32-bit)
rmt_channel_handle_t rmt_chan_handle_ { nullptr };
rmt_encoder_handle_t rmt_copy_encoder_ { nullptr };
rmt_channel_handle_t rmt_chan_handle_{nullptr};
rmt_encoder_handle_t rmt_copy_encoder_{nullptr};
// 4-byte members
int tx_pin_ { -1 };
int rx_pin_ { -1 };
int baud_ { 9600 };
int uart_num_ { -1 };
int rmt_channel_id_ { 0 };
int tx_pin_{-1};
int rx_pin_{-1};
int baud_{9600};
int uart_num_{-1};
int rmt_channel_id_{0};
// 1-byte members packed at the end
bool inverted_ { true };
bool is_initialized_ { false };
bool inverted_{true};
bool is_initialized_{false};
};
} // namespace esphome::ratgdo
+145 -127
View File
@@ -1,11 +1,11 @@
#include "secplus2.h"
#include "ratgdo.h"
#include "esphome/core/gpio.h"
#include "esphome/core/helpers.h"
#include "esphome/core/log.h"
#include "esphome/core/scheduler.h"
#include "ratgdo.h"
extern "C" {
#include "secplus.h"
@@ -14,49 +14,57 @@ extern "C" {
namespace esphome::ratgdo {
namespace secplus2 {
using namespace scheduler_ids;
using namespace scheduler_ids;
// MAX_CODES_WITHOUT_FLASH_WRITE is a bit of a guess
// since we write the flash at most every every 1min
//
// We want the rolling counter to be high enough that the
// GDO will accept the command after an unexpected reboot
// that did not save the counter to flash in time which
// results in the rolling counter being behind what the GDO
// expects.
static const uint8_t MAX_CODES_WITHOUT_FLASH_WRITE = 60;
// MAX_CODES_WITHOUT_FLASH_WRITE is a bit of a guess
// since we write the flash at most every every 1min
//
// We want the rolling counter to be high enough that the
// GDO will accept the command after an unexpected reboot
// that did not save the counter to flash in time which
// results in the rolling counter being behind what the GDO
// expects.
static const uint8_t MAX_CODES_WITHOUT_FLASH_WRITE = 60;
static const char* const TAG = "ratgdo_secplus2";
static const char* const TAG = "ratgdo_secplus2";
void Secplus2::setup(RATGDOComponent* ratgdo, Scheduler* scheduler, InternalGPIOPin* rx_pin, InternalGPIOPin* tx_pin)
{
void Secplus2::setup(RATGDOComponent* ratgdo, Scheduler* scheduler,
InternalGPIOPin* rx_pin, InternalGPIOPin* tx_pin) {
this->ratgdo_ = ratgdo;
this->scheduler_ = scheduler;
this->tx_pin_ = tx_pin;
this->rx_pin_ = rx_pin;
if (mqtt::global_mqtt_client != nullptr) {
this->mqtt_rolling_code_topic_ = mqtt::global_mqtt_client->get_topic_prefix() + "/gdo/rolling_code";
this->mqtt_client_id_topic_ = mqtt::global_mqtt_client->get_topic_prefix() + "/gdo/client_id";
this->mqtt_rolling_code_topic_ =
mqtt::global_mqtt_client->get_topic_prefix() + "/gdo/rolling_code";
this->mqtt_client_id_topic_ =
mqtt::global_mqtt_client->get_topic_prefix() + "/gdo/client_id";
}
this->client_id_pref_ = global_preferences->make_preference<uint32_t>(3497851610U); // fnv1_hash("ratgdo_client_id")
this->client_id_pref_ = global_preferences->make_preference<uint32_t>(
3497851610U); // fnv1_hash("ratgdo_client_id")
uint32_t stored_client_id;
if (this->client_id_pref_.load(&stored_client_id)) {
this->client_id_ = stored_client_id;
ESP_LOGI(TAG, "Restored Client ID from flash: 0x%04X", (unsigned)this->client_id_);
ESP_LOGI(TAG, "Restored Client ID from flash: 0x%04X",
(unsigned)this->client_id_);
if (mqtt::global_mqtt_client != nullptr) {
mqtt::global_mqtt_client->publish(this->mqtt_client_id_topic_, std::to_string(this->client_id_), 0, true);
mqtt::global_mqtt_client->publish(this->mqtt_client_id_topic_,
std::to_string(this->client_id_), 0,
true);
}
} else if (mqtt::global_mqtt_client != nullptr) {
ESP_LOGI(TAG, "No Client ID in flash, waiting for MQTT: %s", this->mqtt_client_id_topic_.c_str());
ESP_LOGI(TAG, "No Client ID in flash, waiting for MQTT: %s",
this->mqtt_client_id_topic_.c_str());
mqtt::global_mqtt_client->subscribe(
this->mqtt_client_id_topic_,
[this](const std::string& topic, const std::string& payload) {
if (this->client_id_ == 0x539) {
uint32_t cid = strtoul(payload.c_str(), nullptr, 10);
if (cid != 0) {
ESP_LOGI(TAG, "Received Client ID from MQTT: 0x%04X", (unsigned)cid);
ESP_LOGI(TAG, "Received Client ID from MQTT: 0x%04X",
(unsigned)cid);
this->set_client_id(cid);
}
}
@@ -71,16 +79,19 @@ namespace secplus2 {
ESP_LOGI(TAG, "Generated new unique Client ID: 0x%04X", (unsigned)new_id);
}
this->rolling_code_pref_ = global_preferences->make_preference<uint32_t>(1868352652U); // fnv1_hash("ratgdo_rolling_code")
this->rolling_code_pref_ = global_preferences->make_preference<uint32_t>(
1868352652U); // fnv1_hash("ratgdo_rolling_code")
uint32_t rolling_code;
if (this->rolling_code_pref_.load(&rolling_code)) {
this->rolling_code_counter_ = rolling_code;
ESP_LOGI(TAG, "Restored rolling code from flash: %u", rolling_code);
if (mqtt::global_mqtt_client != nullptr) {
mqtt::global_mqtt_client->publish(this->mqtt_rolling_code_topic_, std::to_string(rolling_code), 0, true);
mqtt::global_mqtt_client->publish(this->mqtt_rolling_code_topic_,
std::to_string(rolling_code), 0, true);
}
} else if (mqtt::global_mqtt_client != nullptr) {
ESP_LOGI(TAG, "No rolling code in flash, waiting for MQTT: %s", this->mqtt_rolling_code_topic_.c_str());
ESP_LOGI(TAG, "No rolling code in flash, waiting for MQTT: %s",
this->mqtt_rolling_code_topic_.c_str());
mqtt::global_mqtt_client->subscribe(
this->mqtt_rolling_code_topic_,
[this](const std::string& topic, const std::string& payload) {
@@ -99,13 +110,13 @@ namespace secplus2 {
this->rolling_code_pref_.save(&rolling_code);
}
this->uart_.begin(9600, RATGDO_UART_8N1, rx_pin->get_pin(), tx_pin->get_pin(), true);
this->uart_.begin(9600, RATGDO_UART_8N1, rx_pin->get_pin(), tx_pin->get_pin(),
true);
this->uart_.enableIntTx(false);
this->uart_.enableAutoBaud(true);
}
}
void Secplus2::loop()
{
void Secplus2::loop() {
if (this->flags_.transmit_pending) {
if (!this->transmit_packet()) {
return;
@@ -116,22 +127,18 @@ namespace secplus2 {
if (cmd) {
this->handle_command(*cmd);
}
}
}
void Secplus2::dump_config()
{
ESP_LOGCONFIG(TAG, " Rolling Code Counter: %d", *this->rolling_code_counter_);
void Secplus2::dump_config() {
ESP_LOGCONFIG(TAG, " Rolling Code Counter: %d",
*this->rolling_code_counter_);
ESP_LOGCONFIG(TAG, " Client ID: %d", this->client_id_);
ESP_LOGCONFIG(TAG, " Protocol: SEC+ v2");
}
}
void Secplus2::on_shutdown()
{
this->uart_.on_shutdown();
}
void Secplus2::on_shutdown() { this->uart_.on_shutdown(); }
void Secplus2::sync_helper(uint32_t start, uint32_t delay, uint8_t tries)
{
void Secplus2::sync_helper(uint32_t start, uint32_t delay, uint8_t tries) {
if (tries == 0 || *this->ratgdo_->door_state == DoorState::UNKNOWN) {
ESP_LOGD(TAG, "Sync: querying status (attempt %d)...", tries);
this->query_status();
@@ -151,69 +158,63 @@ namespace secplus2 {
this->ratgdo_->synced = false;
this->ratgdo_->sync_failed = true;
} else {
// Use a slightly longer delay between queries during sync to avoid bus saturation
// Use a slightly longer delay between queries during sync to avoid bus
// saturation
uint32_t next_delay = (tries < 5) ? 1000 : 2000;
this->scheduler_->set_timeout(this->ratgdo_, TIMEOUT_SYNC, next_delay, [this, start, next_delay, tries]() {
this->sync_helper(start, next_delay, tries + 1);
this->scheduler_->set_timeout(this->ratgdo_, TIMEOUT_SYNC, next_delay,
[this, start, next_delay, tries]() {
this->sync_helper(start, next_delay,
tries + 1);
});
};
}
}
void Secplus2::sync()
{
void Secplus2::sync() {
ESP_LOGD(TAG, "Starting sync...");
this->ratgdo_->synced = false;
this->scheduler_->cancel_timeout(this->ratgdo_, TIMEOUT_SYNC);
this->sync_helper(millis(), 500, 0);
}
}
void Secplus2::light_action(LightAction action)
{
void Secplus2::light_action(LightAction action) {
if (action == LightAction::UNKNOWN) {
return;
}
this->send_command(Command(CommandType::LIGHT, static_cast<uint8_t>(action)));
}
}
void Secplus2::lock_action(LockAction action)
{
void Secplus2::lock_action(LockAction action) {
if (action == LockAction::UNKNOWN) {
return;
}
this->send_command(Command(CommandType::LOCK, static_cast<uint8_t>(action)));
}
}
void Secplus2::door_action(DoorAction action)
{
void Secplus2::door_action(DoorAction action) {
if (action == DoorAction::UNKNOWN) {
return;
}
this->door_command(action);
}
}
void Secplus2::door_command(DoorAction action)
{
this->send_command(Command(CommandType::DOOR_ACTION, static_cast<uint8_t>(action), 1, 1), IncrementRollingCode::NO, [this, action]() {
void Secplus2::door_command(DoorAction action) {
this->send_command(
Command(CommandType::DOOR_ACTION, static_cast<uint8_t>(action), 1, 1),
IncrementRollingCode::NO, [this, action]() {
this->ratgdo_->set_timeout(150, [this, action] {
this->send_command(Command(CommandType::DOOR_ACTION, static_cast<uint8_t>(action), 0, 1));
this->send_command(Command(CommandType::DOOR_ACTION,
static_cast<uint8_t>(action), 0, 1));
});
});
}
}
void Secplus2::query_status()
{
this->send_command(CommandType::GET_STATUS);
}
void Secplus2::query_status() { this->send_command(CommandType::GET_STATUS); }
void Secplus2::query_openings()
{
void Secplus2::query_openings() {
this->send_command(CommandType::GET_OPENINGS);
}
}
optional<Command> Secplus2::read_command()
{
optional<Command> Secplus2::read_command() {
while (this->uart_.available()) {
uint8_t ser_byte = this->uart_.read();
this->rx_last_read_ = millis();
@@ -241,7 +242,8 @@ namespace secplus2 {
if (this->rx_byte_count_ == PACKET_LENGTH) {
this->flags_.rx_reading_msg = false;
this->rx_byte_count_ = 0;
this->rx_msg_start_ = 0; // clear window to prevent immediate re-trigger
this->rx_msg_start_ =
0; // clear window to prevent immediate re-trigger
this->print_packet(LOG_STR("Received packet"), this->rx_packet_);
return this->decode_packet(this->rx_packet_);
}
@@ -249,26 +251,27 @@ namespace secplus2 {
}
if (this->flags_.rx_reading_msg && (millis() - this->rx_last_read_ > 100)) {
// if we have a partial packet and it's been over 100ms since last byte was read,
// the rest is not coming, discard it.
ESP_LOGW(TAG, "Discard incomplete packet, length: %d", this->rx_byte_count_);
// if we have a partial packet and it's been over 100ms since last byte was
// read, the rest is not coming, discard it.
ESP_LOGW(TAG, "Discard incomplete packet, length: %d",
this->rx_byte_count_);
this->flags_.rx_reading_msg = false;
this->rx_byte_count_ = 0;
this->rx_msg_start_ = 0;
}
return { };
}
return {};
}
void Secplus2::print_packet(const esphome::LogString* prefix, const WirePacket& packet) const
{
void Secplus2::print_packet(const esphome::LogString* prefix,
const WirePacket& packet) const {
constexpr size_t hex_size = format_hex_pretty_size(PACKET_LENGTH);
char hex_buf[hex_size];
ESP_LOGD(TAG, "%s: [%s]", LOG_STR_ARG(prefix), format_hex_pretty_to(hex_buf, packet, PACKET_LENGTH));
}
ESP_LOGD(TAG, "%s: [%s]", LOG_STR_ARG(prefix),
format_hex_pretty_to(hex_buf, packet, PACKET_LENGTH));
}
optional<Command> Secplus2::decode_packet(const WirePacket& packet) const
{
optional<Command> Secplus2::decode_packet(const WirePacket& packet) const {
uint32_t rolling = 0;
uint64_t fixed = 0;
uint32_t data = 0;
@@ -276,17 +279,22 @@ namespace secplus2 {
int err = decode_wireline(packet, &rolling, &fixed, &data);
if (err < 0) {
ESP_LOGW(TAG, "Decode failed (parity error or invalid frame)");
return { };
return {};
}
uint16_t cmd = ((fixed >> 24) & 0xf00) | (data & 0xff);
data &= ~0xf000; // clear parity nibble
if ((fixed & 0xFFFFFFFF) == this->client_id_) { // my commands
ESP_LOGD(TAG, " mine: rolling=%07" PRIx32 " fixed=%010" PRIx64 " data=%08" PRIx32, rolling, fixed, data);
return { };
ESP_LOGD(TAG,
" mine: rolling=%07" PRIx32 " fixed=%010" PRIx64
" data=%08" PRIx32,
rolling, fixed, data);
return {};
} else {
ESP_LOGD(TAG, " rolling=%07" PRIx32 " fixed=%010" PRIx64 " data=%08" PRIx32, rolling, fixed, data);
ESP_LOGD(TAG,
" rolling=%07" PRIx32 " fixed=%010" PRIx64 " data=%08" PRIx32,
rolling, fixed, data);
}
CommandType cmd_type = to_CommandType(cmd, CommandType::UNKNOWN);
@@ -294,34 +302,38 @@ namespace secplus2 {
uint8_t byte1 = (data >> 16) & 0xff;
uint8_t byte2 = (data >> 24) & 0xff;
ESP_LOGD(TAG, " cmd=%03x (%s) byte2=%02x byte1=%02x nibble=%01x", cmd, LOG_STR_ARG(CommandType_to_string(cmd_type)), byte2, byte1, nibble);
ESP_LOGD(TAG, " cmd=%03x (%s) byte2=%02x byte1=%02x nibble=%01x", cmd,
LOG_STR_ARG(CommandType_to_string(cmd_type)), byte2, byte1, nibble);
return Command { cmd_type, nibble, byte1, byte2 };
}
return Command{cmd_type, nibble, byte1, byte2};
}
void Secplus2::handle_command(const Command& cmd)
{
ESP_LOGD(TAG, "Handle command: %s (nibble=%01x byte1=%02x byte2=%02x)", LOG_STR_ARG(CommandType_to_string(cmd.type)), cmd.nibble, cmd.byte1, cmd.byte2);
void Secplus2::handle_command(const Command& cmd) {
ESP_LOGD(TAG, "Handle command: %s (nibble=%01x byte1=%02x byte2=%02x)",
LOG_STR_ARG(CommandType_to_string(cmd.type)), cmd.nibble, cmd.byte1,
cmd.byte2);
if (cmd.type == CommandType::STATUS) {
this->ratgdo_->received(to_DoorState(cmd.nibble, DoorState::UNKNOWN));
this->ratgdo_->received(to_LightState((cmd.byte2 >> 1) & 1, LightState::UNKNOWN));
this->ratgdo_->received(
to_LightState((cmd.byte2 >> 1) & 1, LightState::UNKNOWN));
this->ratgdo_->received(to_LockState((cmd.byte2 & 1), LockState::UNKNOWN));
} else if (cmd.type == CommandType::LIGHT) {
this->ratgdo_->received(to_LightAction(cmd.nibble, LightAction::UNKNOWN));
} else if (cmd.type == CommandType::OPENINGS) {
this->ratgdo_->received(Openings { static_cast<uint16_t>((cmd.byte1 << 8) | cmd.byte2), cmd.nibble });
}
this->ratgdo_->received(Openings{
static_cast<uint16_t>((cmd.byte1 << 8) | cmd.byte2), cmd.nibble});
}
}
void Secplus2::send_command(Command command, IncrementRollingCode increment)
void Secplus2::send_command(Command command, IncrementRollingCode increment) {
{
{
uint8_t data[] = { command.byte2, command.byte1, command.nibble };
uint8_t data[] = {command.byte2, command.byte1, command.nibble};
constexpr size_t hex_size = format_hex_pretty_size(3);
char hex[hex_size];
ESP_LOGD(TAG, "Send command: %s, data: %s", LOG_STR_ARG(CommandType_to_string(command.type)), format_hex_pretty_to(hex, data, 3));
ESP_LOGD(TAG, "Send command: %s, data: %s",
LOG_STR_ARG(CommandType_to_string(command.type)),
format_hex_pretty_to(hex, data, 3));
}
if (!this->flags_.transmit_pending) { // have an untransmitted packet
this->encode_packet(command, this->tx_packet_);
@@ -329,29 +341,34 @@ namespace secplus2 {
this->increment_rolling_code_counter();
}
} else {
// unlikely this would happed (unless not connected to GDO), we're ensuring any pending packet
// is transmitted each loop before doing anyting else
// unlikely this would happed (unless not connected to GDO), we're ensuring
// any pending packet is transmitted each loop before doing anyting else
if (this->transmit_pending_start_ > 0) {
ESP_LOGW(TAG, "Have untransmitted packet, ignoring command: %s", LOG_STR_ARG(CommandType_to_string(command.type)));
ESP_LOGW(TAG, "Have untransmitted packet, ignoring command: %s",
LOG_STR_ARG(CommandType_to_string(command.type)));
} else {
ESP_LOGW(TAG, "Not connected to GDO, ignoring command: %s", LOG_STR_ARG(CommandType_to_string(command.type)));
ESP_LOGW(TAG, "Not connected to GDO, ignoring command: %s",
LOG_STR_ARG(CommandType_to_string(command.type)));
}
}
this->transmit_packet();
}
}
void Secplus2::encode_packet(Command command, WirePacket& packet)
{
void Secplus2::encode_packet(Command command, WirePacket& packet) {
auto cmd = static_cast<uint64_t>(command.type);
uint64_t fixed = ((cmd & ~0xff) << 24) | this->client_id_;
uint32_t data = (static_cast<uint64_t>(command.byte2) << 24) | (static_cast<uint64_t>(command.byte1) << 16) | (static_cast<uint64_t>(command.nibble) << 8) | (cmd & 0xff);
uint32_t data = (static_cast<uint64_t>(command.byte2) << 24) |
(static_cast<uint64_t>(command.byte1) << 16) |
(static_cast<uint64_t>(command.nibble) << 8) | (cmd & 0xff);
ESP_LOGD(TAG, " transmit: rolling=%07" PRIx32 " fixed=%010" PRIx64 " data=%08" PRIx32, *this->rolling_code_counter_, fixed, data);
ESP_LOGD(TAG,
" transmit: rolling=%07" PRIx32 " fixed=%010" PRIx64
" data=%08" PRIx32,
*this->rolling_code_counter_, fixed, data);
encode_wireline(*this->rolling_code_counter_, fixed, data, packet);
}
}
bool Secplus2::transmit_packet()
{
bool Secplus2::transmit_packet() {
auto now = micros();
while (micros() - now < 1300) {
@@ -361,7 +378,8 @@ namespace secplus2 {
this->transmit_pending_start_ = millis();
ESP_LOGD(TAG, "Collision detected, waiting to send packet");
} else if (millis() - this->transmit_pending_start_ >= 5000) {
this->transmit_pending_start_ = 0; // to indicate GDO not connected state
this->transmit_pending_start_ =
0; // to indicate GDO not connected state
}
return false;
}
@@ -377,37 +395,37 @@ namespace secplus2 {
this->transmit_pending_start_ = 0;
this->on_command_sent_.trigger();
return true;
}
}
void Secplus2::increment_rolling_code_counter(int delta)
{
void Secplus2::increment_rolling_code_counter(int delta) {
uint32_t counter = (*this->rolling_code_counter_ + delta) & 0xfffffff;
this->rolling_code_counter_ = counter;
this->rolling_code_pref_.save(&counter);
if (mqtt::global_mqtt_client != nullptr) {
mqtt::global_mqtt_client->publish(this->mqtt_rolling_code_topic_, std::to_string(counter), 0, true);
}
mqtt::global_mqtt_client->publish(this->mqtt_rolling_code_topic_,
std::to_string(counter), 0, true);
}
}
void Secplus2::set_rolling_code_counter(uint32_t counter)
{
void Secplus2::set_rolling_code_counter(uint32_t counter) {
ESP_LOGV(TAG, "Set rolling code counter to %d", counter);
this->rolling_code_counter_ = counter;
this->rolling_code_pref_.save(&counter);
if (mqtt::global_mqtt_client != nullptr) {
mqtt::global_mqtt_client->publish(this->mqtt_rolling_code_topic_, std::to_string(counter), 0, true);
}
mqtt::global_mqtt_client->publish(this->mqtt_rolling_code_topic_,
std::to_string(counter), 0, true);
}
}
void Secplus2::set_client_id(uint64_t client_id)
{
void Secplus2::set_client_id(uint64_t client_id) {
uint32_t cid = client_id & 0xFFFFFFFF;
this->client_id_ = cid;
this->client_id_pref_.save(&cid);
if (mqtt::global_mqtt_client != nullptr) {
mqtt::global_mqtt_client->publish(this->mqtt_client_id_topic_, std::to_string(cid), 0, true);
}
mqtt::global_mqtt_client->publish(this->mqtt_client_id_topic_,
std::to_string(cid), 0, true);
}
}
} // namespace secplus2
} // namespace esphome::ratgdo
+78 -64
View File
@@ -1,14 +1,13 @@
#pragma once
#include "esphome/core/optional.h"
#include "esphome/core/preferences.h"
#include "esphome/components/mqtt/mqtt_client.h"
#include "ratgdo_uart_esp32.h"
#include "callbacks.h"
#include "common.h"
#include "esphome/components/mqtt/mqtt_client.h"
#include "esphome/core/optional.h"
#include "esphome/core/preferences.h"
#include "observable.h"
#include "ratgdo_state.h"
#include "ratgdo_uart_esp32.h"
namespace esphome {
@@ -22,10 +21,10 @@ class RATGDOComponent;
namespace secplus2 {
static const uint8_t PACKET_LENGTH = 19;
typedef uint8_t WirePacket[PACKET_LENGTH];
static const uint8_t PACKET_LENGTH = 19;
typedef uint8_t WirePacket[PACKET_LENGTH];
enum class CommandType : uint16_t {
enum class CommandType : uint16_t {
UNKNOWN = 0x000,
GET_STATUS = 0x080,
STATUS = 0x081,
@@ -34,66 +33,82 @@ namespace secplus2 {
LIGHT = 0x281,
GET_OPENINGS = 0x48b,
OPENINGS = 0x48c // openings = (byte1<<8)+byte2
};
};
inline const char* CommandType_to_string(CommandType e) {
inline const char* CommandType_to_string(CommandType e) {
switch (e) {
case CommandType::UNKNOWN: return "UNKNOWN";
case CommandType::GET_STATUS: return "GET_STATUS";
case CommandType::STATUS: return "STATUS";
case CommandType::LOCK: return "LOCK";
case CommandType::DOOR_ACTION: return "DOOR_ACTION";
case CommandType::LIGHT: return "LIGHT";
case CommandType::GET_OPENINGS: return "GET_OPENINGS";
case CommandType::OPENINGS: return "OPENINGS";
default: return "UNKNOWN";
}
case CommandType::UNKNOWN:
return "UNKNOWN";
case CommandType::GET_STATUS:
return "GET_STATUS";
case CommandType::STATUS:
return "STATUS";
case CommandType::LOCK:
return "LOCK";
case CommandType::DOOR_ACTION:
return "DOOR_ACTION";
case CommandType::LIGHT:
return "LIGHT";
case CommandType::GET_OPENINGS:
return "GET_OPENINGS";
case CommandType::OPENINGS:
return "OPENINGS";
default:
return "UNKNOWN";
}
}
inline CommandType to_CommandType(uint16_t t, CommandType unknown) {
inline CommandType to_CommandType(uint16_t t, CommandType unknown) {
switch (t) {
case static_cast<uint16_t>(CommandType::UNKNOWN): return CommandType::UNKNOWN;
case static_cast<uint16_t>(CommandType::GET_STATUS): return CommandType::GET_STATUS;
case static_cast<uint16_t>(CommandType::STATUS): return CommandType::STATUS;
case static_cast<uint16_t>(CommandType::LOCK): return CommandType::LOCK;
case static_cast<uint16_t>(CommandType::DOOR_ACTION): return CommandType::DOOR_ACTION;
case static_cast<uint16_t>(CommandType::LIGHT): return CommandType::LIGHT;
case static_cast<uint16_t>(CommandType::GET_OPENINGS): return CommandType::GET_OPENINGS;
case static_cast<uint16_t>(CommandType::OPENINGS): return CommandType::OPENINGS;
default: return unknown;
}
case static_cast<uint16_t>(CommandType::UNKNOWN):
return CommandType::UNKNOWN;
case static_cast<uint16_t>(CommandType::GET_STATUS):
return CommandType::GET_STATUS;
case static_cast<uint16_t>(CommandType::STATUS):
return CommandType::STATUS;
case static_cast<uint16_t>(CommandType::LOCK):
return CommandType::LOCK;
case static_cast<uint16_t>(CommandType::DOOR_ACTION):
return CommandType::DOOR_ACTION;
case static_cast<uint16_t>(CommandType::LIGHT):
return CommandType::LIGHT;
case static_cast<uint16_t>(CommandType::GET_OPENINGS):
return CommandType::GET_OPENINGS;
case static_cast<uint16_t>(CommandType::OPENINGS):
return CommandType::OPENINGS;
default:
return unknown;
}
}
inline bool operator==(const uint16_t cmd_i, const CommandType& cmd_e) { return cmd_i == static_cast<uint16_t>(cmd_e); }
inline bool operator==(const CommandType& cmd_e, const uint16_t cmd_i) { return cmd_i == static_cast<uint16_t>(cmd_e); }
inline bool operator==(const uint16_t cmd_i, const CommandType& cmd_e) {
return cmd_i == static_cast<uint16_t>(cmd_e);
}
inline bool operator==(const CommandType& cmd_e, const uint16_t cmd_i) {
return cmd_i == static_cast<uint16_t>(cmd_e);
}
enum class IncrementRollingCode {
enum class IncrementRollingCode {
NO,
YES,
};
};
struct Command {
struct Command {
CommandType type;
uint8_t nibble;
uint8_t byte1;
uint8_t byte2;
Command()
: type(CommandType::UNKNOWN)
{
}
Command(CommandType type_, uint8_t nibble_ = 0, uint8_t byte1_ = 0, uint8_t byte2_ = 0)
: type(type_)
, nibble(nibble_)
, byte1(byte1_)
, byte2(byte2_)
{
}
};
Command() : type(CommandType::UNKNOWN) {}
Command(CommandType type_, uint8_t nibble_ = 0, uint8_t byte1_ = 0,
uint8_t byte2_ = 0)
: type(type_), nibble(nibble_), byte1(byte1_), byte2(byte2_) {}
};
class Secplus2 {
class Secplus2 {
public:
void setup(RATGDOComponent* ratgdo, Scheduler* scheduler, InternalGPIOPin* rx_pin, InternalGPIOPin* tx_pin);
void setup(RATGDOComponent* ratgdo, Scheduler* scheduler,
InternalGPIOPin* rx_pin, InternalGPIOPin* tx_pin);
void loop();
void dump_config();
void on_shutdown();
@@ -115,10 +130,10 @@ namespace secplus2 {
optional<Command> read_command();
void handle_command(const Command& cmd);
void send_command(Command cmd, IncrementRollingCode increment = IncrementRollingCode::YES);
void send_command(Command cmd,
IncrementRollingCode increment = IncrementRollingCode::YES);
template <typename F>
void send_command(Command cmd, IncrementRollingCode increment, F&& on_sent)
{
void send_command(Command cmd, IncrementRollingCode increment, F&& on_sent) {
// Only register the callback if the command will be accepted.
// If transmit_pending is set the command will be dropped, and
// a stale callback would fire when the previous pending packet
@@ -138,15 +153,14 @@ namespace secplus2 {
void door_command(DoorAction action);
void print_packet(const esphome::LogString* prefix, const WirePacket& packet) const;
void print_packet(const esphome::LogString* prefix,
const WirePacket& packet) const;
optional<Command> decode_packet(const WirePacket& packet) const;
void sync_helper(uint32_t start, uint32_t delay, uint8_t tries);
// 8-byte member first (may require 8-byte alignment on some 32-bit systems)
uint64_t client_id_ { 0x539 };
uint64_t client_id_{0x539};
// Pointers (4-byte aligned)
InternalGPIOPin* tx_pin_;
@@ -155,12 +169,12 @@ namespace secplus2 {
Scheduler* scheduler_;
// 4-byte members
uint32_t transmit_pending_start_ { 0 };
uint32_t rx_msg_start_ { 0 };
uint32_t rx_last_read_ { 0 };
uint32_t transmit_pending_start_{0};
uint32_t rx_msg_start_{0};
uint32_t rx_last_read_{0};
// Larger structures
single_observable<uint32_t> rolling_code_counter_ { 0 };
single_observable<uint32_t> rolling_code_counter_{0};
ESPPreferenceObject rolling_code_pref_;
ESPPreferenceObject client_id_pref_;
std::string mqtt_rolling_code_topic_;
@@ -173,11 +187,11 @@ namespace secplus2 {
WirePacket rx_packet_;
// Small members at the end
uint16_t rx_byte_count_ { 0 };
uint16_t rx_byte_count_{0};
struct {
uint8_t transmit_pending : 1;
uint8_t rx_reading_msg : 1;
} flags_ { 0 };
};
} flags_{0};
};
} // namespace secplus2
} // namespace esphome::ratgdo
+25 -23
View File
@@ -1,20 +1,20 @@
#include "ratgdo_sensor.h"
#include "../ratgdo_state.h"
#include "esphome/core/log.h"
namespace esphome::ratgdo {
static const char* const TAG = "ratgdo.sensor";
static const int MIN_DISTANCE = 100; // ignore bugs crawling on the distance sensor & dust protection film
static const int MIN_DISTANCE =
100; // ignore bugs crawling on the distance sensor & dust protection film
static const int MAX_DISTANCE = 4500; // default maximum distance
void RATGDOSensor::setup()
{
void RATGDOSensor::setup() {
switch (this->ratgdo_sensor_type_) {
case RATGDOSensorType::RATGDO_OPENINGS:
this->parent_->subscribe_openings([this](uint16_t value) {
this->publish_state(value);
});
this->parent_->subscribe_openings(
[this](uint16_t value) { this->publish_state(value); });
break;
case RATGDOSensorType::RATGDO_DISTANCE:
this->distance_sensor_.setI2cDevice(&I2C);
@@ -23,19 +23,18 @@ void RATGDOSensor::setup()
this->distance_sensor_.begin();
this->distance_sensor_.VL53L4CX_Off();
this->distance_sensor_.InitSensor(0x59);
this->distance_sensor_.VL53L4CX_SetDistanceMode(VL53L4CX_DISTANCEMODE_LONG);
this->distance_sensor_.VL53L4CX_SetDistanceMode(
VL53L4CX_DISTANCEMODE_LONG);
this->distance_sensor_.VL53L4CX_StartMeasurement();
this->parent_->subscribe_distance_measurement([this](int16_t value) {
this->publish_state(value);
});
this->parent_->subscribe_distance_measurement(
[this](int16_t value) { this->publish_state(value); });
break;
default:
break;
}
}
void RATGDOSensor::dump_config()
{
void RATGDOSensor::dump_config() {
LOG_SENSOR("", "RATGDO Sensor", this);
switch (this->ratgdo_sensor_type_) {
case RATGDOSensorType::RATGDO_OPENINGS:
@@ -49,8 +48,7 @@ void RATGDOSensor::dump_config()
}
}
void RATGDOSensor::loop()
{
void RATGDOSensor::loop() {
if (this->ratgdo_sensor_type_ == RATGDOSensorType::RATGDO_DISTANCE) {
VL53L4CX_MultiRangingData_t distanceData;
VL53L4CX_MultiRangingData_t* pDistanceData = &distanceData;
@@ -59,8 +57,11 @@ void RATGDOSensor::loop()
int16_t maxDistance = -1;
int status;
if (this->distance_sensor_.VL53L4CX_GetMeasurementDataReady(&dataReady) == 0 && dataReady) {
status = this->distance_sensor_.VL53L4CX_GetMultiRangingData(pDistanceData);
if (this->distance_sensor_.VL53L4CX_GetMeasurementDataReady(&dataReady) ==
0 &&
dataReady) {
status =
this->distance_sensor_.VL53L4CX_GetMultiRangingData(pDistanceData);
objCount = pDistanceData->NumberOfObjectsFound;
for (int i = 0; i < distanceData.NumberOfObjectsFound; i++) {
@@ -71,21 +72,22 @@ void RATGDOSensor::loop()
}
}
if (maxDistance < 0)
maxDistance = MAX_DISTANCE;
if (maxDistance < 0) maxDistance = MAX_DISTANCE;
/*
* if the sensor is pointed at glass, there are many error -1 readings which will fill the
* vector with out of range data. The sensor should be sensitive enough to detect the floor
* in most situations, but daylight and/or really high ceilings can cause long distance
* measurements to be out of range.
* if the sensor is pointed at glass, there are many error -1 readings
* which will fill the vector with out of range data. The sensor should be
* sensitive enough to detect the floor in most situations, but daylight
* and/or really high ceilings can cause long distance measurements to be
* out of range.
*/
this->parent_->set_distance_measurement(maxDistance);
// ESP_LOGD(TAG,"# obj found %d; distance %d",objCount, maxDistance);
if (status == 0) {
status = this->distance_sensor_.VL53L4CX_ClearInterruptAndStartMeasurement();
status =
this->distance_sensor_.VL53L4CX_ClearInterruptAndStartMeasurement();
}
}
}
+10 -10
View File
@@ -2,29 +2,29 @@
#include "../ratgdo.h"
#include "../ratgdo_state.h"
#include "Wire.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/component.h"
#include "esphome/core/defines.h"
#include "Wire.h"
#include "vl53l4cx_class.h"
#define I2C Wire
namespace esphome::ratgdo {
enum RATGDOSensorType : uint8_t {
RATGDO_OPENINGS,
RATGDO_DISTANCE = 6
};
enum RATGDOSensorType : uint8_t { RATGDO_OPENINGS, RATGDO_DISTANCE = 6 };
class RATGDOSensor : public sensor::Sensor, public RATGDOClient, public Component {
public:
class RATGDOSensor : public sensor::Sensor,
public RATGDOClient,
public Component {
public:
void dump_config() override;
void setup() override;
void loop() override;
void set_ratgdo_sensor_type(RATGDOSensorType ratgdo_sensor_type_) { this->ratgdo_sensor_type_ = ratgdo_sensor_type_; }
void set_ratgdo_sensor_type(RATGDOSensorType ratgdo_sensor_type_) {
this->ratgdo_sensor_type_ = ratgdo_sensor_type_;
}
protected:
protected:
RATGDOSensorType ratgdo_sensor_type_;
VL53L4CX distance_sensor_;
+4 -6
View File
@@ -1,4 +1,5 @@
#include "ratgdo_switch.h"
#include "../ratgdo_state.h"
#include "esphome/core/log.h"
@@ -6,8 +7,7 @@ namespace esphome::ratgdo {
static const char* const TAG = "ratgdo.switch";
void RATGDOSwitch::dump_config()
{
void RATGDOSwitch::dump_config() {
LOG_SWITCH("", "RATGDO Switch", this);
switch (this->switch_type_) {
case SwitchType::RATGDO_LED:
@@ -18,8 +18,7 @@ void RATGDOSwitch::dump_config()
}
}
void RATGDOSwitch::setup()
{
void RATGDOSwitch::setup() {
switch (this->switch_type_) {
case SwitchType::RATGDO_LED:
this->pin_->setup();
@@ -29,8 +28,7 @@ void RATGDOSwitch::setup()
}
}
void RATGDOSwitch::write_state(bool state)
{
void RATGDOSwitch::write_state(bool state) {
switch (this->switch_type_) {
case SwitchType::RATGDO_LED:
this->pin_->digital_write(state);
+9 -7
View File
@@ -8,20 +8,22 @@
namespace esphome::ratgdo {
enum SwitchType {
RATGDO_LED = 1
};
enum SwitchType { RATGDO_LED = 1 };
class RATGDOSwitch : public switch_::Switch, public RATGDOClient, public Component {
public:
class RATGDOSwitch : public switch_::Switch,
public RATGDOClient,
public Component {
public:
void dump_config() override;
void setup() override;
void set_switch_type(SwitchType switch_type_) { this->switch_type_ = switch_type_; }
void set_switch_type(SwitchType switch_type_) {
this->switch_type_ = switch_type_;
}
void write_state(bool state) override;
void set_pin(GPIOPin* pin) { pin_ = pin; }
protected:
protected:
SwitchType switch_type_;
GPIOPin* pin_;
};
+6 -6
View File
@@ -7,7 +7,7 @@
namespace esphome {
namespace somfy {
static const char *const TAG = "somfy";
static const char* const TAG = "somfy";
static const uint8_t CMD_STOP = 0x01;
static const uint8_t CMD_UP = 0x02;
@@ -34,8 +34,8 @@ struct SomfyRTSProtocolData {
class SomfyRTSProtocol
: public remote_base::RemoteProtocol<SomfyRTSProtocolData> {
public:
virtual void encode(remote_base::RemoteTransmitData *dst,
const ProtocolData &data) override {
virtual void encode(remote_base::RemoteTransmitData* dst,
const ProtocolData& data) override {
/*
* 1. Build a frame.
*/
@@ -101,7 +101,7 @@ class SomfyRTSProtocol
}
}
virtual void dump(const ProtocolData &data) override { data.dump(); }
virtual void dump(const ProtocolData& data) override { data.dump(); }
virtual optional<ProtocolData> decode(
remote_base::RemoteReceiveData src) override {
@@ -155,7 +155,7 @@ void SomfyRTSCover::setup() {
// MQTT.
mqtt::global_mqtt_client->subscribe(
mqtt_topic_prefix_ + std::to_string(remote_id_),
[this](const std::string &topic, const std::string &payload) {
[this](const std::string& topic, const std::string& payload) {
if (rolling_code_ == 0) {
ESP_LOGI(TAG, "Received rolling code for remote #%d from MQTT: %s",
remote_id_, payload.c_str());
@@ -171,7 +171,7 @@ void SomfyRTSCover::setup() {
}
}
void SomfyRTSCover::control(const cover::CoverCall &call) {
void SomfyRTSCover::control(const cover::CoverCall& call) {
if (call.get_position().has_value()) {
float position = *call.get_position();
send(position > 0.5 ? CMD_UP : CMD_DOWN);
+3 -3
View File
@@ -16,7 +16,7 @@ namespace somfy {
class SomfyRTSCover : public cover::Cover, public Component {
public:
void set_transmitter(
remote_transmitter::RemoteTransmitterComponent *transmitter) {
remote_transmitter::RemoteTransmitterComponent* transmitter) {
this->transmitter_ = transmitter;
}
void set_remote_id(uint32_t remote_id) { this->remote_id_ = remote_id; }
@@ -24,7 +24,7 @@ class SomfyRTSCover : public cover::Cover, public Component {
cover::CoverTraits get_traits() override;
void setup() override;
void dump_config() override;
void control(const cover::CoverCall &call) override;
void control(const cover::CoverCall& call) override;
protected:
/* Wake up the blinds motor controller and send the command.
@@ -39,7 +39,7 @@ class SomfyRTSCover : public cover::Cover, public Component {
uint32_t rolling_code_;
std::string mqtt_topic_prefix_;
ESPPreferenceObject rolling_code_pref_;
remote_transmitter::RemoteTransmitterComponent *transmitter_{nullptr};
remote_transmitter::RemoteTransmitterComponent* transmitter_{nullptr};
};
} // namespace somfy
+6 -6
View File
@@ -3,16 +3,16 @@
#include "esphome/components/remote_base/remote_base.h"
namespace {
static const char *const TAG = __FILE__;
static const char* const TAG = __FILE__;
static const uint8_t MIN_TEMPERATURE = 35;
static const uint8_t MAX_TEMPERATURE = 70;
static const uint8_t TEMPERATURE_LEVELS = 8;
static void add_header_(esphome::remote_base::RemoteTransmitData *data) {
static void add_header_(esphome::remote_base::RemoteTransmitData* data) {
data->item(30, 1000);
}
static void add_byte_(esphome::remote_base::RemoteTransmitData *data,
static void add_byte_(esphome::remote_base::RemoteTransmitData* data,
uint8_t value) {
for (int i = 0; i < 8; ++i) {
data->item(30, value & 0b10000000 ? 830 : 650);
@@ -20,7 +20,7 @@ static void add_byte_(esphome::remote_base::RemoteTransmitData *data,
}
}
static void add_post_(esphome::remote_base::RemoteTransmitData *data) {
static void add_post_(esphome::remote_base::RemoteTransmitData* data) {
data->item(30, 460);
data->item(30, 650);
}
@@ -29,7 +29,7 @@ static void add_post_(esphome::remote_base::RemoteTransmitData *data) {
namespace esphome {
namespace zehnder {
void ZehnderComponent::control(const climate::ClimateCall &call) {
void ZehnderComponent::control(const climate::ClimateCall& call) {
float target_temp = this->target_temperature;
climate::ClimateMode mode = this->mode;
@@ -101,7 +101,7 @@ void ZehnderComponent::dump_config() {
this->has_temperature_sensor_ ? "yes" : "no");
}
bool ZehnderComponent::transmit_temperature_(float *temp) {
bool ZehnderComponent::transmit_temperature_(float* temp) {
uint8_t level;
if (*temp == 0) {
level = 0;
+5 -5
View File
@@ -22,11 +22,11 @@ class ZehnderComponent : public climate::Climate, public PollingComponent {
// PollingComponent.
void update() override;
void set_transmitter(remote_transmitter::RemoteTransmitterComponent *t) {
void set_transmitter(remote_transmitter::RemoteTransmitterComponent* t) {
this->transmitter_ = t;
}
void add_temperature_sensor(sensor::Sensor *s) {
void add_temperature_sensor(sensor::Sensor* s) {
has_temperature_sensor_ = true;
s->add_on_state_callback([this](float temperature_value) {
this->current_temperature = temperature_value;
@@ -36,13 +36,13 @@ class ZehnderComponent : public climate::Climate, public PollingComponent {
protected:
// climate::Climate.
void control(const climate::ClimateCall &call) override;
void control(const climate::ClimateCall& call) override;
climate::ClimateTraits traits() override;
bool transmit_temperature_(float *temp);
bool transmit_temperature_(float* temp);
bool transmit_level_(uint8_t level);
remote_transmitter::RemoteTransmitterComponent *transmitter_ = nullptr;
remote_transmitter::RemoteTransmitterComponent* transmitter_ = nullptr;
bool has_temperature_sensor_ = false;
};
+2 -2
View File
@@ -31,12 +31,12 @@ esp32_camera:
idle_framerate: 0.1fps
output:
- platform: ledc
- platform: ledc
pin: GPIO4
channel: 2 # PWM channel 1 is used for esp32_camera.
id: led
light:
- platform: monochromatic
- platform: monochromatic
output: led
name: Flash
+4 -4
View File
@@ -19,7 +19,7 @@ external_components:
- source:
type: local
path: components
components: [ ratgdo ]
components: [ratgdo]
packages:
wifi: !include templates/wifi.yaml
@@ -49,7 +49,7 @@ time:
binary_sensor:
- platform: template
name: "Sync failed"
lambda: 'return *id(garage_gate_controller).sync_failed;'
lambda: "return *id(garage_gate_controller).sync_failed;"
device_class: problem
entity_category: diagnostic
@@ -114,7 +114,7 @@ cover:
on_state_change:
- if:
condition:
lambda: 'return id(garage_gate).current_operation == COVER_OPERATION_CLOSING;'
lambda: "return id(garage_gate).current_operation == COVER_OPERATION_CLOSING;"
then:
- script.execute: play_siren
else:
@@ -167,7 +167,7 @@ script:
then:
- while:
condition:
lambda: 'return id(garage_gate).current_operation == COVER_OPERATION_CLOSING;'
lambda: "return id(garage_gate).current_operation == COVER_OPERATION_CLOSING;"
then:
- rtttl.play: "siren:d=8,o=6,b=100:e,d#,e,d#,e,d#,e,d#"
- wait_until:
+2 -3
View File
@@ -40,7 +40,7 @@ ethernet:
domain: ""
text_sensor:
- platform: ethernet_info
- platform: ethernet_info
ip_address:
name: "ESP chip IP (Ethernet)"
icon: mdi:ip-network
@@ -48,9 +48,8 @@ text_sensor:
name: "ESP chip MAC (Ethernet)"
icon: mdi:expansion-card
sn74hc595: # write
- id: 'sn74hc595_hub'
- id: "sn74hc595_hub"
clock_pin: GPIO14 # SRCLK (serial clock)
data_pin: GPIO13 # SER (serial input)
latch_pin: GPIO15 # RCLK (latch for outputs)
+12 -12
View File
@@ -42,12 +42,12 @@ i2c:
scl: GPIO18
font:
- file: "fonts/DejaVuSans.ttf"
- file: "fonts/DejaVuSans.ttf"
id: font_sans
size: 20
display:
- platform: ssd1306_i2c
- platform: ssd1306_i2c
model: "SSD1306 128x32"
id: oled_display
lambda: |-
@@ -64,28 +64,28 @@ display:
}
one_wire:
- platform: gpio
- platform: gpio
pin: GPIO27
sensor:
- platform: dallas_temp
- platform: dallas_temp
address: 0x133c2cf648f40728
id: boiler_temperature
name: "Boiler temperature"
filters:
- offset: 0.5
- platform: dallas_temp
- platform: dallas_temp
address: 0x4845b7211864ff28
id: hot_water_temperature
name: "Hot water temperature"
- platform: dallas_temp
- platform: dallas_temp
address: 0x6a0316643959ff28
id: floor_temperature
name: "Floor temperature"
- platform: adc
- platform: adc
pin: GPIO32
update_interval: 1s
id: furnace_burning_led_brightness
@@ -95,7 +95,7 @@ sensor:
entity_category: diagnostic
accuracy_decimals: 2
- platform: adc
- platform: adc
pin: GPIO33
update_interval: 1s
id: floor_active_led_brightness
@@ -106,7 +106,7 @@ sensor:
accuracy_decimals: 2
binary_sensor:
- platform: analog_threshold
- platform: analog_threshold
id: furnace_burning
name: "Furnace burning"
sensor_id: furnace_burning_led_brightness
@@ -116,7 +116,7 @@ binary_sensor:
filters:
- invert:
- platform: analog_threshold
- platform: analog_threshold
id: heating_enabled
name: "Floor active"
sensor_id: floor_active_led_brightness
@@ -126,14 +126,14 @@ binary_sensor:
- invert:
switch:
- platform: gpio
- platform: gpio
pin: GPIO25
id: relay_temperature_manual
inverted: true
# Non-manual is no longer wired to anything.
restore_mode: ALWAYS_ON
- platform: gpio
- platform: gpio
pin: GPIO26
name: "Floor intent"
restore_mode: RESTORE_DEFAULT_OFF
+4 -4
View File
@@ -72,19 +72,19 @@ binary_sensor:
- platform: template
name: "Garden Peach relay"
entity_category: diagnostic
lambda: 'return id(relay_1).state;'
lambda: "return id(relay_1).state;"
- platform: template
name: "Garden Berries relay"
entity_category: diagnostic
lambda: 'return id(relay_2).state;'
lambda: "return id(relay_2).state;"
- platform: template
name: "Shower relay"
entity_category: diagnostic
lambda: 'return id(relay_3).state;'
lambda: "return id(relay_3).state;"
- platform: template
name: "Relay 4"
entity_category: diagnostic
lambda: 'return id(relay_4).state;'
lambda: "return id(relay_4).state;"
switch:
- platform: gpio
+1 -2
View File
@@ -10,12 +10,11 @@ packages:
time: !include templates/time.yaml
time:
- platform: sntp
- platform: sntp
id: sntp_time
servers: !secret sntp_servers
timezone: Europe/Zurich
on_time:
#
# Pool pump: must run during saltwater system cycle, and an additional hour.
# Saltwater 16:30 - 19:30, so we stop at 20:35 (Pool instructions).
+1 -1
View File
@@ -28,7 +28,7 @@ output:
id: mic_power
sensor:
- platform: pulse_meter
- platform: pulse_meter
internal_filter: 50ms
pin:
+1 -2
View File
@@ -8,9 +8,8 @@ esphome:
packages:
device_base: !include templates/mystrom.yaml
interval:
- interval: 1min
- interval: 1min
then:
- if:
condition:
+2 -2
View File
@@ -13,7 +13,7 @@ globals:
- id: ble_scans
type: int
restore_value: no
initial_value: '0'
initial_value: "0"
esp32_ble_tracker:
scan_parameters:
@@ -25,7 +25,7 @@ esp32_ble_tracker:
- then:
- sensor.template.publish:
id: ble_scans_finished
state: !lambda 'return ++id(ble_scans);'
state: !lambda "return ++id(ble_scans);"
- script.execute: restart_after_delay
bluetooth_proxy:
+1 -1
View File
@@ -12,7 +12,7 @@ packages:
logger:
switch:
- platform: gpio
- platform: gpio
pin: GPIO0
name: None
inverted: true
+1 -1
View File
@@ -16,7 +16,7 @@ ethernet:
domain: ""
text_sensor:
- platform: ethernet_info
- platform: ethernet_info
ip_address:
name: "ESP chip IP (Ethernet)"
icon: mdi:ip-network
+1 -1
View File
@@ -1,7 +1,7 @@
# Make sure nothing is connected to the A0 pin.
sensor:
- platform: adc
- platform: adc
pin: VCC
name: "ESP chip VCC Voltage"
entity_category: diagnostic
+8 -8
View File
@@ -41,7 +41,7 @@ status_led:
pin: GPIO16
binary_sensor:
- platform: gpio
- platform: gpio
id: mystrom_side
name: "Side button (plus) pressed"
pin:
@@ -50,7 +50,7 @@ binary_sensor:
input: true
pullup: true
inverted: true
- platform: gpio
- platform: gpio
id: mystrom_bottom
name: "Bottom button (power) pressed"
pin:
@@ -64,7 +64,7 @@ binary_sensor:
- switch.toggle: mystrom_relay
script:
- id: power_cycle_relay
- id: power_cycle_relay
mode: single
then:
- if:
@@ -83,7 +83,7 @@ button:
- script.execute: power_cycle_relay
sensor:
- platform: pulse_counter
- platform: pulse_counter
pin: 4
update_interval: 10s
id: mystrom_power_consumption
@@ -104,7 +104,7 @@ sensor:
filters:
- multiply: 5.48E-07 # pulses -> kWh
- platform: tmp102
- platform: tmp102
id: mystrom_temperature
name: "Internal temperature"
update_interval: 60s
@@ -115,14 +115,14 @@ sensor:
then:
- switch.turn_off: mystrom_relay
- platform: duty_time
- platform: duty_time
id: continuous_on_time
name: Continuous on time
lambda: "return id(mystrom_relay).state;"
accuracy_decimals: 0
switch:
- platform: gpio
- platform: gpio
name: None # Main entity for the device.
pin: GPIO27
id: mystrom_relay
@@ -131,7 +131,7 @@ switch:
on_turn_off:
- sensor.duty_time.reset: continuous_on_time
- platform: gpio
- platform: gpio
# Exposing this as a switch rather than light to avoid
# automations and dashboard picking it up as illuminance
# source.
+1 -1
View File
@@ -1,5 +1,5 @@
button:
- platform: restart
- platform: restart
name: "ESP chip restart"
entity_category: diagnostic
id: restart_button
+2 -2
View File
@@ -1,6 +1,6 @@
binary_sensor:
- platform: template
- platform: template
name: "ESP chip clock invalid"
lambda: 'return !id(sntp_time).now().is_valid();'
lambda: "return !id(sntp_time).now().is_valid();"
entity_category: diagnostic
device_class: problem
+5 -5
View File
@@ -38,7 +38,7 @@ external_components:
- source: github://oxan/esphome-stream-server
script:
- id: fw_update_mode
- id: fw_update_mode
then:
- switch.turn_on: zBSL
- delay: 1s
@@ -51,21 +51,21 @@ script:
- logger.log: "Please try update with cc2538-bsl tool now"
- logger.log: "cc-bsl usage: cc2538-bsl.py -p socket://ip-of-gw:6638 -evw firmware.hex"
- id: cc2652_reset
- id: cc2652_reset
then:
- switch.turn_on: zRST_gpio
- delay: 15ms
- switch.turn_off: zRST_gpio
button:
- platform: template
- platform: template
name: "ZigBee Module reset"
disabled_by_default: true
id: zRST
on_press:
- script.execute: cc2652_reset
- platform: template
- platform: template
name: "ZigBee Module enter programming mode"
disabled_by_default: true
on_press:
@@ -78,6 +78,6 @@ stream_server:
buffer_size: 4096
binary_sensor:
- platform: stream_server
- platform: stream_server
connected:
name: "ZigBee Module serial stream connected"
+1 -1
View File
@@ -1,3 +1,3 @@
sensor:
- platform: uptime
- platform: uptime
name: "ESP chip uptime"
+2 -2
View File
@@ -1,9 +1,9 @@
sensor:
- platform: wifi_signal
- platform: wifi_signal
name: "ESP chip WiFi signal"
text_sensor:
- platform: wifi_info
- platform: wifi_info
mac_address:
name: "ESP chip MAC"
icon: mdi:wifi-cog
+1 -1
View File
@@ -12,7 +12,7 @@ packages:
sensor: !include templates/esp8266-vcc.yaml
sensor:
- platform: pulse_meter
- platform: pulse_meter
# Our meter (USLC/20) is rated Qmax=5.0 (m3/h).
# The official one is rated 5.0.
#
+2 -2
View File
@@ -13,13 +13,13 @@ packages:
device_base: !include templates/tubeszb-coordinator.yaml
switch:
- platform: gpio
- platform: gpio
pin: 33
id: zRST_gpio
inverted: yes
restore_mode: ALWAYS_OFF
- platform: gpio
- platform: gpio
pin: 32
id: zBSL
inverted: yes
+2 -2
View File
@@ -16,13 +16,13 @@ packages:
device_base: !include templates/tubeszb-coordinator.yaml
switch:
- platform: gpio
- platform: gpio
pin: 5
id: zRST_gpio
inverted: yes
restore_mode: ALWAYS_OFF
- platform: gpio
- platform: gpio
pin: 16
id: zBSL
inverted: yes