irrigation_system/software/lib/canbus.c

95 lines
2.5 KiB
C

#include "canbus.h"
#include <zephyr/logging/log.h>
#include <zephyr/kernel.h>
#include "settings.h"
const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus));
K_THREAD_STACK_DEFINE(rx_thread_stack, RX_THREAD_STACK_SIZE);
static uint8_t node_id = 12; // Default node ID
LOG_MODULE_REGISTER(canbus, CONFIG_LOG_CAN_LEVEL);
static int canbus_set(const char *key, size_t len, settings_read_cb read_cb, void *cb_arg)
{
const char *next;
int rc;
// Handle setting values for CAN bus configuration
LOG_DBG("Setting CAN bus configuration: key=%s, len=%zu", key, len);
if (settings_name_steq(key, "node_id", &next) && next != NULL)
{
if (len != sizeof(node_id))
{
LOG_ERR("Invalid length for node_id setting: %zu", len);
return -EINVAL; // Invalid argument
}
int rc = read_cb(cb_arg, &node_id, sizeof(node_id));
if (rc < 0)
{
LOG_ERR("Failed to read node_id setting: %d", rc);
return rc; // Read error
}
LOG_DBG("Set CAN bus node ID to: %d", node_id);
}
return 0; // Return 0 on success
}
struct settings_handler canbus_settings_handler = {
.name = "canbus",
.h_set = canbus_set, // No settings set handler
};
int canbus_init(void)
{
int rc;
settings_subsys_init();
settings_register(&canbus_settings_handler);
settings_load();
rc = settings_get_val_len("canbus/node_id");
if (rc < 0)
{
LOG_ERR("Failed to check CAN bus settings: %d", rc);
return rc;
}
else if (rc == 0)
{
LOG_WRN("No CAN bus node id found in settings, using default default (%d)", node_id);
settings_save_one("canbus/node_id", &node_id, sizeof(node_id));
if (rc < 0)
{
LOG_ERR("Failed to save default CAN bus node id: %d", rc);
return rc;
}
}
else
{
rc = settings_load_one("canbus/node_id", &node_id, sizeof(node_id));
if (rc < 0)
{
LOG_ERR("Failed to load CAN bus node id from settings: %d", rc);
return rc;
}
LOG_DBG("Loaded CAN bus node id: %d", node_id);
}
if (!device_is_ready(can_dev))
{
LOG_ERR("CAN device %s is not ready", can_dev->name);
return -ENODEV;
}
#ifdef CONFIG_LOOPBACK_MODE
rc = can_set_mode(can_dev, CAN_MODE_LOOPBACK);
if (rc != 0)
{
LOG_ERR("Failed to set CAN loopback mode: %d", rc);
return rc;
}
#endif
return 0;
}