refactor: restructure slave_node into libraries

This commit is contained in:
Eduard Iten 2025-07-02 09:45:22 +02:00
parent 0088030d66
commit 6cfd4b8b4d
11 changed files with 354 additions and 424 deletions

View File

@ -6,4 +6,22 @@ list(APPEND BOARD_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(slave_node) project(slave_node)
target_sources(app PRIVATE src/main.c src/shell_modbus.c src/shell_system.c) # Define a variable for the lib directory
set(LIB_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../lib)
# Add the include directories for the libraries
target_include_directories(app PRIVATE
${LIB_DIR}/valve
${LIB_DIR}/modbus_server
${LIB_DIR}/fwu
)
# Add the source files from the app and the libraries
target_sources(app PRIVATE
src/main.c
src/shell_modbus.c
src/shell_system.c
${LIB_DIR}/valve/valve.c
${LIB_DIR}/modbus_server/modbus_server.c
${LIB_DIR}/fwu/fwu.c
)

View File

@ -1,401 +1,24 @@
/**
* @file main.c
* @brief Main application for the Irrigation System Slave Node.
*
* This file contains the main logic for the Modbus RTU slave node, including
* valve control, digital I/O, system status, and a simulated firmware update process.
*
* @copyright Copyright (c) 2020 PHYTEC Messtechnik GmbH
* @copyright Copyright (c) 2022 Nordic Semiconductor ASA
* @copyright SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h> #include <zephyr/kernel.h>
#include <zephyr/sys/util.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/modbus/modbus.h>
#include <zephyr/usb/usb_device.h>
#include <zephyr/settings/settings.h> #include <zephyr/settings/settings.h>
#include <zephyr/sys/crc.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/logging/log.h> #include <zephyr/logging/log.h>
#include "modbus_bridge.h" #include "modbus_server.h"
#include "valve.h"
#include "fwu.h"
/** @brief Logging module registration. */ LOG_MODULE_REGISTER(main, LOG_LEVEL_INF);
LOG_MODULE_REGISTER(mbs_sample, LOG_LEVEL_INF);
/** @brief Major version of the application firmware. */
#define APP_VERSION_MAJOR 1
/** @brief Minor version of the application firmware. */
#define APP_VERSION_MINOR 0
/** @brief Patch version of the application firmware. */
#define APP_VERSION_PATCH 0
/**
* @brief Modbus Input Register Addresses.
*/
enum {
/* Valve Control & Status */
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000,
REG_INPUT_MOTOR_CURRENT_MA = 0x0001,
/* Digital Inputs */
REG_INPUT_DIGITAL_INPUTS_STATE = 0x0020,
REG_INPUT_BUTTON_EVENTS = 0x0021,
/* System Config & Status */
REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR = 0x00F0,
REG_INPUT_FIRMWARE_VERSION_PATCH = 0x00F1,
REG_INPUT_DEVICE_STATUS = 0x00F2,
REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3,
REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4,
/* Firmware Update */
REG_INPUT_FWU_LAST_CHUNK_CRC = 0x0100,
};
/**
* @brief Modbus Holding Register Addresses.
*/
enum {
/* Valve Control */
REG_HOLDING_VALVE_COMMAND = 0x0000,
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001,
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002,
/* Digital Outputs */
REG_HOLDING_DIGITAL_OUTPUTS_STATE = 0x0010,
/* System Config */
REG_HOLDING_WATCHDOG_TIMEOUT_S = 0x00F0,
/* Firmware Update */
REG_HOLDING_FWU_COMMAND = 0x0100,
REG_HOLDING_FWU_CHUNK_OFFSET_LOW = 0x0101,
REG_HOLDING_FWU_CHUNK_OFFSET_HIGH = 0x0102,
REG_HOLDING_FWU_CHUNK_SIZE = 0x0103,
REG_HOLDING_FWU_DATA_BUFFER = 0x0180,
};
/** @brief Represents the physical state of the valve. */
enum valve_state { VALVE_STATE_CLOSED, VALVE_STATE_OPEN };
/** @brief Represents the current movement of the valve. */
enum valve_movement { VALVE_MOVEMENT_IDLE, VALVE_MOVEMENT_OPENING, VALVE_MOVEMENT_CLOSING, VALVE_MOVEMENT_ERROR };
/* --- State Variables --- */
static enum valve_state current_state = VALVE_STATE_CLOSED;
static enum valve_movement current_movement = VALVE_MOVEMENT_IDLE;
static uint16_t max_opening_time_s = 60;
static uint16_t max_closing_time_s = 60;
static struct k_work_delayable valve_work;
static uint16_t digital_outputs_state = 0;
static uint16_t digital_inputs_state = 0;
static uint16_t button_events = 0;
static uint16_t device_status = 0;
static uint16_t watchdog_timeout_s = 0;
static struct k_timer watchdog_timer;
/** @brief Size of the buffer for firmware update chunks. */
#define FWU_BUFFER_SIZE 256
static uint8_t fwu_buffer[FWU_BUFFER_SIZE];
static uint32_t fwu_chunk_offset = 0;
static uint16_t fwu_chunk_size = 0;
static uint16_t fwu_last_chunk_crc = 0;
static int modbus_iface;
static struct modbus_iface_param server_param = {
.mode = MODBUS_MODE_RTU,
.server = { .user_cb = NULL, .unit_id = 1 },
.serial = { .baud = 19200, .parity = UART_CFG_PARITY_NONE },
};
/**
* @brief Triggers the closing of the valve.
*
* If the valve is currently open, this function initiates the closing movement
* and schedules the completion via the valve_work handler.
*/
static void close_valve_action(void)
{
if (current_state == VALVE_STATE_OPEN) {
current_movement = VALVE_MOVEMENT_CLOSING;
k_work_schedule(&valve_work, K_SECONDS(max_closing_time_s));
}
}
/**
* @brief Watchdog timer expiration handler.
*
* This function is called by the kernel when the Modbus watchdog timer expires.
* It triggers the fail-safe action of closing the valve.
*
* @param timer_id Pointer to the timer instance that expired.
*/
static void watchdog_timer_handler(struct k_timer *timer_id)
{
LOG_WRN("Modbus watchdog expired! Closing valve as a fail-safe.");
close_valve_action();
}
/**
* @brief Resets the Modbus communication watchdog timer.
*
* This function should be called on any valid Modbus communication to prevent
* the fail-safe timeout from occurring.
*/
static inline void reset_watchdog(void)
{
if (watchdog_timeout_s > 0) {
k_timer_start(&watchdog_timer, K_SECONDS(watchdog_timeout_s), K_NO_WAIT);
}
}
/**
* @brief Work handler for completing valve movement.
*
* This function is called from a workqueue to finalize the state of the valve
* after a time-based movement simulation has completed.
*
* @param work Pointer to the work item.
*/
static void valve_work_handler(struct k_work *work)
{
if (current_movement == VALVE_MOVEMENT_OPENING) {
LOG_INF("Virtual valve finished opening");
} else if (current_movement == VALVE_MOVEMENT_CLOSING) {
current_state = VALVE_STATE_CLOSED;
LOG_INF("Virtual valve finished closing");
}
current_movement = VALVE_MOVEMENT_IDLE;
}
/**
* @brief Modbus callback for reading holding registers.
* @param addr Register address.
* @param reg Pointer to store the read value.
* @return 0 on success, negative error code otherwise.
*/
static int holding_reg_rd(uint16_t addr, uint16_t *reg)
{
reset_watchdog();
switch (addr) {
case REG_HOLDING_MAX_OPENING_TIME_S: *reg = max_opening_time_s; break;
case REG_HOLDING_MAX_CLOSING_TIME_S: *reg = max_closing_time_s; break;
case REG_HOLDING_DIGITAL_OUTPUTS_STATE: *reg = digital_outputs_state; break;
case REG_HOLDING_WATCHDOG_TIMEOUT_S: *reg = watchdog_timeout_s; break;
default: *reg = 0; break;
}
return 0;
}
/**
* @brief Modbus callback for writing holding registers.
* @param addr Register address.
* @param reg Value to write.
* @return 0 on success, negative error code otherwise.
*/
static int holding_reg_wr(uint16_t addr, uint16_t reg)
{
reset_watchdog();
switch (addr) {
case REG_HOLDING_VALVE_COMMAND:
if (reg == 1) { /* Open */
if (current_state == VALVE_STATE_CLOSED) {
current_state = VALVE_STATE_OPEN;
current_movement = VALVE_MOVEMENT_OPENING;
k_work_schedule(&valve_work, K_SECONDS(max_opening_time_s));
}
} else if (reg == 2) { /* Close */
close_valve_action();
} else if (reg == 0) { /* Stop */
k_work_cancel_delayable(&valve_work);
current_movement = VALVE_MOVEMENT_IDLE;
}
break;
case REG_HOLDING_MAX_OPENING_TIME_S:
max_opening_time_s = reg;
settings_save_one("valve/max_open_time", &max_opening_time_s, sizeof(max_opening_time_s));
break;
case REG_HOLDING_MAX_CLOSING_TIME_S:
max_closing_time_s = reg;
settings_save_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s));
break;
case REG_HOLDING_DIGITAL_OUTPUTS_STATE:
digital_outputs_state = reg;
LOG_INF("Digital outputs set to 0x%04X", digital_outputs_state);
break;
case REG_HOLDING_WATCHDOG_TIMEOUT_S:
watchdog_timeout_s = reg;
if (watchdog_timeout_s > 0) {
LOG_INF("Watchdog enabled with %u s timeout.", watchdog_timeout_s);
reset_watchdog();
} else {
LOG_INF("Watchdog disabled.");
k_timer_stop(&watchdog_timer);
}
break;
case REG_HOLDING_FWU_COMMAND:
if (reg == 1) { LOG_INF("FWU: Chunk at offset %u (size %u) verified.", fwu_chunk_offset, fwu_chunk_size); }
else if (reg == 2) { LOG_INF("FWU: Finalize command received. Rebooting (simulated)."); }
break;
case REG_HOLDING_FWU_CHUNK_OFFSET_LOW: fwu_chunk_offset = (fwu_chunk_offset & 0xFFFF0000) | reg; break;
case REG_HOLDING_FWU_CHUNK_OFFSET_HIGH: fwu_chunk_offset = (fwu_chunk_offset & 0x0000FFFF) | ((uint32_t)reg << 16); break;
case REG_HOLDING_FWU_CHUNK_SIZE: fwu_chunk_size = (reg > FWU_BUFFER_SIZE) ? FWU_BUFFER_SIZE : reg; break;
default:
if (addr >= REG_HOLDING_FWU_DATA_BUFFER && addr < (REG_HOLDING_FWU_DATA_BUFFER + (FWU_BUFFER_SIZE / 2))) {
uint16_t index = (addr - REG_HOLDING_FWU_DATA_BUFFER) * 2;
if (index < sizeof(fwu_buffer)) {
sys_put_be16(reg, &fwu_buffer[index]);
if (index + 2 >= fwu_chunk_size) {
fwu_last_chunk_crc = crc16_ccitt(0xffff, fwu_buffer, fwu_chunk_size);
LOG_INF("FWU: Chunk received, CRC is 0x%04X", fwu_last_chunk_crc);
}
}
}
break;
}
return 0;
}
/**
* @brief Modbus callback for reading input registers.
* @param addr Register address.
* @param reg Pointer to store the read value.
* @return 0 on success, negative error code otherwise.
*/
static int input_reg_rd(uint16_t addr, uint16_t *reg)
{
reset_watchdog();
uint32_t uptime_s = k_uptime_get_32() / 1000;
switch (addr) {
case REG_INPUT_VALVE_STATE_MOVEMENT: *reg = (current_movement << 8) | (current_state & 0xFF); break;
case REG_INPUT_MOTOR_CURRENT_MA: *reg = (current_movement != VALVE_MOVEMENT_IDLE) ? 150 : 10; break;
case REG_INPUT_DIGITAL_INPUTS_STATE: *reg = digital_inputs_state; break;
case REG_INPUT_BUTTON_EVENTS: *reg = button_events; button_events = 0; break;
case REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR: *reg = (APP_VERSION_MAJOR << 8) | (APP_VERSION_MINOR & 0xFF); break;
case REG_INPUT_FIRMWARE_VERSION_PATCH: *reg = APP_VERSION_PATCH; break;
case REG_INPUT_DEVICE_STATUS: *reg = device_status; break;
case REG_INPUT_UPTIME_SECONDS_LOW: *reg = (uint16_t)(uptime_s & 0xFFFF); break;
case REG_INPUT_UPTIME_SECONDS_HIGH: *reg = (uint16_t)(uptime_s >> 16); break;
case REG_INPUT_FWU_LAST_CHUNK_CRC: *reg = fwu_last_chunk_crc; break;
default: *reg = 0; break;
}
return 0;
}
static struct modbus_user_callbacks mbs_cbs = {
.holding_reg_rd = holding_reg_rd,
.holding_reg_wr = holding_reg_wr,
.input_reg_rd = input_reg_rd,
};
/** @brief Device tree node for the Modbus serial interface. */
#define MODBUS_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_modbus_serial)
/**
* @brief Reconfigures the Modbus interface with new parameters.
* @param baudrate New baud rate.
* @param unit_id New unit ID.
* @return 0 on success, negative error code otherwise.
*/
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id) { /* ... */ return 0; }
/**
* @brief Gets the current Modbus baud rate.
* @return Current baud rate.
*/
uint32_t modbus_get_baudrate(void) { return server_param.serial.baud; }
/**
* @brief Gets the current Modbus unit ID.
* @return Current unit ID.
*/
uint8_t modbus_get_unit_id(void) { return server_param.server.unit_id; }
/**
* @brief Sets the maximum valve opening time.
* @param seconds Time in seconds.
*/
void valve_set_max_open_time(uint16_t seconds) { max_opening_time_s = seconds; settings_save_one("valve/max_open_time", &max_opening_time_s, sizeof(max_opening_time_s)); }
/**
* @brief Sets the maximum valve closing time.
* @param seconds Time in seconds.
*/
void valve_set_max_close_time(uint16_t seconds) { max_closing_time_s = seconds; settings_save_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s)); }
/**
* @brief Gets the maximum valve opening time.
* @return Time in seconds.
*/
uint16_t valve_get_max_open_time(void) { return max_opening_time_s; }
/**
* @brief Gets the maximum valve closing time.
* @return Time in seconds.
*/
uint16_t valve_get_max_close_time(void) { return max_closing_time_s; }
/**
* @brief Callback for loading settings from non-volatile storage.
* @param name Name of the setting.
* @param len Length of the setting value.
* @param read_cb Function to read the setting value.
* @param cb_arg Callback argument.
* @return 0 on success, negative error code otherwise.
*/
static int settings_load_cb(const char *name, size_t len, settings_read_cb read_cb, void *cb_arg) {
const char *next;
int rc;
if (settings_name_steq(name, "baudrate", &next) && !next) {
rc = read_cb(cb_arg, &server_param.serial.baud, sizeof(server_param.serial.baud));
return (rc < 0) ? rc : 0;
}
if (settings_name_steq(name, "unit_id", &next) && !next) {
rc = read_cb(cb_arg, &server_param.server.unit_id, sizeof(server_param.server.unit_id));
return (rc < 0) ? rc : 0;
}
if (settings_name_steq(name, "max_open_time", &next) && !next) {
rc = read_cb(cb_arg, &max_opening_time_s, sizeof(max_opening_time_s));
return (rc < 0) ? rc : 0;
}
if (settings_name_steq(name, "max_close_time", &next) && !next) {
rc = read_cb(cb_arg, &max_closing_time_s, sizeof(max_closing_time_s));
return (rc < 0) ? rc : 0;
}
return -ENOENT;
}
/** @brief Settings handler definition for Modbus parameters. */
SETTINGS_STATIC_HANDLER_DEFINE(modbus, "modbus", NULL, settings_load_cb, NULL, NULL);
/** @brief Settings handler definition for valve parameters. */
SETTINGS_STATIC_HANDLER_DEFINE(valve, "valve", NULL, settings_load_cb, NULL, NULL);
/**
* @brief Initializes the Modbus server interface.
*
* @return 0 on success, negative error code otherwise.
*/
static int init_modbus_server(void)
{
const char iface_name[] = {DEVICE_DT_NAME(MODBUS_NODE)};
modbus_iface = modbus_iface_get_by_name(iface_name);
if (modbus_iface < 0) { return modbus_iface; }
server_param.server.user_cb = &mbs_cbs;
return modbus_init_server(modbus_iface, server_param);
}
/**
* @brief Main entry point for the application.
*
* Initializes all subsystems including Modbus, settings, and timers,
* then enters an idle state.
*
* @return 0 on success, negative error code otherwise.
*/
int main(void) int main(void)
{ {
LOG_INF("Starting Irrigation System Slave Node"); LOG_INF("Starting Irrigation System Slave Node");
k_work_init_delayable(&valve_work, valve_work_handler);
k_timer_init(&watchdog_timer, watchdog_timer_handler, NULL);
if (settings_subsys_init() || settings_load()) { if (settings_subsys_init() || settings_load()) {
LOG_ERR("Settings initialization or loading failed"); LOG_ERR("Settings initialization or loading failed");
} }
if (init_modbus_server()) { valve_init();
fwu_init();
if (modbus_server_init()) {
LOG_ERR("Modbus RTU server initialization failed"); LOG_ERR("Modbus RTU server initialization failed");
return 0; return 0;
} }

View File

@ -1,32 +0,0 @@
#ifndef MODBUS_BRIDGE_H
#define MODBUS_BRIDGE_H
#include <stdint.h>
/**
* @brief Reconfigures the Modbus server with new parameters.
*
* @param baudrate New baudrate.
* @param unit_id New slave unit ID.
* @return 0 on success, negative error code on failure.
*/
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id);
/**
* @brief Gets the currently active Modbus baudrate.
* @return The current baudrate.
*/
uint32_t modbus_get_baudrate(void);
/**
* @brief Gets the currently active Modbus slave unit ID.
* @return The current slave unit ID.
*/
uint8_t modbus_get_unit_id(void);
void valve_set_max_open_time(uint16_t seconds);
void valve_set_max_close_time(uint16_t seconds);
uint16_t valve_get_max_open_time(void);
uint16_t valve_get_max_close_time(void);
#endif // MODBUS_BRIDGE_H

View File

@ -1,6 +1,7 @@
#include <zephyr/shell/shell.h> #include <zephyr/shell/shell.h>
#include <stdlib.h> #include <stdlib.h>
#include "modbus_bridge.h" #include "modbus_server.h"
#include "valve.h"
static int cmd_modbus_set_baud(const struct shell *sh, size_t argc, char **argv) static int cmd_modbus_set_baud(const struct shell *sh, size_t argc, char **argv)
{ {

View File

@ -1,4 +1,4 @@
# Add your shared libraries here add_subdirectory(modbus)
# Example: add_subdirectory(valve)
# add_library(modbus modbus/modbus.c) add_subdirectory(modbus_server)
# target_include_directories(modbus PUBLIC .) add_subdirectory(fwu)

45
software/lib/fwu/fwu.c Normal file
View File

@ -0,0 +1,45 @@
#include "fwu.h"
#include <zephyr/kernel.h>
#include <zephyr/sys/crc.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(fwu, LOG_LEVEL_INF);
#define FWU_BUFFER_SIZE 256
static uint8_t fwu_buffer[FWU_BUFFER_SIZE];
static uint32_t fwu_chunk_offset = 0;
static uint16_t fwu_chunk_size = 0;
static uint16_t fwu_last_chunk_crc = 0;
void fwu_init(void) {}
void fwu_handler(uint16_t addr, uint16_t reg)
{
// This is a simplified handler. In a real scenario, you would have a proper mapping
// between register addresses and actions.
if (addr == 0x0100) { // FWU_COMMAND
if (reg == 1) { LOG_INF("FWU: Chunk at offset %u (size %u) verified.", fwu_chunk_offset, fwu_chunk_size); }
else if (reg == 2) { LOG_INF("FWU: Finalize command received. Rebooting (simulated)."); }
} else if (addr == 0x0101) { // FWU_CHUNK_OFFSET_LOW
fwu_chunk_offset = (fwu_chunk_offset & 0xFFFF0000) | reg;
} else if (addr == 0x0102) { // FWU_CHUNK_OFFSET_HIGH
fwu_chunk_offset = (fwu_chunk_offset & 0x0000FFFF) | ((uint32_t)reg << 16);
} else if (addr == 0x0103) { // FWU_CHUNK_SIZE
fwu_chunk_size = (reg > FWU_BUFFER_SIZE) ? FWU_BUFFER_SIZE : reg;
} else if (addr >= 0x0180 && addr < (0x0180 + (FWU_BUFFER_SIZE / 2))) {
uint16_t index = (addr - 0x0180) * 2;
if (index < sizeof(fwu_buffer)) {
sys_put_be16(reg, &fwu_buffer[index]);
if (index + 2 >= fwu_chunk_size) {
fwu_last_chunk_crc = crc16_ccitt(0xffff, fwu_buffer, fwu_chunk_size);
LOG_INF("FWU: Chunk received, CRC is 0x%04X", fwu_last_chunk_crc);
}
}
}
}
uint16_t fwu_get_last_chunk_crc(void)
{
return fwu_last_chunk_crc;
}

10
software/lib/fwu/fwu.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef FWU_H
#define FWU_H
#include <stdint.h>
void fwu_init(void);
void fwu_handler(uint16_t addr, uint16_t reg);
uint16_t fwu_get_last_chunk_crc(void);
#endif // FWU_H

View File

@ -0,0 +1,169 @@
#include <zephyr/kernel.h>
#include "modbus_server.h"
#include <zephyr/modbus/modbus.h>
#include <zephyr/logging/log.h>
#include <zephyr/settings/settings.h>
#include <zephyr/sys/reboot.h>
#include "valve.h"
#include "fwu.h"
LOG_MODULE_REGISTER(modbus_server, LOG_LEVEL_INF);
/**
* @brief Modbus Input Register Addresses.
*/
enum {
/* Valve Control & Status */
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000,
REG_INPUT_MOTOR_CURRENT_MA = 0x0001,
/* Digital Inputs */
REG_INPUT_DIGITAL_INPUTS_STATE = 0x0020,
REG_INPUT_BUTTON_EVENTS = 0x0021,
/* System Config & Status */
REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR = 0x00F0,
REG_INPUT_FIRMWARE_VERSION_PATCH = 0x00F1,
REG_INPUT_DEVICE_STATUS = 0x00F2,
REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3,
REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4,
/* Firmware Update */
REG_INPUT_FWU_LAST_CHUNK_CRC = 0x0100,
};
/**
* @brief Modbus Holding Register Addresses.
*/
enum {
/* Valve Control */
REG_HOLDING_VALVE_COMMAND = 0x0000,
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001,
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002,
/* Digital Outputs */
REG_HOLDING_DIGITAL_OUTPUTS_STATE = 0x0010,
/* System Config */
REG_HOLDING_WATCHDOG_TIMEOUT_S = 0x00F0,
/* Firmware Update */
REG_HOLDING_FWU_COMMAND = 0x0100,
REG_HOLDING_FWU_CHUNK_OFFSET_LOW = 0x0101,
REG_HOLDING_FWU_CHUNK_OFFSET_HIGH = 0x0102,
REG_HOLDING_FWU_CHUNK_SIZE = 0x0103,
REG_HOLDING_FWU_DATA_BUFFER = 0x0180,
};
static int modbus_iface;
static struct modbus_iface_param server_param = {
.mode = MODBUS_MODE_RTU,
.server = { .user_cb = NULL, .unit_id = 1 },
.serial = { .baud = 19200, .parity = UART_CFG_PARITY_NONE },
};
static uint16_t watchdog_timeout_s = 0;
static struct k_timer watchdog_timer;
static void watchdog_timer_handler(struct k_timer *timer_id)
{
LOG_WRN("Modbus watchdog expired! Closing valve as a fail-safe.");
valve_close();
}
static inline void reset_watchdog(void)
{
if (watchdog_timeout_s > 0) {
k_timer_start(&watchdog_timer, K_SECONDS(watchdog_timeout_s), K_NO_WAIT);
}
}
static int holding_reg_rd(uint16_t addr, uint16_t *reg)
{
reset_watchdog();
switch (addr) {
case REG_HOLDING_MAX_OPENING_TIME_S: *reg = valve_get_max_open_time(); break;
case REG_HOLDING_MAX_CLOSING_TIME_S: *reg = valve_get_max_close_time(); break;
case REG_HOLDING_WATCHDOG_TIMEOUT_S: *reg = watchdog_timeout_s; break;
default: *reg = 0; break;
}
return 0;
}
static int holding_reg_wr(uint16_t addr, uint16_t reg)
{
reset_watchdog();
switch (addr) {
case REG_HOLDING_VALVE_COMMAND:
if (reg == 1) { valve_open(); }
else if (reg == 2) { valve_close(); }
else if (reg == 0) { valve_stop(); }
break;
case REG_HOLDING_MAX_OPENING_TIME_S:
valve_set_max_open_time(reg);
break;
case REG_HOLDING_MAX_CLOSING_TIME_S:
valve_set_max_close_time(reg);
break;
case REG_HOLDING_WATCHDOG_TIMEOUT_S:
watchdog_timeout_s = reg;
if (watchdog_timeout_s > 0) {
LOG_INF("Watchdog enabled with %u s timeout.", watchdog_timeout_s);
reset_watchdog();
} else {
LOG_INF("Watchdog disabled.");
k_timer_stop(&watchdog_timer);
}
break;
default:
fwu_handler(addr, reg);
break;
}
return 0;
}
static int input_reg_rd(uint16_t addr, uint16_t *reg)
{
reset_watchdog();
uint32_t uptime_s = k_uptime_get_32() / 1000;
switch (addr) {
case REG_INPUT_VALVE_STATE_MOVEMENT: *reg = (valve_get_movement() << 8) | (valve_get_state() & 0xFF); break;
case REG_INPUT_MOTOR_CURRENT_MA: *reg = valve_get_motor_current(); break;
case REG_INPUT_UPTIME_SECONDS_LOW: *reg = (uint16_t)(uptime_s & 0xFFFF); break;
case REG_INPUT_UPTIME_SECONDS_HIGH: *reg = (uint16_t)(uptime_s >> 16); break;
case REG_INPUT_FWU_LAST_CHUNK_CRC: *reg = fwu_get_last_chunk_crc(); break;
default: *reg = 0; break;
}
return 0;
}
static struct modbus_user_callbacks mbs_cbs = {
.holding_reg_rd = holding_reg_rd,
.holding_reg_wr = holding_reg_wr,
.input_reg_rd = input_reg_rd,
};
#define MODBUS_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_modbus_serial)
int modbus_server_init(void)
{
k_timer_init(&watchdog_timer, watchdog_timer_handler, NULL);
const char iface_name[] = {DEVICE_DT_NAME(MODBUS_NODE)};
modbus_iface = modbus_iface_get_by_name(iface_name);
if (modbus_iface < 0) { return modbus_iface; }
server_param.server.user_cb = &mbs_cbs;
return modbus_init_server(modbus_iface, server_param);
}
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id)
{
server_param.serial.baud = baudrate;
server_param.server.unit_id = unit_id;
int ret = modbus_init_server(modbus_iface, server_param);
if (ret == 0) {
settings_save_one("modbus/baudrate", &baudrate, sizeof(baudrate));
settings_save_one("modbus/unit_id", &unit_id, sizeof(unit_id));
}
return ret;
}
uint32_t modbus_get_baudrate(void) { return server_param.serial.baud; }
uint8_t modbus_get_unit_id(void) { return server_param.server.unit_id; }

View File

@ -0,0 +1,11 @@
#ifndef MODBUS_SERVER_H
#define MODBUS_SERVER_H
#include <stdint.h>
int modbus_server_init(void);
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id);
uint32_t modbus_get_baudrate(void);
uint8_t modbus_get_unit_id(void);
#endif // MODBUS_SERVER_H

View File

@ -0,0 +1,62 @@
#include "valve.h"
#include <zephyr/kernel.h>
#include <zephyr/settings/settings.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(valve, LOG_LEVEL_INF);
static enum valve_state current_state = VALVE_STATE_CLOSED;
static enum valve_movement current_movement = VALVE_MOVEMENT_IDLE;
static uint16_t max_opening_time_s = 60;
static uint16_t max_closing_time_s = 60;
static struct k_work_delayable valve_work;
static void valve_work_handler(struct k_work *work)
{
if (current_movement == VALVE_MOVEMENT_OPENING) {
LOG_INF("Virtual valve finished opening");
} else if (current_movement == VALVE_MOVEMENT_CLOSING) {
current_state = VALVE_STATE_CLOSED;
LOG_INF("Virtual valve finished closing");
}
current_movement = VALVE_MOVEMENT_IDLE;
}
void valve_init(void)
{
k_work_init_delayable(&valve_work, valve_work_handler);
settings_load_one("valve/max_open_time", &max_opening_time_s, sizeof(max_opening_time_s));
settings_load_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s));
}
void valve_open(void)
{
if (current_state == VALVE_STATE_CLOSED) {
current_state = VALVE_STATE_OPEN;
current_movement = VALVE_MOVEMENT_OPENING;
k_work_schedule(&valve_work, K_SECONDS(max_opening_time_s));
}
}
void valve_close(void)
{
if (current_state == VALVE_STATE_OPEN) {
current_movement = VALVE_MOVEMENT_CLOSING;
k_work_schedule(&valve_work, K_SECONDS(max_closing_time_s));
}
}
void valve_stop(void)
{
k_work_cancel_delayable(&valve_work);
current_movement = VALVE_MOVEMENT_IDLE;
}
enum valve_state valve_get_state(void) { return current_state; }
enum valve_movement valve_get_movement(void) { return current_movement; }
uint16_t valve_get_motor_current(void) { return (current_movement != VALVE_MOVEMENT_IDLE) ? 150 : 10; }
void valve_set_max_open_time(uint16_t seconds) { max_opening_time_s = seconds; settings_save_one("valve/max_open_time", &max_opening_time_s, sizeof(max_opening_time_s)); }
void valve_set_max_close_time(uint16_t seconds) { max_closing_time_s = seconds; settings_save_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s)); }
uint16_t valve_get_max_open_time(void) { return max_opening_time_s; }
uint16_t valve_get_max_close_time(void) { return max_closing_time_s; }

View File

@ -0,0 +1,23 @@
#ifndef VALVE_H
#define VALVE_H
#include <stdint.h>
enum valve_state { VALVE_STATE_CLOSED, VALVE_STATE_OPEN };
enum valve_movement { VALVE_MOVEMENT_IDLE, VALVE_MOVEMENT_OPENING, VALVE_MOVEMENT_CLOSING, VALVE_MOVEMENT_ERROR };
void valve_init(void);
void valve_open(void);
void valve_close(void);
void valve_stop(void);
enum valve_state valve_get_state(void);
enum valve_movement valve_get_movement(void);
uint16_t valve_get_motor_current(void);
void valve_set_max_open_time(uint16_t seconds);
void valve_set_max_close_time(uint16_t seconds);
uint16_t valve_get_max_open_time(void);
uint16_t valve_get_max_close_time(void);
#endif // VALVE_H