on_disconnect callback

This commit is contained in:
oarcher 2024-07-17 20:27:25 +02:00
parent a702097b1f
commit 290952fd9c
2 changed files with 26 additions and 0 deletions

View file

@ -8,6 +8,7 @@ from esphome.const import (
CONF_MODEL, CONF_MODEL,
CONF_TRIGGER_ID, CONF_TRIGGER_ID,
CONF_ON_CONNECT, CONF_ON_CONNECT,
CONF_ON_DISCONNECT,
) )
import esphome.codegen as cg import esphome.codegen as cg
import esphome.config_validation as cv import esphome.config_validation as cv
@ -36,6 +37,9 @@ ModemOnNotRespondingTrigger = modem_ns.class_(
ModemOnConnectTrigger = modem_ns.class_( ModemOnConnectTrigger = modem_ns.class_(
"ModemOnConnectTrigger", automation.Trigger.template() "ModemOnConnectTrigger", automation.Trigger.template()
) )
ModemOnDisconnectTrigger = modem_ns.class_(
"ModemOndisconnectTrigger", automation.Trigger.template()
)
CONFIG_SCHEMA = cv.All( CONFIG_SCHEMA = cv.All(
@ -62,6 +66,13 @@ CONFIG_SCHEMA = cv.All(
cv.Optional(CONF_ON_CONNECT): automation.validate_automation( cv.Optional(CONF_ON_CONNECT): automation.validate_automation(
{cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ModemOnConnectTrigger)} {cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(ModemOnConnectTrigger)}
), ),
cv.Optional(CONF_ON_DISCONNECT): automation.validate_automation(
{
cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(
ModemOnDisconnectTrigger
)
}
),
} }
).extend(cv.COMPONENT_SCHEMA), ).extend(cv.COMPONENT_SCHEMA),
cv.require_framework_version( cv.require_framework_version(
@ -130,4 +141,8 @@ async def to_code(config):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var) trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf) await automation.build_automation(trigger, [], conf)
for conf in config.get(CONF_ON_DISCONNECT, []):
trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID], var)
await automation.build_automation(trigger, [], conf)
await cg.register_component(var, config) await cg.register_component(var, config)

View file

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