added formatting

This commit is contained in:
Eduard Iten 2025-07-08 16:06:11 +02:00
parent bc327acc41
commit 9b7159d5a4
33 changed files with 685 additions and 615 deletions

56
setup-format-hook.sh Executable file
View File

@ -0,0 +1,56 @@
#!/bin/sh
# This script sets up a Git pre-commit hook to automatically format C/C++ files
# in the 'software/' subdirectory using clang-format.
# Define the path for the pre-commit hook
HOOK_DIR=".git/hooks"
HOOK_FILE="$HOOK_DIR/pre-commit"
# Create the hooks directory if it doesn't exist
mkdir -p "$HOOK_DIR"
# Create the pre-commit hook script using a 'here document'
cat > "$HOOK_FILE" << 'EOF'
#!/bin/sh
# --- Pre-commit hook for clang-format ---
#
# This hook formats staged C, C++, and Objective-C files in the 'software/'
# subdirectory before a commit is made.
# It automatically finds the .clang-format file in the software/ directory.
#
# Directory to be formatted
TARGET_DIR="software/"
# Use git diff to find staged files that are Added (A), Copied (C), or Modified (M).
# We filter for files only within the TARGET_DIR.
# The grep regex matches common C/C++ and Objective-C file extensions.
FILES_TO_FORMAT=$(git diff --cached --name-only --diff-filter=ACM "$TARGET_DIR" | grep -E '\.(c|h|cpp|hpp|cxx|hxx|cc|hh|m|mm)$')
if [ -z "$FILES_TO_FORMAT" ]; then
# No relevant files to format, exit successfully.
exit 0
fi
echo " Running clang-format on staged files in '$TARGET_DIR'..."
# Run clang-format in-place on the identified files.
# clang-format will automatically find the .clang-format file in the software/ directory
# or any of its parent directories.
echo "$FILES_TO_FORMAT" | xargs clang-format -i
# Since clang-format may have changed the files, we need to re-stage them.
echo "$FILES_TO_FORMAT" | xargs git add
echo " Formatting complete."
exit 0
EOF
# Make the hook executable
chmod +x "$HOOK_FILE"
echo "✅ Git pre-commit hook has been set up successfully."
echo " It will now automatically format files in the '$PWD/software' directory before each commit."

5
software/.clang-format Normal file
View File

@ -0,0 +1,5 @@
# .clang-format
BasedOnStyle: Google
#IndentWidth: 4
#ColumnLimit: 100
#AllowShortFunctionsOnASingleLine: None

View File

@ -1,13 +1,12 @@
{ {
// Hush CMake // Hush CMake
"cmake.configureOnOpen": false, "cmake.configureOnOpen": false,
// IntelliSense // IntelliSense
"C_Cpp.default.compilerPath": "${userHome}/zephyr-sdk-0.17.1/arm-zephyr-eabi/bin/arm-zephyr-eabi-gcc.exe", "C_Cpp.default.compilerPath": "${userHome}/zephyr-sdk-0.17.1/arm-zephyr-eabi/bin/arm-zephyr-eabi-gcc.exe",
"C_Cpp.default.compileCommands": "${workspaceFolder}/build/compile_commands.json", "C_Cpp.default.compileCommands": "${workspaceFolder}/build/compile_commands.json",
// File Associations // File Associations
"files.associations": { "files.associations": {
"app_version.h": "c" "app_version.h": "c"
} },
"C_Cpp.clang_format_style": "file",
} }

View File

