on_connect callback

This commit is contained in:
oarcher 2024-07-17 19:50:36 +02:00
parent 2370d5c83d
commit a702097b1f
3 changed files with 29 additions and 2 deletions

View file

@ -7,6 +7,7 @@ from esphome.const import (
CONF_PASSWORD,
CONF_MODEL,
CONF_TRIGGER_ID,
CONF_ON_CONNECT,
)
import esphome.codegen as cg
import esphome.config_validation as cv
@ -32,6 +33,9 @@ ModemState = modem_ns.enum("ModemState")
ModemOnNotRespondingTrigger = modem_ns.class_(
"ModemOnNotRespondingTrigger", automation.Trigger.template()
)
ModemOnConnectTrigger = modem_ns.class_(
"ModemOnConnectTrigger", automation.Trigger.template()
)
CONFIG_SCHEMA = cv.All(
@ -55,6 +59,9 @@ CONFIG_SCHEMA = cv.All(
)
}
),
cv.Optional(CONF_ON_CONNECT): automation.validate_automation(
{cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ModemOnConnectTrigger)}
),
}
).extend(cv.COMPONENT_SCHEMA),
cv.require_framework_version(
@ -119,4 +126,8 @@ async def to_code(config):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
for conf in config.get(CONF_ON_CONNECT, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
await cg.register_component(var, config)

View file

@ -20,6 +20,17 @@ class ModemOnNotRespondingTrigger : public Trigger<> {
}
};
class ModemOnConnectTrigger : public Trigger<> {
public:
explicit ModemOnConnectTrigger(ModemComponent *parent) {
parent->add_on_state_callback([this, parent](ModemState state) {
if (!parent->is_failed() && state == ModemState::CONNECTED) {
this->trigger();
}
});
}
};
} // namespace modem
} // namespace esphome
#endif // USE_ESP_IDF

View file

@ -28,7 +28,7 @@ namespace modem {
using namespace esp_modem;
ModemComponent *global_modem_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
ModemComponent *global_modem_component = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
#define ESPHL_ERROR_CHECK(err, message) \
if ((err) != ESP_OK) { \
@ -65,7 +65,10 @@ void set_wdt(uint32_t timeout_s) {
#endif // ESP_IDF_VERSION_MAJOR
}
ModemComponent::ModemComponent() { global_modem_component = this; }
ModemComponent::ModemComponent() {
assert(global_modem_component == nullptr);
global_modem_component = this;
}
void ModemComponent::dump_config() { ESP_LOGCONFIG(TAG, "Config Modem:"); }
@ -293,6 +296,8 @@ void ModemComponent::loop() {
this->dump_connect_params_();
this->status_clear_warning();
this->on_state_callback_.call(ModemState::CONNECTED);
} else if (now - this->connect_begin_ > 45000) {
ESP_LOGW(TAG, "Connecting via Modem failed! Re-connecting...");
this->state_ = ModemComponentState::STOPPED;