49 Commits

Author SHA1 Message Date
84e7d02db8 defunct: playing around with bootloaders 2025-07-08 14:11:22 +02:00
cc6b4488ee Fix MCUboot and app flash partitioning
- Corrected device tree overlays to prevent MCUboot and app overlap
- MCUboot now at 0x8000000 (32KB), app at 0x8008000 (96KB)
- Successfully boots MCUboot which chains to application
- Shell and reset command working properly
- Black Magic Probe flashing confirmed working for both domains
2025-07-07 16:04:29 +02:00
928a176e7c Step 2 complete: MCUboot integration with single-slot configuration
- Created sysbuild configuration for MCUboot bootloader
- Added device tree overlays for correct partition layout (32KB MCUboot, 96KB app)
- Fixed MCUboot partition addressing to use boot_partition instead of slot0_partition
- MCUboot successfully boots and chains to application
- Application runs with shell and custom reset command
- Disabled signature validation for testing purposes
2025-07-07 15:59:41 +02:00
8255b2a672 Add firmware_node app - Step 1: Shell with reset command
- Create new Zephyr app for firmware management
- Target: weact_stm32g431_core board
- Features: Shell interface with custom reset command
- Tested on Zephyr 4.1.99
- Flash usage: 55,400 bytes (42.27% of 128KB)
- RAM usage: 12,864 bytes (39.26% of 32KB)
- Black Magic Probe flash runner support
2025-07-07 13:49:03 +02:00
d48281436e Fix ADC devicetree compilation error for voltage divider
- Fix voltage divider devicetree configuration to reference ADC controller directly instead of channel node
- Switch from ADC API to sensor API for voltage divider usage
- Add required sensor and voltage divider configuration options
- Remove unnecessary zephyr,user node that was causing compilation issues
- The voltage divider now properly uses sensor framework and builds successfully

Hardware setup:
- Uses ADC1 channel 1 on pin PA0
- Voltage divider with 2.2kΩ output and 3.2kΩ total resistance
- Provides voltage readings through sensor API accounting for divider ratio
2025-07-07 13:36:44 +02:00
dcb73c0a25 Working DT ADC sample WITHOUT resistor divider 2025-07-07 12:32:53 +02:00
2c21f1f9cb feat: Revert ADC changes and set channel 12 for VREFINT 2025-07-06 15:27:14 +02:00
a2afec52e2 fix(adc_test): correct ADC reference configuration
- Revert ADC_GAIN to ADC_GAIN_1 due to driver limitation.
- Revert ADC_REF to ADC_REF_INTERNAL due to driver limitation.
- Set zephyr,vref-mv to 3300 to match observed hardware behavior.
2025-07-06 10:24:37 +02:00
2cc258e8e2 feat(adc_test): use devicetree for adc configuration
- Use named adc channel 'multisense' from devicetree
- Enable adc calibration
2025-07-06 09:55:10 +02:00
a77298b3a6 Implement VND7050AJ supply voltage reading function
- Added devicetree overlay for VND7050AJ with GPIO and ADC configuration
- Created custom devicetree binding for VND7050AJ valve controller
- Implemented valve_get_supply_voltage() function with proper pin control:
  - RST=HIGH to enable VND7050AJ
  - S0=1, S1=1 for supply voltage sensing mode
  - SEN=1 to enable MULTISENSE output
  - ADC reading on PA0 (ADC1_IN1) with 12-bit resolution
- Fixed supply voltage calculation (VCC/8 per datasheet)
- Added comprehensive debug logging for all steps
- Tested and verified ADC functionality
- Current reading: 5.1V (may be limited by hardware power supply)

Files modified:
- software/lib/valve/valve.c: Main implementation
- software/apps/slave_node/boards/weact_stm32g431_core.overlay: DT config
- software/apps/slave_node/dts/bindings/vnd7050aj-valve-controller.yaml: DT binding
- software/apps/slave_node/src/main.c: Test code
- software/apps/slave_node/prj.conf: ADC driver enablement
2025-07-04 08:54:47 +02:00
45d011952f fix(valve): Correct VND7050AJ initialization and pin configuration
- Initialize RST pin as active to keep VND7050AJ out of reset state
- Clarify S0/S1 pins as output select pins with descriptive comments
- Add initialization logging to show configured max open/close times
- Ensure proper valve controller startup sequence
2025-07-03 19:04:20 +02:00
bb25134b6c feat(modbus): Implement persistent and improved reconfiguration for Modbus server
This commit enhances the Modbus server's configuration handling by:

- Loading saved baudrate and unit ID settings during initialization, ensuring persistence across reboots.
- Providing improved feedback during `modbus_reconfigure`, including logging for successful changes and informing the user when a device restart is required for changes to take effect.
- Saving new configuration settings even if immediate reinitialization fails, allowing them to be applied on the next boot.
2025-07-03 18:59:01 +02:00
9f96384aa5 fix(cdc-acm): Correct CDC ACM overlay configuration
This commit fixes an issue in the `cdc-acm.overlay` file.
2025-07-03 18:57:06 +02:00
b543579393 feat(modbus): Add supply voltage register and display in tool
This commit introduces a new Modbus input register for the system's supply voltage.

- The `modbus-registers.de.md` documentation is updated to include the `SUPPLY_VOLTAGE_MV` register at address `0x00F5` within the system block.
- The `modbus_server.h` header defines the new register.
- The `modbus_server.c` implementation provides a fixed value (12300 mV) for this register.
- The `modbus_tool.py` script is updated to read and display this new supply voltage value in the UI.

This lays the groundwork for integrating actual voltage measurements in the future.
2025-07-03 18:47:48 +02:00
69cf7e9511 feat(valve): Implement GPIO control for VND7050AJ
This commit implements the real valve control using the GPIOs connected to the VND7050AJ driver.

- The `weact_stm32g431_core.overlay` is updated with a specific compatible string and a device tree label for the valve controller.
- `valve.h` is extended to include GPIO device specifications.
- `valve.c` now initializes and controls the GPIOs for opening and closing the valve, including the reset logic. The IN0 and IN1 pins are interlocked to prevent simultaneous activation. The RST pin is activated before each movement and deactivated afterward.

This replaces the previous virtual/simulated valve logic with actual hardware control.
2025-07-03 18:17:31 +02:00
8df7aef51b Removed unused lib dir 2025-07-03 17:47:48 +02:00
f6ee0a5122 feat(weact_stm32g431_core): Configure VND7050AJ driver pins in overlay
Updated the weact_stm32g431_core.overlay to define the GPIO and ADC
pin assignments for the VND7050AJ driver. This includes:
- Digital I/O pins (IN0, IN1, RST, S0, S1, SEN) configured as GPIOs.
- Analog input pin (MULTISENSE/PA0) configured for ADC1.
2025-07-03 17:39:04 +02:00
6c1ff0c4df feat(refactor): Restructure project for improved modularity and clarity
This commit introduces a major refactoring of the project structure to align
with Zephyr's recommended multi-application and library organization.

Key changes include:
- Relocation of custom modules from 'software/modules/' to 'software/lib/'.
- Introduction of a central 'software/CMakeLists.txt' to manage application
  and library subdirectories.
- Creation of new Kconfig files for 'software/' and 'software/apps/slave_node/'
  to define project-wide and application-specific configurations.
- Removal of the 'gateway' and 'stm32g431_tests' applications.
- Removal of 'shell_modbus.c' and 'shell_system.c' from 'slave_node' application's
  direct source files, indicating a shift towards library-based shell commands.
- Updates to 'software/apps/slave_node/CMakeLists.txt', 'prj.conf', and
  'boards/bluepill_f103rb.conf' to reflect the new structure and dependencies.
2025-07-03 16:58:43 +02:00
3f0d5a76c6 feat(cdc_acm): Add CDC-ACM support and remove old test applications
- Implemented CDC-ACM (USB Virtual COM Port) support for the slave_node application.
- Removed the now obsolete 'hello_world' and 'stm32g431_tests' applications.
2025-07-03 14:31:17 +02:00
10a770de59 fix(modbus_server): Implement hardcoded firmware version 0.0.1
Set firmware version to 0.0.1 in modbus_server.c for Modbus tool display.
This is a temporary solution until MCUboot integration is complete.
2025-07-03 13:43:15 +02:00
1b0519aadf Resolve merge conflict in modbus_server.c and add hardcoded firmware version. 2025-07-03 13:34:59 +02:00
e429a0874d Revert "feat(slave_node): Refine Modbus UART and add CDC-ACM support"
This reverts commit 3a05c80b25.
2025-07-03 13:34:01 +02:00
3a05c80b25 feat(slave_node): Refine Modbus UART and add CDC-ACM support
- Adjusted Device Tree Overlays for bluepill_f103rb and weact_stm32g431_core
  to correctly define Modbus UART via 'modbus0' subnode with 'zephyr,modbus-serial'
  compatibility, aligning with rtu_server sample.
- Prepared modbus_server.c to use the correct Device Tree node for Modbus UART.
2025-07-03 13:18:47 +02:00
5208f1370d feat(slave_node): Support multi-board build for bluepill_f103rb and weact_stm32g431_core
Refactor slave_node application to support building for both bluepill_f103rb and
weact_stm32g431_core boards.

- Moved RTT-specific console and shell backend configurations from prj.conf
  into board-specific .conf files (bluepill_f103rb.conf).
- Configured USART2 as console/shell for weact_stm32g431_core.
- Added Device Tree Overlay for weact_stm32g431_core to enable USART1 for Modbus
  communication (PA9/PA10).
2025-07-03 10:53:21 +02:00
a59e8518cc Rename hello_world app to stm32g431_tests 2025-07-03 10:02:53 +02:00
2a2890b675 Fix: hello_world prj.conf - set correct board name 2025-07-03 09:21:48 +02:00
38fd3a6aac Add hello_world Zephyr application for stm32g431_core 2025-07-03 09:15:11 +02:00
c3df6565b7 Refactor fwu library into a Zephyr module 2025-07-02 21:30:15 +02:00
140d2baa24 Fix: modbus_tool.py - replace is_connected() with is_socket_open() and fix UnboundLocalError 2025-07-02 21:05:40 +02:00
711341f362 Refactor slave_node application to use Zephyr modules 2025-07-02 20:47:16 +02:00
a5da0a61dd Update modbus_tool.py 2025-07-02 17:10:11 +02:00
b54c73edb1 fix: handle connection loss and re-establish in modbus_tool.py 2025-07-02 10:03:23 +02:00
2418d4e218 fix: resolve build error by moving modbus register enums to header 2025-07-02 10:02:40 +02:00
2b4890f052 fix: correct modbus_tool.py update for reset command 2025-07-02 09:58:19 +02:00
85d493f24a feat: implement modbus reset command and update docs/tool 2025-07-02 09:55:42 +02:00
f486d4c4ab cleanup: remove unused CMakeLists.txt and empty modbus directory 2025-07-02 09:54:01 +02:00
6cfd4b8b4d refactor: restructure slave_node into libraries 2025-07-02 09:45:22 +02:00
0088030d66 docs: replace svg logo with png version 2025-07-02 09:22:37 +02:00
4d828b41f1 docs: Add project logo to all markdown files
Added the new project logo to the header of all relevant markdown documentation files to improve brand consistency and visual appeal.
2025-07-01 23:37:30 +02:00
95f435923f feat(main): Add detailed source code documentation
Add comprehensive Doxygen-style comments to all functions, enums, and macros in `main.c`. This improves code clarity and maintainability. The Doxygen configuration itself was removed after deciding against generating a separate HTML manual, but the in-code comments provide significant value on their own.
2025-07-01 23:29:26 +02:00
33f2a15cf3 docs(slave_node): Add Doxygen comments to main.c
- Add Doxygen-compliant comments to functions, enums, and state variables in `main.c`.
- This provides a foundation for automatically generating source code documentation.
- Remove the separate, now redundant, `firmware-manual.de.md` file.
2025-07-01 22:56:30 +02:00
c4e87a3125 docs: Add firmware manual and update main README
- Create a new firmware manual (`firmware-manual.de.md`) to document the current features of the slave node.
- Add a linked table of contents to the new manual.
- Update the main `README.de.md` to link to the new firmware manual and the existing Modbus tool README.
2025-07-01 22:51:17 +02:00
773027f6b0 feat(slave_node): Implement Modbus watchdog timer
- Add a fail-safe watchdog using a Zephyr kernel timer.
- The timer is reset on any successful Modbus communication.
- If the timer expires (no communication within the configured timeout), the valve is automatically closed as a safety measure.
- The watchdog is enabled by writing a non-zero value to the `WATCHDOG_TIMEOUT_S` register and disabled by writing 0.
2025-07-01 22:46:57 +02:00
461cce7a48 fix(modbus_tool): Adjust UI layout for alignment
- Shorten "Device Status" label to "Dev. Status".
- Realign the rightmost column for better readability.
2025-07-01 22:38:52 +02:00
23b88ada83 feat(modbus_tool): Add interactive file browser for firmware updates
- Implement a simple, curses-based file browser to allow selecting firmware files from the filesystem.
- The selected file path is used for the firmware update process.
- Fix a visual bug where the progress bar would not reach 100% upon completion.
- Remove a leftover  function that was causing a NameError.
2025-07-01 22:15:44 +02:00
c2916662e2 feat(modbus_tool): Implement simulated firmware update
- Add a new thread to handle the firmware update process, preventing the UI from freezing.
- The UI now displays a progress bar and status messages during the update.
- The tool reads a  file and sends it to the slave in chunks.
- Add a dummy  for testing purposes.
- Fix Modbus communication issues by reducing the chunk size to a safe value (248 bytes) and sending data in smaller bursts to improve stability.
- Update the README with the new features and instructions.
2025-07-01 21:55:19 +02:00
24087f5622 fix(slave_node): Increase Modbus buffer size
- Set CONFIG_MODBUS_BUFFER_SIZE to 256 to ensure the slave can handle larger data packets sent by the client during firmware updates.
2025-07-01 21:55:01 +02:00
95fd88e93e feat(modbus_tool): Adapt UI to full register map
- Update the TUI to display all new registers from the slave, including digital I/O and system status.
- Add new menu buttons to control digital outputs and set the watchdog timer.
- Add a placeholder button for the firmware update process.
- Fix various bugs, including incorrect argument passing in Modbus calls and a module import error.
2025-07-01 21:36:28 +02:00
21797d8507 feat(slave_node): Implement full Modbus register map
- Implement all remaining Modbus registers as defined in the documentation v1.0.
- Add support for digital I/O, system status, and a simulated watchdog.
- Implement a placeholder for the firmware update mechanism, including CRC calculation for received data chunks.
- Remove the input simulation timer; digital inputs are now static and ready for real hardware.
2025-07-01 21:36:10 +02:00
99 changed files with 2419 additions and 571 deletions

