Compare commits
26 Commits
c2916662e2
...
v0.0.1
| Author | SHA1 | Date | |
|---|---|---|---|
| 10a770de59 | |||
| 1b0519aadf | |||
| e429a0874d | |||
| 3a05c80b25 | |||
| 5208f1370d | |||
| a59e8518cc | |||
| 2a2890b675 | |||
| 38fd3a6aac | |||
| c3df6565b7 | |||
| 140d2baa24 | |||
| 711341f362 | |||
| a5da0a61dd | |||
| b54c73edb1 | |||
| 2418d4e218 | |||
| 2b4890f052 | |||
| 85d493f24a | |||
| f486d4c4ab | |||
| 6cfd4b8b4d | |||
| 0088030d66 | |||
| 4d828b41f1 | |||
| 95f435923f | |||
| 33f2a15cf3 | |||
| c4e87a3125 | |||
| 773027f6b0 | |||
| 461cce7a48 | |||
| 23b88ada83 |
@@ -1,3 +1,5 @@
|
||||
<img src="./docs/img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
🇩🇪 Deutsch | [🇬🇧 English](README.md) | [🇫🇷 Français](README.fr.md) | [🇪🇸 Español](README.es.md)
|
||||
|
||||
# Modulares Bewässerungssystem
|
||||
@@ -11,6 +13,8 @@ Die detaillierte Dokumentation befindet sich im Verzeichnis [`docs/`](./docs/):
|
||||
* **[Konzept](./docs/concept.de.md)**: Beschreibt die Systemarchitektur, die verwendeten Komponenten und die grundlegenden Design-Entscheidungen.
|
||||
* **[MODBUS Register](./docs/modbus-registers.de.md)**: Definiert die Register-Map für die Kommunikation mit den Slave-Nodes.
|
||||
* **[Projektplan](./docs/planning.de.md)**: Enthält den Entwicklungs- und Implementierungsplan.
|
||||
* **[Firmware-Handbuch](./docs/firmware-manual.de.md)**: Beschreibt den Funktionsumfang und die Bedienung der Slave-Node-Firmware.
|
||||
* **[Modbus Test-Tool](./software/tools/modbus_tool/README.de.md)**: Anleitung für das Python-basierte Kommandozeilen-Tool zum Testen der Slaves.
|
||||
|
||||
## Schnellstart
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./docs/img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](README.de.md) | [🇬🇧 English](README.md) | [🇫🇷 Français](README.fr.md) | 🇪🇸 Español
|
||||
|
||||
# Sistema de riego modular
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./docs/img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](README.de.md) | [🇬🇧 English](README.md) | 🇫🇷 Français | [🇪🇸 Español](README.es.md)
|
||||
|
||||
# Système d'irrigation modulaire
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./docs/img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](README.de.md) | 🇬🇧 English | [🇫🇷 Français](README.fr.md) | [🇪🇸 Español](README.es.md)
|
||||
|
||||
# Modular Irrigation System
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
🇩🇪 Deutsch | [🇬🇧 English](concept.en.md) | [🇫🇷 Français](concept.fr.md) | [🇪🇸 Español](concept.es.md)
|
||||
|
||||
# Konzept: Modulares Bewässerungssystem
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](concept.de.md) | 🇬🇧 English | [🇫🇷 Français](concept.fr.md) | [🇪🇸 Español](concept.es.md)
|
||||
|
||||
# Concept: Modular Irrigation System
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](concept.de.md) | [🇬🇧 English](concept.en.md) | [🇫🇷 Français](concept.fr.md) | 🇪🇸 Español
|
||||
|
||||
# Concepto: Sistema de riego modular
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](concept.de.md) | [🇬🇧 English](concept.en.md) | 🇫🇷 Français | [🇪🇸 Español](concept.es.md)
|
||||
|
||||
# Concept : Système d'irrigation modulaire
|
||||
|
||||
BIN
docs/img/logo.png
Normal file
BIN
docs/img/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 272 KiB |
16
docs/img/logo.svg
Normal file
16
docs/img/logo.svg
Normal file
@@ -0,0 +1,16 @@
|
||||
<svg width="100" height="120" viewBox="0 0 100 120" xmlns="http://www.w3.org/2000/svg" aria-labelledby="logoTitle">
|
||||
<title id="logoTitle">Logo: Wassertropfen mit integriertem Chip</title>
|
||||
|
||||
<path
|
||||
d="M50 115 C 85 85, 95 65, 95 45 A 45 45 0 1 0 5 45 C 5 65, 15 85, 50 115 Z"
|
||||
fill="#2563EB"
|
||||
/>
|
||||
|
||||
<g fill="#FFFFFF">
|
||||
<rect x="25" y="35" width="50" height="8" rx="2"/>
|
||||
<rect x="25" y="50" width="35" height="8" rx="2"/>
|
||||
<rect x="70" y="50" width="5" height="8" rx="2"/>
|
||||
<rect x="25" y="65" width="50" height="8" rx="2"/>
|
||||
</g>
|
||||
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 568 B |
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
🇩🇪 Deutsch | [🇬🇧 English](modbus-registers.en.md) | [🇫🇷 Français](modbus-registers.fr.md) | [🇪🇸 Español](modbus-registers.es.md)
|
||||
|
||||
# MODBUS Register Map Definition v1.0
|
||||
@@ -47,6 +49,7 @@ Alle Register sind in einer einzigen, durchgehenden Liste pro Register-Typ (`Inp
|
||||
| **0x0002** | `MAX_SCHLIESSZEIT_S` | Ventil | Sicherheits-Timeout in Sekunden für den Schliessen-Vorgang. |
|
||||
| **0x0010** | `DIGITAL_AUSGAENGE_ZUSTAND` | Ausgänge | Bitmaske zum Lesen und Schreiben der Ausgänge. Bit 0: Ausgang 1, Bit 1: Ausgang 2. `1`=AN, `0`=AUS. |
|
||||
| **0x00F0** | `WATCHDOG_TIMEOUT_S` | System | Timeout des Fail-Safe-Watchdogs in Sekunden. `0`=Deaktiviert. |
|
||||
| **0x00F1** | `DEVICE_RESET` | System | Schreibt `1` um das Gerät neu zu starten. |
|
||||
| **0x0100** | `FWU_COMMAND` | Firmware-Update | `1`: **Verify Chunk**: Der zuletzt übertragene Chunk wurde vom Client als gültig befunden. Der Slave soll ihn nun ins Flash schreiben. `2`: **Finalize Update**: Alle Chunks sind übertragen. Installation abschliessen und neu starten. |
|
||||
| **0x0101** | `FWU_CHUNK_OFFSET_LOW` | Firmware-Update | Untere 16 Bit des 32-Bit-Offsets, an den der nächste Chunk geschrieben werden soll. |
|
||||
| **0x0102** | `FWU_CHUNK_OFFSET_HIGH` | Firmware-Update | Obere 16 Bit des 32-Bit-Offsets. |
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](modbus-registers.de.md) | 🇬🇧 English | [🇫🇷 Français](modbus-registers.fr.md) | [🇪🇸 Español](modbus-registers.es.md)
|
||||
|
||||
# MODBUS Register Map Definition v1.0
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](modbus-registers.de.md) | [🇬🇧 English](modbus-registers.en.md) | [🇫🇷 Français](modbus-registers.fr.md) | 🇪🇸 Español
|
||||
|
||||
# Definición del mapa de registros MODBUS v1.0
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](modbus-registers.de.md) | [🇬🇧 English](modbus-registers.en.md) | 🇫🇷 Français | [🇪🇸 Español](modbus-registers.es.md)
|
||||
|
||||
# Définition de la carte des registres MODBUS v1.0
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
🇩🇪 Deutsch | [🇬🇧 English](planning.en.md) | [🇫🇷 Français](planning.fr.md) | [🇪🇸 Español](planning.es.md)
|
||||
|
||||
# Projektplan: Modulares Bewässerungssystem
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](planning.de.md) | 🇬🇧 English | [🇫🇷 Français](planning.fr.md) | [🇪🇸 Español](planning.es.md)
|
||||
|
||||
# Project Plan: Modular Irrigation System
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](planning.de.md) | [🇬🇧 English](planning.en.md) | [🇫🇷 Français](planning.fr.md) | 🇪🇸 Español
|
||||
|
||||
# Plan del proyecto: Sistema de riego modular
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="./img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
[🇩🇪 Deutsch](planning.de.md) | [🇬🇧 English](planning.en.md) | 🇫🇷 Français | [🇪🇸 Español](planning.es.md)
|
||||
|
||||
# Plan de projet : Système d'irrigation modulaire
|
||||
|
||||
8
software/CMakeLists.txt
Normal file
8
software/CMakeLists.txt
Normal file
@@ -0,0 +1,8 @@
|
||||
cmake_minimum_required(VERSION 3.13.1)
|
||||
|
||||
project(software)
|
||||
|
||||
add_subdirectory(modules/modbus_server)
|
||||
add_subdirectory(modules/valve)
|
||||
add_subdirectory(modules/fwu)
|
||||
add_subdirectory(apps/stm32g431_tests)
|
||||
6
software/apps/hello_world/CMakeLists.txt
Normal file
6
software/apps/hello_world/CMakeLists.txt
Normal file
@@ -0,0 +1,6 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
|
||||
project(hello_world)
|
||||
|
||||
target_sources(app PRIVATE src/main.c)
|
||||
4
software/apps/hello_world/prj.conf
Normal file
4
software/apps/hello_world/prj.conf
Normal file
@@ -0,0 +1,4 @@
|
||||
|
||||
CONFIG_CONSOLE=y
|
||||
CONFIG_LOG=y
|
||||
CONFIG_UART_CONSOLE=y
|
||||
9
software/apps/hello_world/src/main.c
Normal file
9
software/apps/hello_world/src/main.c
Normal file
@@ -0,0 +1,9 @@
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/sys/printk.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
printk("Hello World! %s\n", CONFIG_BOARD);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -6,4 +6,22 @@ list(APPEND BOARD_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
|
||||
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
|
||||
project(slave_node)
|
||||
|
||||
target_sources(app PRIVATE src/main.c src/shell_modbus.c src/shell_system.c)
|
||||
list(APPEND KCONFIG_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../../modules/modbus_server/Kconfig)
|
||||
list(APPEND KCONFIG_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../../modules/valve/Kconfig)
|
||||
list(APPEND KCONFIG_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/../../modules/fwu/Kconfig)
|
||||
|
||||
target_include_directories(app PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../modules/valve/include
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../modules/modbus_server/include
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../modules/fwu/include
|
||||
)
|
||||
|
||||
# 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
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../modules/valve/src/valve.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../modules/modbus_server/src/modbus_server.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/../../modules/fwu/src/fwu.c
|
||||
)
|
||||
6
software/apps/slave_node/boards/bluepill_f103rb.conf
Normal file
6
software/apps/slave_node/boards/bluepill_f103rb.conf
Normal file
@@ -0,0 +1,6 @@
|
||||
# Disable UART console
|
||||
CONFIG_UART_CONSOLE=n
|
||||
|
||||
# Enable RTT console
|
||||
CONFIG_RTT_CONSOLE=y
|
||||
CONFIG_USE_SEGGER_RTT=y
|
||||
@@ -0,0 +1,9 @@
|
||||
&usart1 {
|
||||
modbus0 {
|
||||
compatible = "zephyr,modbus-serial";
|
||||
status = "okay";
|
||||
};
|
||||
status = "okay";
|
||||
pinctrl-0 = <&usart1_tx_pa9 &usart1_rx_pa10>;
|
||||
pinctrl-names = "default";
|
||||
};
|
||||
@@ -2,13 +2,6 @@
|
||||
CONFIG_CONSOLE=y
|
||||
CONFIG_LOG=y
|
||||
|
||||
# Disable UART console
|
||||
CONFIG_UART_CONSOLE=n
|
||||
|
||||
# Enable RTT console
|
||||
CONFIG_RTT_CONSOLE=y
|
||||
CONFIG_USE_SEGGER_RTT=y
|
||||
|
||||
# Enable Shell
|
||||
CONFIG_SHELL=y
|
||||
CONFIG_SHELL_BACKEND_RTT=y
|
||||
@@ -28,3 +21,4 @@ CONFIG_UART_INTERRUPT_DRIVEN=y
|
||||
CONFIG_MODBUS=y
|
||||
CONFIG_MODBUS_ROLE_SERVER=y
|
||||
CONFIG_MODBUS_BUFFER_SIZE=256
|
||||
|
||||
|
||||
@@ -1,286 +1,28 @@
|
||||
/*
|
||||
* Copyright (c) 2020 PHYTEC Messtechnik GmbH
|
||||
* Copyright (c) 2022 Nordic Semiconductor ASA
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#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/sys/crc.h>
|
||||
#include <zephyr/sys/byteorder.h>
|
||||
|
||||
#include <zephyr/logging/log.h>
|
||||
#include "modbus_bridge.h"
|
||||
#include <modbus_server.h>
|
||||
#include <valve.h>
|
||||
#include <fwu.h>
|
||||
|
||||
LOG_MODULE_REGISTER(mbs_sample, LOG_LEVEL_INF);
|
||||
|
||||
#define APP_VERSION_MAJOR 1
|
||||
#define APP_VERSION_MINOR 0
|
||||
#define APP_VERSION_PATCH 0
|
||||
|
||||
/* Register Definitions from Documentation */
|
||||
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,
|
||||
};
|
||||
|
||||
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,
|
||||
};
|
||||
|
||||
/* Valve Simulation */
|
||||
enum valve_state { VALVE_STATE_CLOSED, VALVE_STATE_OPEN };
|
||||
enum valve_movement { VALVE_MOVEMENT_IDLE, VALVE_MOVEMENT_OPENING, VALVE_MOVEMENT_CLOSING, VALVE_MOVEMENT_ERROR };
|
||||
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;
|
||||
|
||||
/* Digital I/O State */
|
||||
static uint16_t digital_outputs_state = 0;
|
||||
static uint16_t digital_inputs_state = 0; // Will be controlled by real hardware
|
||||
static uint16_t button_events = 0; // Clear-on-read
|
||||
|
||||
/* System State */
|
||||
static uint16_t device_status = 0; // 0 = OK
|
||||
static uint16_t watchdog_timeout_s = 0;
|
||||
|
||||
/* Firmware Update State */
|
||||
#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;
|
||||
|
||||
/* Modbus Configuration */
|
||||
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 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;
|
||||
}
|
||||
|
||||
static int holding_reg_rd(uint16_t addr, uint16_t *reg)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
static int holding_reg_wr(uint16_t addr, uint16_t reg)
|
||||
{
|
||||
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 */
|
||||
if (current_state == VALVE_STATE_OPEN) {
|
||||
current_movement = VALVE_MOVEMENT_CLOSING;
|
||||
k_work_schedule(&valve_work, K_SECONDS(max_closing_time_s));
|
||||
}
|
||||
} 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);
|
||||
// Here you would typically write to GPIOs
|
||||
break;
|
||||
case REG_HOLDING_WATCHDOG_TIMEOUT_S:
|
||||
watchdog_timeout_s = reg;
|
||||
LOG_INF("Watchdog timeout set to %u s", watchdog_timeout_s);
|
||||
break;
|
||||
case REG_HOLDING_FWU_COMMAND:
|
||||
if (reg == 1) { // Verify Chunk
|
||||
LOG_INF("FWU: Chunk at offset %u (size %u) verified by client, writing to flash (simulated).", fwu_chunk_offset, fwu_chunk_size);
|
||||
} else if (reg == 2) { // Finalize Update
|
||||
LOG_INF("FWU: Finalize command received. Rebooting (simulated).");
|
||||
// In a real scenario: sys_reboot(SYS_REBOOT_WARM);
|
||||
}
|
||||
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:
|
||||
// Handle FWU_DATA_BUFFER writes
|
||||
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]);
|
||||
// After the last register of a chunk is written, calculate CRC
|
||||
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;
|
||||
}
|
||||
|
||||
static int input_reg_rd(uint16_t addr, uint16_t *reg)
|
||||
{
|
||||
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; // Simulated
|
||||
case REG_INPUT_DIGITAL_INPUTS_STATE: *reg = digital_inputs_state; break;
|
||||
case REG_INPUT_BUTTON_EVENTS:
|
||||
*reg = button_events;
|
||||
button_events = 0; // Clear-on-read
|
||||
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,
|
||||
};
|
||||
|
||||
#define MODBUS_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_modbus_serial)
|
||||
|
||||
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id)
|
||||
{
|
||||
int err;
|
||||
err = modbus_disable(modbus_iface);
|
||||
if (err) { return err; }
|
||||
server_param.serial.baud = baudrate;
|
||||
server_param.server.unit_id = unit_id;
|
||||
err = modbus_init_server(modbus_iface, server_param);
|
||||
return err;
|
||||
}
|
||||
|
||||
uint32_t modbus_get_baudrate(void) { return server_param.serial.baud; }
|
||||
uint8_t modbus_get_unit_id(void) { return server_param.server.unit_id; }
|
||||
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; }
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
SETTINGS_STATIC_HANDLER_DEFINE(modbus, "modbus", NULL, settings_load_cb, NULL, NULL);
|
||||
SETTINGS_STATIC_HANDLER_DEFINE(valve, "valve", NULL, settings_load_cb, NULL, NULL);
|
||||
|
||||
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);
|
||||
}
|
||||
LOG_MODULE_REGISTER(main, LOG_LEVEL_INF);
|
||||
|
||||
int main(void)
|
||||
{
|
||||
LOG_INF("Starting Irrigation System Slave Node");
|
||||
|
||||
k_work_init_delayable(&valve_work, valve_work_handler);
|
||||
|
||||
if (settings_subsys_init() || settings_load()) {
|
||||
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");
|
||||
return 0;
|
||||
}
|
||||
|
||||
LOG_INF("Irrigation System Slave Node started successfully");
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <zephyr/shell/shell.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)
|
||||
{
|
||||
|
||||
6
software/apps/stm32g431_tests/CMakeLists.txt
Normal file
6
software/apps/stm32g431_tests/CMakeLists.txt
Normal file
@@ -0,0 +1,6 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
|
||||
project(stm32g431_tests)
|
||||
|
||||
target_sources(app PRIVATE src/main.c)
|
||||
4
software/apps/stm32g431_tests/prj.conf
Normal file
4
software/apps/stm32g431_tests/prj.conf
Normal file
@@ -0,0 +1,4 @@
|
||||
|
||||
CONFIG_CONSOLE=y
|
||||
CONFIG_LOG=y
|
||||
CONFIG_UART_CONSOLE=y
|
||||
9
software/apps/stm32g431_tests/src/main.c
Normal file
9
software/apps/stm32g431_tests/src/main.c
Normal file
@@ -0,0 +1,9 @@
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/sys/printk.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
printk("Hello World! %s\n", CONFIG_BOARD);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
# Add your shared libraries here
|
||||
# Example:
|
||||
# add_library(modbus modbus/modbus.c)
|
||||
# target_include_directories(modbus PUBLIC .)
|
||||
7
software/modules/fwu/CMakeLists.txt
Normal file
7
software/modules/fwu/CMakeLists.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.13.1)
|
||||
include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE)
|
||||
|
||||
project(fwu)
|
||||
|
||||
target_sources(app PRIVATE src/fwu.c)
|
||||
target_include_directories(app PUBLIC include)
|
||||
5
software/modules/fwu/Kconfig
Normal file
5
software/modules/fwu/Kconfig
Normal file
@@ -0,0 +1,5 @@
|
||||
config FWU
|
||||
bool "Enable Firmware Update Library"
|
||||
default y
|
||||
help
|
||||
Enable the Firmware Update module.
|
||||
10
software/modules/fwu/include/fwu.h
Normal file
10
software/modules/fwu/include/fwu.h
Normal 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
|
||||
45
software/modules/fwu/src/fwu.c
Normal file
45
software/modules/fwu/src/fwu.c
Normal 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;
|
||||
}
|
||||
7
software/modules/modbus_server/CMakeLists.txt
Normal file
7
software/modules/modbus_server/CMakeLists.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.13.1)
|
||||
include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE)
|
||||
|
||||
project(modbus_server)
|
||||
|
||||
target_sources(app PRIVATE src/modbus_server.c)
|
||||
target_include_directories(app PUBLIC include)
|
||||
5
software/modules/modbus_server/Kconfig
Normal file
5
software/modules/modbus_server/Kconfig
Normal file
@@ -0,0 +1,5 @@
|
||||
config MODBUS_SERVER
|
||||
bool "Enable Modbus Server Library"
|
||||
default y
|
||||
help
|
||||
Enable the Modbus Server module.
|
||||
52
software/modules/modbus_server/include/modbus_server.h
Normal file
52
software/modules/modbus_server/include/modbus_server.h
Normal file
@@ -0,0 +1,52 @@
|
||||
#ifndef MODBUS_SERVER_H
|
||||
#define MODBUS_SERVER_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
* @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,
|
||||
REG_HOLDING_DEVICE_RESET = 0x00F1,
|
||||
/* 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,
|
||||
};
|
||||
|
||||
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
|
||||
202
software/modules/modbus_server/src/modbus_server.c
Normal file
202
software/modules/modbus_server/src/modbus_server.c
Normal file
@@ -0,0 +1,202 @@
|
||||
#include <zephyr/kernel.h>
|
||||
#include <zephyr/drivers/uart.h>
|
||||
#include <zephyr/device.h>
|
||||
#include <zephyr/modbus/modbus.h>
|
||||
#include <zephyr/logging/log.h>
|
||||
#include <zephyr/settings/settings.h>
|
||||
#include <zephyr/sys/reboot.h>
|
||||
#include "modbus_server.h"
|
||||
#include "valve.h"
|
||||
#include "fwu.h"
|
||||
|
||||
#include <zephyr/usb/usb_device.h>
|
||||
|
||||
LOG_MODULE_REGISTER(modbus_server, LOG_LEVEL_INF);
|
||||
|
||||
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;
|
||||
case REG_HOLDING_DEVICE_RESET:
|
||||
if (reg == 1)
|
||||
{
|
||||
LOG_WRN("Modbus reset command received. Rebooting...");
|
||||
sys_reboot(SYS_REBOOT_WARM);
|
||||
}
|
||||
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;
|
||||
case REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR:
|
||||
*reg = (0 << 8) | 0;
|
||||
break;
|
||||
case REG_INPUT_FIRMWARE_VERSION_PATCH:
|
||||
*reg = 1;
|
||||
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)};
|
||||
#if DT_NODE_HAS_COMPAT(DT_PARENT(MODBUS_NODE), zephyr_cdc_acm_uart)
|
||||
const struct device *const dev = DEVICE_DT_GET(DT_PARENT(MODBUS_NODE));
|
||||
uint32_t dtr = 0;
|
||||
|
||||
if (!device_is_ready(dev) || usb_enable(NULL))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
while (!dtr)
|
||||
{
|
||||
uart_line_ctrl_get(dev, UART_LINE_CTRL_DTR, &dtr);
|
||||
k_sleep(K_MSEC(100));
|
||||
}
|
||||
|
||||
LOG_INF("Client connected to server on %s", dev->name);
|
||||
#endif
|
||||
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; }
|
||||
7
software/modules/valve/CMakeLists.txt
Normal file
7
software/modules/valve/CMakeLists.txt
Normal file
@@ -0,0 +1,7 @@
|
||||
cmake_minimum_required(VERSION 3.13.1)
|
||||
include($ENV{ZEPHYR_BASE}/cmake/app/boilerplate.cmake NO_POLICY_SCOPE)
|
||||
|
||||
project(valve)
|
||||
|
||||
target_sources(app PRIVATE src/valve.c)
|
||||
target_include_directories(app PUBLIC include)
|
||||
5
software/modules/valve/Kconfig
Normal file
5
software/modules/valve/Kconfig
Normal file
@@ -0,0 +1,5 @@
|
||||
config VALVE
|
||||
bool "Enable Valve Library"
|
||||
default y
|
||||
help
|
||||
Enable the Valve module.
|
||||
23
software/modules/valve/include/valve.h
Normal file
23
software/modules/valve/include/valve.h
Normal 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
|
||||
62
software/modules/valve/src/valve.c
Normal file
62
software/modules/valve/src/valve.c
Normal 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; }
|
||||
@@ -1,3 +1,5 @@
|
||||
<img src="../../../docs/img/logo.png" alt="Logo" width="100"/>
|
||||
|
||||
# Modbus Tool für Bewässerungssystem-Knoten
|
||||
|
||||
Dieses Python-Skript bietet eine interaktive Kommandozeilen-Benutzeroberfläche (TUI) zur Steuerung und Überwachung eines Ventil-Knotens des Bewässerungssystems über Modbus RTU.
|
||||
|
||||
@@ -9,7 +9,7 @@ from pymodbus.client import ModbusSerialClient
|
||||
from pymodbus.exceptions import ModbusException
|
||||
|
||||
# --- Register Definitions ---
|
||||
# Input Registers
|
||||
# (omitted for brevity, no changes here)
|
||||
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000
|
||||
REG_INPUT_MOTOR_CURRENT_MA = 0x0001
|
||||
REG_INPUT_DIGITAL_INPUTS_STATE = 0x0020
|
||||
@@ -20,19 +20,19 @@ REG_INPUT_DEVICE_STATUS = 0x00F2
|
||||
REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3
|
||||
REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4
|
||||
REG_INPUT_FWU_LAST_CHUNK_CRC = 0x0100
|
||||
|
||||
# Holding Registers
|
||||
REG_HOLDING_VALVE_COMMAND = 0x0000
|
||||
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001
|
||||
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002
|
||||
REG_HOLDING_DIGITAL_OUTPUTS_STATE = 0x0010
|
||||
REG_HOLDING_WATCHDOG_TIMEOUT_S = 0x00F0
|
||||
REG_HOLDING_DEVICE_RESET = 0x00F1
|
||||
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
|
||||
|
||||
|
||||
# --- Global State ---
|
||||
stop_event = threading.Event()
|
||||
client = None
|
||||
@@ -54,88 +54,111 @@ def format_uptime(seconds):
|
||||
|
||||
def poll_status(slave_id, interval):
|
||||
global status_data
|
||||
reconnect_attempts = 0
|
||||
max_reconnect_attempts = 5
|
||||
reconnect_delay = 1 # seconds
|
||||
|
||||
while not stop_event.is_set():
|
||||
if update_status["running"]: time.sleep(interval); continue
|
||||
new_data = {"error": None}
|
||||
if update_status["running"]:
|
||||
time.sleep(interval)
|
||||
continue
|
||||
|
||||
new_data = {}
|
||||
try:
|
||||
if not client.is_socket_open():
|
||||
reconnect_attempts += 1
|
||||
if reconnect_attempts >= max_reconnect_attempts:
|
||||
new_data["error"] = f"Failed to reconnect after {max_reconnect_attempts} attempts. Exiting."
|
||||
stop_event.set()
|
||||
break
|
||||
|
||||
# Attempt to connect
|
||||
if client.connect():
|
||||
reconnect_attempts = 0
|
||||
new_data["error"] = None # Clear error on successful reconnect
|
||||
else:
|
||||
new_data["error"] = f"Connection lost. Attempting to reconnect ({reconnect_attempts}/{max_reconnect_attempts})..."
|
||||
time.sleep(reconnect_delay)
|
||||
continue
|
||||
|
||||
# If connected, try to read data
|
||||
ir_valve = client.read_input_registers(REG_INPUT_VALVE_STATE_MOVEMENT, count=2, slave=slave_id)
|
||||
ir_dig = client.read_input_registers(REG_INPUT_DIGITAL_INPUTS_STATE, count=2, slave=slave_id)
|
||||
ir_sys = client.read_input_registers(REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR, count=5, slave=slave_id)
|
||||
hr_valve = client.read_holding_registers(REG_HOLDING_MAX_OPENING_TIME_S, count=2, slave=slave_id)
|
||||
hr_dig = client.read_holding_registers(REG_HOLDING_DIGITAL_OUTPUTS_STATE, count=1, slave=slave_id)
|
||||
hr_sys = client.read_holding_registers(REG_HOLDING_WATCHDOG_TIMEOUT_S, count=1, slave=slave_id)
|
||||
|
||||
for res in [ir_valve, ir_dig, ir_sys, hr_valve, hr_dig, hr_sys]:
|
||||
if res.isError(): raise ModbusException(str(res))
|
||||
if res.isError():
|
||||
raise ModbusException(str(res))
|
||||
|
||||
valve_state_raw = ir_valve.registers[0]
|
||||
movement_map = {0: "Idle", 1: "Opening", 2: "Closing", 3: "Error"}; state_map = {0: "Closed", 1: "Open"}
|
||||
new_data["movement"] = movement_map.get(valve_state_raw >> 8, 'Unknown'); new_data["state"] = state_map.get(valve_state_raw & 0xFF, 'Unknown')
|
||||
new_data["motor_current"] = f"{ir_valve.registers[1]} mA"; new_data["open_time"] = f"{hr_valve.registers[0]}s"; new_data["close_time"] = f"{hr_valve.registers[1]}s"
|
||||
new_data["digital_inputs"] = f"0x{ir_dig.registers[0]:04X}"; new_data["button_events"] = f"0x{ir_dig.registers[1]:04X}"; new_data["digital_outputs"] = f"0x{hr_dig.registers[0]:04X}"
|
||||
movement_map = {0: "Idle", 1: "Opening", 2: "Closing", 3: "Error"}
|
||||
state_map = {0: "Closed", 1: "Open"}
|
||||
new_data["movement"] = movement_map.get(valve_state_raw >> 8, 'Unknown')
|
||||
new_data["state"] = state_map.get(valve_state_raw & 0xFF, 'Unknown')
|
||||
new_data["motor_current"] = f"{ir_valve.registers[1]} mA"
|
||||
new_data["open_time"] = f"{hr_valve.registers[0]}s"
|
||||
new_data["close_time"] = f"{hr_valve.registers[1]}s"
|
||||
new_data["digital_inputs"] = f"0x{ir_dig.registers[0]:04X}"
|
||||
new_data["button_events"] = f"0x{ir_dig.registers[1]:04X}"
|
||||
new_data["digital_outputs"] = f"0x{hr_dig.registers[0]:04X}"
|
||||
|
||||
fw_major = ir_sys.registers[0] >> 8; fw_minor = ir_sys.registers[0] & 0xFF; fw_patch = ir_sys.registers[1]
|
||||
fw_major = ir_sys.registers[0] >> 8
|
||||
fw_minor = ir_sys.registers[0] & 0xFF
|
||||
fw_patch = ir_sys.registers[1]
|
||||
uptime_seconds = (ir_sys.registers[4] << 16) | ir_sys.registers[3]
|
||||
new_data["firmware"] = f"v{fw_major}.{fw_minor}.{fw_patch}"; new_data["device_status"] = "OK" if ir_sys.registers[2] == 0 else "ERROR"
|
||||
new_data["uptime"] = format_uptime(uptime_seconds); new_data["watchdog"] = f"{hr_sys.registers[0]}s"
|
||||
new_data["firmware"] = f"v{fw_major}.{fw_minor}.{fw_patch}"
|
||||
new_data["device_status"] = "OK" if ir_sys.registers[2] == 0 else "ERROR"
|
||||
new_data["uptime"] = format_uptime(uptime_seconds)
|
||||
new_data["watchdog"] = f"{hr_sys.registers[0]}s"
|
||||
new_data["error"] = None # Clear any previous error on successful read
|
||||
reconnect_attempts = 0 # Reset attempts on successful communication
|
||||
except Exception as e:
|
||||
new_data["error"] = f"Error: {e}"
|
||||
with status_lock: status_data = new_data
|
||||
time.sleep(interval)
|
||||
new_data["error"] = f"Communication Error: {e}. Closing connection."
|
||||
client.close() # Close connection to force reconnect attempt in next loop
|
||||
finally:
|
||||
with status_lock:
|
||||
status_data = new_data
|
||||
time.sleep(interval)
|
||||
|
||||
def firmware_update_thread(slave_id, filepath):
|
||||
global update_status
|
||||
with update_lock:
|
||||
update_status = {"running": True, "message": "Starting update...", "progress": 0.0}
|
||||
|
||||
try:
|
||||
with open(filepath, 'rb') as f:
|
||||
firmware = f.read()
|
||||
|
||||
with open(filepath, 'rb') as f: firmware = f.read()
|
||||
file_size = len(firmware)
|
||||
chunk_size = 248 # Max payload size for write_registers is ~248 bytes
|
||||
chunk_size = 248
|
||||
offset = 0
|
||||
|
||||
while offset < file_size:
|
||||
chunk = firmware[offset:offset + chunk_size]
|
||||
|
||||
with update_lock:
|
||||
update_status["message"] = f"Sending chunk {offset//chunk_size + 1}/{(file_size + chunk_size - 1)//chunk_size}..."
|
||||
update_status["progress"] = offset / file_size
|
||||
|
||||
# 1. Set offset and size
|
||||
client.write_register(REG_HOLDING_FWU_CHUNK_OFFSET_LOW, offset & 0xFFFF, slave=slave_id)
|
||||
client.write_register(REG_HOLDING_FWU_CHUNK_OFFSET_HIGH, (offset >> 16) & 0xFFFF, slave=slave_id)
|
||||
client.write_register(REG_HOLDING_FWU_CHUNK_SIZE, len(chunk), slave=slave_id)
|
||||
|
||||
# 2. Write data buffer in smaller bursts to avoid timing issues
|
||||
padded_chunk = chunk
|
||||
if len(padded_chunk) % 2 != 0:
|
||||
padded_chunk += b'\x00'
|
||||
|
||||
all_registers = [int.from_bytes(padded_chunk[i:i+2], 'big') for i in range(0, len(padded_chunk), 2)]
|
||||
|
||||
burst_size_regs = 16 # 32 bytes per burst
|
||||
for i in range(0, len(all_registers), burst_size_regs):
|
||||
reg_burst = all_registers[i:i + burst_size_regs]
|
||||
padded_chunk = chunk + (b'\x00' if len(chunk) % 2 != 0 else b'')
|
||||
registers = [int.from_bytes(padded_chunk[i:i+2], 'big') for i in range(0, len(padded_chunk), 2)]
|
||||
burst_size_regs = 16
|
||||
for i in range(0, len(registers), burst_size_regs):
|
||||
reg_burst = registers[i:i + burst_size_regs]
|
||||
start_addr = REG_HOLDING_FWU_DATA_BUFFER + i
|
||||
client.write_registers(start_addr, reg_burst, slave=slave_id)
|
||||
time.sleep(0.02) # Small delay between bursts
|
||||
|
||||
# 3. Read back CRC
|
||||
time.sleep(0.1) # Give slave time to calculate
|
||||
remote_crc = client.read_input_registers(REG_INPUT_FWU_LAST_CHUNK_CRC, count=1, slave=slave_id).registers[0]
|
||||
|
||||
# 4. Verify (not implemented in this simulation) and command write
|
||||
client.write_register(REG_HOLDING_FWU_COMMAND, 1, slave=slave_id) # Command: Verify Chunk
|
||||
|
||||
time.sleep(0.02)
|
||||
time.sleep(0.1)
|
||||
client.read_input_registers(REG_INPUT_FWU_LAST_CHUNK_CRC, count=1, slave=slave_id)
|
||||
client.write_register(REG_HOLDING_FWU_COMMAND, 1, slave=slave_id)
|
||||
offset += len(chunk)
|
||||
|
||||
with update_lock: update_status["message"] = "Finalizing update..."
|
||||
client.write_register(REG_HOLDING_FWU_COMMAND, 2, slave=slave_id) # Command: Finalize
|
||||
with update_lock:
|
||||
update_status["progress"] = 1.0
|
||||
update_status["message"] = "Finalizing update..."
|
||||
client.write_register(REG_HOLDING_FWU_COMMAND, 2, slave=slave_id)
|
||||
time.sleep(1)
|
||||
with update_lock: update_status["message"] = "Update complete! Slave is rebooting."
|
||||
time.sleep(2)
|
||||
|
||||
except Exception as e:
|
||||
with update_lock: update_status["message"] = f"Error: {e}"
|
||||
time.sleep(3)
|
||||
@@ -143,17 +166,64 @@ def firmware_update_thread(slave_id, filepath):
|
||||
with update_lock: update_status["running"] = False
|
||||
|
||||
def draw_button(stdscr, y, x, text, selected=False):
|
||||
"""Draws a button, handling selection highlight."""
|
||||
color = curses.color_pair(2) if selected else curses.color_pair(1)
|
||||
stdscr.addstr(y, x, f" {' ' * len(text)} ", color)
|
||||
button_width = len(text) + 2
|
||||
stdscr.addstr(y, x, " " * button_width, color)
|
||||
stdscr.addstr(y, x + 1, text, color)
|
||||
|
||||
def file_browser(stdscr):
|
||||
"""A simple curses file browser."""
|
||||
curses.curs_set(1)
|
||||
path = os.getcwd()
|
||||
selected_index = 0
|
||||
|
||||
while True:
|
||||
stdscr.clear()
|
||||
h, w = stdscr.getmaxyx()
|
||||
stdscr.addstr(0, 0, f"Select Firmware File: {path}".ljust(w-1), curses.color_pair(2))
|
||||
|
||||
try:
|
||||
items = sorted(os.listdir(path))
|
||||
except OSError as e:
|
||||
items = [f".. (Error: {e})"]
|
||||
|
||||
items.insert(0, "..")
|
||||
|
||||
for i, item_name in enumerate(items):
|
||||
if i >= h - 2: break
|
||||
display_name = item_name
|
||||
if os.path.isdir(os.path.join(path, item_name)):
|
||||
display_name += "/"
|
||||
|
||||
if i == selected_index:
|
||||
stdscr.addstr(i + 1, 0, display_name, curses.color_pair(2))
|
||||
else:
|
||||
stdscr.addstr(i + 1, 0, display_name)
|
||||
|
||||
key = stdscr.getch()
|
||||
|
||||
if key == curses.KEY_UP:
|
||||
selected_index = max(0, selected_index - 1)
|
||||
elif key == curses.KEY_DOWN:
|
||||
selected_index = min(len(items) - 1, selected_index + 1)
|
||||
elif key == curses.KEY_ENTER or key in [10, 13]:
|
||||
selected_item_path = os.path.join(path, items[selected_index])
|
||||
if os.path.isdir(selected_item_path):
|
||||
path = os.path.abspath(selected_item_path)
|
||||
selected_index = 0
|
||||
else:
|
||||
return selected_item_path
|
||||
elif key == 27: # ESC key
|
||||
return None
|
||||
|
||||
def main_menu(stdscr, slave_id):
|
||||
global status_data, update_status
|
||||
curses.curs_set(0); stdscr.nodelay(1); stdscr.timeout(100)
|
||||
curses.start_color(); curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE); curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_WHITE); curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLUE)
|
||||
stdscr.bkgd(' ', curses.color_pair(1))
|
||||
|
||||
menu = ["Open Valve", "Close Valve", "Stop Valve", "Toggle Output 1", "Toggle Output 2", "Set Watchdog", "Firmware Update", "Exit"]
|
||||
menu = ["Open Valve", "Close Valve", "Stop Valve", "Toggle Output 1", "Toggle Output 2", "Set Watchdog", "Reset Node", "Firmware Update", "Exit"]
|
||||
current_row_idx = 0
|
||||
message, message_time = "", 0
|
||||
input_mode, input_prompt, input_str, input_target_reg = False, "", "", 0
|
||||
@@ -165,7 +235,6 @@ def main_menu(stdscr, slave_id):
|
||||
with update_lock: is_updating = update_status["running"]
|
||||
|
||||
if is_updating:
|
||||
# Update display only, no input handling
|
||||
pass
|
||||
elif input_mode:
|
||||
if key in [10, 13]:
|
||||
@@ -196,24 +265,31 @@ def main_menu(stdscr, slave_id):
|
||||
except Exception as e: message = f"-> Error: {e}"
|
||||
elif selected_option == "Set Watchdog":
|
||||
input_mode, input_prompt, input_target_reg = True, "Enter Watchdog Timeout (s): ", REG_HOLDING_WATCHDOG_TIMEOUT_S
|
||||
elif selected_option == "Reset Node":
|
||||
try:
|
||||
client.write_register(REG_HOLDING_DEVICE_RESET, 1, slave=slave_id)
|
||||
message = "-> Sent RESET command. Node should reboot."
|
||||
except Exception as e:
|
||||
message = f"-> Error sending reset: {e}"
|
||||
elif selected_option == "Firmware Update":
|
||||
threading.Thread(target=firmware_update_thread, args=(slave_id, "firmware.bin"), daemon=True).start()
|
||||
filepath = file_browser(stdscr)
|
||||
if filepath:
|
||||
threading.Thread(target=firmware_update_thread, args=(slave_id, filepath), daemon=True).start()
|
||||
else:
|
||||
message = "-> Firmware update cancelled."
|
||||
|
||||
stdscr.clear()
|
||||
if is_updating:
|
||||
with update_lock:
|
||||
prog = update_status["progress"]
|
||||
msg = update_status["message"]
|
||||
with update_lock: prog, msg = update_status["progress"], update_status["message"]
|
||||
stdscr.addstr(h // 2 - 1, w // 2 - 25, "FIRMWARE UPDATE IN PROGRESS", curses.A_BOLD | curses.color_pair(2))
|
||||
stdscr.addstr(h // 2, w // 2 - 25, f"[{'#' * int(prog * 50):<50}] {prog:.0%}")
|
||||
stdscr.addstr(h // 2 + 1, w // 2 - 25, msg.ljust(50))
|
||||
else:
|
||||
with status_lock: current_data = status_data.copy()
|
||||
bold, normal = curses.color_pair(1) | curses.A_BOLD, curses.color_pair(1)
|
||||
if current_data.get("error"): stdscr.addstr(0, 0, current_data["error"], curses.color_pair(3) | curses.A_BOLD)
|
||||
else:
|
||||
bold, normal = curses.color_pair(1) | curses.A_BOLD, curses.color_pair(1)
|
||||
col1, col2, col3, col4 = 2, 30, 58, 88
|
||||
# Status display lines...
|
||||
stdscr.addstr(1, col1, "State:", bold); stdscr.addstr(1, col1 + 18, str(current_data.get('state', 'N/A')), normal)
|
||||
stdscr.addstr(2, col1, "Movement:", bold); stdscr.addstr(2, col1 + 18, str(current_data.get('movement', 'N/A')), normal)
|
||||
stdscr.addstr(3, col1, "Motor Current:", bold); stdscr.addstr(3, col1 + 18, str(current_data.get('motor_current', 'N/A')), normal)
|
||||
@@ -223,9 +299,9 @@ def main_menu(stdscr, slave_id):
|
||||
stdscr.addstr(1, col3, "Max Open Time:", bold); stdscr.addstr(1, col3 + 16, str(current_data.get('open_time', 'N/A')), normal)
|
||||
stdscr.addstr(2, col3, "Max Close Time:", bold); stdscr.addstr(2, col3 + 16, str(current_data.get('close_time', 'N/A')), normal)
|
||||
stdscr.addstr(3, col3, "Watchdog:", bold); stdscr.addstr(3, col3 + 16, str(current_data.get('watchdog', 'N/A')), normal)
|
||||
stdscr.addstr(1, col4, "Firmware:", bold); stdscr.addstr(1, col4 + 12, str(current_data.get('firmware', 'N/A')), normal)
|
||||
stdscr.addstr(2, col4, "Uptime:", bold); stdscr.addstr(2, col4 + 12, str(current_data.get('uptime', 'N/A')), normal)
|
||||
stdscr.addstr(3, col4, "Device Status:", bold); stdscr.addstr(3, col4 + 12, str(current_data.get('device_status', 'N/A')), normal)
|
||||
stdscr.addstr(1, col4, "Firmware:", bold); stdscr.addstr(1, col4 + 14, str(current_data.get('firmware', 'N/A')), normal)
|
||||
stdscr.addstr(2, col4, "Uptime:", bold); stdscr.addstr(2, col4 + 14, str(current_data.get('uptime', 'N/A')), normal)
|
||||
stdscr.addstr(3, col4, "Dev. Status:", bold); stdscr.addstr(3, col4 + 14, str(current_data.get('device_status', 'N/A')), normal)
|
||||
stdscr.addstr(5, 0, "─" * (w - 1), normal)
|
||||
for idx, row in enumerate(menu):
|
||||
draw_button(stdscr, h // 2 - len(menu) + (idx * 2), w // 2 - len(row) // 2, row, idx == current_row_idx)
|
||||
@@ -251,4 +327,4 @@ def main():
|
||||
if client.is_socket_open(): client.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user