@ -2,31 +2,19 @@
"version": "2.0.0", "version": "2.0.0",
"tasks": [ "tasks": [
{ {
"label": "West Build", "label": "Format All C/C++ Files",
"type": "shell", "type": "shell",
"command": "find . -name \"*.c\" -o -name \"*.h\" | xargs clang-format -i",
"problemMatcher": [],
"group": { "group": {
"kind": "build", "kind": "build",
"isDefault": true "isDefault": true
}, },
"linux": { "presentation": {
"command": "${userHome}/zephyrproject/.venv/bin/west" "reveal": "silent",
}, "clear": true,
"windows": { "panel": "shared"
"command": "${userHome}/zephyrproject/.venv/Scripts/west.exe" }
},
"osx": {
"command": "${userHome}/zephyrproject/.venv/bin/west"
},
"args": [
"build",
"-p",
"auto",
"-b",
"valve_node"
],
"problemMatcher": [
"$gcc"
]
}, },
{ {
"label": "West Configurable Build", "label": "West Configurable Build",

View File

View File

View File

View File

View File

@ -6,8 +6,7 @@
#include <zephyr/kernel.h> #include <zephyr/kernel.h>
int main(void) int main(void) {
{
printk("Hello from Gateway!\n"); printk("Hello from Gateway!\n");
return 0; return 0;
} }

View File

@ -0,0 +1,12 @@
{
"configurations": [
{
"name": "Linux",
"compileCommands": "${workspaceFolder}/build/compile_commands.json",
"cStandard": "c99",
"cppStandard": "gnu++17",
"intelliSenseMode": "linux-gcc-arm"
}
],
"version": 4
}

View File

@ -0,0 +1,5 @@
VERSION_MAJOR = 0
VERSION_MINOR = 0
PATCHLEVEL = 1
VERSION_TWEAK = 1
EXTRAVERSION = devel

View File

@ -1,16 +1,17 @@
#include <zephyr/kernel.h> #include <app_version.h>
#include <zephyr/settings/settings.h> #include <lib/fwu.h>
#include <zephyr/logging/log.h>
#include <lib/modbus_server.h> #include <lib/modbus_server.h>
#include <lib/valve.h> #include <lib/valve.h>
#include <lib/fwu.h> #include <zephyr/kernel.h>
#include <app_version.h> #include <zephyr/logging/log.h>
#include <zephyr/settings/settings.h>
LOG_MODULE_REGISTER(main, LOG_LEVEL_INF); LOG_MODULE_REGISTER(main, LOG_LEVEL_INF);
int main(void) int main(void) {
{ int rc;
LOG_INF("Starting Irrigation System Slave Node version %s (Build version %s)", APP_VERSION_STRING, STRINGIFY(APP_BUILD_VERSION)); LOG_INF("Starting Irrigation System Slave Node version %s (Build version %s)",
APP_VERSION_STRING, STRINGIFY(APP_BUILD_VERSION));
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");
@ -19,7 +20,8 @@ int main(void)
valve_init(); valve_init();
fwu_init(); fwu_init();
if (modbus_server_init()) { rc = modbus_server_init();
if (rc < 0) {
LOG_ERR("Modbus RTU server initialization failed"); LOG_ERR("Modbus RTU server initialization failed");
return 0; return 0;
} }

View File

@ -7,16 +7,15 @@
* @file modbus_server.h * @file modbus_server.h
* @brief API for the Modbus server implementation. * @brief API for the Modbus server implementation.
* *
* This file defines the Modbus register map and provides functions to initialize * This file defines the Modbus register map and provides functions to
* and manage the Modbus server. * initialize and manage the Modbus server.
*/ */
/** /**
* @brief Modbus Input Register Addresses (Read-Only). * @brief Modbus Input Register Addresses (Read-Only).
* @see docs/modbus-registers.de.md * @see docs/modbus-registers.de.md
*/ */
enum enum {
{
/** /**
* @brief Kombiniertes Status-Register für das Ventil. * @brief Kombiniertes Status-Register für das Ventil.
* High-Byte: Bewegung (0=Idle, 1=Öffnet, 2=Schliesst, 3=Fehler). * High-Byte: Bewegung (0=Idle, 1=Öffnet, 2=Schliesst, 3=Fehler).
@ -28,11 +27,13 @@ enum
*/ */
REG_INPUT_MOTOR_CURRENT_MA = 0x0001, REG_INPUT_MOTOR_CURRENT_MA = 0x0001,
/** /**
* @brief Bitmaske der digitalen Eingänge. Bit 0: Eingang 1, Bit 1: Eingang 2. 1=Aktiv. * @brief Bitmaske der digitalen Eingänge. Bit 0: Eingang 1, Bit 1: Eingang 2.
* 1=Aktiv.
*/ */
REG_INPUT_DIGITAL_INPUTS_STATE = 0x0020, REG_INPUT_DIGITAL_INPUTS_STATE = 0x0020,
/** /**
* @brief Event-Flags für Taster (Clear-on-Read). Bit 0: Taster 1 gedrückt. Bit 1: Taster 2 gedrückt. * @brief Event-Flags für Taster (Clear-on-Read). Bit 0: Taster 1 gedrückt.
* Bit 1: Taster 2 gedrückt.
*/ */
REG_INPUT_BUTTON_EVENTS = 0x0021, REG_INPUT_BUTTON_EVENTS = 0x0021,
/** /**
@ -60,7 +61,8 @@ enum
*/ */
REG_INPUT_SUPPLY_VOLTAGE_MV = 0x00F5, REG_INPUT_SUPPLY_VOLTAGE_MV = 0x00F5,
/** /**
* @brief CRC16 des zuletzt im Puffer empfangenen Daten-Chunks für das Firmware-Update. * @brief CRC16 des zuletzt im Puffer empfangenen Daten-Chunks für das
* Firmware-Update.
*/ */
REG_INPUT_FWU_LAST_CHUNK_CRC = 0x0100 REG_INPUT_FWU_LAST_CHUNK_CRC = 0x0100
}; };
@ -69,8 +71,7 @@ enum
* @brief Modbus Holding Register Addresses (Read/Write). * @brief Modbus Holding Register Addresses (Read/Write).
* @see docs/modbus-registers.de.md * @see docs/modbus-registers.de.md
*/ */
enum enum {
{
/** /**
* @brief Ventilsteuerungsbefehl (1=Öffnen, 2=Schliessen, 0=Bewegung stoppen). * @brief Ventilsteuerungsbefehl (1=Öffnen, 2=Schliessen, 0=Bewegung stoppen).
*/ */
@ -84,7 +85,8 @@ enum
*/ */
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002, REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002,
/** /**
* @brief Bitmaske zum Lesen und Schreiben der digitalen Ausgänge. Bit 0: Ausgang 1, Bit 1: Ausgang 2. 1=AN, 0=AUS. * @brief Bitmaske zum Lesen und Schreiben der digitalen Ausgänge. Bit 0:
* Ausgang 1, Bit 1: Ausgang 2. 1=AN, 0=AUS.
*/ */
REG_HOLDING_DIGITAL_OUTPUTS_STATE = 0x0010, REG_HOLDING_DIGITAL_OUTPUTS_STATE = 0x0010,
/** /**
@ -102,11 +104,13 @@ enum
*/ */
REG_HOLDING_FWU_COMMAND = 0x0100, REG_HOLDING_FWU_COMMAND = 0x0100,
/** /**
* @brief Untere 16 Bit des 32-Bit-Offsets für den nächsten Firmware-Update-Chunk. * @brief Untere 16 Bit des 32-Bit-Offsets für den nächsten
* Firmware-Update-Chunk.
*/ */
REG_HOLDING_FWU_CHUNK_OFFSET_LOW = 0x0101, REG_HOLDING_FWU_CHUNK_OFFSET_LOW = 0x0101,
/** /**
* @brief Obere 16 Bit des 32-Bit-Offsets für den nächsten Firmware-Update-Chunk. * @brief Obere 16 Bit des 32-Bit-Offsets für den nächsten
* Firmware-Update-Chunk.
*/ */
REG_HOLDING_FWU_CHUNK_OFFSET_HIGH = 0x0102, REG_HOLDING_FWU_CHUNK_OFFSET_HIGH = 0x0102,
/** /**
@ -137,8 +141,9 @@ int modbus_server_init(void);
* *
* @param baudrate The new baudrate to set. * @param baudrate The new baudrate to set.
* @param unit_id The new Modbus unit ID (slave address). * @param unit_id The new Modbus unit ID (slave address).
* @return 0 on success, or a negative error code if immediate reconfiguration fails. * @return 0 on success, or a negative error code if immediate reconfiguration
* Returns 0 even on failure if settings could be saved for the next boot. * fails. Returns 0 even on failure if settings could be saved for the next
* boot.
*/ */
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id); int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id);

View File

@ -8,17 +8,19 @@
* @file valve.h * @file valve.h
* @brief API for controlling the motorized valve. * @brief API for controlling the motorized valve.
* *
* This library provides functions to initialize, open, close, and stop the valve. * This library provides functions to initialize, open, close, and stop the
* It also allows getting the valve's state and movement status, and configuring * valve. It also allows getting the valve's state and movement status, and
* the maximum opening and closing times. * configuring the maximum opening and closing times.
*/ */
/** /**
* @brief Defines the GPIO pins used for the valve controller. * @brief Defines the GPIO pins used for the valve controller.
*/ */
struct valve_gpios { struct valve_gpios {
const struct gpio_dt_spec in0; /**< Control input 0 for the VND7050AJ driver. */ const struct gpio_dt_spec
const struct gpio_dt_spec in1; /**< Control input 1 for the VND7050AJ driver. */ in0; /**< Control input 0 for the VND7050AJ driver. */
const struct gpio_dt_spec
in1; /**< Control input 1 for the VND7050AJ driver. */
const struct gpio_dt_spec rst; /**< Reset pin for the VND7050AJ driver. */ const struct gpio_dt_spec rst; /**< Reset pin for the VND7050AJ driver. */
const struct gpio_dt_spec sen; /**< Sense (current measurement) pin. */ const struct gpio_dt_spec sen; /**< Sense (current measurement) pin. */
const struct gpio_dt_spec s0; /**< S0 select pin. */ const struct gpio_dt_spec s0; /**< S0 select pin. */

View File

@ -2,14 +2,14 @@
* @file adc_sensor.c * @file adc_sensor.c
* @brief Implementation of the ADC sensor library. * @brief Implementation of the ADC sensor library.
* *
* This file contains the implementation for initializing and reading from ADC sensors. * This file contains the implementation for initializing and reading from ADC
* It currently provides simulated values for voltage and current, with placeholders * sensors. It currently provides simulated values for voltage and current, with
* for real hardware ADC implementation. * placeholders for real hardware ADC implementation.
*/ */
#include <lib/adc_sensor.h>
#include <zephyr/kernel.h> #include <zephyr/kernel.h>
#include <zephyr/logging/log.h> #include <zephyr/logging/log.h>
#include <lib/adc_sensor.h>
LOG_MODULE_REGISTER(adc_sensor, LOG_LEVEL_INF); LOG_MODULE_REGISTER(adc_sensor, LOG_LEVEL_INF);
@ -17,17 +17,18 @@ LOG_MODULE_REGISTER(adc_sensor, LOG_LEVEL_INF);
#define SIMULATED_VOLTAGE_MV 12000 #define SIMULATED_VOLTAGE_MV 12000
#define SIMULATED_CURRENT_MA 45 #define SIMULATED_CURRENT_MA 45
static bool initialized = false; // Flag to indicate if the ADC sensor is initialized static bool initialized =
false; // Flag to indicate if the ADC sensor is initialized
int adc_sensor_init(void) int adc_sensor_init(void) {
{
if (initialized) { if (initialized) {
return 0; return 0;
} }
#ifdef CONFIG_ADC_SENSOR_SIMULATED #ifdef CONFIG_ADC_SENSOR_SIMULATED
LOG_INF("ADC sensor initialized (simulated mode)"); LOG_INF("ADC sensor initialized (simulated mode)");
LOG_INF("Simulated values: %dmV, %dmA", SIMULATED_VOLTAGE_MV, SIMULATED_CURRENT_MA); LOG_INF("Simulated values: %dmV, %dmA", SIMULATED_VOLTAGE_MV,
SIMULATED_CURRENT_MA);
#else #else
// TODO: Initialize real ADC hardware // TODO: Initialize real ADC hardware
LOG_INF("ADC sensor initialized (real ADC mode - not yet implemented)"); LOG_INF("ADC sensor initialized (real ADC mode - not yet implemented)");
@ -37,8 +38,7 @@ int adc_sensor_init(void)
return 0; return 0;
} }
uint16_t adc_sensor_get_voltage_mv(void) uint16_t adc_sensor_get_voltage_mv(void) {
{
if (!initialized) { if (!initialized) {
LOG_WRN("ADC sensor not initialized, calling adc_sensor_init()"); LOG_WRN("ADC sensor not initialized, calling adc_sensor_init()");
adc_sensor_init(); adc_sensor_init();
@ -53,8 +53,7 @@ uint16_t adc_sensor_get_voltage_mv(void)
#endif #endif
} }
uint16_t adc_sensor_get_current_ma(void) uint16_t adc_sensor_get_current_ma(void) {
{
if (!initialized) { if (!initialized) {
LOG_WRN("ADC sensor not initialized, calling adc_sensor_init()"); LOG_WRN("ADC sensor not initialized, calling adc_sensor_init()");
adc_sensor_init(); adc_sensor_init();

View File

@ -8,29 +8,35 @@
* the update process. The actual writing to flash is simulated. * the update process. The actual writing to flash is simulated.
*/ */
#include <zephyr/kernel.h>
#include <zephyr/sys/crc.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/logging/log.h>
#include <lib/fwu.h> #include <lib/fwu.h>
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/sys/crc.h>
LOG_MODULE_REGISTER(fwu, LOG_LEVEL_INF); LOG_MODULE_REGISTER(fwu, LOG_LEVEL_INF);
#define FWU_BUFFER_SIZE 256 #define FWU_BUFFER_SIZE 256
static uint8_t fwu_buffer[FWU_BUFFER_SIZE]; // Buffer to store incoming firmware data chunks static uint8_t fwu_buffer[FWU_BUFFER_SIZE]; // Buffer to store incoming
static uint32_t fwu_chunk_offset = 0; // Offset for the current firmware chunk in the overall image // firmware data chunks
static uint32_t fwu_chunk_offset =
0; // Offset for the current firmware chunk in the overall image
static uint16_t fwu_chunk_size = 0; // Size of the current firmware chunk static uint16_t fwu_chunk_size = 0; // Size of the current firmware chunk
static uint16_t fwu_last_chunk_crc = 0; // CRC16 of the last received firmware chunk static uint16_t fwu_last_chunk_crc =
0; // CRC16 of the last received firmware chunk
void fwu_init(void) {} void fwu_init(void) {}
void fwu_handler(uint16_t addr, uint16_t reg) void fwu_handler(uint16_t addr, uint16_t reg) {
{ // This is a simplified handler. In a real scenario, you would have a proper
// This is a simplified handler. In a real scenario, you would have a proper mapping // mapping between register addresses and actions.
// between register addresses and actions.
if (addr == 0x0100) { // FWU_COMMAND if (addr == 0x0100) { // FWU_COMMAND
if (reg == 1) { LOG_INF("FWU: Chunk at offset %u (size %u) verified.", fwu_chunk_offset, fwu_chunk_size); } if (reg == 1) {
else if (reg == 2) { LOG_INF("FWU: Finalize command received. Rebooting (simulated)."); } 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 } else if (addr == 0x0101) { // FWU_CHUNK_OFFSET_LOW
fwu_chunk_offset = (fwu_chunk_offset & 0xFFFF0000) | reg; fwu_chunk_offset = (fwu_chunk_offset & 0xFFFF0000) | reg;
} else if (addr == 0x0102) { // FWU_CHUNK_OFFSET_HIGH } else if (addr == 0x0102) { // FWU_CHUNK_OFFSET_HIGH
@ -49,7 +55,4 @@ void fwu_handler(uint16_t addr, uint16_t reg)
} }
} }
uint16_t fwu_get_last_chunk_crc(void) uint16_t fwu_get_last_chunk_crc(void) { return fwu_last_chunk_crc; }
{
return fwu_last_chunk_crc;
}

View File

@ -7,19 +7,18 @@
* libraries like valve control, ADC sensors, and firmware updates. * libraries like valve control, ADC sensors, and firmware updates.
*/ */
#include <zephyr/kernel.h> #include <app_version.h>
#include <zephyr/drivers/uart.h> #include <lib/adc_sensor.h>
#include <zephyr/device.h> #include <lib/fwu.h>
#include <zephyr/modbus/modbus.h>
#include <zephyr/logging/log.h>
#include <zephyr/settings/settings.h>
#include <zephyr/sys/reboot.h>
#include <lib/modbus_server.h> #include <lib/modbus_server.h>
#include <lib/valve.h> #include <lib/valve.h>
#include <lib/fwu.h> #include <zephyr/device.h>
#include <lib/adc_sensor.h> #include <zephyr/drivers/uart.h>
#include <app_version.h> #include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/modbus/modbus.h>
#include <zephyr/settings/settings.h>
#include <zephyr/sys/reboot.h>
#include <zephyr/usb/usb_device.h> #include <zephyr/usb/usb_device.h>
LOG_MODULE_REGISTER(modbus_server, LOG_LEVEL_INF); LOG_MODULE_REGISTER(modbus_server, LOG_LEVEL_INF);
@ -43,8 +42,7 @@ static struct k_timer watchdog_timer;
* *
* @param timer_id Pointer to the timer instance. * @param timer_id Pointer to the timer instance.
*/ */
static void watchdog_timer_handler(struct k_timer *timer_id) static void watchdog_timer_handler(struct k_timer *timer_id) {
{
LOG_WRN("Modbus watchdog expired! Closing valve as a fail-safe."); LOG_WRN("Modbus watchdog expired! Closing valve as a fail-safe.");
valve_close(); valve_close();
} }
@ -55,10 +53,8 @@ static void watchdog_timer_handler(struct k_timer *timer_id)
* This function should be called upon receiving any valid Modbus request * This function should be called upon receiving any valid Modbus request
* to prevent the watchdog from expiring. * to prevent the watchdog from expiring.
*/ */
static inline void reset_watchdog(void) static inline void reset_watchdog(void) {
{ if (watchdog_timeout_s > 0) {
if (watchdog_timeout_s > 0)
{
k_timer_start(&watchdog_timer, K_SECONDS(watchdog_timeout_s), K_NO_WAIT); k_timer_start(&watchdog_timer, K_SECONDS(watchdog_timeout_s), K_NO_WAIT);
} }
} }
@ -70,11 +66,9 @@ static inline void reset_watchdog(void)
* @param reg Pointer to store the read value. * @param reg Pointer to store the read value.
* @return 0 on success. * @return 0 on success.
*/ */
static int holding_reg_rd(uint16_t addr, uint16_t *reg) static int holding_reg_rd(uint16_t addr, uint16_t *reg) {
{
reset_watchdog(); reset_watchdog();
switch (addr) switch (addr) {
{
case REG_HOLDING_MAX_OPENING_TIME_S: case REG_HOLDING_MAX_OPENING_TIME_S:
*reg = valve_get_max_open_time(); *reg = valve_get_max_open_time();
break; break;
@ -98,22 +92,15 @@ static int holding_reg_rd(uint16_t addr, uint16_t *reg)
* @param reg Value to write. * @param reg Value to write.
* @return 0 on success. * @return 0 on success.
*/ */
static int holding_reg_wr(uint16_t addr, uint16_t reg) static int holding_reg_wr(uint16_t addr, uint16_t reg) {
{
reset_watchdog(); reset_watchdog();
switch (addr) switch (addr) {
{
case REG_HOLDING_VALVE_COMMAND: case REG_HOLDING_VALVE_COMMAND:
if (reg == 1) if (reg == 1) {
{
valve_open(); valve_open();
} } else if (reg == 2) {
else if (reg == 2)
{
valve_close(); valve_close();
} } else if (reg == 0) {
else if (reg == 0)
{
valve_stop(); valve_stop();
} }
break; break;
@ -125,20 +112,16 @@ static int holding_reg_wr(uint16_t addr, uint16_t reg)
break; break;
case REG_HOLDING_WATCHDOG_TIMEOUT_S: case REG_HOLDING_WATCHDOG_TIMEOUT_S:
watchdog_timeout_s = reg; watchdog_timeout_s = reg;
if (watchdog_timeout_s > 0) if (watchdog_timeout_s > 0) {
{
LOG_INF("Watchdog enabled with %u s timeout.", watchdog_timeout_s); LOG_INF("Watchdog enabled with %u s timeout.", watchdog_timeout_s);
reset_watchdog(); reset_watchdog();
} } else {
else
{
LOG_INF("Watchdog disabled."); LOG_INF("Watchdog disabled.");
k_timer_stop(&watchdog_timer); k_timer_stop(&watchdog_timer);
} }
break; break;
case REG_HOLDING_DEVICE_RESET: case REG_HOLDING_DEVICE_RESET:
if (reg == 1) if (reg == 1) {
{
LOG_WRN("Modbus reset command received. Rebooting..."); LOG_WRN("Modbus reset command received. Rebooting...");
sys_reboot(SYS_REBOOT_WARM); sys_reboot(SYS_REBOOT_WARM);
} }
@ -157,12 +140,10 @@ static int holding_reg_wr(uint16_t addr, uint16_t reg)
* @param reg Pointer to store the read value. * @param reg Pointer to store the read value.
* @return 0 on success. * @return 0 on success.
*/ */
static int input_reg_rd(uint16_t addr, uint16_t *reg) static int input_reg_rd(uint16_t addr, uint16_t *reg) {
{
reset_watchdog(); reset_watchdog();
uint32_t uptime_s = k_uptime_get_32() / 1000; uint32_t uptime_s = k_uptime_get_32() / 1000;
switch (addr) switch (addr) {
{
case REG_INPUT_VALVE_STATE_MOVEMENT: case REG_INPUT_VALVE_STATE_MOVEMENT:
*reg = (valve_get_movement() << 8) | (valve_get_state() & 0xFF); *reg = (valve_get_movement() << 8) | (valve_get_state() & 0xFF);
break; break;
@ -194,7 +175,8 @@ static int input_reg_rd(uint16_t addr, uint16_t *reg)
return 0; return 0;
} }
static struct modbus_user_callbacks mbs_cbs = { // Modbus server callback functions static struct modbus_user_callbacks mbs_cbs = {
// Modbus server callback functions
.holding_reg_rd = holding_reg_rd, .holding_reg_rd = holding_reg_rd,
.holding_reg_wr = holding_reg_wr, .holding_reg_wr = holding_reg_wr,
.input_reg_rd = input_reg_rd, .input_reg_rd = input_reg_rd,
@ -202,8 +184,7 @@ static struct modbus_user_callbacks mbs_cbs = { // Modbus server callback functi
#define MODBUS_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_modbus_serial) #define MODBUS_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_modbus_serial)
int modbus_server_init(void) int modbus_server_init(void) {
{
k_timer_init(&watchdog_timer, watchdog_timer_handler, NULL); k_timer_init(&watchdog_timer, watchdog_timer_handler, NULL);
// Initialize ADC sensor // Initialize ADC sensor
@ -228,13 +209,11 @@ int modbus_server_init(void)
const struct device *const dev = DEVICE_DT_GET(DT_PARENT(MODBUS_NODE)); const struct device *const dev = DEVICE_DT_GET(DT_PARENT(MODBUS_NODE));
uint32_t dtr = 0; uint32_t dtr = 0;
if (!device_is_ready(dev) || usb_enable(NULL)) if (!device_is_ready(dev) || usb_enable(NULL)) {
{
return 0; return 0;
} }
while (!dtr) while (!dtr) {
{
uart_line_ctrl_get(dev, UART_LINE_CTRL_DTR, &dtr); uart_line_ctrl_get(dev, UART_LINE_CTRL_DTR, &dtr);
k_sleep(K_MSEC(100)); k_sleep(K_MSEC(100));
} }
@ -242,18 +221,17 @@ int modbus_server_init(void)
LOG_INF("Client connected to server on %s", dev->name); LOG_INF("Client connected to server on %s", dev->name);
#endif #endif
modbus_iface = modbus_iface_get_by_name(iface_name); modbus_iface = modbus_iface_get_by_name(iface_name);
if (modbus_iface < 0) if (modbus_iface < 0) {
{
return modbus_iface; return modbus_iface;
} }
server_param.server.user_cb = &mbs_cbs; server_param.server.user_cb = &mbs_cbs;
LOG_INF("Starting Modbus server: baudrate=%u, unit_id=%u", saved_baudrate, saved_unit_id); LOG_INF("Starting Modbus server: baudrate=%u, unit_id=%u", saved_baudrate,
saved_unit_id);
return modbus_init_server(modbus_iface, server_param); return modbus_init_server(modbus_iface, server_param);
} }
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id) int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id) {
{
// Update parameters // Update parameters
server_param.serial.baud = baudrate; server_param.serial.baud = baudrate;
server_param.server.unit_id = unit_id; server_param.server.unit_id = unit_id;
@ -261,14 +239,11 @@ int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id)
// Try to reinitialize - this should work for most cases // Try to reinitialize - this should work for most cases
int ret = modbus_init_server(modbus_iface, server_param); int ret = modbus_init_server(modbus_iface, server_param);
if (ret == 0) if (ret == 0) {
{
settings_save_one("modbus/baudrate", &baudrate, sizeof(baudrate)); settings_save_one("modbus/baudrate", &baudrate, sizeof(baudrate));
settings_save_one("modbus/unit_id", &unit_id, sizeof(unit_id)); settings_save_one("modbus/unit_id", &unit_id, sizeof(unit_id));
LOG_INF("Modbus reconfigured: baudrate=%u, unit_id=%u", baudrate, unit_id); LOG_INF("Modbus reconfigured: baudrate=%u, unit_id=%u", baudrate, unit_id);
} } else {
else
{
LOG_ERR("Failed to reconfigure Modbus: %d", ret); LOG_ERR("Failed to reconfigure Modbus: %d", ret);
LOG_INF("Modbus reconfiguration requires restart to take effect"); LOG_INF("Modbus reconfiguration requires restart to take effect");
@ -276,7 +251,9 @@ int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id)
settings_save_one("modbus/baudrate", &baudrate, sizeof(baudrate)); settings_save_one("modbus/baudrate", &baudrate, sizeof(baudrate));
settings_save_one("modbus/unit_id", &unit_id, sizeof(unit_id)); settings_save_one("modbus/unit_id", &unit_id, sizeof(unit_id));
LOG_INF("Settings saved. Type 'reset' to restart the device and apply the change."); LOG_INF(
"Settings saved. Type 'reset' to restart the device and apply the "
"change.");
return 0; // Return success since settings are saved return 0; // Return success since settings are saved
} }

View File

@ -8,10 +8,10 @@
* storage. * storage.
*/ */
#include <zephyr/shell/shell.h>
#include <stdlib.h>
#include <lib/modbus_server.h> #include <lib/modbus_server.h>
#include <lib/valve.h> #include <lib/valve.h>
#include <stdlib.h>
#include <zephyr/shell/shell.h>
/** /**
* @brief Shell command to set the Modbus baudrate. * @brief Shell command to set the Modbus baudrate.
@ -21,15 +21,16 @@
* @param argv Argument values. * @param argv Argument values.
* @return 0 on success, -EINVAL on error. * @return 0 on success, -EINVAL on error.
*/ */
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) {
if (argc != 2) { if (argc != 2) {
shell_error(sh, "Usage: set_baud <baudrate>"); shell_error(sh, "Usage: set_baud <baudrate>");
return -EINVAL; return -EINVAL;
} }
uint32_t new_baud = (uint32_t)strtoul(argv[1], NULL, 10); uint32_t new_baud = (uint32_t)strtoul(argv[1], NULL, 10);
const uint32_t valid_baud_rates[] = {1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200}; const uint32_t valid_baud_rates[] = {1200, 2400, 4800, 9600,
19200, 38400, 57600, 115200};
bool is_valid = false; bool is_valid = false;
for (int i = 0; i < ARRAY_SIZE(valid_baud_rates); i++) { for (int i = 0; i < ARRAY_SIZE(valid_baud_rates); i++) {
@ -41,9 +42,11 @@ static int cmd_modbus_set_baud(const struct shell *sh, size_t argc, char **argv)
if (!is_valid) { if (!is_valid) {
char error_msg[128]; char error_msg[128];
int offset = snprintf(error_msg, sizeof(error_msg), "Invalid baudrate. Valid rates are: "); int offset = snprintf(error_msg, sizeof(error_msg),
"Invalid baudrate. Valid rates are: ");
for (int i = 0; i < ARRAY_SIZE(valid_baud_rates); i++) { for (int i = 0; i < ARRAY_SIZE(valid_baud_rates); i++) {
offset += snprintf(error_msg + offset, sizeof(error_msg) - offset, "%u ", valid_baud_rates[i]); offset += snprintf(error_msg + offset, sizeof(error_msg) - offset, "%u ",
valid_baud_rates[i]);
} }
shell_error(sh, "%s", error_msg); shell_error(sh, "%s", error_msg);
return -EINVAL; return -EINVAL;
@ -66,8 +69,7 @@ static int cmd_modbus_set_baud(const struct shell *sh, size_t argc, char **argv)
* @param argv Argument values. * @param argv Argument values.
* @return 0 on success, -EINVAL on error. * @return 0 on success, -EINVAL on error.
*/ */
static int cmd_modbus_set_id(const struct shell *sh, size_t argc, char **argv) static int cmd_modbus_set_id(const struct shell *sh, size_t argc, char **argv) {
{
if (argc != 2) { if (argc != 2) {
shell_error(sh, "Usage: set_id <slave_id>"); shell_error(sh, "Usage: set_id <slave_id>");
return -EINVAL; return -EINVAL;
@ -75,7 +77,8 @@ static int cmd_modbus_set_id(const struct shell *sh, size_t argc, char **argv)
uint32_t new_id_u32 = (uint32_t)strtoul(argv[1], NULL, 10); uint32_t new_id_u32 = (uint32_t)strtoul(argv[1], NULL, 10);
if (new_id_u32 == 0 || new_id_u32 > 247) { if (new_id_u32 == 0 || new_id_u32 > 247) {
shell_error(sh, "Invalid slave ID: %s. Must be between 1 and 247.", argv[1]); shell_error(sh, "Invalid slave ID: %s. Must be between 1 and 247.",
argv[1]);
return -EINVAL; return -EINVAL;
} }
uint8_t new_id = (uint8_t)new_id_u32; uint8_t new_id = (uint8_t)new_id_u32;
@ -97,8 +100,8 @@ static int cmd_modbus_set_id(const struct shell *sh, size_t argc, char **argv)
* @param argv Argument values. * @param argv Argument values.
* @return 0 on success, -EINVAL on error. * @return 0 on success, -EINVAL on error.
*/ */
static int cmd_valve_set_open_time(const struct shell *sh, size_t argc, char **argv) static int cmd_valve_set_open_time(const struct shell *sh, size_t argc,
{ char **argv) {
if (argc != 2) { if (argc != 2) {
shell_error(sh, "Usage: set_open_time <seconds>"); shell_error(sh, "Usage: set_open_time <seconds>");
return -EINVAL; return -EINVAL;
@ -119,8 +122,8 @@ static int cmd_valve_set_open_time(const struct shell *sh, size_t argc, char **a
* @param argv Argument values. * @param argv Argument values.
* @return 0 on success, -EINVAL on error. * @return 0 on success, -EINVAL on error.
*/ */
static int cmd_valve_set_close_time(const struct shell *sh, size_t argc, char **argv) static int cmd_valve_set_close_time(const struct shell *sh, size_t argc,
{ char **argv) {
if (argc != 2) { if (argc != 2) {
shell_error(sh, "Usage: set_close_time <seconds>"); shell_error(sh, "Usage: set_close_time <seconds>");
return -EINVAL; return -EINVAL;
@ -141,8 +144,7 @@ static int cmd_valve_set_close_time(const struct shell *sh, size_t argc, char **
* @param argv Argument values. * @param argv Argument values.
* @return 0 on success. * @return 0 on success.
*/ */
static int cmd_config_show(const struct shell *sh, size_t argc, char **argv) static int cmd_config_show(const struct shell *sh, size_t argc, char **argv) {
{
shell_print(sh, "Current Modbus Configuration:"); shell_print(sh, "Current Modbus Configuration:");
shell_print(sh, " Baudrate: %u", modbus_get_baudrate()); shell_print(sh, " Baudrate: %u", modbus_get_baudrate());
shell_print(sh, " Slave ID: %u", modbus_get_unit_id()); shell_print(sh, " Slave ID: %u", modbus_get_unit_id());
@ -153,17 +155,22 @@ static int cmd_config_show(const struct shell *sh, size_t argc, char **argv)
} }
SHELL_STATIC_SUBCMD_SET_CREATE(sub_modbus_cmds, SHELL_STATIC_SUBCMD_SET_CREATE(sub_modbus_cmds,
SHELL_CMD(set_baud, NULL, "Set Modbus baudrate", cmd_modbus_set_baud), SHELL_CMD(set_baud, NULL, "Set Modbus baudrate",
SHELL_CMD(set_id, NULL, "Set Modbus slave ID", cmd_modbus_set_id), cmd_modbus_set_baud),
SHELL_SUBCMD_SET_END SHELL_CMD(set_id, NULL, "Set Modbus slave ID",
); cmd_modbus_set_id),
SHELL_SUBCMD_SET_END);
SHELL_STATIC_SUBCMD_SET_CREATE(sub_valve_cmds, SHELL_STATIC_SUBCMD_SET_CREATE(sub_valve_cmds,
SHELL_CMD(set_open_time, NULL, "Set max valve opening time", cmd_valve_set_open_time), SHELL_CMD(set_open_time, NULL,
SHELL_CMD(set_close_time, NULL, "Set max valve closing time", cmd_valve_set_close_time), "Set max valve opening time",
SHELL_SUBCMD_SET_END cmd_valve_set_open_time),
); SHELL_CMD(set_close_time, NULL,
"Set max valve closing time",
cmd_valve_set_close_time),
SHELL_SUBCMD_SET_END);
SHELL_CMD_REGISTER(modbus, &sub_modbus_cmds, "Modbus configuration", NULL); SHELL_CMD_REGISTER(modbus, &sub_modbus_cmds, "Modbus configuration", NULL);
SHELL_CMD_REGISTER(valve, &sub_valve_cmds, "Valve configuration", NULL); SHELL_CMD_REGISTER(valve, &sub_valve_cmds, "Valve configuration", NULL);
SHELL_CMD_REGISTER(show_config, NULL, "Show all configurations", cmd_config_show); SHELL_CMD_REGISTER(show_config, NULL, "Show all configurations",
cmd_config_show);

View File

@ -20,8 +20,7 @@
* @param argv Argument values. * @param argv Argument values.
* @return 0 on success. * @return 0 on success.
*/ */
static int cmd_reset(const struct shell *sh, size_t argc, char **argv) static int cmd_reset(const struct shell *sh, size_t argc, char **argv) {
{
shell_print(sh, "Rebooting system..."); shell_print(sh, "Rebooting system...");
k_sleep(K_MSEC(100)); // Allow the shell to print the message k_sleep(K_MSEC(100)); // Allow the shell to print the message
sys_reboot(SYS_REBOOT_WARM); sys_reboot(SYS_REBOOT_WARM);

View File

@ -7,12 +7,12 @@
* safety timeouts for opening and closing operations. * safety timeouts for opening and closing operations.
*/ */
#include <zephyr/kernel.h> #include <lib/valve.h>
#include <zephyr/settings/settings.h>
#include <zephyr/logging/log.h>
#include <zephyr/device.h> #include <zephyr/device.h>
#include <zephyr/drivers/gpio.h> #include <zephyr/drivers/gpio.h>
#include <lib/valve.h> #include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/settings/settings.h>
LOG_MODULE_REGISTER(valve, LOG_LEVEL_INF); LOG_MODULE_REGISTER(valve, LOG_LEVEL_INF);
@ -29,7 +29,8 @@ static enum valve_state current_state = VALVE_STATE_CLOSED;
static enum valve_movement current_movement = VALVE_MOVEMENT_IDLE; static enum valve_movement current_movement = VALVE_MOVEMENT_IDLE;
static uint16_t max_opening_time_s = 60; static uint16_t max_opening_time_s = 60;
static uint16_t max_closing_time_s = 60; static uint16_t max_closing_time_s = 60;
static struct k_work_delayable valve_work; // Work item for scheduling valve movement timeouts static struct k_work_delayable
valve_work; // Work item for scheduling valve movement timeouts
/** /**
* @brief Work handler for valve movement timeouts. * @brief Work handler for valve movement timeouts.
@ -39,8 +40,7 @@ static struct k_work_delayable valve_work; // Work item for scheduling valve mov
* *
* @param work Pointer to the k_work item. * @param work Pointer to the k_work item.
*/ */
static void valve_work_handler(struct k_work *work) static void valve_work_handler(struct k_work *work) {
{
gpio_pin_set_dt(&valve_gpios.in0, 0); gpio_pin_set_dt(&valve_gpios.in0, 0);
gpio_pin_set_dt(&valve_gpios.in1, 0); gpio_pin_set_dt(&valve_gpios.in1, 0);
gpio_pin_set_dt(&valve_gpios.rst, 0); gpio_pin_set_dt(&valve_gpios.rst, 0);
@ -54,24 +54,28 @@ static void valve_work_handler(struct k_work *work)
current_movement = VALVE_MOVEMENT_IDLE; current_movement = VALVE_MOVEMENT_IDLE;
} }
void valve_init(void) void valve_init(void) {
{
k_work_init_delayable(&valve_work, valve_work_handler); 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_open_time", &max_opening_time_s,
settings_load_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s)); sizeof(max_opening_time_s));
settings_load_one("valve/max_close_time", &max_closing_time_s,
sizeof(max_closing_time_s));
gpio_pin_configure_dt(&valve_gpios.in0, GPIO_OUTPUT_INACTIVE); gpio_pin_configure_dt(&valve_gpios.in0, GPIO_OUTPUT_INACTIVE);
gpio_pin_configure_dt(&valve_gpios.in1, GPIO_OUTPUT_INACTIVE); gpio_pin_configure_dt(&valve_gpios.in1, GPIO_OUTPUT_INACTIVE);
gpio_pin_configure_dt(&valve_gpios.rst, GPIO_OUTPUT_ACTIVE); // Keep VND7050AJ out of reset gpio_pin_configure_dt(&valve_gpios.rst,
GPIO_OUTPUT_ACTIVE); // Keep VND7050AJ out of reset
gpio_pin_configure_dt(&valve_gpios.sen, GPIO_OUTPUT_INACTIVE); gpio_pin_configure_dt(&valve_gpios.sen, GPIO_OUTPUT_INACTIVE);
gpio_pin_configure_dt(&valve_gpios.s0, GPIO_OUTPUT_INACTIVE); // S0 select pin - output gpio_pin_configure_dt(&valve_gpios.s0,
gpio_pin_configure_dt(&valve_gpios.s1, GPIO_OUTPUT_INACTIVE); // S1 select pin - output GPIO_OUTPUT_INACTIVE); // S0 select pin - output
gpio_pin_configure_dt(&valve_gpios.s1,
GPIO_OUTPUT_INACTIVE); // S1 select pin - output
LOG_INF("Valve initialized: max_open=%us, max_close=%us", max_opening_time_s, max_closing_time_s); LOG_INF("Valve initialized: max_open=%us, max_close=%us", max_opening_time_s,
max_closing_time_s);
} }
void valve_open(void) void valve_open(void) {
{
if (current_state == VALVE_STATE_CLOSED) { if (current_state == VALVE_STATE_CLOSED) {
gpio_pin_set_dt(&valve_gpios.rst, 1); gpio_pin_set_dt(&valve_gpios.rst, 1);
gpio_pin_set_dt(&valve_gpios.in1, 0); gpio_pin_set_dt(&valve_gpios.in1, 0);
@ -82,8 +86,7 @@ void valve_open(void)
} }
} }
void valve_close(void) void valve_close(void) {
{
if (current_state == VALVE_STATE_OPEN) { if (current_state == VALVE_STATE_OPEN) {
gpio_pin_set_dt(&valve_gpios.rst, 1); gpio_pin_set_dt(&valve_gpios.rst, 1);
gpio_pin_set_dt(&valve_gpios.in0, 0); gpio_pin_set_dt(&valve_gpios.in0, 0);
@ -93,17 +96,26 @@ void valve_close(void)
} }
} }
void valve_stop(void) void valve_stop(void) {
{
k_work_cancel_delayable(&valve_work); k_work_cancel_delayable(&valve_work);
current_movement = VALVE_MOVEMENT_IDLE; current_movement = VALVE_MOVEMENT_IDLE;
} }
enum valve_state valve_get_state(void) { return current_state; } enum valve_state valve_get_state(void) { return current_state; }
enum valve_movement valve_get_movement(void) { return current_movement; } 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; } 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_open_time(uint16_t 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)); } 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_open_time(void) { return max_opening_time_s; }
uint16_t valve_get_max_close_time(void) { return max_closing_time_s; } uint16_t valve_get_max_close_time(void) { return max_closing_time_s; }