View File

@@ -0,0 +1,7 @@
feat(modbus): Implement persistent and improved reconfiguration for Modbus server
This commit enhances the Modbus server's configuration handling by:
- Loading saved baudrate and unit ID settings during initialization, ensuring persistence across reboots.
- Providing improved feedback during `modbus_reconfigure`, including logging for successful changes and informing the user when a device restart is required for changes to take effect.
- Saving new configuration settings even if immediate reinitialization fails, allowing them to be applied on the next boot.

5
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"files.associations": {
"fwu.h": "c"
}
}

View File

@@ -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) 🇩🇪 Deutsch | [🇬🇧 English](README.md) | [🇫🇷 Français](README.fr.md) | [🇪🇸 Español](README.es.md)
# Modulares Bewässerungssystem # 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. * **[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. * **[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. * **[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 ## Schnellstart

View File

@@ -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 [🇩🇪 Deutsch](README.de.md) | [🇬🇧 English](README.md) | [🇫🇷 Français](README.fr.md) | 🇪🇸 Español
# Sistema de riego modular # Sistema de riego modular

View File

@@ -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) [🇩🇪 Deutsch](README.de.md) | [🇬🇧 English](README.md) | 🇫🇷 Français | [🇪🇸 Español](README.es.md)
# Système d'irrigation modulaire # Système d'irrigation modulaire

View File

@@ -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) [🇩🇪 Deutsch](README.de.md) | 🇬🇧 English | [🇫🇷 Français](README.fr.md) | [🇪🇸 Español](README.es.md)
# Modular Irrigation System # Modular Irrigation System

View File

@@ -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) 🇩🇪 Deutsch | [🇬🇧 English](concept.en.md) | [🇫🇷 Français](concept.fr.md) | [🇪🇸 Español](concept.es.md)
# Konzept: Modulares Bewässerungssystem # Konzept: Modulares Bewässerungssystem

View File

@@ -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) [🇩🇪 Deutsch](concept.de.md) | 🇬🇧 English | [🇫🇷 Français](concept.fr.md) | [🇪🇸 Español](concept.es.md)
# Concept: Modular Irrigation System # Concept: Modular Irrigation System

View File

@@ -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 [🇩🇪 Deutsch](concept.de.md) | [🇬🇧 English](concept.en.md) | [🇫🇷 Français](concept.fr.md) | 🇪🇸 Español
# Concepto: Sistema de riego modular # Concepto: Sistema de riego modular

View File

@@ -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) [🇩🇪 Deutsch](concept.de.md) | [🇬🇧 English](concept.en.md) | 🇫🇷 Français | [🇪🇸 Español](concept.es.md)
# Concept : Système d'irrigation modulaire # Concept : Système d'irrigation modulaire

BIN
docs/img/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 KiB

16
docs/img/logo.svg Normal file
View 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

View File

