/* * SPDX-FileCopyrightText: 2025 Kozmotronik Tech * * SPDX-License-Identifier: MIT */ #include "esp_check.h" #include "relay_chn_priv_types.h" #include "relay_chn_core.h" #include "relay_chn_ctl.h" #include "relay_chn_output.h" #if CONFIG_RELAY_CHN_ENABLE_NVS #include "relay_chn_nvs.h" #endif static const char *TAG = "RELAY_CHN_CTL"; static relay_chn_ctl_t chn_ctl; esp_err_t relay_chn_ctl_init(relay_chn_output_t *output, relay_chn_run_info_t *run_info) { // Initialize the relay channel chn_ctl.id = 0; // Single channel, so ID is 0 chn_ctl.state = RELAY_CHN_STATE_IDLE; chn_ctl.pending_cmd = RELAY_CHN_CMD_NONE; chn_ctl.output = output; chn_ctl.run_info = run_info; #if CONFIG_RELAY_CHN_ENABLE_RUN_LIMIT uint16_t run_limit_sec = CONFIG_RELAY_CHN_RUN_LIMIT_DEFAULT_SEC; esp_err_t ret; #if CONFIG_RELAY_CHN_ENABLE_NVS // Load run limit value from NVS ret = relay_chn_nvs_get_run_limit(chn_ctl.id, &run_limit_sec); if (ret != ESP_OK && ret != ESP_ERR_NVS_NOT_FOUND) { ESP_LOGE(TAG, "Failed to load run limit from NVS with error: %s", esp_err_to_name(ret)); } #endif chn_ctl.run_limit_sec = run_limit_sec; ret = relay_chn_init_run_limit_timer(&chn_ctl); ESP_RETURN_ON_ERROR(ret, TAG, "Failed to initialize run limit timer"); #endif return relay_chn_init_timer(&chn_ctl); // Create direction change inertia timer } void relay_chn_ctl_deinit() { if (chn_ctl.inertia_timer != NULL) { esp_timer_delete(chn_ctl.inertia_timer); chn_ctl.inertia_timer = NULL; } #if CONFIG_RELAY_CHN_ENABLE_RUN_LIMIT if (chn_ctl.run_limit_timer != NULL) { esp_timer_delete(chn_ctl.run_limit_timer); chn_ctl.run_limit_timer = NULL; } #endif } /* relay_chn APIs */ relay_chn_state_t relay_chn_ctl_get_state() { return chn_ctl.state; } char *relay_chn_ctl_get_state_str() { return relay_chn_state_str(chn_ctl.state); } void relay_chn_ctl_run_forward() { relay_chn_issue_cmd(&chn_ctl, RELAY_CHN_CMD_FORWARD); } void relay_chn_ctl_run_reverse() { relay_chn_issue_cmd(&chn_ctl, RELAY_CHN_CMD_REVERSE); } void relay_chn_ctl_stop() { relay_chn_issue_cmd(&chn_ctl, RELAY_CHN_CMD_STOP); } void relay_chn_ctl_flip_direction() { relay_chn_issue_cmd(&chn_ctl, RELAY_CHN_CMD_FLIP); } relay_chn_direction_t relay_chn_ctl_get_direction() { return relay_chn_output_get_direction(chn_ctl.output); } #if CONFIG_RELAY_CHN_ENABLE_RUN_LIMIT uint16_t relay_chn_ctl_get_run_limit() { return chn_ctl.run_limit_sec; } void relay_chn_ctl_set_run_limit(uint16_t time_sec) { // Check for boundaries if (time_sec > CONFIG_RELAY_CHN_RUN_LIMIT_MAX_SEC) time_sec = CONFIG_RELAY_CHN_RUN_LIMIT_MAX_SEC; else if (time_sec < CONFIG_RELAY_CHN_RUN_LIMIT_MIN_SEC) time_sec = CONFIG_RELAY_CHN_RUN_LIMIT_MIN_SEC; chn_ctl.run_limit_sec = time_sec; #if CONFIG_RELAY_CHN_ENABLE_NVS relay_chn_nvs_set_run_limit(chn_ctl.id, time_sec); #endif } #endif /* relay_chn APIs */ relay_chn_ctl_t *relay_chn_ctl_get() { return &chn_ctl; }