@@ -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) 🇩🇪 Deutsch | [🇬🇧 English](modbus-registers.en.md) | [🇫🇷 Français](modbus-registers.fr.md) | [🇪🇸 Español](modbus-registers.es.md)
# MODBUS Register Map Definition v1.0 # MODBUS Register Map Definition v1.0
@@ -36,6 +38,7 @@ Alle Register sind in einer einzigen, durchgehenden Liste pro Register-Typ (`Inp
| **0x00F2** | `DEVICE_STATUS` | System | `0`=OK, `1`=Allgemeiner Fehler. | | **0x00F2** | `DEVICE_STATUS` | System | `0`=OK, `1`=Allgemeiner Fehler. |
| **0x00F3** | `UPTIME_SECONDS_LOW` | System | Untere 16 Bit der Uptime in Sekunden. | | **0x00F3** | `UPTIME_SECONDS_LOW` | System | Untere 16 Bit der Uptime in Sekunden. |
| **0x00F4** | `UPTIME_SECONDS_HIGH` | System | Obere 16 Bit der Uptime. | | **0x00F4** | `UPTIME_SECONDS_HIGH` | System | Obere 16 Bit der Uptime. |
| **0x00F5** | `SUPPLY_VOLTAGE_MV` | System | Aktuelle Versorgungsspannung in Millivolt (mV). |
| **0x0100** | `FWU_LAST_CHUNK_CRC` | Firmware-Update | Enthält den CRC16 des zuletzt im Puffer empfangenen Daten-Chunks. | | **0x0100** | `FWU_LAST_CHUNK_CRC` | Firmware-Update | Enthält den CRC16 des zuletzt im Puffer empfangenen Daten-Chunks. |
## 3. Holding Registers (4xxxx, Read/Write) ## 3. Holding Registers (4xxxx, Read/Write)
@@ -47,6 +50,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. | | **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. | | **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. | | **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. | | **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. | | **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. | | **0x0102** | `FWU_CHUNK_OFFSET_HIGH` | Firmware-Update | Obere 16 Bit des 32-Bit-Offsets. |

View File

@@ -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) [🇩🇪 Deutsch](modbus-registers.de.md) | 🇬🇧 English | [🇫🇷 Français](modbus-registers.fr.md) | [🇪🇸 Español](modbus-registers.es.md)
# MODBUS Register Map Definition v1.0 # MODBUS Register Map Definition v1.0

View File

@@ -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 [🇩🇪 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 # Definición del mapa de registros MODBUS v1.0

View File

@@ -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) [🇩🇪 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 # Définition de la carte des registres MODBUS v1.0

View File

@@ -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) 🇩🇪 Deutsch | [🇬🇧 English](planning.en.md) | [🇫🇷 Français](planning.fr.md) | [🇪🇸 Español](planning.es.md)
# Projektplan: Modulares Bewässerungssystem # Projektplan: Modulares Bewässerungssystem

View File

@@ -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) [🇩🇪 Deutsch](planning.de.md) | 🇬🇧 English | [🇫🇷 Français](planning.fr.md) | [🇪🇸 Español](planning.es.md)
# Project Plan: Modular Irrigation System # Project Plan: Modular Irrigation System

View File

@@ -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 [🇩🇪 Deutsch](planning.de.md) | [🇬🇧 English](planning.en.md) | [🇫🇷 Français](planning.fr.md) | 🇪🇸 Español
# Plan del proyecto: Sistema de riego modular # Plan del proyecto: Sistema de riego modular

View File

@@ -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) [🇩🇪 Deutsch](planning.de.md) | [🇬🇧 English](planning.en.md) | 🇫🇷 Français | [🇪🇸 Español](planning.es.md)
# Plan de projet : Système d'irrigation modulaire # Plan de projet : Système d'irrigation modulaire

View File

@@ -8,5 +8,10 @@
// File Associations // File Associations
"files.associations": { "files.associations": {
"array": "c",
"string_view": "c",
"initializer_list": "c",
"span": "c",
"format": "c"
} }
} }

1
software/Kconfig Normal file
View File

@@ -0,0 +1 @@
rsource "lib/Kconfig"

View File

@@ -0,0 +1,8 @@
# SPDX-License-Identifier: Apache-2.0
cmake_minimum_required(VERSION 3.20.0)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(ADC)
target_sources(app PRIVATE src/main.c)

View File

@@ -0,0 +1,62 @@
.. zephyr:code-sample:: adc_dt
:name: Analog-to-Digital Converter (ADC) with devicetree
:relevant-api: adc_interface
Read analog inputs from ADC channels.
Overview
********
This sample demonstrates how to use the :ref:`ADC driver API <adc_api>`.
Depending on the target board, it reads ADC samples from one or more channels
and prints the readings on the console. If voltage of the used reference can
be obtained, the raw readings are converted to millivolts.
The pins of the ADC channels are board-specific. Please refer to the board
or MCU datasheet for further details.
Building and Running
********************
The ADC peripheral and pinmux is configured in the board's ``.dts`` file. Make
sure that the ADC is enabled (``status = "okay";``).
In addition to that, this sample requires an ADC channel specified in the
``io-channels`` property of the ``zephyr,user`` node. This is usually done with
a devicetree overlay. The example overlay in the ``boards`` subdirectory for
the ``nucleo_l073rz`` board can be easily adjusted for other boards.
Configuration of channels (settings like gain, reference, or acquisition time)
also needs to be specified in devicetree, in ADC controller child nodes. Also
the ADC resolution and oversampling setting (if used) need to be specified
there. See :zephyr_file:`boards/nrf52840dk_nrf52840.overlay
<samples/drivers/adc/adc_dt/boards/nrf52840dk_nrf52840.overlay>` for an example of
such setup.
Building and Running for ST Nucleo L073RZ
=========================================
The sample can be built and executed for the
:zephyr:board:`nucleo_l073rz` as follows:
.. zephyr-app-commands::
:zephyr-app: samples/drivers/adc/adc_dt
:board: nucleo_l073rz
:goals: build flash
:compact:
To build for another board, change "nucleo_l073rz" above to that board's name
and provide a corresponding devicetree overlay.
Sample output
=============
You should get a similar output as below, repeated every second:
.. code-block:: console
ADC reading:
- ADC_0, channel 7: 36 = 65mV
.. note:: If the ADC is not supported, the output will be an error message.

View File

@@ -0,0 +1,38 @@
/ {
vdd_sense: voltage-divider {
compatible = "voltage-divider";
/*
* This reference must provide one argument (the channel number)
* because of the "#io-channel-cells = <1>" in the &adc1 node.
*/
io-channels = <&adc1 1>;
output-ohms = <2200>;
full-ohms = <3200>;
};
};
&adc1 {
status = "okay";
pinctrl-0 = <&adc1_in1_pa0>;
pinctrl-names = "default";
st,adc-clock-source = "SYNC";
st,adc-prescaler = <4>;
#address-cells = <1>;
#size-cells = <0>;
/*
* This line is required by the st,stm32-adc driver binding.
* It declares that references to its channels need one extra argument.
*/
#io-channel-cells = <1>;
adc_channel_1: channel@1 {
reg = <1>;
zephyr,gain = "ADC_GAIN_1";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
zephyr,resolution = <12>;
};
};

View File

@@ -0,0 +1,4 @@
CONFIG_ADC=y
CONFIG_SENSOR=y
CONFIG_VOLTAGE_DIVIDER=y
CONFIG_LOG=y

View File

@@ -0,0 +1,53 @@
sample:
name: ADC devicetree driver sample
tests:
sample.drivers.adc.adc_dt:
tags:
- adc
depends_on: adc
platform_allow:
- nucleo_l073rz
- disco_l475_iot1
- cc3220sf_launchxl
- cc3235sf_launchxl
- cy8cproto_063_ble
- stm32l496g_disco
- stm32h735g_disco
- nrf51dk/nrf51822
- nrf52840dk/nrf52840
- nrf54l15dk/nrf54l15/cpuapp
- nrf54h20dk/nrf54h20/cpuapp
- ophelia4ev/nrf54l15/cpuapp
- mec172xevb_assy6906
- gd32f350r_eval
- gd32f450i_eval
- gd32vf103v_eval
- gd32f403z_eval
- esp32_devkitc/esp32/procpu
- esp32s2_saola
- esp32c3_devkitm
- gd32l233r_eval
- lpcxpresso55s36
- mr_canhubk3
- longan_nano
- longan_nano/gd32vf103/lite
- rd_rw612_bga
- frdm_mcxn947/mcxn947/cpu0
- mcx_n9xx_evk/mcxn947/cpu0
- frdm_mcxc242
- ucans32k1sic
- xg24_rb4187c
- xg29_rb4412a
- raytac_an54l15q_db/nrf54l15/cpuapp
- frdm_mcxa166
- frdm_mcxa276
integration_platforms:
- nucleo_l073rz
- nrf52840dk/nrf52840
harness: console
timeout: 10
harness_config:
type: multi_line
regex:
- "ADC reading\\[\\d+\\]:"
- "- .+, channel \\d+: -?\\d+"

View File

@@ -0,0 +1,25 @@
/*
* Copyright (c) 2022 Wolter HV <wolterhv@gmx.de>
*
* SPDX-License-Identifier: Apache-2.0
*/
/ {
zephyr,user {
io-channels = <&adc0 0>;
};
};
&adc0 {
status = "okay";
#address-cells = <1>;
#size-cells = <0>;
channel@0 {
reg = <0>;
zephyr,gain = "ADC_GAIN_1_4";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
zephyr,resolution = <12>;
};
};

View File

@@ -0,0 +1,25 @@
/*
* Copyright (c) 2022 Wolter HV <wolterhv@gmx.de>
*
* SPDX-License-Identifier: Apache-2.0
*/
/ {
zephyr,user {
io-channels = <&adc0 0>;
};
};
&adc0 {
status = "okay";
#address-cells = <1>;
#size-cells = <0>;
channel@0 {
reg = <0>;
zephyr,gain = "ADC_GAIN_1_4";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
zephyr,resolution = <12>;
};
};

View File

@@ -0,0 +1,25 @@
/*
* Copyright (c) 2022 Wolter HV <wolterhv@gmx.de>
*
* SPDX-License-Identifier: Apache-2.0
*/
/ {
zephyr,user {
io-channels = <&adc0 0>;
};
};
&adc0 {
status = "okay";
#address-cells = <1>;
#size-cells = <0>;
channel@0 {
reg = <0>;
zephyr,gain = "ADC_GAIN_1_4";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
zephyr,resolution = <12>;
};
};

View File

@@ -0,0 +1,25 @@
/*
* Copyright (c) 2022 Wolter HV <wolterhv@gmx.de>
*
* SPDX-License-Identifier: Apache-2.0
*/
/ {
zephyr,user {
io-channels = <&adc0 0>;
};
};
&adc0 {
status = "okay";
#address-cells = <1>;
#size-cells = <0>;
channel@0 {
reg = <0>;
zephyr,gain = "ADC_GAIN_1_4";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
zephyr,resolution = <12>;
};
};

View File

@@ -0,0 +1,45 @@
#include <zephyr/kernel.h>
#include <zephyr/device.h>
#include <zephyr/devicetree.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/logging/log.h>
LOG_MODULE_REGISTER(adc_dt_example, LOG_LEVEL_DBG);
/* Get the voltage divider device */
#define VOLTAGE_DIVIDER_NODE DT_NODELABEL(vdd_sense)
int main(void)
{
const struct device *vdd_dev = DEVICE_DT_GET(VOLTAGE_DIVIDER_NODE);
struct sensor_value val;
int err;
if (!device_is_ready(vdd_dev)) {
LOG_ERR("Voltage divider device not ready");
return 0;
}
LOG_INF("Voltage divider device ready!");
while (1) {
err = sensor_sample_fetch(vdd_dev);
if (err < 0) {
LOG_ERR("Could not fetch sample (%d)", err);
k_sleep(K_MSEC(1000));
continue;
}
err = sensor_channel_get(vdd_dev, SENSOR_CHAN_VOLTAGE, &val);
if (err < 0) {
LOG_ERR("Could not get channel (%d)", err);
k_sleep(K_MSEC(1000));
continue;
}
LOG_INF("Voltage reading: %d.%06d V", val.val1, val.val2);
k_sleep(K_MSEC(1000));
}
return 0;
}

View File

@@ -0,0 +1,6 @@
cmake_minimum_required(VERSION 3.20)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(adc_test)
target_sources(app PRIVATE src/main.c)

View File

@@ -0,0 +1,8 @@
&adc1 {
pinctrl-0 = <&adc1_in1_pa0>;
pinctrl-names = "default";
status = "okay";
st,adc-clock-source = "SYNC";
st,adc-prescaler = <4>;
};

View File

@@ -0,0 +1,3 @@
CONFIG_ADC=y
CONFIG_ADC_STM32=y
CONFIG_LOG=y

View File

@@ -0,0 +1,73 @@
#include <zephyr/kernel.h>
#include <zephyr/drivers/adc.h>
#include <zephyr/device.h>
#include <zephyr/sys/printk.h>
// ADC-Knoten holen
static const struct device *adc_dev = DEVICE_DT_GET(DT_NODELABEL(adc1));
// Kanaldefinitionen
#define MY_SIGNAL_CHANNEL 1 // PA0
#define ADC_VREFINT_CHANNEL 18 // Intern
// Puffer für ZWEI Messwerte
static int16_t sample_buffer[2];
void main(void)
{
int err;
// Die VREFINT-Spannung in mV aus dem Datenblatt deines Controllers
#define VREFINT_MV 1212
printk("*** ADC Ratiometric Measurement (Single Sequence) ***\n");
if (!device_is_ready(adc_dev)) {
printk("ADC device not ready!\n");
return;
}
// --- Einmaliges Setup der beiden Kanäle ---
const struct adc_channel_cfg signal_channel_cfg = {
.gain = ADC_GAIN_1,
.reference = ADC_REF_INTERNAL,
.acquisition_time = ADC_ACQ_TIME_DEFAULT, // Kurz für niederohmige Quellen
.channel_id = MY_SIGNAL_CHANNEL,
};
const struct adc_channel_cfg vrefint_channel_cfg = {
.gain = ADC_GAIN_1,
.reference = ADC_REF_INTERNAL,
.acquisition_time = ADC_ACQ_TIME_MAX, // Lang für VREFINT
.channel_id = ADC_VREFINT_CHANNEL,
};
adc_channel_setup(adc_dev, &signal_channel_cfg);
adc_channel_setup(adc_dev, &vrefint_channel_cfg);
// --- EINE Sequenz, die BEIDE Kanäle enthält ---
const struct adc_sequence sequence = {
.channels = BIT(MY_SIGNAL_CHANNEL) | BIT(ADC_VREFINT_CHANNEL),
.buffer = sample_buffer,
.buffer_size = sizeof(sample_buffer),
.resolution = 12,
};
while (1) {
err = adc_read(adc_dev, &sequence);
if (err != 0) {
printk("ADC read failed with code %d\n", err);
} else {
// Die Ergebnisse sind in der Reihenfolge der Kanalnummern im Puffer
// Kanal 1 (MY_SIGNAL_CHANNEL) kommt vor Kanal 18 (ADC_VREFINT_CHANNEL)
int16_t signal_raw = sample_buffer[0];
int16_t vrefint_raw = sample_buffer[1];
// Ratiometrische Berechnung
int32_t signal_mv = (int32_t)signal_raw * VREFINT_MV / vrefint_raw;
printk("Signal: raw=%4d | VREFINT: raw=%4d | Calculated Voltage: %d mV\n",
signal_raw, vrefint_raw, signal_mv);
}
k_msleep(2000);
}
}

View File

@@ -0,0 +1,80 @@
#include <zephyr/kernel.h>
#include <zephyr/drivers/adc.h>
#include <zephyr/device.h>
// Definiere die Kanäle
#define ADC_VREFINT_CHANNEL 18 // Muss mit dem DTS übereinstimmen
#define MY_SIGNAL_CHANNEL 1 // Muss mit dem pinctrl im DTS übereinstimmen
// ADC Device
static const struct device *adc_dev = DEVICE_DT_GET(DT_NODELABEL(adc1));
// ADC Kanal Konfigurationen
static const struct adc_channel_cfg vrefint_channel_cfg = {
.gain = ADC_GAIN_1,
.reference = ADC_REF_INTERNAL, // Bedeutet VDDA
.acquisition_time = ADC_ACQ_TIME_MAX,
.channel_id = ADC_VREFINT_CHANNEL,
.differential = 0,
};
static const struct adc_channel_cfg signal_channel_cfg = {
.gain = ADC_GAIN_1,
.reference = ADC_REF_INTERNAL, // Bedeutet VDDA
.acquisition_time = ADC_ACQ_TIME_MAX,
.channel_id = MY_SIGNAL_CHANNEL,
.differential = 0,
};
// Puffer für die Messwerte
#define BUFFER_SIZE 1
static int16_t sample_buffer[BUFFER_SIZE];
// Sequenz für die Messungen
struct adc_sequence sequence_vrefint = {
.channels = BIT(ADC_VREFINT_CHANNEL),
.buffer = sample_buffer,
.buffer_size = sizeof(sample_buffer),
.resolution = 12, // STM32G4 hat 12-bit
};
struct adc_sequence sequence_signal = {
.channels = BIT(MY_SIGNAL_CHANNEL),
.buffer = sample_buffer,
.buffer_size = sizeof(sample_buffer),
.resolution = 12,
};
void main(void) {
if (!device_is_ready(adc_dev)) {
printk("ADC device not found\n");
return;
}
// Kanäle konfigurieren
adc_channel_setup(adc_dev, &vrefint_channel_cfg);
adc_channel_setup(adc_dev, &signal_channel_cfg);
while (1) {
// 1. VREFINT messen zur Kalibrierung
adc_read(adc_dev, &sequence_vrefint);
int16_t vrefint_raw = sample_buffer[0];
// 2. Dein eigentliches Signal messen
adc_read(adc_dev, &sequence_signal);
int16_t signal_raw = sample_buffer[0];
// 3. Spannung berechnen
// VREFINT Wert für STM32G431 bei 3.0V Vdda ist typ. 1.212V (1212 mV)
// Überprüfe den genauen Wert im Datenblatt für deinen Controller!
#define VREFINT_MV 1212
int32_t signal_mv = (int32_t)signal_raw * VREFINT_MV / vrefint_raw;
printk("VREFINT raw: %d, Signal raw: %d, Calculated Voltage: %d mV\n",
vrefint_raw, signal_raw, signal_mv);
k_msleep(1000);
}
}

View File

@@ -0,0 +1,38 @@
#include <zephyr.h>
#include <drivers/adc.h>
#define PA0_PIN 0x04
#define ADC_CHANNEL 0x03
int main(void) {
int16_t adc_value = 0;
// Initialize the ADC
adc_config_t adc_config;
adc_config.mode = ADC_MODE_SINGLE_SHOT;
adc_config.channel = ADC_CHANNEL_PA0;
adc_config.sampling_rate = ADC_SAMP_RATE_1MS;
adc_config.data_rate = ADC_DATA_RATE_4MS;
adc_config.aux = ADC_AUX_ALL;
adc_config.atten = ADC_ATTEN_DB_11;
adc_config.ref = ADC_REF_INTERNAL;
adc_config.cal = ADC_CAL_ALL;
if (adc_config_data(&adc_config, &adc_context) < 0) {
zephyr_printf("Failed to configure ADC\n");
return -1;
}
// Read the analog input value
if (adc_read(&adc_context, &adc_value) < 0) {
zephyr_printf("Failed to read ADC value\n");
return -1;
}
zephyr_printf("ADC Value: %d\n", adc_value);
return 0;
}

View File

@@ -0,0 +1,8 @@
cmake_minimum_required(VERSION 3.20)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(firmware_node LANGUAGES C)
zephyr_include_directories(../../include)
add_subdirectory(../../lib lib)
target_sources(app PRIVATE src/main.c)

View File

@@ -0,0 +1,34 @@
# Firmware Node Application
This Zephyr application provides firmware management capabilities for the irrigation system.
**Tested on Zephyr 4.1.99**
## Features
### Step 1: Shell with Reset Command
- Shell interface with custom "reset" command
- Warm reboot functionality
### Planned Features
- MCUboot support with partition manager
- Firmware version display
- MCUmgr support for OTA updates
## Building
```bash
west build -p auto -b weact_stm32g431_core apps/firmware_node -- -DBOARD_FLASH_RUNNER=blackmagicprobe
```
## Flashing
```bash
west flash
```
## Usage
Connect to the device via serial console and use the shell:
- `reset` - Reboot the system
- `help` - Show available commands

View File

@@ -0,0 +1,29 @@
/*
* Flash partition layout for STM32G431 (128KB total flash)
* MCUboot + single application slot configuration
*/
&flash0 {
partitions {
compatible = "fixed-partitions";
#address-cells = <1>;
#size-cells = <1>;
boot_partition: partition@0 {
label = "mcuboot";
reg = <0x00000000 0x0000A000>; /* 40 KB for MCUboot */
read-only;
};
slot0_partition: partition@A000 {
label = "image-0";
reg = <0x0000A000 0x00016000>; /* 88 KB for application */
};
};
};
/ {
chosen {
zephyr,code-partition = &slot0_partition;
};
};

View File

@@ -0,0 +1,2 @@
# Board specific configuration for weact_stm32g431_core
# This file can be used for board-specific overrides if needed

View File

@@ -0,0 +1,7 @@
/*
* Copyright (c) 2021 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "flash_partitions_128kb.dtsi"

View File

@@ -0,0 +1,18 @@
&flash0 {
partitions {
compatible = "fixed-partitions";
#address-cells = <1>;
#size-cells = <1>;
boot_partition: partition@0 {
label = "mcuboot";
reg = <0x00000000 0x00008000>; /* 32 KB */
read-only;
};
slot0_partition: partition@8000 {
label = "image-0";
reg = <0x00008000 0x00018000>; /* 96 KB */
};
};
};

View File

@@ -0,0 +1,25 @@
# Partition manager configuration for firmware_node
# Boot partition (MCUboot)
mcuboot_primary:
address: 0x00000000
size: 0x8000
region: flash_primary
# Application partition (primary slot)
mcuboot_primary_app:
address: 0x00008000
size: 0x18000
region: flash_primary
# Secondary slot for updates
mcuboot_secondary:
address: 0x00020000
size: 0x18000
region: flash_primary
# Settings partition
settings_partition:
address: 0x00038000
size: 0x8000
region: flash_primary

View File

@@ -0,0 +1,21 @@
# Enable Console and printk for logging
CONFIG_CONSOLE=y
CONFIG_LOG=y
CONFIG_LOG_PROCESS_THREAD=y
# Enable Shell
CONFIG_SHELL=y
CONFIG_REBOOT=y
# Enable the reset command
CONFIG_KERNEL_SHELL=y
# Enable settings for persistent storage
CONFIG_SETTINGS=y
CONFIG_SETTINGS_NVS=y
CONFIG_NVS=y
# Enable Flash and Flash Map for image trailer manipulation
CONFIG_FLASH=y
CONFIG_FLASH_MAP=y
CONFIG_FLASH_PAGE_LAYOUT=y

View File

@@ -0,0 +1,167 @@
#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/shell/shell.h>
#include <zephyr/sys/reboot.h>
#include <zephyr/drivers/flash.h>
#include <zephyr/storage/flash_map.h>
#include <zephyr/devicetree.h>
LOG_MODULE_REGISTER(firmware_node, LOG_LEVEL_INF);
// Image header magic number (from MCUboot)
#define IMAGE_MAGIC 0x96f3b83d
#define IMAGE_HEADER_SIZE 32
// Function to invalidate current image and trigger serial recovery
static int invalidate_current_image(void)
{
const struct flash_area *fa;
int rc;
// Get the flash area for the current image slot (slot0_partition)
rc = flash_area_open(FIXED_PARTITION_ID(slot0_partition), &fa);
if (rc != 0) {
LOG_ERR("Failed to open flash area: %d", rc);
return rc;
}
// Ensure the flash area is valid
if (fa->fa_id != FIXED_PARTITION_ID(slot0_partition)) {
LOG_ERR("Invalid flash area ID: %d", fa->fa_id);
flash_area_close(fa);
return -EINVAL;
}
// Get the flash device associated with this area
// This is necessary to perform erase operations
const struct device *flash_dev = flash_area_get_device(fa);
if (flash_dev == NULL) {
LOG_ERR("Failed to get flash device for area");
flash_area_close(fa);
return -ENODEV;
}
struct flash_pages_info page_info;
off_t last_block_offset;
// Find the last block of the flash area
rc = flash_get_page_info_by_offs(flash_dev, fa->fa_off + fa->fa_size - 1, &page_info);
if (rc != 0) {
LOG_ERR("Failed to get page info: %d", rc);
flash_area_close(fa);
return rc;
}
// Calculate the last block offset
rc = flash_get_page_info_by_offs(flash_dev, fa->fa_off + fa->fa_size - 1, &page_info);
if (rc != 0) {
LOG_ERR("Failed to get page info: %d", rc);
flash_area_close(fa);
return rc;
}
last_block_offset = page_info.start_offset;
// Convert absolute flash offset to relative offset within the flash area
off_t relative_offset = last_block_offset - fa->fa_off;
// Erase the image trailer/metadata at the end of the partition
LOG_INF("Erasing image trailer at absolute offset: %ld, relative offset: %ld, size: %d bytes",
last_block_offset, relative_offset, page_info.size);
rc = flash_area_erase(fa, relative_offset, page_info.size);
if (rc != 0) {
LOG_ERR("Failed to erase image trailer: %d", rc);
} else {
LOG_INF("Image trailer erased successfully");
}
flash_area_close(fa);
return rc;
}
// Custom reset command handler
static int cmd_reset(const struct shell *shell, size_t argc, char **argv)
{
ARG_UNUSED(argc);
ARG_UNUSED(argv);
shell_print(shell, "Resetting system...");
k_msleep(100); // Give time for the message to be sent
sys_reboot(SYS_REBOOT_COLD);
return 0;
}
// MCUboot serial recovery command handler
static int cmd_recovery(const struct shell *shell, size_t argc, char **argv)
{
ARG_UNUSED(argc);
ARG_UNUSED(argv);
shell_print(shell, "Entering MCUboot serial recovery mode...");
shell_print(shell, "Corrupting current image magic to trigger recovery...");
// Invalidate the current image by corrupting its header
int rc = invalidate_current_image();
if (rc != 0) {
shell_error(shell, "Failed to invalidate image: %d", rc);
return rc;
}
shell_print(shell, "Image magic corrupted. System will reset and MCUboot will detect bad image.");
shell_print(shell, "MCUboot should show error and wait for recovery.");
k_msleep(100); // Give time for the message to be sent
// Reset the system - MCUboot will detect invalid image and enter serial recovery
// log_process(true);
// sys_reboot(SYS_REBOOT_COLD);
return 0;
}
// Command to show firmware info
static int cmd_info(const struct shell *shell, size_t argc, char **argv)
{
ARG_UNUSED(argc);
ARG_UNUSED(argv);
const struct flash_area *fa;
int rc = flash_area_open(FIXED_PARTITION_ID(slot0_partition), &fa);
if (rc != 0) {
shell_error(shell, "Failed to open flash area: %d", rc);
return rc;
}
// Read the first few bytes to check the image header
uint32_t magic;
rc = flash_area_read(fa, 0, &magic, sizeof(magic));
if (rc == 0) {
shell_print(shell, "Image magic: 0x%08x", magic);
if (magic == IMAGE_MAGIC) {
shell_print(shell, "Image header is valid");
shell_print(shell, "Image starts at flash offset: 0x%lx", (unsigned long)fa->fa_off);
shell_print(shell, "Image partition size: %d bytes", fa->fa_size);
} else {
shell_print(shell, "Image header is INVALID (expected 0x%08x)", IMAGE_MAGIC);
}
} else {
shell_error(shell, "Failed to read image header: %d", rc);
}
flash_area_close(fa);
return 0;
}
SHELL_CMD_REGISTER(reset, NULL, "Reset the system", cmd_reset);
SHELL_CMD_REGISTER(recovery, NULL, "Enter MCUboot serial recovery mode", cmd_recovery);
SHELL_CMD_REGISTER(info, NULL, "Show firmware info", cmd_info);
int main(void)
{
LOG_INF("Firmware Node starting up");
LOG_INF("Shell with reset command available");
LOG_INF("Serial recovery command available");
return 0;
}

View File

@@ -0,0 +1,4 @@
# Sysbuild configuration for firmware_node with MCUboot
# Enable MCUboot as bootloader
set(SB_CONFIG_BOOTLOADER_MCUBOOT TRUE)

View File

@@ -0,0 +1,5 @@
# Sysbuild configuration for firmware_node with MCUboot
# Enable MCUboot as bootloader
SB_CONFIG_BOOTLOADER_MCUBOOT=y
SB_CONFIG_MCUBOOT_MODE_SINGLE_APP=y

View File

@@ -0,0 +1,13 @@
/*
* Copyright (c) 2021 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "../boards/flash_partitions_128kb.dtsi"
/ {
chosen {
zephyr,code-partition = &slot0_partition;
};
};

View File

@@ -0,0 +1,31 @@
# MCUboot configuration for firmware_node
# Enable basic console and logging for debugging
CONFIG_LOG=y
CONFIG_BOOT_BANNER=y
CONFIG_CONSOLE=y
CONFIG_UART_CONSOLE=y
CONFIG_PRINTK=y
# Single slot configuration (no upgrades)
CONFIG_SINGLE_APPLICATION_SLOT=y
# Enable serial recovery mode (temporarily commented out for debugging)
# CONFIG_MCUBOOT_SERIAL=y
# CONFIG_BOOT_SERIAL_UART=y
# CONFIG_BOOT_SERIAL_DETECT_PORT=y
# Disable signature validation for testing to save space
CONFIG_BOOT_SIGNATURE_TYPE_NONE=y
# Size optimizations to fit in 40KB flash
CONFIG_SIZE_OPTIMIZATIONS=y
CONFIG_CBPRINTF_NANO=y
CONFIG_MINIMAL_LIBC=y
CONFIG_ASSERT=n
# Disable debug features for size
CONFIG_DEBUG_INFO=n
CONFIG_DEBUG_OPTIMIZATIONS=n
# Minimal heap for size optimization
CONFIG_HEAP_MEM_POOL_SIZE=0

View File

@@ -0,0 +1,12 @@
/*
* MCUboot device tree overlay for firmware_node
* Uses shared flash partition layout
*/
#include "../boards/flash_partitions_128kb.dtsi"
/ {
chosen {
zephyr,code-partition = &boot_partition;
};
};

View File

@@ -0,0 +1,33 @@
/*
* MCUboot specific overlay for weact_stm32g431_core
* This overlay defines flash partitions for MCUboot
*/
&flash0 {
partitions {
compatible = "fixed-partitions";
#address-cells = <1>;
#size-cells = <1>;
boot_partition: partition@0 {
label = "mcuboot";
reg = <0x00000000 0x00008000>;
};
slot0_partition: partition@8000 {
label = "image-0";
reg = <0x00008000 0x0000E000>;
};
slot1_partition: partition@16000 {
label = "image-1";
reg = <0x00016000 0x0000E000>;
};
storage_partition: partition@24000 {
label = "storage";
reg = <0x00024000 0x00004000>;
};
};
};
&chosen {
zephyr,boot-partition = &boot_partition;
};

View File

@@ -1,9 +1,8 @@
cmake_minimum_required(VERSION 3.20) cmake_minimum_required(VERSION 3.20)
# Point BOARD_ROOT and DTS_ROOT to the 'software' directory, which contains 'boards'.
list(APPEND BOARD_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../..)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(slave_node)
target_sources(app PRIVATE src/main.c src/shell_modbus.c src/shell_system.c) project(slave_node LANGUAGES C)
zephyr_include_directories(../../include)
add_subdirectory(../../lib lib)
target_sources(app PRIVATE src/main.c)

View File

@@ -0,0 +1,2 @@
rsource "../../lib/Kconfig"
source "Kconfig.zephyr"

View File

@@ -0,0 +1,7 @@
# Disable UART console
CONFIG_UART_CONSOLE=n
# Enable RTT console
CONFIG_RTT_CONSOLE=y
CONFIG_USE_SEGGER_RTT=y
CONFIG_SHELL_BACKEND_RTT=y

View File

@@ -0,0 +1,64 @@
/ {
vnd7050aj: vnd7050aj {
compatible = "vnd7050aj-valve-controller";
status = "okay";
// VND7050AJ GPIO pin definitions
in0-gpios = <&gpiob 7 GPIO_ACTIVE_HIGH>; // IN0 (PB7) - Input 0 control signal
in1-gpios = <&gpiob 9 GPIO_ACTIVE_HIGH>; // IN1 (PB9) - Input 1 control signal
rst-gpios = <&gpiob 3 GPIO_ACTIVE_HIGH>; // RST (PB3) - Reset pin for VND7050AJ
sen-gpios = <&gpiob 4 GPIO_ACTIVE_HIGH>; // SEN (PB4) - Sense Enable for current monitoring
s0-gpios = <&gpiob 6 GPIO_ACTIVE_HIGH>; // S0 (PB6) - Status/Select 0 output from VND7050AJ
s1-gpios = <&gpiob 5 GPIO_ACTIVE_HIGH>; // S1 (PB5) - Status/Select 1 output from VND7050AJ
};
};
&usart1 {
modbus0 {
compatible = "zephyr,modbus-serial";
status = "okay";
};
status = "okay";
pinctrl-0 = <&usart1_tx_pa9 &usart1_rx_pa10>; // PA9=TX, PA10=RX for Modbus communication
pinctrl-names = "default";
};
&adc1 {
status = "okay";
pinctrl-0 = <&adc1_in1_pa0 &adc1_in15_pb0>;
pinctrl-names = "default";
st,adc-clock-source = "SYNC";
st,adc-prescaler = <1>;
#address-cells = <1>;
#size-cells = <0>;
channel@1 {
reg = <1>;
zephyr,gain = "ADC_GAIN_1";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME_MAX>; // Use maximum acquisition time for stability
zephyr,resolution = <12>;
zephyr,vref-mv = <2048>; // STM32G431 VREFBUF at 2.048V
};
channel@15 {
reg = <15>;
zephyr,gain = "ADC_GAIN_1";
zephyr,reference = "ADC_REF_INTERNAL";
zephyr,acquisition-time = <ADC_ACQ_TIME_DEFAULT>;
zephyr,resolution = <12>;
zephyr,vref-mv = <2048>; // STM32G431 VREFBUF at 2.048V
};
};
&pinctrl {
// Pinmux für PA0 als ADC1_IN1 (Analogmodus)
adc1_in1_pa0: adc1_in1_pa0 {
pinmux = <STM32_PINMUX('A', 0, ANALOG)>; // PA0 in den Analogmodus setzen
};
// Pinmux für PB0 als ADC1_IN15 (Analogmodus) - for lab supply testing
adc1_in15_pb0: adc1_in15_pb0 {
pinmux = <STM32_PINMUX('B', 0, ANALOG)>; // PB0 in den Analogmodus setzen
};
};

View File

@@ -0,0 +1,14 @@
&zephyr_udc0 {
cdc_acm_uart0: cdc_acm_uart0 {
compatible = "zephyr,cdc-acm-uart";
modbus0 {
compatible = "zephyr,modbus-serial";
status = "okay";
};
};
};
&usart1 {
/delete-node/ modbus0;
};

View File

@@ -0,0 +1,35 @@
# VND7050AJ Valve Controller binding
description: VND7050AJ valve controller GPIO configuration
compatible: "vnd7050aj-valve-controller"
properties:
in0-gpios:
type: phandle-array
description: GPIO for IN0 control signal
required: true
in1-gpios:
type: phandle-array
description: GPIO for IN1 control signal
required: true
rst-gpios:
type: phandle-array
description: GPIO for reset pin
required: true
sen-gpios:
type: phandle-array
description: GPIO for sense enable pin
required: true
s0-gpios:
type: phandle-array
description: GPIO for select 0 pin
required: true
s1-gpios:
type: phandle-array
description: GPIO for select 1 pin
required: true

View File

@@ -0,0 +1,4 @@
CONFIG_USB_DEVICE_STACK=y
CONFIG_USB_DEVICE_PRODUCT="Modbus slave node"
CONFIG_UART_LINE_CTRL=y
CONFIG_USB_DEVICE_INITIALIZE_AT_BOOT=n

View File

@@ -2,16 +2,8 @@
CONFIG_CONSOLE=y CONFIG_CONSOLE=y
CONFIG_LOG=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 # Enable Shell
CONFIG_SHELL=y CONFIG_SHELL=y
CONFIG_SHELL_BACKEND_RTT=y
CONFIG_REBOOT=y CONFIG_REBOOT=y
# Enable Settings Subsystem # Enable Settings Subsystem
@@ -27,3 +19,9 @@ CONFIG_SETTINGS_LOG_LEVEL_DBG=y
CONFIG_UART_INTERRUPT_DRIVEN=y CONFIG_UART_INTERRUPT_DRIVEN=y
CONFIG_MODBUS=y CONFIG_MODBUS=y
CONFIG_MODBUS_ROLE_SERVER=y CONFIG_MODBUS_ROLE_SERVER=y
CONFIG_MODBUS_BUFFER_SIZE=256
# Enable ADC driver
CONFIG_ADC=y
CONFIG_ADC_STM32=y

View File

@@ -1,352 +1,35 @@
/*
* Copyright (c) 2020 PHYTEC Messtechnik GmbH
* Copyright (c) 2022 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <zephyr/kernel.h> #include <zephyr/kernel.h>
#include <zephyr/sys/util.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/modbus/modbus.h>
#include <zephyr/usb/usb_device.h>
#include <zephyr/settings/settings.h> #include <zephyr/settings/settings.h>
#include <zephyr/logging/log.h> #include <zephyr/logging/log.h>
#include "modbus_bridge.h" #include <lib/modbus_server.h>
#include <lib/valve.h>
#include <lib/fwu.h>
LOG_MODULE_REGISTER(mbs_sample, LOG_LEVEL_INF); LOG_MODULE_REGISTER(main, LOG_LEVEL_INF);
#define APP_VERSION_MAJOR 1
#define APP_VERSION_MINOR 0
#define APP_VERSION_PATCH 0
enum {
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000,
REG_INPUT_MOTOR_CURRENT_MA = 0x0001,
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,
};
enum {
REG_HOLDING_VALVE_COMMAND = 0x0000,
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001,
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002,
REG_HOLDING_WATCHDOG_TIMEOUT_S = 0x00F0,
};
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 uint16_t watchdog_timeout_s;
static int modbus_iface;
static struct k_work_delayable valve_work;
static struct modbus_iface_param server_param = {
.mode = MODBUS_MODE_RTU,
.server = {
.user_cb = NULL, // Will be set later
.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 coil_rd(uint16_t addr, bool *state)
{
*state = true;
LOG_INF("Coil read, addr %u, %d", addr, (int)*state);
return 0;
}
static int coil_wr(uint16_t addr, bool state)
{
LOG_INF("Coil write, addr %u, %d", addr, (int)state);
return 0;
}
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_WATCHDOG_TIMEOUT_S:
*reg = watchdog_timeout_s;
break;
default:
*reg = 0;
break;
}
LOG_INF("Holding register read, addr %u, value %u", addr, *reg);
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;
LOG_INF("Virtual valve opening...");
k_work_schedule(&valve_work, K_MSEC(max_opening_time_s * 1000 * 0.9));
}
} else if (reg == 2) { /* Close */
if (current_state == VALVE_STATE_OPEN) {
current_movement = VALVE_MOVEMENT_CLOSING;
LOG_INF("Virtual valve closing...");
k_work_schedule(&valve_work, K_MSEC(max_closing_time_s * 1000 * 0.9));
}
} else if (reg == 0) { /* Stop */
k_work_cancel_delayable(&valve_work);
current_movement = VALVE_MOVEMENT_IDLE;
LOG_INF("Virtual valve movement stopped");
}
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_WATCHDOG_TIMEOUT_S:
watchdog_timeout_s = reg;
break;
default:
break;
}
LOG_INF("Holding register write, addr %u, value %u", addr, reg);
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 = 50; /* Dummy value */
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 = 0; /* 0 = OK */
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;
default:
*reg = 0;
break;
}
LOG_INF("Input register read, addr %u, value %u", addr, *reg);
return 0;
}
static struct modbus_user_callbacks mbs_cbs = {
.coil_rd = coil_rd,
.coil_wr = coil_wr,
.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;
LOG_INF("Reconfiguring Modbus: baudrate=%u, id=%u", baudrate, unit_id);
err = modbus_disable(modbus_iface);
if (err) {
LOG_ERR("Failed to disable Modbus: %d", err);
return err;
}
server_param.serial.baud = baudrate;
server_param.server.unit_id = unit_id;
err = modbus_init_server(modbus_iface, server_param);
if (err) {
LOG_ERR("Failed to re-init Modbus server: %d", err);
return err;
}
return 0;
}
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));
if (rc < 0) {
return rc;
}
LOG_INF("Loaded modbus/baudrate: %u", server_param.serial.baud);
return 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));
if (rc < 0) {
return rc;
}
LOG_INF("Loaded modbus/unit_id: %u", server_param.server.unit_id);
return 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));
if (rc < 0) {
return rc;
}
LOG_INF("Loaded valve/max_open_time: %u", max_opening_time_s);
return 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));
if (rc < 0) {
return rc;
}
LOG_INF("Loaded valve/max_close_time: %u", max_closing_time_s);
return 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) {
LOG_ERR("Failed to get iface index for %s", iface_name);
return modbus_iface;
}
server_param.server.user_cb = &mbs_cbs;
return modbus_init_server(modbus_iface, server_param);
}
int main(void) int main(void)
{ {
LOG_INF("Starting APP"); 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 (settings_subsys_init()) {
LOG_ERR("Failed to initialize settings subsystem");
} }
if (settings_load()) { valve_init();
LOG_ERR("Failed to load settings"); fwu_init();
}
if (modbus_server_init()) {
if (init_modbus_server()) {
LOG_ERR("Modbus RTU server initialization failed"); LOG_ERR("Modbus RTU server initialization failed");
return 0;
} }
LOG_INF("APP started");
// Test supply voltage reading periodically
while (1) { while (1) {
k_sleep(K_MSEC(1000)); uint16_t supply_voltage = valve_get_supply_voltage();
LOG_INF("Supply voltage: %u mV", supply_voltage);
k_msleep(5000); // Read every 5 seconds
} }
LOG_INF("Irrigation System Slave Node started successfully");
return 0; return 0;
} }

View File

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

View File

@@ -0,0 +1,8 @@
cmake_minimum_required(VERSION 3.20)
find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(bootloader LANGUAGES C)
zephyr_include_directories(../../../include)
add_subdirectory(../../../lib lib)
target_sources(app PRIVATE src/main.c)

View File

@@ -0,0 +1,34 @@
# Firmware Node Application
This Zephyr application provides firmware management capabilities for the irrigation system.
**Tested on Zephyr 4.1.99**
## Features
### Step 1: Shell with Reset Command
- Shell interface with custom "reset" command
- Warm reboot functionality
### Planned Features
- MCUboot support with partition manager
- Firmware version display
- MCUmgr support for OTA updates
## Building
```bash
west build -p auto -b weact_stm32g431_core apps/firmware_node -- -DBOARD_FLASH_RUNNER=blackmagicprobe
```
## Flashing
```bash
west flash
```
## Usage
Connect to the device via serial console and use the shell:
- `reset` - Reboot the system
- `help` - Show available commands

View File

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

View File

@@ -0,0 +1,8 @@
#!/bin/bash
/home/edi/zephyr-sdk-0.17.1/arm-zephyr-eabi/bin/arm-zephyr-eabi-gdb \
-ex 'target extended-remote /dev/ttyACM0' \
-ex 'monitor swdp_scan' \
-ex 'attach 1' \
-ex 'monitor erase_mass' \
-ex 'detach' \
-ex 'quit' \

View File

@@ -0,0 +1,16 @@
CONFIG_SHELL=y
CONFIG_REBOOT=y
# MCUboot support for recovery request function
CONFIG_MCUBOOT_BOOTUTIL_LIB=y
CONFIG_MCUBOOT_IMG_MANAGER=y
CONFIG_IMG_MANAGER=y
# Flash and Stream Configuration (required for IMG_MANAGER)
CONFIG_FLASH=y
CONFIG_STREAM_FLASH=y
# Retention system
CONFIG_RETENTION=y
CONFIG_RETENTION_BOOT_MODE=y
CONFIG_RETAINED_MEM=y

View File

@@ -0,0 +1,42 @@
#include <zephyr/kernel.h>
#include <app_version.h>
#include <zephyr/shell/shell.h>
#include <zephyr/sys/reboot.h>
#include <zephyr/dfu/mcuboot.h>
#include <zephyr/retention/bootmode.h>
#include <stdlib.h>
/* Shell command handler for "reset" */
static int cmd_reset(const struct shell *sh, size_t argc, char **argv)
{
shell_print(sh, "Rebooting system...");
k_sleep(K_MSEC(100)); // Optional delay for user to see the message
sys_reboot(SYS_REBOOT_WARM);
return 0;
}
static int cmd_download(const struct shell *sh, size_t argc, char **argv)
{
int rc;
/* Set boot mode to serial recovery */
rc = bootmode_set(BOOT_MODE_TYPE_BOOTLOADER);
if (rc < 0) {
shell_error(sh, "Failed to set boot mode: %d", rc);
return rc;
}
shell_print(sh, "Boot mode set to recovery. Rebooting to bootloader...");
k_sleep(K_MSEC(100));
sys_reboot(SYS_REBOOT_WARM);
return 0;
}
/* Register the shell command */
SHELL_CMD_REGISTER(reset, NULL, "Reboot the system", cmd_reset);
SHELL_CMD_REGISTER(download, NULL, "Download firmware", cmd_download);
int main(void){
printk("Bootloader test version %s\n", APP_VERSION_EXTENDED_STRING);
return 0;
}

View File

@@ -0,0 +1,5 @@
# Sysbuild configuration for firmware_node with MCUboot
# Enable MCUboot as bootloader
SB_CONFIG_BOOTLOADER_MCUBOOT=y
SB_CONFIG_MCUBOOT_MODE_SINGLE_APP=y

View File

@@ -0,0 +1,13 @@
/*
* Copyright (c) 2021 Nordic Semiconductor ASA
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "flash_partitions_128kb.dtsi"
/ {
chosen {
zephyr,code-partition = &slot0_partition;
};
};

View File

@@ -0,0 +1,62 @@
/*
* Devicetree Overlay for 128KB Flash
* - MCUboot Bootloader (32KB)
* - Application Slot (96KB)
*/
&flash0 {
/delete-node/ partitions;
partitions {
compatible = "fixed-partitions";
#address-cells = <1>;
#size-cells = <1>;
boot_partition: partition@0 {
label = "mcuboot";
reg = <0x00000000 DT_SIZE_K(32)>;
read-only;
};
slot0_partition: partition@8000 {
label = "image-0";
reg = <0x00008000 DT_SIZE_K(96)>;
};
};
};
/* Add retention memory to the existing SRAM node */
&sram0 {
#address-cells = <1>;
#size-cells = <1>;
retainedmem {
compatible = "zephyr,retained-ram";
status = "okay";
#address-cells = <1>;
#size-cells = <1>;
boot_mode: retention@7f00 {
compatible = "zephyr,retention";
status = "okay";
reg = <0x7f00 0x100>;
prefix = [08 04];
checksum = <1>;
};
};
};
/ {
chosen {
zephyr,boot-mode = &boot_mode;
zephyr,console = &cdc_acm_uart0;
};
};
&zephyr_udc0 {
status = "okay";
cdc_acm_uart0: cdc_acm_uart0 {
compatible = "zephyr,cdc-acm-uart";
label = "CDC_ACM_0";
};
};

View File

@@ -0,0 +1,46 @@
#
# MCUboot Configuration for Serial Recovery over USB-CDC
#
# Enables serial recovery mode in MCUboot.
CONFIG_MCUBOOT_SERIAL=y
# Tell MCUboot to check for a trigger to enter recovery
CONFIG_BOOT_SERIAL_BOOT_MODE=y
# --- USB Stack Configuration ---
CONFIG_USB_DEVICE_STACK=y
CONFIG_USB_DEVICE_PRODUCT="MCUboot Serial Recovery"
# Use USB CDC ACM for MCUboot serial recovery (not UART)
CONFIG_BOOT_SERIAL_CDC_ACM=y
# --- Disable Zephyr Console to avoid conflicts ---
# MCUboot's serial_adapter doesn't work well with the general console subsystem.
CONFIG_UART_CONSOLE=n
CONFIG_CONSOLE_HANDLER=n
CONFIG_CONSOLE=n
# --- Flash and Stream Configuration (required for IMG_MANAGER) ---
CONFIG_FLASH=y
CONFIG_STREAM_FLASH=y
# --- mcumgr Configuration ---
# MCUMGR requires NET_BUF, even for serial transport.
CONFIG_NET_BUF=y
CONFIG_NET_LOG=n
# Enables the mcumgr library and necessary command handlers
CONFIG_MCUMGR=y
CONFIG_IMG_MANAGER=y
CONFIG_MCUMGR_GRP_IMG=y
CONFIG_MCUMGR_GRP_OS=y
# --- Retention Configuration ---
CONFIG_RETAINED_MEM=y
CONFIG_RETENTION=y
CONFIG_RETENTION_BOOT_MODE=y
# --- Optional: Reduce memory usage ---
CONFIG_MAIN_STACK_SIZE=2048
CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=1024

View File

@@ -0,0 +1,17 @@
#include "flash_partitions_128kb.dtsi"
/ {
chosen {
zephyr,code-partition = &boot_partition;
zephyr,console = &cdc_acm_uart0;
};
};
&zephyr_udc0 {
status = "okay";
cdc_acm_uart0: cdc_acm_uart0 {
compatible = "zephyr,cdc-acm-uart";
label = "CDC_ACM_0";
};
};

View File

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

View File

@@ -0,0 +1,54 @@
#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,
REG_INPUT_SUPPLY_VOLTAGE_MV = 0x00F5,
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

View File

@@ -0,0 +1,37 @@
#ifndef VALVE_H
#define VALVE_H
#include <stdint.h>
#include <zephyr/drivers/gpio.h>
struct valve_gpios {
const struct gpio_dt_spec in0;
const struct gpio_dt_spec in1;
const struct gpio_dt_spec rst;
const struct gpio_dt_spec sen;
const struct gpio_dt_spec s0;
const struct gpio_dt_spec s1;
};
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);
uint16_t valve_get_supply_voltage(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

View File

@@ -1,4 +1,5 @@
# Add your shared libraries here add_subdirectory_ifdef(CONFIG_LIB_FWU fwu)
# Example: add_subdirectory_ifdef(CONFIG_LIB_MODBUS_SERVER modbus_server)
# add_library(modbus modbus/modbus.c) add_subdirectory_ifdef(CONFIG_LIB_VALVE valve)
# target_include_directories(modbus PUBLIC .) add_subdirectory_ifdef(CONFIG_SHELL_SYSTEM shell_system)
add_subdirectory_ifdef(CONFIG_SHELL_MODBUS shell_modbus)

8
software/lib/Kconfig Normal file
View File

@@ -0,0 +1,8 @@
menu "Irrigation system software libraries"
rsource "fwu/Kconfig"
rsource "modbus_server/Kconfig"
rsource "valve/Kconfig"
rsource "shell_system/Kconfig"
rsource "shell_modbus/Kconfig"
endmenu

View File

@@ -0,0 +1 @@
zephyr_library_sources(fwu.c)

5
software/lib/fwu/Kconfig Normal file
View File

@@ -0,0 +1,5 @@
config LIB_FWU
bool "Enable Firmware Update Library"
default y
help
Enable the Firmware Update Library.

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

@@ -0,0 +1,45 @@
#include <zephyr/kernel.h>
#include <zephyr/sys/crc.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/logging/log.h>
#include <lib/fwu.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;
}

View File

@@ -0,0 +1 @@
zephyr_library_sources(modbus_server.c)

View File

@@ -0,0 +1,5 @@
config LIB_MODBUS_SERVER
bool "Enable Modbus Server Library"
default y
help
Enable the Modbus Server Library.

View File

@@ -0,0 +1,233 @@
#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 <lib/modbus_server.h>
#include <lib/valve.h>
#include <lib/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_SUPPLY_VOLTAGE_MV:
*reg = 12300;
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 = 2;
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);
// Load saved settings
uint32_t saved_baudrate = 19200;
uint8_t saved_unit_id = 1;
settings_load_one("modbus/baudrate", &saved_baudrate, sizeof(saved_baudrate));
settings_load_one("modbus/unit_id", &saved_unit_id, sizeof(saved_unit_id));
// Apply loaded settings
server_param.serial.baud = saved_baudrate;
server_param.server.unit_id = saved_unit_id;
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;
LOG_INF("Starting Modbus server: baudrate=%u, unit_id=%u", saved_baudrate, saved_unit_id);
return modbus_init_server(modbus_iface, server_param);
}
int modbus_reconfigure(uint32_t baudrate, uint8_t unit_id)
{
// Update parameters
server_param.serial.baud = baudrate;
server_param.server.unit_id = unit_id;
// Try to reinitialize - this should work for most cases
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));
LOG_INF("Modbus reconfigured: baudrate=%u, unit_id=%u", baudrate, unit_id);
}
else
{
LOG_ERR("Failed to reconfigure Modbus: %d", ret);
LOG_INF("Modbus reconfiguration requires restart to take effect");
// Save settings for next boot
settings_save_one("modbus/baudrate", &baudrate, sizeof(baudrate));
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.");
return 0; // Return success since settings are saved
}
return ret;
}
uint32_t modbus_get_baudrate(void) { return server_param.serial.baud; }
uint8_t modbus_get_unit_id(void) { return server_param.server.unit_id; }

View File

@@ -0,0 +1 @@
zephyr_library_sources(shell_modbus.c)

View File

@@ -0,0 +1,5 @@
config SHELL_MODBUS
bool "Enable Shell Modbus"
default y
help
Enable the modnbus shell commands.

View File

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

View File

@@ -0,0 +1 @@
zephyr_library_sources(shell_system.c)

View File

@@ -0,0 +1,5 @@
config SHELL_SYSTEM
bool "Enable Shell System"
default y
help
Enable the system commands.

View File

@@ -0,0 +1 @@
zephyr_library_sources(valve.c)

View File

@@ -0,0 +1,5 @@
config LIB_VALVE
bool "Enable Valve Library"
default y
help
Enable the Valve Library.

216
software/lib/valve/valve.c Normal file
View File

@@ -0,0 +1,216 @@
#include <zephyr/kernel.h>
#include <zephyr/settings/settings.h>
#include <zephyr/logging/log.h>
#include <zephyr/device.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/drivers/adc.h>
#include <lib/valve.h>
LOG_MODULE_REGISTER(valve, LOG_LEVEL_DBG);
// ADC configuration for MULTISENSE (PA0)
static const struct device *adc_dev = DEVICE_DT_GET(DT_NODELABEL(adc1));
static const struct adc_channel_cfg adc_channel_cfg = {
.gain = ADC_GAIN_1,
.reference = ADC_REF_INTERNAL, // STM32 only supports internal ref (1.2V)
.acquisition_time = ADC_ACQ_TIME_DEFAULT, // Use default acquisition time
.channel_id = 1, // ADC1_IN1 (PA0)
.differential = 0,
};
static const struct valve_gpios valve_gpios = {
.in0 = GPIO_DT_SPEC_GET(DT_NODELABEL(vnd7050aj), in0_gpios),
.in1 = GPIO_DT_SPEC_GET(DT_NODELABEL(vnd7050aj), in1_gpios),
.rst = GPIO_DT_SPEC_GET(DT_NODELABEL(vnd7050aj), rst_gpios),
.sen = GPIO_DT_SPEC_GET(DT_NODELABEL(vnd7050aj), sen_gpios),
.s0 = GPIO_DT_SPEC_GET(DT_NODELABEL(vnd7050aj), s0_gpios),
.s1 = GPIO_DT_SPEC_GET(DT_NODELABEL(vnd7050aj), s1_gpios),
};
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)
{
gpio_pin_set_dt(&valve_gpios.in0, 0);
gpio_pin_set_dt(&valve_gpios.in1, 0);
gpio_pin_set_dt(&valve_gpios.rst, 0);
if (current_movement == VALVE_MOVEMENT_OPENING) {
LOG_INF("Valve finished opening");
} else if (current_movement == VALVE_MOVEMENT_CLOSING) {
current_state = VALVE_STATE_CLOSED;
LOG_INF("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));
// Initialize ADC for MULTISENSE
if (!device_is_ready(adc_dev)) {
LOG_ERR("ADC device not ready");
return;
}
int ret = adc_channel_setup(adc_dev, &adc_channel_cfg);
if (ret < 0) {
LOG_ERR("Could not setup ADC channel (%d)", ret);
return;
}
gpio_pin_configure_dt(&valve_gpios.in0, GPIO_OUTPUT_INACTIVE); // IN0 control pin - output, deactivate
gpio_pin_configure_dt(&valve_gpios.in1, GPIO_OUTPUT_INACTIVE); // IN1 control pin - output, deactivate
gpio_pin_configure_dt(&valve_gpios.rst, GPIO_OUTPUT_INACTIVE); // Keep VND7050AJ in reset
gpio_pin_configure_dt(&valve_gpios.sen, GPIO_OUTPUT_INACTIVE); // Sensor enable pin - output, inactive
// S0 and S1 pins are used for selecting the valve state, they are initially inactive
// and will be set to active when the valve is opened or closed.
gpio_pin_configure_dt(&valve_gpios.s0, 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);
}
void valve_open(void)
{
if (current_state == VALVE_STATE_CLOSED) {
gpio_pin_set_dt(&valve_gpios.rst, 1);
gpio_pin_set_dt(&valve_gpios.in1, 0);
gpio_pin_set_dt(&valve_gpios.in0, 1);
current_state = VALVE_STATE_OPEN;
current_movement = VALVE_MOVEMENT_OPENING;
k_work_schedule(&valve_work, K_MSEC(max_opening_time_s * 1000 * 0.9));
}
}
void valve_close(void)
{
if (current_state == VALVE_STATE_OPEN) {
gpio_pin_set_dt(&valve_gpios.rst, 1);
gpio_pin_set_dt(&valve_gpios.in0, 0);
gpio_pin_set_dt(&valve_gpios.in1, 1);
current_movement = VALVE_MOVEMENT_CLOSING;
k_work_schedule(&valve_work, K_MSEC(max_closing_time_s * 1000 * 0.9));
}
}
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; }
uint16_t valve_get_supply_voltage(void)
{
LOG_INF("=== ADC TEST MODE - PA0 LAB SUPPLY TEST ===");
LOG_INF("Connect lab supply to PA0. Recommended: 1.0V");
LOG_INF("Expected raw value for 1.0V: ~2007 (using 2.048V VREFBUF)");
LOG_INF("ADC range: 0-2.048V (STM32G431 VREFBUF internal reference)");
LOG_INF("");
// No VND7050AJ configuration - pure ADC test
// Just make sure pins are in safe state
gpio_pin_configure_dt(&valve_gpios.rst, GPIO_OUTPUT);
gpio_pin_configure_dt(&valve_gpios.sen, GPIO_OUTPUT);
gpio_pin_configure_dt(&valve_gpios.s0, GPIO_OUTPUT);
gpio_pin_configure_dt(&valve_gpios.s1, GPIO_OUTPUT);
gpio_pin_configure_dt(&valve_gpios.in0, GPIO_OUTPUT);
gpio_pin_configure_dt(&valve_gpios.in1, GPIO_OUTPUT);
// Set all VND7050AJ pins LOW for safety
gpio_pin_set_dt(&valve_gpios.rst, 0);
gpio_pin_set_dt(&valve_gpios.s0, 0);
gpio_pin_set_dt(&valve_gpios.s1, 0);
gpio_pin_set_dt(&valve_gpios.sen, 0);
gpio_pin_set_dt(&valve_gpios.in0, 0);
gpio_pin_set_dt(&valve_gpios.in1, 0);
LOG_INF("VND7050AJ disabled - all pins LOW");
LOG_INF("PA0 is now isolated for lab supply testing");
k_msleep(100);
// Setup simple ADC sequence
int16_t buf;
struct adc_sequence sequence = {
.buffer = &buf,
.buffer_size = sizeof(buf),
.channels = BIT(adc_channel_cfg.channel_id),
.resolution = 12,
};
LOG_INF("Starting continuous ADC readings every 500ms...");
// Continuous monitoring loop with improved stability
int reading_count = 0;
int32_t samples[10]; // Buffer for averaging
while (1) {
// Take multiple samples and average them for stability
int valid_samples = 0;
int32_t sum = 0;
for (int i = 0; i < 10; i++) {
k_msleep(50); // Longer delay between samples for stability
int adc_ret = adc_read(adc_dev, &sequence);
if (adc_ret == 0 && buf > 100) { // Filter out near-zero readings (floating input)
samples[i] = buf;
sum += buf;
valid_samples++;
} else {
LOG_WRN("Sample %d invalid: raw=%d, ret=%d", i, buf, adc_ret);
samples[i] = 0; // Mark as invalid
}
}
if (valid_samples > 0) {
// Calculate average
int32_t avg_raw = sum / valid_samples;
// Calculate voltage using the correct VREFBUF reference (2.048V)
int32_t pa0_mv = (avg_raw * 2048) / 4096; // Using 2.048V VREFBUF
// Calculate standard deviation to show stability
int32_t variance = 0;
for (int i = 0; i < valid_samples; i++) {
int32_t diff = samples[i] - avg_raw;
variance += diff * diff;
}
int32_t std_dev = (valid_samples > 1) ? variance / (valid_samples - 1) : 0;
// Find min/max for this sample set
int32_t min_raw = samples[0], max_raw = samples[0];
for (int i = 1; i < valid_samples; i++) {
if (samples[i] < min_raw) min_raw = samples[i];
if (samples[i] > max_raw) max_raw = samples[i];
}
LOG_INF("Reading %d: avg_raw=%d (%dmV) | range=%d-%d | std_dev=%d | samples=%d/10",
reading_count, (int)avg_raw, (int)pa0_mv,
(int)min_raw, (int)max_raw, (int)std_dev, valid_samples);
} else {
LOG_ERR("Reading %d: All ADC samples failed", reading_count);
}
reading_count++;
k_msleep(400); // Wait before next reading set
}
return 0; // Never reached
}
void valve_set_max_open_time(uint16_t seconds) { max_opening_time_s = seconds; settings_save_one("valve/max_open_time", &max_opening_time_s, sizeof(max_opening_time_s)); }
void valve_set_max_close_time(uint16_t seconds) { max_closing_time_s = seconds; settings_save_one("valve/max_close_time", &max_closing_time_s, sizeof(max_closing_time_s)); }
uint16_t valve_get_max_open_time(void) { return max_opening_time_s; }
uint16_t valve_get_max_close_time(void) { return max_closing_time_s; }

View File

@@ -0,0 +1,43 @@
#!/usr/bin/env python3
import serial
import time
import sys
import argparse
def monitor_serial(port):
try:
# Open serial connection
ser = serial.Serial(port, 115200, timeout=1)
print(f"Connected to {port}")
# Send reset command
ser.write(b'reset\n')
print("Sent reset command")
# Wait a bit and then read output
time.sleep(0.5)
# Read output for 10 seconds
start_time = time.time()
while 1: #time.time() - start_time < 10:
if ser.in_waiting > 0:
data = ser.read(ser.in_waiting)
try:
text = data.decode('utf-8', errors='ignore')
print(text, end='')
except:
print(f"Raw bytes: {data}")
time.sleep(0.1)
ser.close()
print("\nSerial monitor closed")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Serial monitor.')
parser.add_argument('-p', '--port', help='Serial port to connect to', required=True)
args = parser.parse_args()
monitor_serial(args.port)

View File

@@ -0,0 +1,55 @@
#!/usr/bin/env python3
import serial
import time
import sys
def monitor_serial_with_reset():
try:
# Open serial port
ser = serial.Serial('/dev/ttyACM1', 115200, timeout=1)
print("Serial port opened successfully")
# Clear any existing data
ser.flushInput()
ser.flushOutput()
# Send reset command
print("Sending reset command...")
ser.write(b"reset\n")
time.sleep(0.1)
# Read output for 10 seconds
print("Reading serial output...")
start_time = time.time()
output_lines = []
while time.time() - start_time < 10:
if ser.in_waiting > 0:
try:
line = ser.readline().decode('utf-8', errors='replace').strip()
if line:
print(f"[{time.time() - start_time:.3f}s] {line}")
output_lines.append(line)
except Exception as e:
print(f"Error reading line: {e}")
time.sleep(0.01)
ser.close()
print("\nSerial monitoring complete")
# Summary
print("\n=== SUMMARY ===")
supply_voltage_lines = [line for line in output_lines if "Supply voltage" in line]
if supply_voltage_lines:
print("Supply voltage readings:")
for line in supply_voltage_lines:
print(f" {line}")
else:
print("No supply voltage readings found")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
monitor_serial_with_reset()

View File

@@ -1,3 +1,5 @@
<img src="../../../docs/img/logo.png" alt="Logo" width="100"/>
# Modbus Tool für Bewässerungssystem-Knoten # 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. Dieses Python-Skript bietet eine interaktive Kommandozeilen-Benutzeroberfläche (TUI) zur Steuerung und Überwachung eines Ventil-Knotens des Bewässerungssystems über Modbus RTU.
@@ -5,10 +7,15 @@ Dieses Python-Skript bietet eine interaktive Kommandozeilen-Benutzeroberfläche
## Features ## Features
- **Interaktive Benutzeroberfläche:** Eine benutzerfreundliche, auf `curses` basierende Oberfläche, die eine einfache Bedienung ermöglicht. - **Interaktive Benutzeroberfläche:** Eine benutzerfreundliche, auf `curses` basierende Oberfläche, die eine einfache Bedienung ermöglicht.
- **Live-Statusanzeige:** Zeigt tabellarisch und in Echtzeit den Zustand des Ventils, die Bewegung, den Motorstrom, die konfigurierten Öffnungs-/Schließzeiten sowie Firmware-Version und Uptime des Geräts an. - **Live-Statusanzeige:** Zeigt tabellarisch und in Echtzeit alle wichtigen Register des Slaves an:
- **Volle Kontrolle:** Ermöglicht das Senden von Befehlen zum Öffnen, Schließen und Stoppen des Ventils. - Ventilstatus (Zustand, Bewegung, Motorstrom)
- **Konfiguration zur Laufzeit:** Die maximalen Öffnungs- und Schließzeiten können direkt in der Oberfläche geändert werden. - Zustand der digitalen Ein- und Ausgänge
- **Anpassbares Design:** Die Benutzeroberfläche ist für eine klare Lesbarkeit mit einem durchgehenden blauen Hintergrund und abgesetzten Schaltflächen gestaltet. - "Clear-on-Read" Taster-Events
- Systemkonfiguration (Öffnungs-/Schließzeiten, Watchdog-Timeout)
- Gerätestatus (Firmware-Version, Uptime)
- **Volle Kontrolle:** Ermöglicht das Senden von Befehlen zum Öffnen, Schließen und Stoppen des Ventils sowie zum Umschalten der digitalen Ausgänge.
- **Konfiguration zur Laufzeit:** Die maximalen Öffnungs-/Schließzeiten und der Watchdog-Timeout können direkt in der Oberfläche geändert werden.
- **Simulierter Firmware-Upload:** Implementiert den vollständigen, in der Dokumentation beschriebenen Firmware-Update-Prozess. Das Tool sendet eine `firmware.bin`-Datei in Chunks an den Slave und folgt dem CRC-Verifizierungs-Protokoll.
## Installation ## Installation
@@ -91,5 +98,6 @@ Ersetzen Sie `/dev/ttyACM0` durch den korrekten Port Ihres Geräts.
- **Navigation:** Verwenden Sie die **Pfeiltasten (↑/↓)**, um zwischen den Menüpunkten zu navigieren. - **Navigation:** Verwenden Sie die **Pfeiltasten (↑/↓)**, um zwischen den Menüpunkten zu navigieren.
- **Auswählen:** Drücken Sie **Enter**, um den ausgewählten Befehl auszuführen. - **Auswählen:** Drücken Sie **Enter**, um den ausgewählten Befehl auszuführen.
- **Werte eingeben:** Bei Aktionen wie "Set Max Opening Time" werden Sie zur Eingabe eines Wertes aufgefordert. Geben Sie den Wert ein und bestätigen Sie mit **Enter**. - **Werte eingeben:** Bei Aktionen wie "Set Watchdog" werden Sie zur Eingabe eines Wertes aufgefordert. Geben Sie den Wert ein und bestätigen Sie mit **Enter**.
- **Firmware Update:** Diese Funktion startet den Upload der Datei `firmware.bin` aus dem aktuellen Verzeichnis. Während des Updates wird eine Fortschrittsanzeige dargestellt.
- **Beenden:** Wählen Sie den Menüpunkt **"Exit"** und drücken Sie **Enter**. - **Beenden:** Wählen Sie den Menüpunkt **"Exit"** und drücken Sie **Enter**.

Binary file not shown.

View File

@@ -4,251 +4,331 @@ import threading
import time import time
import sys import sys
import curses import curses
import os
from pymodbus.client import ModbusSerialClient from pymodbus.client import ModbusSerialClient
from pymodbus.exceptions import ModbusException from pymodbus.exceptions import ModbusException
# Register Definitions # --- Register Definitions ---
# (omitted for brevity, no changes here)
REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000 REG_INPUT_VALVE_STATE_MOVEMENT = 0x0000
REG_INPUT_MOTOR_CURRENT_MA = 0x0001 REG_INPUT_MOTOR_CURRENT_MA = 0x0001
REG_INPUT_DIGITAL_INPUTS_STATE = 0x0020
REG_INPUT_BUTTON_EVENTS = 0x0021
REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR = 0x00F0 REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR = 0x00F0
REG_INPUT_FIRMWARE_VERSION_PATCH = 0x00F1 REG_INPUT_FIRMWARE_VERSION_PATCH = 0x00F1
REG_INPUT_DEVICE_STATUS = 0x00F2
REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3 REG_INPUT_UPTIME_SECONDS_LOW = 0x00F3
REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4 REG_INPUT_UPTIME_SECONDS_HIGH = 0x00F4
REG_INPUT_SUPPLY_VOLTAGE_MV = 0x00F5
REG_INPUT_FWU_LAST_CHUNK_CRC = 0x0100
REG_HOLDING_VALVE_COMMAND = 0x0000 REG_HOLDING_VALVE_COMMAND = 0x0000
REG_HOLDING_MAX_OPENING_TIME_S = 0x0001 REG_HOLDING_MAX_OPENING_TIME_S = 0x0001
REG_HOLDING_MAX_CLOSING_TIME_S = 0x0002 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
# --- Global State ---
stop_event = threading.Event() stop_event = threading.Event()
client = None client = None
status_data = {} status_data = {}
status_lock = threading.Lock() status_lock = threading.Lock()
update_status = {"running": False, "message": "", "progress": 0.0}
update_lock = threading.Lock()
def format_uptime(seconds): def format_uptime(seconds):
"""Formats seconds into a human-readable d/h/m/s string.""" if not isinstance(seconds, (int, float)) or seconds < 0: return "N/A"
if not isinstance(seconds, (int, float)) or seconds < 0: if seconds == 0: return "0s"
return "N/A" days, rem = divmod(seconds, 86400); hours, rem = divmod(rem, 3600); minutes, secs = divmod(rem, 60)
if seconds == 0:
return "0s"
days, remainder = divmod(seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, secs = divmod(remainder, 60)
parts = [] parts = []
if days > 0: if days > 0: parts.append(f"{int(days)}d")
parts.append(f"{int(days)}d") if hours > 0: parts.append(f"{int(hours)}h")
if hours > 0: if minutes > 0: parts.append(f"{int(minutes)}m")
parts.append(f"{int(hours)}h") if secs > 0 or not parts: parts.append(f"{int(secs)}s")
if minutes > 0:
parts.append(f"{int(minutes)}m")
# Always show seconds if it's the only unit or if other units are present
if secs > 0 or not parts:
parts.append(f"{int(secs)}s")
return " ".join(parts) return " ".join(parts)
def poll_status(slave_id, interval): def poll_status(slave_id, interval):
"""Periodically polls the status of the node and updates the global status_data dict."""
global status_data global status_data
reconnect_attempts = 0
max_reconnect_attempts = 5
reconnect_delay = 1 # seconds
while not stop_event.is_set(): while not stop_event.is_set():
new_data = {"error": None} if update_status["running"]:
time.sleep(interval)
continue
new_data = {}
try: try:
# Read all registers in a few calls if not client.is_socket_open():
rr = client.read_input_registers(REG_INPUT_VALVE_STATE_MOVEMENT, count=2, slave=slave_id) reconnect_attempts += 1
hr = client.read_holding_registers(REG_HOLDING_MAX_OPENING_TIME_S, count=2, slave=slave_id) if reconnect_attempts >= max_reconnect_attempts:
rr_sys = client.read_input_registers(REG_INPUT_FIRMWARE_VERSION_MAJOR_MINOR, count=5, slave=slave_id) new_data["error"] = f"Failed to reconnect after {max_reconnect_attempts} attempts. Exiting."
stop_event.set()
break
if rr.isError(): raise ModbusException(f"reading valve status: {rr}") # Attempt to connect
if hr.isError(): raise ModbusException(f"reading holding registers: {hr}") if client.connect():
if rr_sys.isError(): raise ModbusException(f"reading system status: {rr_sys}") 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
valve_state_raw = rr.registers[0] # 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=6, 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))
valve_state_raw = ir_valve.registers[0]
movement_map = {0: "Idle", 1: "Opening", 2: "Closing", 3: "Error"} movement_map = {0: "Idle", 1: "Opening", 2: "Closing", 3: "Error"}
state_map = {0: "Closed", 1: "Open"} state_map = {0: "Closed", 1: "Open"}
new_data["movement"] = movement_map.get(valve_state_raw >> 8, 'Unknown') new_data["movement"] = movement_map.get(valve_state_raw >> 8, 'Unknown')
new_data["state"] = state_map.get(valve_state_raw & 0xFF, 'Unknown') new_data["state"] = state_map.get(valve_state_raw & 0xFF, 'Unknown')
new_data["motor_current"] = f"{rr.registers[1]} mA" new_data["motor_current"] = f"{ir_valve.registers[1]} mA"
new_data["open_time"] = f"{hr.registers[0]}s" new_data["open_time"] = f"{hr_valve.registers[0]}s"
new_data["close_time"] = f"{hr.registers[1]}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 = rr_sys.registers[0] >> 8 fw_major = ir_sys.registers[0] >> 8
fw_minor = rr_sys.registers[0] & 0xFF fw_minor = ir_sys.registers[0] & 0xFF
fw_patch = rr_sys.registers[1] fw_patch = ir_sys.registers[1]
uptime_low = rr_sys.registers[3] uptime_seconds = (ir_sys.registers[4] << 16) | ir_sys.registers[3]
uptime_high = rr_sys.registers[4] supply_voltage_mv = ir_sys.registers[5]
uptime_seconds = (uptime_high << 16) | uptime_low
new_data["firmware"] = f"v{fw_major}.{fw_minor}.{fw_patch}" 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["uptime"] = format_uptime(uptime_seconds)
new_data["supply_voltage"] = f"{supply_voltage_mv / 1000.0:.2f} V"
except ModbusException as e: new_data["watchdog"] = f"{hr_sys.registers[0]}s"
new_data["error"] = f"Modbus Error: {e}" new_data["error"] = None # Clear any previous error on successful read
reconnect_attempts = 0 # Reset attempts on successful communication
except Exception as e: except Exception as e:
new_data["error"] = f"Unexpected Error: {e}" 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)
with status_lock: def firmware_update_thread(slave_id, filepath):
status_data = new_data global update_status
time.sleep(interval) with update_lock:
update_status = {"running": True, "message": "Starting update...", "progress": 0.0}
try:
with open(filepath, 'rb') as f: firmware = f.read()
file_size = len(firmware)
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
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)
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)
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["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)
finally:
with update_lock: update_status["running"] = False
def draw_button(stdscr, y, x, text, selected=False): def draw_button(stdscr, y, x, text, selected=False):
"""Draws a button with a border, handling selection highlight.""" """Draws a button, handling selection highlight."""
button_width = len(text) + 4
color = curses.color_pair(2) if selected else curses.color_pair(1) color = curses.color_pair(2) if selected else curses.color_pair(1)
button_width = len(text) + 2
stdscr.addstr(y, x, " " * button_width, color) stdscr.addstr(y, x, " " * button_width, color)
stdscr.addstr(y, x + 2, text, color) stdscr.addstr(y, x + 1, text, color)
stdscr.addstr(y - 1, x, "" + "" * (button_width - 2) + "", color)
stdscr.addstr(y, x, "", color) def file_browser(stdscr):
stdscr.addstr(y, x + button_width - 1, "", color) """A simple curses file browser."""
stdscr.addstr(y + 1, x, "" + "" * (button_width - 2) + "", color) 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): def main_menu(stdscr, slave_id):
"""The main curses UI with a flicker-free, state-based drawing loop.""" global status_data, update_status
global status_data curses.curs_set(0); stdscr.nodelay(1); stdscr.timeout(100)
curses.curs_set(0) 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.nodelay(1)
stdscr.timeout(100)
# --- Color Pairs ---
curses.start_color()
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE) # Main: white on blue
curses.init_pair(2, curses.COLOR_BLUE, curses.COLOR_WHITE) # Selected: blue on white
curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLUE) # Error: red on blue
stdscr.bkgd(' ', curses.color_pair(1)) stdscr.bkgd(' ', curses.color_pair(1))
# --- UI State --- menu = ["Open Valve", "Close Valve", "Stop Valve", "Toggle Output 1", "Toggle Output 2", "Set Watchdog", "Reset Node", "Firmware Update", "Exit"]
menu = ["Open Valve", "Close Valve", "Stop Valve", "Set Max Opening Time", "Set Max Closing Time", "Exit"]
current_row_idx = 0 current_row_idx = 0
message, message_time = "", 0
# State for transient messages input_mode, input_prompt, input_str, input_target_reg = False, "", "", 0
message = ""
message_time = 0
# State for user input
input_mode = False
input_prompt = ""
input_str = ""
input_target_reg = 0
while not stop_event.is_set(): while not stop_event.is_set():
h, w = stdscr.getmaxyx() h, w = stdscr.getmaxyx()
# --- Handle Input and State Changes ---
key = stdscr.getch() key = stdscr.getch()
if input_mode: with update_lock: is_updating = update_status["running"]
if key in [10, 13]: # Enter
if is_updating:
pass
elif input_mode:
if key in [10, 13]:
try: try:
seconds = int(input_str) value = int(input_str)
client.write_register(input_target_reg, seconds, slave=slave_id) client.write_register(input_target_reg, value, slave=slave_id)
message = f"-> Set time to {seconds}s" message = f"-> Set register 0x{input_target_reg:04X} to {value}"
except ValueError: except Exception as e: message = f"-> Error: {e}"
message = "-> Invalid input. Please enter a number." message_time, input_mode, input_str = time.time(), False, ""
except Exception as e: elif key == curses.KEY_BACKSPACE or key == 127: input_str = input_str[:-1]
message = f"-> Error: {e}" elif key != -1 and chr(key).isprintable(): input_str += chr(key)
message_time = time.time() else:
input_mode = False if key == curses.KEY_UP: current_row_idx = (current_row_idx - 1) % len(menu)
input_str = "" elif key == curses.KEY_DOWN: current_row_idx = (current_row_idx + 1) % len(menu)
elif key == curses.KEY_BACKSPACE or key == 127:
input_str = input_str[:-1]
elif key != -1 and chr(key).isprintable():
input_str += chr(key)
else: # Navigation mode
if key == curses.KEY_UP and current_row_idx > 0:
current_row_idx -= 1
elif key == curses.KEY_DOWN and current_row_idx < len(menu) - 1:
current_row_idx += 1
elif key == curses.KEY_ENTER or key in [10, 13]: elif key == curses.KEY_ENTER or key in [10, 13]:
selected_option = menu[current_row_idx] selected_option = menu[current_row_idx]
message_time = time.time() # Set time for all actions message_time = time.time()
if selected_option == "Exit": stop_event.set(); continue
elif selected_option == "Open Valve": client.write_register(REG_HOLDING_VALVE_COMMAND, 1, slave=slave_id); message = "-> Sent OPEN command"
elif selected_option == "Close Valve": client.write_register(REG_HOLDING_VALVE_COMMAND, 2, slave=slave_id); message = "-> Sent CLOSE command"
elif selected_option == "Stop Valve": client.write_register(REG_HOLDING_VALVE_COMMAND, 0, slave=slave_id); message = "-> Sent STOP command"
elif "Toggle Output" in selected_option:
bit = 0 if "1" in selected_option else 1
try:
current_val = client.read_holding_registers(REG_HOLDING_DIGITAL_OUTPUTS_STATE, count=1, slave=slave_id).registers[0]
client.write_register(REG_HOLDING_DIGITAL_OUTPUTS_STATE, current_val ^ (1 << bit), slave=slave_id)
message = f"-> Toggled Output {bit+1}"
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":
filepath = file_browser(stdscr)
if filepath:
threading.Thread(target=firmware_update_thread, args=(slave_id, filepath), daemon=True).start()
else:
message = "-> Firmware update cancelled."
if selected_option == "Exit":
stop_event.set()
continue
elif selected_option == "Open Valve":
client.write_register(REG_HOLDING_VALVE_COMMAND, 1, slave=slave_id)
message = "-> Sent OPEN command"
elif selected_option == "Close Valve":
client.write_register(REG_HOLDING_VALVE_COMMAND, 2, slave=slave_id)
message = "-> Sent CLOSE command"
elif selected_option == "Stop Valve":
client.write_register(REG_HOLDING_VALVE_COMMAND, 0, slave=slave_id)
message = "-> Sent STOP command"
elif "Set Max" in selected_option:
input_mode = True
input_prompt = f"Enter new value for '{selected_option}' (seconds): "
input_target_reg = REG_HOLDING_MAX_OPENING_TIME_S if "Opening" in selected_option else REG_HOLDING_MAX_CLOSING_TIME_S
# --- Drawing Logic (Single Source of Truth) ---
stdscr.clear() stdscr.clear()
if is_updating:
# 1. Draw Status Area with update_lock: prog, msg = update_status["progress"], update_status["message"]
with status_lock: stdscr.addstr(h // 2 - 1, w // 2 - 25, "FIRMWARE UPDATE IN PROGRESS", curses.A_BOLD | curses.color_pair(2))
current_data = status_data.copy() 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))
if current_data.get("error"):
stdscr.addstr(0, 0, current_data["error"], curses.color_pair(3) | curses.A_BOLD)
else: else:
bold = curses.color_pair(1) | curses.A_BOLD with status_lock: current_data = status_data.copy()
normal = curses.color_pair(1) bold, normal = curses.color_pair(1) | curses.A_BOLD, curses.color_pair(1)
col1_x, col2_x, col3_x = 2, 35, 70 if current_data.get("error"): stdscr.addstr(0, 0, current_data["error"], curses.color_pair(3) | curses.A_BOLD)
stdscr.addstr(1, col1_x, "Valve State:", bold); stdscr.addstr(1, col1_x + 14, str(current_data.get('state', 'N/A')), normal) else:
stdscr.addstr(2, col1_x, "Movement:", bold); stdscr.addstr(2, col1_x + 14, str(current_data.get('movement', 'N/A')), normal) col1, col2, col3, col4 = 2, 30, 58, 88
stdscr.addstr(3, col1_x, "Motor Current:", bold); stdscr.addstr(3, col1_x + 14, str(current_data.get('motor_current', 'N/A')), normal) stdscr.addstr(1, col1, "State:", bold); stdscr.addstr(1, col1 + 18, str(current_data.get('state', 'N/A')), normal)
stdscr.addstr(1, col2_x, "Max Open Time:", bold); stdscr.addstr(1, col2_x + 16, str(current_data.get('open_time', 'N/A')), normal) stdscr.addstr(2, col1, "Movement:", bold); stdscr.addstr(2, col1 + 18, str(current_data.get('movement', 'N/A')), normal)
stdscr.addstr(2, col2_x, "Max Close Time:", bold); stdscr.addstr(2, col2_x + 16, str(current_data.get('close_time', 'N/A')), normal) stdscr.addstr(3, col1, "Motor Current:", bold); stdscr.addstr(3, col1 + 18, str(current_data.get('motor_current', 'N/A')), normal)
stdscr.addstr(1, col3_x, "Firmware:", bold); stdscr.addstr(1, col3_x + 11, str(current_data.get('firmware', 'N/A')), normal) stdscr.addstr(1, col2, "Digital Inputs:", bold); stdscr.addstr(1, col2 + 18, str(current_data.get('digital_inputs', 'N/A')), normal)
stdscr.addstr(2, col3_x, "Uptime:", bold); stdscr.addstr(2, col3_x + 11, str(current_data.get('uptime', 'N/A')), normal) stdscr.addstr(2, col2, "Digital Outputs:", bold); stdscr.addstr(2, col2 + 18, str(current_data.get('digital_outputs', 'N/A')), normal)
stdscr.addstr(5, 0, "" * (w - 1), normal) stdscr.addstr(3, col2, "Button Events:", bold); stdscr.addstr(3, col2 + 18, str(current_data.get('button_events', 'N/A')), normal)
stdscr.addstr(1, col3, "Max Open Time:", bold); stdscr.addstr(1, col3 + 16, str(current_data.get('open_time', 'N/A')), normal)
# 2. Draw Menu Buttons stdscr.addstr(2, col3, "Max Close Time:", bold); stdscr.addstr(2, col3 + 16, str(current_data.get('close_time', 'N/A')), normal)
for idx, row in enumerate(menu): stdscr.addstr(3, col3, "Watchdog:", bold); stdscr.addstr(3, col3 + 16, str(current_data.get('watchdog', 'N/A')), normal)
x = w // 2 - (len(row) + 4) // 2 stdscr.addstr(1, col4, "Firmware:", bold); stdscr.addstr(1, col4 + 14, str(current_data.get('firmware', 'N/A')), normal)
y = h // 2 - len(menu) + (idx * 3) stdscr.addstr(2, col4, "Uptime:", bold); stdscr.addstr(2, col4 + 14, str(current_data.get('uptime', 'N/A')), normal)
draw_button(stdscr, y, x, row, idx == current_row_idx) stdscr.addstr(3, col4, "Dev. Status:", bold); stdscr.addstr(3, col4 + 14, str(current_data.get('device_status', 'N/A')), normal)
stdscr.addstr(4, col4, "Supply V:", bold); stdscr.addstr(4, col4 + 14, str(current_data.get('supply_voltage', 'N/A')), normal)
# 3. Draw Transient Message or Input Prompt stdscr.addstr(5, 0, "" * (w - 1), normal)
if time.time() - message_time < 2.0: for idx, row in enumerate(menu):
stdscr.addstr(h - 2, 0, message.ljust(w - 1), curses.color_pair(1) | curses.A_BOLD) draw_button(stdscr, h // 2 - len(menu) + (idx * 2), w // 2 - len(row) // 2, row, idx == current_row_idx)
if time.time() - message_time < 2.0: stdscr.addstr(h - 2, 0, message.ljust(w - 1), curses.color_pair(1) | curses.A_BOLD)
if input_mode: if input_mode:
curses.curs_set(1) curses.curs_set(1); stdscr.addstr(h - 2, 0, (input_prompt + input_str).ljust(w-1), curses.color_pair(2)); stdscr.move(h - 2, len(input_prompt) + len(input_str))
stdscr.addstr(h - 2, 0, (input_prompt + input_str).ljust(w-1), curses.color_pair(2)) else: curses.curs_set(0)
stdscr.move(h - 2, len(input_prompt) + len(input_str))
else:
curses.curs_set(0)
stdscr.refresh() stdscr.refresh()
def main(): def main():
global client global client
parser = argparse.ArgumentParser(description="Modbus tool for irrigation system nodes.") parser = argparse.ArgumentParser(description="Modbus tool for irrigation system nodes.")
parser.add_argument("port", help="Serial port (e.g., /dev/ttyACM0)") parser.add_argument("port", help="Serial port"); parser.add_argument("--baud", type=int, default=19200); parser.add_argument("--slave-id", type=int, default=1); parser.add_argument("--interval", type=float, default=1.0)
parser.add_argument("--baud", type=int, default=19200, help="Baud rate")
parser.add_argument("--slave-id", type=int, default=1, help="Modbus slave ID")
parser.add_argument("--interval", type=float, default=1.0, help="Polling interval (sec)")
args = parser.parse_args() args = parser.parse_args()
client = ModbusSerialClient(port=args.port, baudrate=args.baud, stopbits=1, bytesize=8, parity="N", timeout=1) client = ModbusSerialClient(port=args.port, baudrate=args.baud, stopbits=1, bytesize=8, parity="N", timeout=1)
if not client.connect(): if not client.connect(): print(f"Error: Failed to connect to serial port {args.port}"); sys.exit(1)
print(f"Error: Failed to connect to serial port {args.port}") print("Successfully connected. Starting UI..."); time.sleep(0.5)
sys.exit(1) threading.Thread(target=poll_status, args=(args.slave_id, args.interval), daemon=True).start()
try: curses.wrapper(main_menu, args.slave_id)
print(f"Successfully connected to {args.port}. Starting UI...")
time.sleep(0.5)
poll_thread = threading.Thread(target=poll_status, args=(args.slave_id, args.interval))
poll_thread.daemon = True
poll_thread.start()
try:
curses.wrapper(main_menu, args.slave_id)
finally: finally:
stop_event.set() stop_event.set()
print("\nExiting...") print("\nExiting...")
if client.is_socket_open(): if client.is_socket_open(): client.close()
client.close()
poll_thread.join(timeout=2)
if __name__ == "__main__": if __name__ == "__main__":
main() main()