diff --git a/.github/workflows/doxygen.yml b/.github/workflows/doxygen.yml new file mode 100644 index 0000000..6bd8f2a --- /dev/null +++ b/.github/workflows/doxygen.yml @@ -0,0 +1,28 @@ +name: Documentation + +on: + push: + branches: [ main ] + +jobs: + build-documentation: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Doxygen Action + uses: mattnotmitt/doxygen-action@v1.1.0 + with: + doxyfile-path: ./Doxyfile + working-directory: . + + - name: GH Pages Deployment + uses: peaceiris/actions-gh-pages@v3 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + publish_dir: ./html/ + enable_jekyll: false + allow_empty_commit: false + force_orphan: true + publish_branch: gh-pages diff --git a/.github/workflows/zephyr.yml b/.github/workflows/zephyr.yml new file mode 100644 index 0000000..2e2dfb9 --- /dev/null +++ b/.github/workflows/zephyr.yml @@ -0,0 +1,47 @@ +name: Build with Zephyr toolchain + +on: [push, pull_request] + +jobs: + build: + runs-on: ubuntu-latest + container: zephyrprojectrtos/ci:v0.21.0 + env: + CMAKE_PREFIX_PATH: /opt/toolchains + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + path: charge-controller-firmware + submodules: recursive + + - name: Set up Python + uses: actions/setup-python@v1 + + - name: Initialize + working-directory: charge-controller-firmware + run: | + pip3 install -U west + west init -l app + west update + pip3 install -r zephyr/scripts/requirements-base.txt + + - name: Trailing whitespace check + working-directory: charge-controller-firmware + run: | + git diff --check `git rev-list --max-parents=0 HEAD`..HEAD + + - name: Build firmware + working-directory: charge-controller-firmware + run: | + cd app + west build -b mppt_2420_hc@0.2 -p + west build -b mppt_2420_lc -p + west build -b mppt_1210_hus@0.7 -p + west build -b pwm_2420_lus@0.3 -p + + - name: Run unit-tests + working-directory: charge-controller-firmware + run: | + cd tests + west build -b native_posix -t run diff --git a/.gitignore b/.gitignore index 57be60e..21031a6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,25 @@ -.pio -.clang_complete -.gcc-flags.json -.vscode/browse.vc.db* -.vscode -.west -html -memory.map -custom.ini -tools +# backup files *.bak *_bak + +# folders generated by west +.west +bootloader +build +modules +tools +zephyr + +# editors +.vscode/* +!.vscode/c_cpp_properties.json +*.swp +*~ + +# others +.clang_complete +.gcc-flags.json +.pio +bin +html +scripts diff --git a/.gitmodules b/.gitmodules index 3716117..bed68be 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ -[submodule "lib/thingset"] - path = lib/thingset - url = https://github.com/LibreSolar/thingset-device-library [submodule "lib/oled-display"] path = lib/oled-display url = https://github.com/LibreSolar/oled-display-library diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6ab8436..0000000 --- a/.travis.yml +++ /dev/null @@ -1,38 +0,0 @@ -language: python - -# Cache PlatformIO packages using Travis CI container-based infrastructure -sudo: false -cache: - directories: - - "~/.platformio" - -env: - - PLATFORMIO_CI_SRC=src - -install: - - pip install wheel - - pip install -U platformio - - platformio platform install native - - platformio update - -addons: - apt: - packages: - - doxygen - -script: - # check for trailing white spaces (comparing with first commit in git log) - - git diff --check `git rev-list HEAD | tail -n 1`.. - - platformio run -e mppt_2420_lc -e mppt_1210_hus -e mppt_2420_hc -e pwm_2420_lus - - platformio test -e unit_test - - platformio check -e mppt_1210_hus -e pwm_2420_lus --skip-packages --fail-on-defect high - - doxygen Doxyfile - -deploy: - provider: pages - skip_cleanup: true - local_dir: html - github_token: $GH_REPO_TOKEN - on: - repo: LibreSolar/charge-controller-firmware - branch: main diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..84152a4 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,37 @@ +{ + "configurations": [ + { + "name": "Zephyr", + "includePath": [ + "${workspaceFolder}/app/src", + "${workspaceFolder}/app/build/zephyr/include/generated", + "${workspaceFolder}/lib/oled-display/src", + "${workspaceFolder}/modules/hal/cmsis/CMSIS/Core/Include", + "${workspaceFolder}/modules/hal/stm32/stm32cube/stm32g0xx/soc", + "${workspaceFolder}/modules/thingset/src", + "${workspaceFolder}/modules/unity/src", + "${workspaceFolder}/zephyr/include", + "${workspaceFolder}/zephyr/soc/arm/st_stm32/common", + "${workspaceFolder}/zephyr/soc/arm/st_stm32/stm32g0", + "" + ], + "browse": { + "path": [ + "${workspaceFolder}/app/src", + "${workspaceFolder}/modules/thingset/src", + "${workspaceFolder}/modules/unity/src" + ], + "limitSymbolsToIncludedHeaders": true + }, + "defines": [ + "FIRMWARE_VERSION_ID=\"v21.0-21-ga535fa8\"" + ], + "cStandard": "c99", + "cppStandard": "c++14", + "forcedInclude": [ + "${workspaceFolder}/app/build/zephyr/include/generated/autoconf.h" + ] + } + ], + "version": 4 +} diff --git a/README.md b/README.md index 2fdfe7e..4e1d31c 100644 --- a/README.md +++ b/README.md @@ -35,38 +35,22 @@ git clone --recursive https://github.com/LibreSolar/charge-controller-firmware Unfortunately, the green GitHub "Clone or download" button does not include submodules. If you cloned the repository already and want to pull the submodules, run `git submodule update --init --recursive`. -### PlatformIO +Building the firmware requires the native Zephyr build system. -It is suggested to use Visual Studio Code and PlatformIO for firmware development, as it simplifies compiling and uploading the code a lot: +This guide assumes you have already installed the Zephyr SDK and the `west` tool according to the [Zephyr documentation](https://docs.zephyrproject.org/latest/getting_started/). -1. Install Visual Studio Code and [PlatformIO](https://platformio.org/platformio-ide) to build the firmware. +The repository root directory is the `west` workspace. The `app` subfolder contains all application source files, the CMake entry point and the `west` manifest, so we have to move into this folder: -2. Adjust configuration in `zephyr/prj.conf` if necessary. + cd app -3. Select the correct board in `platformio.ini` by setting the variable `default_envs` under `[platformio]` to your board or create a file `custom.ini` with your personal settings. PlatformIO is configured for latest revision of the boards (see table above). For older revisions adjust `platformio.ini` and the `.json` files in `boards` folder manually or use native Zephyr environment. +The following command initializes the west workspace: -4. Connect the board via a programmer. See the Libre Solar website for [further project-agnostic instructions](https://learn.libre.solar/development/flashing_debugging.html ). + west init -l . -5. Press the upload button at the bottom left corner in VS Code. - -### Native Zephyr environment - -You can also use the Zephyr build system directly for advanced configuration with `menuconfig` or if you need more recently added features. - -This guide assumes you have already installed the Zephyr SDK and the west tool according to the [Zephyr documentation](https://docs.zephyrproject.org/latest/getting_started/). Also make sure that `west` is at least at version `0.8.0`. - -Now after you cloned the repository (see above), go into the root firmware directory and initialize a west workspace: - - west init -l zephyr - -This command will create a `.west/config` file and set up the repository as specified in `zephyr/west.yml` file. Afterwards the following command pulls the Zephyr source and all necessary modules, which might take a while: +This command will create a `.west/config` file in the workspace root and set up the repository as specified in the `west.yml` file. Afterwards the following command pulls the Zephyr source and all necessary modules, which might take a while: west update -The CMake entry point is in the `zephyr` subfolder, so you need to run `west build` and `west flash` command in that directory. - - cd zephyr - Initial board selection (see `boards` subfolder for correct names): west build -b @ @@ -150,22 +134,17 @@ The documentation auto-generated by Doxygen can be found [here](https://libre.so ## Conformance testing We are using Travis CI to perform several checks for each commit or pull-request. In order to run -the same tests locally (recommended before pushing to the server) use the script `check.sh` or ` check.bat`: +the same tests locally (recommended before pushing to the server) use the script `check.sh` or ` check.bat` in the `scripts` folder: - bash check.sh # Linux - cmd check.bat # Windows + bash scripts/check.sh # Linux + cmd scripts\check.bat # Windows ### Unit-tests -Core functions of the firmware are covered by unit-tests (located in test directory). Run the tests with the following command: +Core functions of the firmware are covered by unit-tests (located in `tests` directory). Build and run the tests with the following command: - platformio test -e unit_test - -### Static code analysis - -PlatformIO integrates cppcheck and clangtidy. The following command is an example to run the checks for MPPT 1210 HUS charge controller code: - - platformio check -e mppt_1210_hus + cd tests + west build -p -b native_posix -t run ## Additional firmware documentation (docs folder) @@ -181,35 +160,6 @@ The standard OpenOCD settings sometimes fail to flash firmware to this MCU, whic Try one of these workarounds: -1. Change OpenOCD settings to `adapter_khz 500` in line 70 in `~/.platformio/packages/tool-openocd/scripts/target/stm32l0.cfg`. +1. Change OpenOCD settings to `adapter_khz 500` in `openocd-path/scripts/target/stm32l0.cfg`. 2. Use other tools or debug probes such as [STM32CubeProgrammer](https://www.st.com/en/development-tools/stm32cubeprog.html) or [Segger J-Link](https://www.segger.com/products/debug-probes/j-link/). - -### Connection failures - -If flashing fails like this in PlatformIO: - -``` -Error: init mode failed (unable to connect to the target) -in procedure 'program' -** OpenOCD init failed ** -shutdown command invoked -``` - -or with ST-Link: - -```bash -$ st-flash write .pio/build/mppt-1210-hus-v0.4/firmware.bin 0x08000000 -st-flash 1.5.1 -2019-06-21T18:13:03 INFO common.c: Loading device parameters.... -2019-06-21T18:13:03 WARN common.c: unknown chip id! 0x5fa0004 -``` - -check the connection between the programmer (for example the ST-Link of the Nucleo board) and the charge controller. - -With PlatformIO on Linux: -``` -Error: libusb_open() failed with LIBUSB_ERROR_ACCESS -Error: open failed -``` -means that a udev rule is missing. The [openocd.rules file](https://sourceforge.net/p/openocd/code/ci/master/tree/contrib/60-openocd.rules) needs to be copied to `/etc/udev/rules.d/` and the user executing PlatformIO should be added to the group `plugdev`. diff --git a/zephyr/.gitignore b/app/.gitignore similarity index 93% rename from zephyr/.gitignore rename to app/.gitignore index 0b28f71..c3092fa 100644 --- a/zephyr/.gitignore +++ b/app/.gitignore @@ -10,5 +10,3 @@ boards* # folders generated by west build -modules -rtos diff --git a/zephyr/CMakeLists.txt b/app/CMakeLists.txt similarity index 85% rename from zephyr/CMakeLists.txt rename to app/CMakeLists.txt index eb1c465..50d287f 100644 --- a/zephyr/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -2,16 +2,15 @@ # SPDX-License-Identifier: Apache-2.0 set(BOARD_ROOT ${CMAKE_SOURCE_DIR}/..) -set(DTS_ROOT ${CMAKE_SOURCE_DIR}) +set(DTS_ROOT ${CMAKE_SOURCE_DIR}/..) cmake_minimum_required(VERSION 3.13.1) find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) project(libre_solar_charge_controller) -add_subdirectory(../src build/src) +add_subdirectory(src) -add_subdirectory(../lib/thingset build/thingset) add_subdirectory(../lib/oled-display build/oled-display) # determine git tag and commit hash for automatic firmware versioning diff --git a/zephyr/Kconfig b/app/Kconfig similarity index 94% rename from zephyr/Kconfig rename to app/Kconfig index f0d42ec..394edbf 100644 --- a/zephyr/Kconfig +++ b/app/Kconfig @@ -204,21 +204,21 @@ config CELL_OCV_EMPTY_MV help Voltages during idle (no charging/discharging current) -config CELL_TRICKLE - bool "Enable trickle charging phase" +config CELL_FLOAT + bool "Enable float charging phase" default y -config CELL_TRICKLE_VOLTAGE_MV - int "Trickle charging cell voltage (mV)" if CELL_TRICKLE +config CELL_FLOAT_VOLTAGE_MV + int "Float charging cell voltage (mV)" if CELL_FLOAT default 2300 help - Charger target voltage for trickle charging of lead-acid batteries + Charger target voltage for float charging of lead-acid batteries -config CELL_TRICKLE_RECHARGE_TIME - int "Trickle recharge time (s)" if CELL_TRICKLE +config CELL_FLOAT_RECHARGE_TIME + int "Float recharge time (s)" if CELL_FLOAT default 1800 help - If the trickle voltage is not reached anymore (e.g. because of lack of solar + If the float voltage is not reached anymore (e.g. because of lack of solar input power) for this period of time, the charger state machine goes back into CC/bulk charging mode. @@ -399,8 +399,8 @@ config DAQ_LOG_LEVEL help Log level for the DAQ module. 0=off, 1=ERR, 2=WRN, 3=INF, 4=DBG -config DATA_NODES_LOG_LEVEL - int "Log level for the data nodes module" +config DATA_OBJECTS_LOG_LEVEL + int "Log level for the data objects module" default 2 depends on LOG help @@ -453,12 +453,12 @@ menuconfig CUSTOMIZATION if CUSTOMIZATION -config CUSTOM_DATA_NODES_FILE +config CUSTOM_DATA_OBJECTS_FILE bool "Use custom data nodes file" default n help - Use a custom file instead of default data_nodes.cpp for - ThingSet configuration. + Use the file data_objects_custom.cpp instead of the default data_objects.cpp + for ThingSet configuration. config CUSTOM_DCDC_CONTROLLER bool "Custom implementation of DC/DC controller" @@ -473,5 +473,9 @@ endif # include custom Kconfig if existing orsource "../src/custom/Kconfig" +#if 0 +#orsource "modules/thingset/zephyr/Kconfig.thingset" +#endif + # include main Zephyr menu entries from Zephyr root directory source "Kconfig.zephyr" diff --git a/zephyr/prj.conf b/app/prj.conf similarity index 96% rename from zephyr/prj.conf rename to app/prj.conf index 9d47148..893d04a 100644 --- a/zephyr/prj.conf +++ b/app/prj.conf @@ -4,6 +4,7 @@ CONFIG_HEAP_MEM_POOL_SIZE=256 CONFIG_CPLUSPLUS=y +CONFIG_LIB_CPLUSPLUS=y CONFIG_NEWLIB_LIBC=y CONFIG_NEWLIB_LIBC_FLOAT_PRINTF=y @@ -24,6 +25,8 @@ CONFIG_CONSOLE_GETCHAR=y CONFIG_LOG=y CONFIG_LOG_MODE_MINIMAL=y +CONFIG_THINGSET=y + # ThingSet protocol interface via UART serial CONFIG_THINGSET_SERIAL=y diff --git a/src/CMakeLists.txt b/app/src/CMakeLists.txt similarity index 84% rename from src/CMakeLists.txt rename to app/src/CMakeLists.txt index 1757d8e..04dc798 100644 --- a/src/CMakeLists.txt +++ b/app/src/CMakeLists.txt @@ -4,7 +4,7 @@ zephyr_include_directories(.) target_sources(app PRIVATE bat_charger.cpp - data_nodes.cpp + data_objects.cpp data_storage.cpp daq.cpp daq_driver.c @@ -24,8 +24,8 @@ target_sources(app PRIVATE add_subdirectory(ext) -if(${CONFIG_CUSTOM_DATA_NODES_FILE}) - target_sources(app PRIVATE data_nodes_custom.cpp) +if(${CONFIG_CUSTOM_DATA_OBJECTS_FILE}) + target_sources(app PRIVATE data_objects_custom.cpp) endif() # Using this option enables user-specific customization of the firmware. The diff --git a/src/bat_charger.cpp b/app/src/bat_charger.cpp similarity index 73% rename from src/bat_charger.cpp rename to app/src/bat_charger.cpp index aa60f94..125b4c7 100644 --- a/src/bat_charger.cpp +++ b/app/src/bat_charger.cpp @@ -8,10 +8,8 @@ #include -#ifndef UNIT_TEST #include LOG_MODULE_REGISTER(bat_charger, CONFIG_BAT_LOG_LEVEL); -#endif #include // for fabs function #include @@ -51,19 +49,19 @@ void battery_conf_init(BatConf *bat, int type, int num_cells, float nominal_capa case BAT_TYPE_FLOODED: case BAT_TYPE_AGM: case BAT_TYPE_GEL: - bat->voltage_absolute_max = static_cast(num_cells) * 2.45F; + bat->absolute_max_voltage = static_cast(num_cells) * 2.45F; bat->topping_voltage = static_cast(num_cells) * 2.4F; - bat->voltage_recharge = static_cast(num_cells) * 2.3F; + bat->recharge_voltage = static_cast(num_cells) * 2.2F; // Cell-level thresholds based on EN 62509:2011 (both thresholds current-compensated) - bat->voltage_load_disconnect = static_cast(num_cells) * 1.95F; - bat->voltage_load_reconnect = static_cast(num_cells) * 2.10F; + bat->load_disconnect_voltage = static_cast(num_cells) * 1.95F; + bat->load_reconnect_voltage = static_cast(num_cells) * 2.10F; // assumption: Battery selection matching charge controller bat->internal_resistance = static_cast(num_cells) * (1.95F - 1.80F) / DISCHARGE_CURRENT_MAX; - bat->voltage_absolute_min = static_cast(num_cells) * 1.6F; + bat->absolute_min_voltage = static_cast(num_cells) * 1.6F; // Voltages during idle (no charging/discharging current) bat->ocv_full = static_cast(num_cells) * @@ -71,12 +69,12 @@ void battery_conf_init(BatConf *bat, int type, int num_cells, float nominal_capa bat->ocv_empty = static_cast(num_cells) * 1.90F; // https://batteryuniversity.com/learn/article/charging_the_lead_acid_battery - bat->topping_current_cutoff = bat->nominal_capacity * 0.04F; // 3-5 % of C/1 + bat->topping_cutoff_current = bat->nominal_capacity * 0.04F; // 3-5 % of C/1 - bat->trickle_enabled = true; - bat->trickle_recharge_time = 30*60; + bat->float_enabled = true; + bat->float_recharge_time = 30*60; // Values as suggested in EN 62509:2011 - bat->trickle_voltage = static_cast(num_cells) * + bat->float_voltage = static_cast(num_cells) * ((type == BAT_TYPE_FLOODED) ? 2.35F : 2.3F); // Enable for flooded batteries only, according to @@ -94,26 +92,26 @@ void battery_conf_init(BatConf *bat, int type, int num_cells, float nominal_capa break; case BAT_TYPE_LFP: - bat->voltage_absolute_max = static_cast(num_cells) * 3.60F; + bat->absolute_max_voltage = static_cast(num_cells) * 3.60F; bat->topping_voltage = static_cast(num_cells) * 3.55F; // CV voltage - bat->voltage_recharge = static_cast(num_cells) * 3.35F; + bat->recharge_voltage = static_cast(num_cells) * 3.35F; - bat->voltage_load_disconnect = static_cast(num_cells) * 3.00F; - bat->voltage_load_reconnect = static_cast(num_cells) * 3.15F; + bat->load_disconnect_voltage = static_cast(num_cells) * 3.00F; + bat->load_reconnect_voltage = static_cast(num_cells) * 3.15F; // 5% voltage drop at max current - bat->internal_resistance = bat->voltage_load_disconnect * 0.05F / + bat->internal_resistance = bat->load_disconnect_voltage * 0.05F / DISCHARGE_CURRENT_MAX; - bat->voltage_absolute_min = static_cast(num_cells) * 2.0F; + bat->absolute_min_voltage = static_cast(num_cells) * 2.0F; // will give really nonlinear SOC calculation because of flat OCV of LFP cells... bat->ocv_full = static_cast(num_cells) * 3.4F; bat->ocv_empty = static_cast(num_cells) * 3.0F; // C/10 cut-off at end of CV phase by default - bat->topping_current_cutoff = bat->nominal_capacity / 10; + bat->topping_cutoff_current = bat->nominal_capacity / 10; - bat->trickle_enabled = false; + bat->float_enabled = false; bat->equalization_enabled = false; bat->temperature_compensation = 0; bat->charge_temp_min = 0; @@ -123,26 +121,26 @@ void battery_conf_init(BatConf *bat, int type, int num_cells, float nominal_capa case BAT_TYPE_NMC_HV: bat->topping_voltage = static_cast(num_cells) * ((type == BAT_TYPE_NMC_HV) ? 4.35F : 4.20F); - bat->voltage_absolute_max = bat->topping_voltage + + bat->absolute_max_voltage = bat->topping_voltage + static_cast(num_cells) * 0.05F; - bat->voltage_recharge = static_cast(num_cells) * 3.9F; + bat->recharge_voltage = static_cast(num_cells) * 3.9F; - bat->voltage_load_disconnect = static_cast(num_cells) * 3.3F; - bat->voltage_load_reconnect = static_cast(num_cells) * 3.6F; + bat->load_disconnect_voltage = static_cast(num_cells) * 3.3F; + bat->load_reconnect_voltage = static_cast(num_cells) * 3.6F; // 5% voltage drop at max current - bat->internal_resistance = bat->voltage_load_disconnect * 0.05F / + bat->internal_resistance = bat->load_disconnect_voltage * 0.05F / DISCHARGE_CURRENT_MAX; - bat->voltage_absolute_min = static_cast(num_cells) * 2.5F; + bat->absolute_min_voltage = static_cast(num_cells) * 2.5F; bat->ocv_full = static_cast(num_cells) * 4.0F; bat->ocv_empty = static_cast(num_cells) * 3.0F; // C/10 cut-off at end of CV phase by default - bat->topping_current_cutoff = bat->nominal_capacity / 10; + bat->topping_cutoff_current = bat->nominal_capacity / 10; - bat->trickle_enabled = false; + bat->float_enabled = false; bat->equalization_enabled = false; bat->temperature_compensation = 0; bat->charge_temp_min = 0; @@ -150,24 +148,24 @@ void battery_conf_init(BatConf *bat, int type, int num_cells, float nominal_capa case BAT_TYPE_CUSTOM: #ifdef CONFIG_BAT_TYPE_CUSTOM - bat->voltage_absolute_max = 0.001F * + bat->absolute_max_voltage = 0.001F * static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_ABS_MAX_VOLTAGE_MV); bat->topping_voltage = 0.001F * static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_TOPPING_VOLTAGE_MV); - bat->voltage_recharge = 0.001F * + bat->recharge_voltage = 0.001F * static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_RECHARGE_VOLTAGE_MV); - bat->voltage_load_disconnect = 0.001F * + bat->load_disconnect_voltage = 0.001F * static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_DISCONNECT_VOLTAGE_MV); - bat->voltage_load_reconnect = 0.001F * + bat->load_reconnect_voltage = 0.001F * static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_RECONNECT_VOLTAGE_MV); bat->internal_resistance = 0.001F * static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_INTERNAL_RESISTANCE_MOHM); - bat->voltage_absolute_min = 0.001F * + bat->absolute_min_voltage = 0.001F * static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_ABS_MIN_VOLTAGE_MV); // Voltages during idle (no charging/discharging current) @@ -177,12 +175,12 @@ void battery_conf_init(BatConf *bat, int type, int num_cells, float nominal_capa static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_OCV_EMPTY_MV); // https://batteryuniversity.com/learn/article/charging_the_lead_acid_battery - bat->topping_current_cutoff = bat->nominal_capacity * 0.04F; // 3-5 % of C/1 + bat->topping_cutoff_current = bat->nominal_capacity * 0.04F; // 3-5 % of C/1 - bat->trickle_enabled = IS_ENABLED(CONFIG_CELL_TRICKLE); - bat->trickle_recharge_time = CONFIG_CELL_TRICKLE_RECHARGE_TIME; - bat->trickle_voltage = 0.001F * - static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_TRICKLE_VOLTAGE_MV); + bat->float_enabled = IS_ENABLED(CONFIG_CELL_FLOAT); + bat->float_recharge_time = CONFIG_CELL_FLOAT_RECHARGE_TIME; + bat->float_voltage = 0.001F * + static_cast(CONFIG_BAT_NUM_CELLS * CONFIG_CELL_FLOAT_VOLTAGE_MV); bat->equalization_enabled = IS_ENABLED(CONFIG_CELL_EQUALIZATION); bat->equalization_voltage = 0.001F * @@ -215,33 +213,33 @@ bool battery_conf_check(BatConf *bat_conf) // - capacity plausible LOG_DBG("battery_conf_check: %d %d %d %d %d %d %d", - bat_conf->voltage_load_reconnect > (bat_conf->voltage_load_disconnect + 0.6), - bat_conf->voltage_recharge < (bat_conf->topping_voltage - 0.4), - bat_conf->voltage_recharge > (bat_conf->voltage_load_disconnect + 1), - bat_conf->voltage_load_disconnect > (bat_conf->voltage_absolute_min + 0.4), - bat_conf->topping_current_cutoff < (bat_conf->nominal_capacity / 10.0), - bat_conf->topping_current_cutoff > 0.01, - (bat_conf->trickle_enabled == false || - (bat_conf->trickle_voltage < bat_conf->topping_voltage && - bat_conf->trickle_voltage > bat_conf->voltage_load_disconnect)) + bat_conf->load_reconnect_voltage > (bat_conf->load_disconnect_voltage + 0.6), + bat_conf->recharge_voltage < (bat_conf->topping_voltage - 0.4), + bat_conf->recharge_voltage > (bat_conf->load_disconnect_voltage + 1), + bat_conf->load_disconnect_voltage > (bat_conf->absolute_min_voltage + 0.4), + bat_conf->topping_cutoff_current < (bat_conf->nominal_capacity / 10.0), + bat_conf->topping_cutoff_current > 0.01, + (bat_conf->float_enabled == false || + (bat_conf->float_voltage < bat_conf->topping_voltage && + bat_conf->float_voltage > bat_conf->load_disconnect_voltage)) ); return ( - bat_conf->voltage_load_reconnect > (bat_conf->voltage_load_disconnect + 0.4) && - bat_conf->voltage_recharge < (bat_conf->topping_voltage - 0.4) && - bat_conf->voltage_recharge > (bat_conf->voltage_load_disconnect + 1) && - bat_conf->voltage_load_disconnect > (bat_conf->voltage_absolute_min + 0.4) && + bat_conf->load_reconnect_voltage > (bat_conf->load_disconnect_voltage + 0.4) && + bat_conf->recharge_voltage < (bat_conf->topping_voltage - 0.4) && + bat_conf->recharge_voltage > (bat_conf->load_disconnect_voltage + 1) && + bat_conf->load_disconnect_voltage > (bat_conf->absolute_min_voltage + 0.4) && // max. 10% drop - bat_conf->internal_resistance < bat_conf->voltage_load_disconnect * 0.1 / + bat_conf->internal_resistance < bat_conf->load_disconnect_voltage * 0.1 / DISCHARGE_CURRENT_MAX && // max. 3% loss bat_conf->wire_resistance < bat_conf->topping_voltage * 0.03 / DISCHARGE_CURRENT_MAX && // C/10 or lower current cutoff allowed - bat_conf->topping_current_cutoff < (bat_conf->nominal_capacity / 10.0) && - bat_conf->topping_current_cutoff > 0.01 && - (bat_conf->trickle_enabled == false || - (bat_conf->trickle_voltage < bat_conf->topping_voltage && - bat_conf->trickle_voltage > bat_conf->voltage_load_disconnect)) + bat_conf->topping_cutoff_current < (bat_conf->nominal_capacity / 10.0) && + bat_conf->topping_cutoff_current > 0.01 && + (bat_conf->float_enabled == false || + (bat_conf->float_voltage < bat_conf->topping_voltage && + bat_conf->float_voltage > bat_conf->load_disconnect_voltage)) ); } @@ -250,17 +248,17 @@ void battery_conf_overwrite(BatConf *source, BatConf *destination, Charger *char // TODO: stop DC/DC destination->topping_voltage = source->topping_voltage; - destination->voltage_recharge = source->voltage_recharge; - destination->voltage_load_reconnect = source->voltage_load_reconnect; - destination->voltage_load_disconnect = source->voltage_load_disconnect; - destination->voltage_absolute_max = source->voltage_absolute_max; - destination->voltage_absolute_min = source->voltage_absolute_min; + destination->recharge_voltage = source->recharge_voltage; + destination->load_reconnect_voltage = source->load_reconnect_voltage; + destination->load_disconnect_voltage = source->load_disconnect_voltage; + destination->absolute_max_voltage = source->absolute_max_voltage; + destination->absolute_min_voltage = source->absolute_min_voltage; destination->charge_current_max = source->charge_current_max; - destination->topping_current_cutoff = source->topping_current_cutoff; + destination->topping_cutoff_current = source->topping_cutoff_current; destination->topping_duration = source->topping_duration; - destination->trickle_enabled = source->trickle_enabled; - destination->trickle_voltage = source->trickle_voltage; - destination->trickle_recharge_time = source->trickle_recharge_time; + destination->float_enabled = source->float_enabled; + destination->float_voltage = source->float_voltage; + destination->float_recharge_time = source->float_recharge_time; destination->charge_temp_max = source->charge_temp_max; destination->charge_temp_min = source->charge_temp_min; destination->discharge_temp_max = source->discharge_temp_max; @@ -288,17 +286,17 @@ bool battery_conf_changed(BatConf *a, BatConf *b) { return ( a->topping_voltage != b->topping_voltage || - a->voltage_recharge != b->voltage_recharge || - a->voltage_load_reconnect != b->voltage_load_reconnect || - a->voltage_load_disconnect != b->voltage_load_disconnect || - a->voltage_absolute_max != b->voltage_absolute_max || - a->voltage_absolute_min != b->voltage_absolute_min || + a->recharge_voltage != b->recharge_voltage || + a->load_reconnect_voltage != b->load_reconnect_voltage || + a->load_disconnect_voltage != b->load_disconnect_voltage || + a->absolute_max_voltage != b->absolute_max_voltage || + a->absolute_min_voltage != b->absolute_min_voltage || a->charge_current_max != b->charge_current_max || - a->topping_current_cutoff != b->topping_current_cutoff || + a->topping_cutoff_current != b->topping_cutoff_current || a->topping_duration != b->topping_duration || - a->trickle_enabled != b->trickle_enabled || - a->trickle_voltage != b->trickle_voltage || - a->trickle_recharge_time != b->trickle_recharge_time || + a->float_enabled != b->float_enabled || + a->float_voltage != b->float_voltage || + a->float_recharge_time != b->float_recharge_time || a->charge_temp_max != b->charge_temp_max || a->charge_temp_min != b->charge_temp_min || a->discharge_temp_max != b->discharge_temp_max || @@ -311,8 +309,8 @@ bool battery_conf_changed(BatConf *a, BatConf *b) void Charger::detect_num_batteries(BatConf *bat) const { - if (port->bus->voltage > bat->voltage_absolute_min * 2 && - port->bus->voltage < bat->voltage_absolute_max * 2) + if (port->bus->voltage > bat->absolute_min_voltage * 2 && + port->bus->voltage < bat->absolute_max_voltage * 2) { port->bus->series_multiplier = 2; printf("Detected two batteries (total %.2f V max)\n", bat->topping_voltage * 2); @@ -397,7 +395,7 @@ void Charger::discharge_control(BatConf *bat_conf) // This limit should normally never be reached, as the load output settings should be // higher. The flag can be used to trigger actions of last resort, e.g. deep-sleep // of the charge controller itself. - if (port->bus->voltage < port->bus->src_control_voltage(bat_conf->voltage_absolute_min)) { + if (port->bus->voltage < port->bus->src_control_voltage(bat_conf->absolute_min_voltage)) { port->neg_current_limit = 0; dev_stat.set_error(ERR_BAT_UNDERVOLTAGE); } @@ -415,7 +413,7 @@ void Charger::discharge_control(BatConf *bat_conf) // discharging currently not allowed. should we allow it? if (port->bus->voltage >= - port->bus->src_control_voltage(bat_conf->voltage_absolute_min + 0.1F)) + port->bus->src_control_voltage(bat_conf->absolute_min_voltage + 0.1F)) { dev_stat.clear_error(ERR_BAT_UNDERVOLTAGE); } @@ -453,23 +451,33 @@ void Charger::charge_control(BatConf *bat_conf) } if (dev_stat.has_error(ERR_BAT_OVERVOLTAGE) && - port->bus->voltage < (bat_conf->voltage_absolute_max - 0.5F) * port->bus->series_multiplier) + port->bus->voltage < (bat_conf->absolute_max_voltage - 0.5F) * + port->bus->series_multiplier) { dev_stat.clear_error(ERR_BAT_OVERVOLTAGE); } + if (state != CHG_STATE_FOLLOWER && (uptime() - time_last_ctrl_msg) <= 1) { + enter_state(CHG_STATE_FOLLOWER); + } + // state machine switch (state) { case CHG_STATE_IDLE: { - if (port->bus->voltage < port->bus->sink_control_voltage(bat_conf->voltage_recharge) - && port->bus->voltage > port->bus->sink_control_voltage(bat_conf->voltage_absolute_min) // ToDo set error flag otherwise - && (uptime() - time_state_changed) > bat_conf->time_limit_recharge + if ((time_state_changed == CHARGER_TIME_NEVER || + ((uptime() - time_state_changed) > bat_conf->time_limit_recharge && + port->bus->voltage < port->bus->sink_control_voltage( + bat_conf->recharge_voltage)) + ) + && port->bus->voltage > port->bus->sink_control_voltage( + bat_conf->absolute_min_voltage) // ToDo set error flag otherwise && bat_temperature < bat_conf->charge_temp_max - 1 && bat_temperature > bat_conf->charge_temp_min + 1) { port->bus->sink_voltage_intercept = bat_conf->topping_voltage + bat_conf->temperature_compensation * (bat_temperature - 25); port->pos_current_limit = bat_conf->charge_current_max; + target_current_control = port->pos_current_limit; full = false; dev_stat.clear_error(ERR_BAT_CHG_OVERTEMP); dev_stat.clear_error(ERR_BAT_CHG_UNDERTEMP); @@ -494,10 +502,13 @@ void Charger::charge_control(BatConf *bat_conf) port->bus->sink_voltage_intercept = bat_conf->topping_voltage + bat_conf->temperature_compensation * (bat_temperature - 25); + // power sharing: multiple devices in parallel supply the same current + target_current_control = port->current_filtered; + if (port->bus->voltage_filtered >= port->bus->sink_control_voltage() - 0.05F) { // battery is full if topping target voltage is still reached (i.e. sufficient // solar power available) and time limit or cut-off current reached - if (port->current_filtered < bat_conf->topping_current_cutoff || + if (port->current_filtered < bat_conf->topping_cutoff_current || target_voltage_timer > bat_conf->topping_duration) { full = true; @@ -524,10 +535,10 @@ void Charger::charge_control(BatConf *bat_conf) port->pos_current_limit = bat_conf->equalization_current_limit; enter_state(CHG_STATE_EQUALIZATION); } - else if (bat_conf->trickle_enabled) { - port->bus->sink_voltage_intercept = bat_conf->trickle_voltage + + else if (bat_conf->float_enabled) { + port->bus->sink_voltage_intercept = bat_conf->float_voltage + bat_conf->temperature_compensation * (bat_temperature - 25); - enter_state(CHG_STATE_TRICKLE); + enter_state(CHG_STATE_FLOAT); } else { port->pos_current_limit = 0; @@ -536,22 +547,26 @@ void Charger::charge_control(BatConf *bat_conf) } break; } - case CHG_STATE_TRICKLE: { + case CHG_STATE_FLOAT: { // continuously adjust voltage setting for temperature compensation - port->bus->sink_voltage_intercept = bat_conf->trickle_voltage + + port->bus->sink_voltage_intercept = bat_conf->float_voltage + bat_conf->temperature_compensation * (bat_temperature - 25); + target_current_control = port->current_filtered; + if (port->bus->voltage >= port->bus->sink_control_voltage()) { time_target_voltage_reached = uptime(); } - if (uptime() - time_target_voltage_reached > bat_conf->trickle_recharge_time) + if ((uptime() - time_target_voltage_reached > bat_conf->float_recharge_time) && + port->bus->voltage_filtered < port->bus->sink_control_voltage( + bat_conf->recharge_voltage)) { - // the battery was discharged: trickle voltage could not be reached anymore + // the battery was discharged: float voltage could not be reached anymore port->pos_current_limit = bat_conf->charge_current_max; full = false; - // assumption: trickle does not harm the battery --> never go back to idle - // (for Li-ion battery: disable trickle!) + // assumption: float does not harm the battery --> never go back to idle + // (for Li-ion battery: disable float!) enter_state(CHG_STATE_BULK); } break; @@ -561,6 +576,8 @@ void Charger::charge_control(BatConf *bat_conf) port->bus->sink_voltage_intercept = bat_conf->equalization_voltage + bat_conf->temperature_compensation * (bat_temperature - 25); + target_current_control = port->current_filtered; + // current or time limit for equalization reached if (uptime() - time_state_changed > bat_conf->equalization_duration) { @@ -570,10 +587,10 @@ void Charger::charge_control(BatConf *bat_conf) discharged_Ah = 0; // reset coulomb counter again - if (bat_conf->trickle_enabled) { - port->bus->sink_voltage_intercept = bat_conf->trickle_voltage + + if (bat_conf->float_enabled) { + port->bus->sink_voltage_intercept = bat_conf->float_voltage + bat_conf->temperature_compensation * (bat_temperature - 25); - enter_state(CHG_STATE_TRICKLE); + enter_state(CHG_STATE_FLOAT); } else { port->pos_current_limit = 0; @@ -582,13 +599,27 @@ void Charger::charge_control(BatConf *bat_conf) } break; } + case CHG_STATE_FOLLOWER: { + if ((uptime() - time_last_ctrl_msg) > 1) { + // go back to normal state machine + port->pos_current_limit = bat_conf->charge_current_max; + enter_state(CHG_STATE_BULK); + } + else { + // set current target as received from external device + port->pos_current_limit = target_current_control; + // set safety limit for voltage + port->bus->sink_voltage_intercept = bat_conf->absolute_max_voltage; + } + break; + } } } void Charger::init_terminal(BatConf *bat) const { port->bus->sink_voltage_intercept = bat->topping_voltage; - port->bus->src_voltage_intercept = bat->voltage_load_disconnect; + port->bus->src_voltage_intercept = bat->load_disconnect_voltage; port->neg_current_limit = -bat->discharge_current_max; port->pos_current_limit = bat->charge_current_max; diff --git a/src/bat_charger.h b/app/src/bat_charger.h similarity index 84% rename from src/bat_charger.h rename to app/src/bat_charger.h index 96eeda9..a2b9238 100644 --- a/src/bat_charger.h +++ b/app/src/bat_charger.h @@ -19,6 +19,8 @@ #include "power_port.h" +#define CHARGER_TIME_NEVER INT32_MIN + /** * Battery cell types */ @@ -57,28 +59,28 @@ typedef struct * Remark: Setting the value too close to the max voltage will cause more charging stress on * lithium based batteries. */ - float voltage_recharge; + float recharge_voltage; /** * Recharge time limit (sec) * * Start charging of previously fully charged battery earliest after this period of time. */ - int32_t time_limit_recharge; + uint32_t time_limit_recharge; /** * Absolute maximum voltage (V) * * Above this voltage the battery or loads might get damaged. */ - float voltage_absolute_max; + float absolute_max_voltage; /** * Absolute minimum voltage (V) * * Below this voltage the battery is considered damaged. */ - float voltage_absolute_min; + float absolute_min_voltage; /** * Maximum charge current in *CC/bulk* phase (A) @@ -106,42 +108,42 @@ typedef struct * * Constant voltage charging phase stopped if current is below this value. */ - float topping_current_cutoff; + float topping_cutoff_current; /** * CV phase cut-off time limit (s) * * After this time, CV charging is stopped independent of current. */ - int32_t topping_duration; + uint32_t topping_duration; /** * Enable float/trickle charging * - * Caution: Do not enable trickle charging for lithium-ion batteries + * Caution: Do not enable float charging for lithium-ion batteries */ - bool trickle_enabled; + bool float_enabled; /** - * Trickle voltage (V) + * Float voltage (V) * - * Charger target voltage for trickle charging of lead-acid batteries + * Charger target voltage for float charging of lead-acid batteries */ - float trickle_voltage; + float float_voltage; /** - * Trickle recharge time (s) + * Float recharge time (s) * - * If the trickle voltage is not reached anymore (e.g. because of lack of solar + * If the float voltage is not reached anymore (e.g. because of lack of solar * input power) for this period of time, the charger state machine goes back * into CC/bulk charging mode. */ - int32_t trickle_recharge_time; + uint32_t float_recharge_time; /** * Enable equalization charging * - * Caution: Do not enable trickle charging for lithium-ion batteries + * Caution: Do not enable float charging for lithium-ion batteries */ bool equalization_enabled; @@ -157,7 +159,7 @@ typedef struct * * After this time, equalization charging is stopped. */ - int32_t equalization_duration; + uint32_t equalization_duration; /** * Equalization phase maximum current (A) @@ -171,14 +173,14 @@ typedef struct * * After passing specified amount of days, an equalization charge is triggered. */ - int32_t equalization_trigger_days; + uint32_t equalization_trigger_days; /** * Equalization trigger deep-discharge cycles * * After specified number of deep discharges, an equalization charge is triggered. */ - int32_t equalization_trigger_deep_cycles; + uint32_t equalization_trigger_deep_cycles; /** * Load disconnect open circuit voltage (V) @@ -186,11 +188,11 @@ typedef struct * Load output is disabled if battery voltage is below this threshold. * * The voltage is current-compensated using the battery internal resistance: - * threshold = voltage_load_disconnect + battery_current * internal_resistance + * threshold = load_disconnect_voltage + battery_current * internal_resistance * * (Remark: battery_current negative during discharge, internal_resistance positive) */ - float voltage_load_disconnect; + float load_disconnect_voltage; /** * Load reconnect open circuit voltage (V) @@ -198,11 +200,11 @@ typedef struct * Re-enable the load only after charged beyond this value. * * The voltage is current-compensated using the battery internal resistance: - * threshold = voltage_load_reconnect + battery_current * internal_resistance + * threshold = load_reconnect_voltage + battery_current * internal_resistance * * (Remark: battery_current positive during charge, internal_resistance positive) */ - float voltage_load_reconnect; + float load_reconnect_voltage; /** * Battery internal resistance (Ohm) @@ -267,6 +269,71 @@ typedef struct } BatConf; +/** + * Possible charger states + * + * Further information: + * - https://en.wikipedia.org/wiki/IUoU_battery_charging + * - https://batteryuniversity.com/learn/article/charging_the_lead_acid_battery + */ +enum ChargerState { + + /** + * Idle + * + * Initial state of the charge controller. If the solar voltage is high enough + * and the battery is not full, bulk charging mode is started. + */ + CHG_STATE_IDLE, + + /** + * Bulk / CC / MPPT charging + * + * The battery is charged with maximum possible current (MPPT algorithm is + * active) until the CV voltage limit is reached. + */ + CHG_STATE_BULK, + + /** + * Topping / CV / absorption charging + * + * Lead-acid batteries are charged for some time using a slightly higher charge + * voltage. After a current cutoff limit or a time limit is reached, the charger + * goes into float or equalization mode for lead-acid batteries or back into + * Standby for Li-ion batteries. + */ + CHG_STATE_TOPPING, + + /** + * Float / trickle charging + * + * This mode is kept forever for a lead-acid battery and keeps the battery at + * full state of charge. If too much power is drawn from the battery, the + * charger switches back into CC / bulk charging mode. + */ + CHG_STATE_FLOAT, + + /** + * Equalization charging + * + * This mode is only used for lead-acid batteries after several deep-discharge + * cycles or a very long period of time with no equalization. Voltage is + * increased to 15V or above, so care must be taken for the other system + * components attached to the battery. (currently, no equalization charging is + * enabled in the software) + */ + CHG_STATE_EQUALIZATION, + + /** + * Parallel operation of multiple converters + * + * This mode is enabled if the device receives commands from an external controller with + * higher priority on the CAN bus. The device goes in current control modes and tries to + * match the current of the other controller. + */ + CHG_STATE_FOLLOWER +}; + /** * Charger configuration and battery state */ @@ -281,7 +348,7 @@ public: /** * Current charger state (see enum ChargerState) */ - uint32_t state; + uint32_t state = CHG_STATE_IDLE; /** * Battery temperature (°C) from ext. temperature sensor (if existing) @@ -326,28 +393,28 @@ public: /** * Timestamp of last state change */ - time_t time_state_changed; + time_t time_state_changed = CHARGER_TIME_NEVER; /** * Last time the CV limit was reached */ - time_t time_target_voltage_reached; + time_t time_target_voltage_reached = CHARGER_TIME_NEVER; /** * Counts the number of seconds during which the target voltage of current charging phase was * reached. */ - int target_voltage_timer; + uint32_t target_voltage_timer; /** * Timestamp after finish of last equalization charge */ - time_t time_last_equalization; + time_t time_last_equalization = CHARGER_TIME_NEVER; /** * Deep discharge counter value after last equalization */ - int deep_dis_last_equalization; + uint32_t deep_dis_last_equalization; /** * Flag to indicate if battery was fully charged @@ -359,6 +426,17 @@ public: */ bool empty; + /** + * Last time a control message from external device was received + */ + time_t time_last_ctrl_msg = CHARGER_TIME_NEVER; + + /** + * Target current of the converter if operating in follower mode (received from external + * converter with higher priority via CAN) + */ + float target_current_control; + /** * Detect if two batteries are connected in series (12V/24V auto-detection) */ @@ -392,63 +470,6 @@ private: void enter_state(int next_state); }; - -/** - * Possible charger states - * - * Further information: - * - https://en.wikipedia.org/wiki/IUoU_battery_charging - * - https://batteryuniversity.com/learn/article/charging_the_lead_acid_battery - */ -enum ChargerState { - - /** - * Idle - * - * Initial state of the charge controller. If the solar voltage is high enough - * and the battery is not full, bulk charging mode is started. - */ - CHG_STATE_IDLE, - - /** - * Bulk / CC / MPPT charging - * - * The battery is charged with maximum possible current (MPPT algorithm is - * active) until the CV voltage limit is reached. - */ - CHG_STATE_BULK, - - /** - * Topping / CV / absorption charging - * - * Lead-acid batteries are charged for some time using a slightly higher charge - * voltage. After a current cutoff limit or a time limit is reached, the charger - * goes into trickle or equalization mode for lead-acid batteries or back into - * Standby for Li-ion batteries. - */ - CHG_STATE_TOPPING, - - /** - * Trickle charging - * - * This mode is kept forever for a lead-acid battery and keeps the battery at - * full state of charge. If too much power is drawn from the battery, the - * charger switches back into CC / bulk charging mode. - */ - CHG_STATE_TRICKLE, - - /** - * Equalization charging - * - * This mode is only used for lead-acid batteries after several deep-discharge - * cycles or a very long period of time with no equalization. Voltage is - * increased to 15V or above, so care must be taken for the other system - * components attached to the battery. (currently, no equalization charging is - * enabled in the software) - */ - CHG_STATE_EQUALIZATION -}; - /** * Basic initialization of battery configuration * diff --git a/src/board.h b/app/src/board.h similarity index 77% rename from src/board.h rename to app/src/board.h index 58430ea..50aeaea 100644 --- a/src/board.h +++ b/app/src/board.h @@ -19,5 +19,7 @@ #define BOARD_HAS_PWM_PORT DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), pwm_switch)) #define BOARD_HAS_LOAD_OUTPUT DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), load)) #define BOARD_HAS_USB_OUTPUT DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), usb_pwr)) +#define BOARD_HAS_TEMP_FETS DT_NODE_EXISTS(DT_CHILD(DT_PATH(adc_inputs), temp_fets)) +#define BOARD_HAS_TEMP_BAT DT_NODE_EXISTS(DT_CHILD(DT_PATH(adc_inputs), temp_bat)) #endif /* BOARD_H_ */ diff --git a/src/daq.cpp b/app/src/daq.cpp similarity index 96% rename from src/daq.cpp rename to app/src/daq.cpp index 43e325b..035e75d 100644 --- a/src/daq.cpp +++ b/app/src/daq.cpp @@ -8,10 +8,8 @@ #include -#ifndef UNIT_TEST #include LOG_MODULE_REGISTER(daq, CONFIG_DAQ_LOG_LEVEL); -#endif #include // log for thermistor calculation #include @@ -24,6 +22,7 @@ LOG_MODULE_REGISTER(daq, CONFIG_DAQ_LOG_LEVEL); // filter parameter c for additional battery voltage and current low-pass filter // c = dt / (tau + dt) = 0.1s / (10s + 0.1s) +#define HV_BUS_VOLTAGE_FILTER_CONST 0.0099F #define LV_BUS_VOLTAGE_FILTER_CONST 0.0099F #define LV_TERMINAL_CURRENT_FILTER_CONST 0.0099F #define PWM_CURRENT_FILTER_CONST 0.0625F // 1.5 seconds @@ -185,6 +184,15 @@ void daq_update() #if BOARD_HAS_DCDC hv_bus.voltage = adc_scaled(ADC_POS(v_high), vref, ADC_GAIN(v_high)); + + if (hv_bus.voltage_filtered != 0.0F) { + hv_bus.voltage_filtered = HV_BUS_VOLTAGE_FILTER_CONST * hv_bus.voltage + + (1.0F - HV_BUS_VOLTAGE_FILTER_CONST) * hv_bus.voltage_filtered; + } + else { + // initialize properly at startup + hv_bus.voltage_filtered = hv_bus.voltage; + } #endif #if BOARD_HAS_PWM_PORT @@ -236,7 +244,7 @@ void daq_update() load.power = load.bus->voltage * load.current; #endif -#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(adc_inputs), temp_bat)) +#if BOARD_HAS_TEMP_BAT // battery temperature calculation float bat_temp = ntc_temp(ADC_POS(temp_bat), vref, ADC_GAIN(temp_bat)); @@ -252,8 +260,7 @@ void daq_update() } #endif -#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(adc_inputs), temp_fets)) - // MOSFET temperature calculation +#if BOARD_HAS_TEMP_FETS dcdc.temp_mosfets = ntc_temp(ADC_POS(temp_fets), vref, ADC_GAIN(temp_fets)); #endif @@ -355,9 +362,9 @@ void daq_set_hv_limit(float hv_overvoltage) } #endif -#if defined(UNIT_TEST) +#if !defined(CONFIG_SOC_FAMILY_STM32) -#include "../test/daq_stub.h" +#include "daq_stub.h" void prepare_adc_readings(AdcValues values) { diff --git a/src/daq.h b/app/src/daq.h similarity index 100% rename from src/daq.h rename to app/src/daq.h diff --git a/src/daq_driver.c b/app/src/daq_driver.c similarity index 100% rename from src/daq_driver.c rename to app/src/daq_driver.c diff --git a/app/src/data_objects.cpp b/app/src/data_objects.cpp new file mode 100644 index 0000000..ad82008 --- /dev/null +++ b/app/src/data_objects.cpp @@ -0,0 +1,1347 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include "data_objects.h" + +#include +#include + +#include +#include + +#ifdef CONFIG_SOC_FAMILY_STM32 +#include +#endif + +#include +#include + +#include "data_storage.h" +#include "dcdc.h" +#include "hardware.h" +#include "setup.h" +#include "thingset.h" +#include "helper.h" + +LOG_MODULE_REGISTER(data_objects, CONFIG_DATA_OBJECTS_LOG_LEVEL); + +// can be used to configure custom data objects in separate file instead +// (e.g. data_objects_custom.cpp) +#ifndef CONFIG_CUSTOM_DATA_OBJECTS_FILE + +const char manufacturer[] = "Libre Solar"; +const char metadata_url[] = + "https://files.libre.solar/tsm/cc-" STRINGIFY(DATA_OBJECTS_VERSION) ".json"; +const char device_type[] = DT_PROP(DT_PATH(pcb), type); +const char hardware_version[] = DT_PROP(DT_PATH(pcb), version_str); +const char firmware_version[] = FIRMWARE_VERSION_ID; +char device_id[9]; + +#ifdef CONFIG_SOC_FAMILY_STM32 +uint32_t flash_size = LL_GetFlashSize(); +uint32_t flash_page_size = FLASH_PAGE_SIZE; +#else +uint32_t flash_size = 128; +uint32_t flash_page_size = 0x800; +#endif + +static char auth_password[11]; + +#if CONFIG_LV_TERMINAL_BATTERY +#define bat_bus lv_bus +#elif CONFIG_HV_TERMINAL_BATTERY +#define bat_bus hv_bus +#endif + +#if CONFIG_HV_TERMINAL_SOLAR +#define solar_bus hv_bus +#elif CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR +#define solar_bus lv_bus +#endif + +bool pub_serial_enable = IS_ENABLED(CONFIG_THINGSET_SERIAL_PUB_DEFAULT); + +#if CONFIG_THINGSET_CAN +bool pub_can_enable = IS_ENABLED(CONFIG_THINGSET_CAN_PUB_DEFAULT); +uint16_t can_node_addr = CONFIG_THINGSET_CAN_DEFAULT_NODE_ID; +#endif + +/** + * Thing Set Data Objects (see thingset.io for specification) + */ +static ThingSetDataObject data_objects[] = { + + /* + * Device information (IDs >= 0x20) + */ + TS_GROUP(ID_INFO, "info", TS_NO_CALLBACK, ID_ROOT), + + /*{ + "title": { + "en": "ThingSet Metadata URL", + "de": "ThingSet Metadata URL" + } + }*/ + TS_ITEM_STRING(0x18, "MetadataURL", metadata_url, sizeof(metadata_url), + ID_INFO, TS_ANY_R, SUBSET_NVM), + + /*{ + "title": { + "en": "Device ID", + "de": "Geräte-ID" + } + }*/ + TS_ITEM_STRING(0x1D, "DeviceID", device_id, sizeof(device_id), + ID_INFO, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Manufacturer", + "de": "Hersteller" + } + }*/ + TS_ITEM_STRING(0x20, "Manufacturer", manufacturer, 0, + ID_INFO, TS_ANY_R, 0), + + /*{ + "title": { + "en": "Device Type", + "de": "Gerätetyp" + } + }*/ + TS_ITEM_STRING(0x21, "DeviceType", device_type, 0, + ID_INFO, TS_ANY_R, 0), + + /*{ + "title": { + "en": "Hardware Version", + "de": "Hardware-Version" + } + }*/ + TS_ITEM_STRING(0x22, "HardwareVersion", hardware_version, 0, + ID_INFO, TS_ANY_R, 0), + + /*{ + "title": { + "en": "Firmware Version", + "de": "Firmware-Version" + } + }*/ + TS_ITEM_STRING(0x23, "FirmwareVersion", firmware_version, 0, + ID_INFO, TS_ANY_R, 0), + + /* + * Measurement data (IDs >= 0x30) + */ + TS_GROUP(ID_MEAS, "meas", TS_NO_CALLBACK, ID_ROOT), + + /*{ + "title": { + "en": "Time since last reset", + "de": "Zeit seit Systemstart" + }, + "unit": "s" + }*/ + TS_ITEM_UINT32(0x30, "Uptime_s", ×tamp, + ID_MEAS, TS_ANY_R, SUBSET_SER), + + /*{ + "title": { + "en": "Battery Voltage", + "de": "Batterie-Spannung" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0x31, "Bat_V", &bat_bus.voltage, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "Battery Current", + "de": "Batterie-Strom" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0x32, "Bat_A", &bat_terminal.current, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "Battery Power", + "de": "Batterie-Leistung" + }, + "unit": "W" + }*/ + TS_ITEM_FLOAT(0x33, "Bat_W", &bat_terminal.power, 2, + ID_MEAS, TS_ANY_R, 0), + +#if BOARD_HAS_TEMP_FETS + /*{ + "title": { + "en": "Battery Temperature", + "de": "Batterie-Temperatur" + }, + "unit": "°C" + }*/ + TS_ITEM_FLOAT(0x34, "Bat_degC", &charger.bat_temperature, 1, + ID_MEAS, TS_ANY_R, 0), + + /*{ + "title": { + "en": "External Temperature Sensor", + "de": "Externer Temperatursensor" + } + }*/ + TS_ITEM_BOOL(0x35, "BatTempExt", &charger.ext_temp_sensor, + ID_MEAS, TS_ANY_R, 0), +#endif + + /*{ + "title": { + "en": "Internal Temperature", + "de": "Interne Temperatur" + }, + "unit": "°C" + }*/ + TS_ITEM_FLOAT(0x36, "Int_degC", &dev_stat.internal_temp, 1, + ID_MEAS, TS_ANY_R, 0), + +#if BOARD_HAS_TEMP_FETS + /*{ + "title": { + "en": "MOSFET Temperature", + "de": "MOSFET-Temperatur" + }, + "unit": "°C" + }*/ + TS_ITEM_FLOAT(0x37, "Mosfet_degC", &dcdc.temp_mosfets, 1, + ID_MEAS, TS_ANY_R, 0), +#endif + +#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR + /*{ + "title": { + "en": "Solar Voltage", + "de": "Solar-Spannung" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0x38, "Solar_V", &solar_bus.voltage, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), +#elif CONFIG_PWM_TERMINAL_SOLAR + TS_ITEM_FLOAT(0x38, "Solar_V", &pwm_switch.ext_voltage, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), +#endif + +#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR + /*{ + "title": { + "en": "Solar Current", + "de": "Solar-Strom" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0x39, "Solar_A", &solar_terminal.current, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "Solar Power", + "de": "Solar-Leistung" + }, + "unit": "W" + }*/ + TS_ITEM_FLOAT(0x3A, "Solar_W", &solar_terminal.power, 2, + ID_MEAS, TS_ANY_R, 0), +#endif + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Load Outupt Current", + "de": "Lastausgangs-Strom" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0x3B, "Load_A", &load.current, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "Load Output Power", + "de": "Lastausgangs-Leistung" + }, + "unit": "W" + }*/ + TS_ITEM_FLOAT(0x3C, "Load_W", &load.power, 2, + ID_MEAS, TS_ANY_R, 0), +#endif + +#if CONFIG_HV_TERMINAL_NANOGRID + /*{ + "title": { + "en": "DC Grid Voltage", + "de": "Spannung DC-Netz" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0x3D, "Grid_V", &hv_bus.voltage, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "DC Grid Current", + "de": "Strom DC-Netz" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0x3E, "Grid_A", &hv_terminal.current, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "DC Grid Power", + "de": "Leistung DC-Grid" + }, + "unit": "W" + }*/ + TS_ITEM_FLOAT(0x3F, "Grid_W", &hv_terminal.power, 2, + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), +#endif + + /*{ + "title": { + "en": "State of Charge", + "de": "Batterie-Ladezustand" + }, + "unit": "%" + }*/ + TS_ITEM_UINT16(0x40, "SOC_pct", &charger.soc, // output will be uint8_t + ID_MEAS, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /* + * State data (IDs >= 0x50) + */ + TS_GROUP(ID_STATE, "state", TS_NO_CALLBACK, ID_ROOT), + + /*{ + "title": { + "en": "Charger State", + "de": "Ladegerät-Zustand" + } + }*/ + TS_ITEM_UINT32(0x50, "ChgState", &charger.state, + ID_STATE, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "Charge Target Voltage", + "de": "Ziel-Ladespannung" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0x51, "ChgTarget_V", &bat_bus.sink_voltage_intercept, 2, + ID_STATE, TS_ANY_R, 0), + + /*{ + "title": { + "en": "Charge Target Current", + "de": "Ziel-Ladestrom" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0x52, "ChgTarget_A", &bat_terminal.pos_current_limit, 2, + ID_STATE, TS_ANY_R, 0), + + /*{ + "title": { + "en": "Number of Batteries", + "de": "Anzahl Batterien" + } + }*/ + TS_ITEM_INT16(0x53, "NumBatteries", &lv_bus.series_multiplier, + ID_MEAS, TS_ANY_R, 0), + +#if BOARD_HAS_DCDC + /*{ + "title": { + "en": "DC/DC State", + "de": "DC/DC-Zustand" + } + }*/ + TS_ITEM_UINT16(0x54, "DCDCState", &dcdc.state, + ID_STATE, TS_ANY_R, SUBSET_SER | SUBSET_CAN), +#endif + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Load Info", + "de": "Last-Info" + } + }*/ + TS_ITEM_INT32(0x55, "LoadInfo", &load.info, + ID_STATE, TS_ANY_R, SUBSET_SER | SUBSET_CAN), +#endif + +#if BOARD_HAS_USB_OUTPUT + /*{ + "title": { + "en": "USB Info", + "de": "USB-Info" + } + }*/ + TS_ITEM_INT32(0x56, "UsbInfo", &usb_pwr.info, + ID_STATE, TS_ANY_R, SUBSET_SER | SUBSET_CAN), +#endif + + /*{ + "title": { + "en": "Error Flags", + "de": "Fehlercode" + } + }*/ + TS_ITEM_UINT32(0x5F, "ErrorFlags", &dev_stat.error_flags, + ID_STATE, TS_ANY_R, SUBSET_SER | SUBSET_CAN), + + /* + * Recorded data (IDs >= 0x60) + */ + TS_GROUP(ID_REC, "rec", TS_NO_CALLBACK, ID_ROOT), + + /*{ + "title": { + "en": "Charged Energy (total)", + "de": "Energiedurchsatz Ladung (gesamt)" + }, + "unit": "Wh" + }*/ + TS_ITEM_UINT32(0x60, "BatChgTotal_Wh", &dev_stat.bat_chg_total_Wh, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Discharged Energy (total)", + "de": "Energiedurchsatz Entladung (gesamt)" + }, + "unit": "Wh" + }*/ + TS_ITEM_UINT32(0x61, "BatDisTotal_Wh", &dev_stat.bat_dis_total_Wh, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Full Charge Counter", + "de": "Zähler Vollladezyklen" + } + }*/ + TS_ITEM_UINT16(0x62, "FullChgCount", &charger.num_full_charges, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Deep Discharge Counter", + "de": "Zähler Tiefentladungen" + } + }*/ + TS_ITEM_UINT16(0x63, "DeepDisCount", &charger.num_deep_discharges, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_SER | SUBSET_NVM), + + /*{ + "title": { + "en": "Usable Battery Capacity", + "de": "Nutzbare Batterie-Kapazität" + }, + "unit": "Wh" + }*/ + TS_ITEM_FLOAT(0x64, "BatUsable_Ah", &charger.usable_capacity, 1, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_SER | SUBSET_NVM), + + /*{ + "title": { + "en": "Solar Energy (total)", + "de": "Solar-Energie (gesamt)" + }, + "unit": "Wh" + }*/ + TS_ITEM_UINT32(0x65, "SolarInTotal_Wh", &dev_stat.solar_in_total_Wh, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Load Output Energy (total)", + "de": "Energiedurchsatz Lastausgang (gesamt)" + }, + "unit": "W" + }*/ + TS_ITEM_UINT32(0x66, "LoadOutTotal_Wh", &dev_stat.load_out_total_Wh, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), +#endif + +#if CONFIG_HV_TERMINAL_NANOGRID + /*{ + "title": { + "en": "Grid Imported Energy (total)", + "de": "Energie-Import DC-Netz (gesamt)" + }, + "unit": "Wh" + }*/ + TS_ITEM_UINT32(0x67, "GridImportTotal_Wh", &dev_stat.grid_import_total_Wh, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Grid Exported Energy (total)", + "de": "Energie-Export DC-Netz (gesamt)" + }, + "unit": "Wh" + }*/ + TS_ITEM_UINT32(0x68, "GridExportTotal_Wh", &dev_stat.grid_export_total_Wh, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), +#endif + + /*{ + "title": { + "en": "Charged Energy (today)", + "de": "Geladene Energie (heute)" + }, + "unit": "Wh" + }*/ + TS_ITEM_FLOAT(0x69, "BatChgDay_Wh", &bat_terminal.pos_energy_Wh, 2, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "Discharged Energy (today)", + "de": "Entladene Energie (heute)" + }, + "unit": "Wh" + }*/ + TS_ITEM_FLOAT(0x6A, "BatDisDay_Wh", &bat_terminal.neg_energy_Wh, 2, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_SER | SUBSET_CAN), + + /*{ + "title": { + "en": "Discharged Battery Capacity", + "de": "Entladene Batterie-Kapazität" + }, + "unit": "Ah" + }*/ + TS_ITEM_FLOAT(0x6B, "Dis_Ah", &charger.discharged_Ah, 0, // coulomb counter + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_SER | SUBSET_CAN), + +#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR + /*{ + "title": { + "en": "Solar Energy (today)", + "de": "Solar-Ertrag (heute)" + }, + "unit": "Wh" + }*/ + TS_ITEM_FLOAT(0x6C, "SolarInDay_Wh", &solar_terminal.neg_energy_Wh, 2, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_SER | SUBSET_CAN), +#endif + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Load Output Energy (today)", + "de": "Energie Last-Ausgang (heute)" + }, + "unit": "Wh" + }*/ + TS_ITEM_FLOAT(0x6D, "LoadOutDay_Wh", &load.pos_energy_Wh, 2, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_SER | SUBSET_CAN), +#endif + + /*{ + "title": { + "en": "Peak Solar Power (today)", + "de": "Maximale Solarleistung (heute)" + }, + "unit": "W" + }*/ + TS_ITEM_UINT16(0x6E, "SolarMaxDay_W", &dev_stat.solar_power_max_day, + ID_REC, TS_ANY_R | TS_MKR_W, 0), + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Peak Load Power (today)", + "de": "Maximale Lastleistung (heute)" + }, + "unit": "W" + }*/ + TS_ITEM_UINT16(0x6F, "LoadMaxDay_W", &dev_stat.load_power_max_day, + ID_REC, TS_ANY_R | TS_MKR_W, 0), +#endif + + /*{ + "title": { + "en": "Battery State of Health", + "de": "Batterie-Gesundheitszustand" + }, + "unit": "%" + }*/ + TS_ITEM_UINT16(0x70, "SOH_pct", &charger.soh, // output will be uint8_t + ID_REC, TS_ANY_R | TS_MKR_W, 0), + + /*{ + "title": { + "en": "Day Counter", + "de": "Tagzähler" + } + }*/ + TS_ITEM_UINT32(0x71, "DayCount", &dev_stat.day_counter, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Solar Peak Power (total)", + "de": "Maximalleistung Solar (gesamt)" + }, + "unit": "W" + }*/ + TS_ITEM_UINT16(0x72, "SolarMaxTotal_W", &dev_stat.solar_power_max_total, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Load Peak Power (total)", + "de": "Maximalleistung Last-Ausgang (gesamt)" + }, + "unit": "W" + }*/ + TS_ITEM_UINT16(0x73, "LoadMaxTotal_W", &dev_stat.load_power_max_total, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), +#endif + + /*{ + "title": { + "en": "Battery Peak Voltage (total)", + "de": "Maximalspannung Batterie (gesamt)" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0x74, "BatMaxTotal_V", &dev_stat.battery_voltage_max, 2, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Solar Peak Voltage (all-time)", + "de": "Maximalspannung Solar (gesamt)" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0x75, "SolarMaxTotal_V", &dev_stat.solar_voltage_max, 2, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "DC/DC Peak Current (all-time)", + "de": "Maximalstrom DC/DC (gesamt)" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0x76, "DcdcMaxTotal_A", &dev_stat.dcdc_current_max, 2, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Load Peak Current (all-time)", + "de": "Maximalstrom Lastausgang (gesamt)" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0x77, "LoadMaxTotal_A", &dev_stat.load_current_max, 2, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), +#endif + + /*{ + "title": { + "en": "Battery Peak Temperature (all-time)", + "de": "Maximaltemperatur Batterie (gesamt)" + }, + "unit": "°C" + }*/ + TS_ITEM_INT16(0x78, "BatMax_degC", &dev_stat.bat_temp_max, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Peak Internal Temperature (all-time)", + "de": "Interne Maximaltemperatur (gesamt)" + }, + "unit": "°C" + }*/ + TS_ITEM_INT16(0x79, "IntMax_degC", &dev_stat.int_temp_max, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Peak MOSFET Temperature (all-time)", + "de": "MOSFET Maximaltemperatur (gesamt)" + }, + "unit": "°C" + }*/ + TS_ITEM_INT16(0x7A, "MosfetMax_degC", &dev_stat.mosfet_temp_max, + ID_REC, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /* + * Input data (IDs >= 0x80) + */ + TS_GROUP(ID_INPUT, "input", TS_NO_CALLBACK, ID_ROOT), + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Enable Load", + "de": "Last einschalten" + } + }*/ + TS_ITEM_BOOL(0x80, "LoadEn", &load.enable, + ID_INPUT, TS_ANY_R | TS_ANY_W, 0), +#endif + +#if BOARD_HAS_USB_OUTPUT + /*{ + "title": { + "en": "Enable USB", + "de": "USB einschalten" + } + }*/ + TS_ITEM_BOOL(0x81, "UsbEn", &usb_pwr.enable, + ID_INPUT, TS_ANY_R | TS_ANY_W, 0), +#endif + +#if BOARD_HAS_DCDC + /*{ + "title": { + "en": "Enable DC/DC", + "de": "DC/DC einschalten" + } + }*/ + TS_ITEM_BOOL(0x82, "DcdcEn", &dcdc.enable, + ID_INPUT, TS_ANY_R | TS_ANY_W, 0), +#endif + +#if BOARD_HAS_PWM_PORT + /*{ + "title": { + "en": "Enable PWM Solar Input", + "de": "PWM Solar-Eingang einschalten" + } + }*/ + TS_ITEM_BOOL(0x83, "PwmEn", &pwm_switch.enable, + ID_INPUT, TS_ANY_R | TS_ANY_W, 0), +#endif + +#if CONFIG_HV_TERMINAL_NANOGRID + /*{ + "title": { + "en": "DC Grid Export Voltage", + "de": "DC-Grid Export-Spannung" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0x84, "GridSink_V", &hv_bus.sink_voltage_intercept, 2, + ID_INPUT, TS_ANY_R | TS_ANY_W, 0), + + /*{ + "title": { + "en": "DC Grid Import Voltage", + "de": "DC-Grid Import-Spannung" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0x85, "GridSrc_V", &hv_bus.src_voltage_intercept, 2, + ID_INPUT, TS_ANY_R | TS_ANY_W, 0), +#endif + + /* + * Configuration data (IDs >= 0xA0) + */ + TS_GROUP(ID_CONF, "conf", &data_objects_update_conf, ID_ROOT), + + /*{ + "title": { + "en": "Nominal Battery Capacity", + "de": "Nominelle Batteriekapazität" + }, + "unit": "Ah", + "min": 1, + "max": 1000 + }*/ + TS_ITEM_FLOAT(0xA0, "BatNom_Ah", &bat_conf_user.nominal_capacity, 1, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Battery Maximum Charge Current (bulk)", + "de": "Maximaler Batterie-Ladestrom (bulk)" + }, + "unit": "A", + "min": 10.0, + "max": 30.0 + }*/ + TS_ITEM_FLOAT(0xA1, "ChgMax_A", &bat_conf_user.charge_current_max, 1, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Battery Charge Voltage (topping)", + "de": "Batterie-Ladespannung (topping)" + }, + "unit": "V", + "min": 10.0, + "max": 30.0 + }*/ + TS_ITEM_FLOAT(0xA2, "Chg_V", &bat_conf_user.topping_voltage, 2, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Topping Cut-off Current", + "de": "Abschaltstrom Vollladung" + }, + "unit": "A", + "min": 0.0, + "max": 20.0 + }*/ + TS_ITEM_FLOAT(0xA3, "ChgCutoff_A", &bat_conf_user.topping_cutoff_current, 1, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Topping Time Limit", + "de": "Zeitbregrenzung Vollladung" + }, + "unit": "s" + }*/ + TS_ITEM_UINT32(0xA4, "ChgCutoff_s", &bat_conf_user.topping_duration, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Enable Float Charging", + "de": "Erhaltungsladung einschalten" + } + }*/ + TS_ITEM_BOOL(0xA5, "FloatChgEn", &bat_conf_user.float_enabled, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Float Voltage", + "de": "Spannung Erhaltungsladung" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0xA6, "FloatChg_V", &bat_conf_user.float_voltage, 2, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Float Recharge Time", + "de": "Wiedereinschaltdauer Erhaltungsladung" + }, + "unit": "s" + }*/ + TS_ITEM_UINT32(0xA7, "FloatRechg_s", &bat_conf_user.float_recharge_time, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Enable Equalization Charging", + "de": "Ausgleichsladung einschalten" + } + }*/ + TS_ITEM_BOOL(0xA8, "EqlChgEn", &bat_conf_user.equalization_enabled, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Equalization Voltage", + "de": "Spannung Ausgleichsladung" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0xA9, "EqlChg_V", &bat_conf_user.equalization_voltage, 2, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Equalization Current Limit", + "de": "Maximalstrom Ausgleichsladung" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0xAA, "EqlChg_A", &bat_conf_user.equalization_current_limit, 2, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Equalization Duration", + "de": "Zeitbegrenzung Ausgleichsladung" + }, + "unit": "s" + }*/ + TS_ITEM_UINT32(0xAB, "EqlDuration_s", &bat_conf_user.equalization_duration, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Maximum Equalization Interval", + "de": "Max. Intervall zwischen Ausgleichsladungen" + }, + "unit": "d" + }*/ + TS_ITEM_UINT32(0xAC, "EqlInterval_d", &bat_conf_user.equalization_trigger_days, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Maximum Deep Discharges for Equalization", + "de": "Max. Tiefenentladungszyklen zwischen Ausgleichsladungen" + } + }*/ + TS_ITEM_UINT32(0xAD, "EqlDeepDisTrigger", &bat_conf_user.equalization_trigger_deep_cycles, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Battery Recharge Voltage", + "de": "Batterie-Nachladespannung" + }, + "unit": "V", + "min": 10.0, + "max": 30.0 + }*/ + TS_ITEM_FLOAT(0xAE, "BatRechg_V", &bat_conf_user.recharge_voltage, 2, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Battery Minimum Voltage", + "de": "Batterie-Minimalspannung" + }, + "unit": "V", + "min": 8.0, + "max": 30.0 + }*/ + TS_ITEM_FLOAT(0xAF, "BatAbsMin_V", &bat_conf_user.absolute_min_voltage, 2, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Temperature Compensation", + "de": "Temperaturausgleich" + }, + "unit": "mV/K" + }*/ + TS_ITEM_FLOAT(0xB0, "BatTempComp_mV_K", &bat_conf_user.temperature_compensation, 3, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Battery Internal Resistance", + "de": "Innenwiderstand Batterie" + }, + "unit": "Ohm" + }*/ + TS_ITEM_FLOAT(0xB1, "BatInt_Ohm", &bat_conf_user.internal_resistance, 3, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Battery Wire Resistance", + "de": "Kabelwiderstand Batterie" + }, + "unit": "Ohm" + }*/ + TS_ITEM_FLOAT(0xB2, "BatWire_Ohm", &bat_conf_user.wire_resistance, 3, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Maximum Charge Temperature", + "de": "Maximale Ladetemperatur" + }, + "unit": "°C" + }*/ + TS_ITEM_FLOAT(0xB3, "BatChgMax_degC", &bat_conf_user.charge_temp_max, 1, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Minimum Charge Temperature", + "de": "Minimale Ladetemperatur" + }, + "unit": "°C" + }*/ + TS_ITEM_FLOAT(0xB4, "BatChgMin_degC", &bat_conf_user.charge_temp_min, 1, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Maximum Discharge Temperature", + "de": "Maximale Entladetemperatur" + }, + "unit": "°C" + }*/ + TS_ITEM_FLOAT(0xB5, "BatDisMax_degC", &bat_conf_user.discharge_temp_max, 1, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Minimum Discharge Temperature", + "de": "Minimale Entladetemperatur" + }, + "unit": "°C" + }*/ + TS_ITEM_FLOAT(0xB6, "BatDisMin_degC", &bat_conf_user.discharge_temp_min, 1, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + +#if BOARD_HAS_LOAD_OUTPUT + /*{ + "title": { + "en": "Automatic Load Output Enable", + "de": "Last-Ausgang automatisch einschalten" + } + }*/ + TS_ITEM_BOOL(0xB7, "LoadEnDefault", &load.enable, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Load Disconnect Voltage ", + "de": "Abschaltspannung Lastausgang" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0xB8, "LoadDisconnect_V", &bat_conf_user.load_disconnect_voltage, 2, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Load Reconnect Voltage", + "de": "Wiedereinschalt-Spannung Lastausgang" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0xB9, "LoadReconnect_V", &bat_conf_user.load_reconnect_voltage, 2, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Overcurrent Recovery Delay", + "de": "Wiedereinschalt-Verzögerung nach Überstrom" + }, + "unit": "s" + }*/ + TS_ITEM_UINT32(0xBA, "LoadOCRecovery_s", &load.oc_recovery_delay, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Low Voltage Disconnect Recovery Delay", + "de": "Wiedereinschalt-Verzögerung nach Unterspannung" + }, + "unit": "s" + }*/ + TS_ITEM_UINT32(0xBB, "LoadUVRecovery_s", &load.lvd_recovery_delay, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), +#endif + +#if BOARD_HAS_USB_OUTPUT + /*{ + "title": { + "en": "Automatic USB Power Output Enable", + "de": "USB Ladeport automatisch einschalten" + }, + "unit": "s" + }*/ + TS_ITEM_BOOL(0xBC, "UsbEnDefault", &usb_pwr.enable, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + //TS_ITEM_FLOAT(0x56, "UsbDisconnect_V", &bat_conf_user.load_disconnect_voltage, 2, + // ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + //TS_ITEM_FLOAT(0x57, "UsbReconnect_V", &bat_conf_user.load_reconnect_voltage, 2, + // ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), + + /*{ + "title": { + "en": "USB low voltage disconnect recovery delay", + "de": "Wiedereinschalt-Verzögerung USB nach Unterspannung" + }, + "unit": "s" + }*/ + TS_ITEM_UINT32(0xBD, "UsbUVRecovery_s", &usb_pwr.lvd_recovery_delay, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), +#endif + +#if CONFIG_THINGSET_CAN + /*{ + "title": { + "en": "CAN Node Address", + "de": "CAN Node-Adresse" + } + }*/ + TS_ITEM_UINT16(0xBE, "CanAddress", &can_node_addr, + ID_CONF, TS_ANY_R | TS_ANY_W, SUBSET_NVM), +#endif + + // CALIBRATION DATA /////////////////////////////////////////////////////// + // using IDs >= 0xD0 + + TS_GROUP(ID_CAL, "cal", TS_NO_CALLBACK, ID_ROOT), + +#if BOARD_HAS_DCDC + /*{ + "title": { + "en": "DC/DC minimum output power w/o shutdown", + "de": "DC/DC Mindest-Leistung vor Abschaltung" + }, + "unit": "W" + }*/ + TS_ITEM_FLOAT(0xD0, "DcdcMin_W", &dcdc.output_power_min, 1, + ID_CAL, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "Absolute Maximum Solar Voltage", + "de": "Maximal erlaubte Solar-Spannung" + }, + "unit": "V" + }*/ + TS_ITEM_FLOAT(0xD1, "SolarAbsMax_V", &dcdc.hs_voltage_max, 1, + ID_CAL, TS_ANY_R | TS_MKR_W, SUBSET_NVM), + + /*{ + "title": { + "en": "DC/DC Restart Interval", + "de": "DC/DC Restart Intervall" + }, + "unit": "s" + }*/ + TS_ITEM_UINT32(0xD2, "DcdcRestart_s", &dcdc.restart_interval, + ID_CAL, TS_ANY_R | TS_MKR_W, SUBSET_NVM), +#endif + + /* + * Remote procedure calls (IDs >= 0xE0) + */ + TS_GROUP(ID_RPC, "rpc", TS_NO_CALLBACK, ID_ROOT), + + /*{ + "title": { + "en": "Reset the Device", + "de": "Gerät zurücksetzen" + } + }*/ + TS_FUNCTION(0xE0, "x-reset", &reset_device, ID_RPC, TS_ANY_RW), + + /* 0xE2 reserved (previously used for bootloader-stm) */ + + /*{ + "title": { + "en": "Save Settings to EEPROM", + "de": "Einstellungen ins EEPROM schreiben" + } + }*/ + TS_FUNCTION(0xE1, "x-save-settings", &data_storage_write, ID_RPC, TS_ANY_RW), + + /*{ + "title": { + "en": "Thingset Authentication", + "de": "Thingset Anmeldung" + } + }*/ + TS_FUNCTION(0xEE, "x-auth", &thingset_auth, ID_ROOT, TS_ANY_RW), + TS_ITEM_STRING(0xEF, "Password", auth_password, sizeof(auth_password), 0xEE, TS_ANY_RW, 0), + + // DEVICE FIRMWARE UPGRADE (DFU) ////////////////////////////////////////// + // using IDs >= 0xF0 + + TS_GROUP(ID_DFU, "dfu", TS_NO_CALLBACK, ID_ROOT), + + /*{ + "title": { + "en": "Start the Bootloader", + "de": "Bootloader starten" + } + }*/ + TS_FUNCTION(0xF0, "bootloader-stm", &start_stm32_bootloader, 0xF0, TS_ANY_RW), + + /*{ + "title": { + "en": "Flash Memory Size", + "de": "Flash-Speicher Gesamtgröße" + }, + "unit": "KiB" + }*/ + TS_ITEM_UINT32(0xF1, "FlashSize_KiB", &flash_size, 0xF0, TS_ANY_R, 0), + + /*{ + "title": { + "en": "Flash Memory Page Size", + "de": "Flash-Speicher Seitengröße" + }, + "unit": "B" + }*/ + TS_ITEM_UINT32(0xF2, "FlashPageSize_B", &flash_page_size, 0xF0, TS_ANY_R, 0), + + // PUBLICATION DATA /////////////////////////////////////////////////////// + // using IDs >= 0x100 + + TS_SUBSET(0x0A, "serial", SUBSET_SER, ID_ROOT, TS_ANY_RW), +#if CONFIG_THINGSET_CAN + TS_SUBSET(0x0B, "can", SUBSET_CAN, ID_ROOT, TS_ANY_RW), +#endif + + TS_GROUP(ID_PUB, ".pub", TS_NO_CALLBACK, ID_ROOT), + + TS_GROUP(0x101, "serial", NULL, ID_PUB), + + /*{ + "title": { + "en": "Enable/Disable serial publications", + "de": "Serielle Publikation (de)aktivieren" + } + }*/ + TS_ITEM_BOOL(0x102, "Enable", &pub_serial_enable, 0x101, TS_ANY_RW, 0), + +#if CONFIG_THINGSET_CAN + TS_GROUP(0x103, "can", TS_NO_CALLBACK, ID_PUB), + + /*{ + "title": { + "en": "Enable/Disable CAN publications", + "de": "CAN Publikation (de)aktivieren" + } + }*/ + TS_ITEM_BOOL(0x104, "Enable", &pub_can_enable, 0x103, TS_ANY_RW, 0), +#endif + + /* + * Control parameters (IDs >= 0x8000) + * + * Temporarily choosing free IDs >= 0x7000 for testing. + */ + TS_GROUP(ID_CTRL, "ctrl", TS_NO_CALLBACK, ID_PUB), + + /*{ + "title": { + "en": "Current control target", + "de": "Sollwert Strom-Regelung" + }, + "unit": "A" + }*/ + TS_ITEM_FLOAT(0x7001, "CtrlTarget_A", &charger.target_current_control, 1, + ID_CTRL, TS_ANY_RW, SUBSET_CTRL), +}; + +ThingSet ts(data_objects, sizeof(data_objects)/sizeof(ThingSetDataObject)); + +void data_objects_update_conf() +{ + bool changed; + if (battery_conf_check(&bat_conf_user)) { + LOG_INF("New config valid and activated."); + battery_conf_overwrite(&bat_conf_user, &bat_conf, &charger); +#if BOARD_HAS_LOAD_OUTPUT + load.set_voltage_limits(bat_conf.load_disconnect_voltage, bat_conf.load_reconnect_voltage, + bat_conf.absolute_max_voltage); +#endif + changed = true; + } + else { + LOG_ERR("Requested config change not valid and rejected."); + battery_conf_overwrite(&bat_conf, &bat_conf_user); + changed = false; + } + + // TODO: check also for changes in Load/USB EnDefault + changed = true; // temporary hack + + if (changed) { + data_storage_write(); + } +} + +void data_objects_init() +{ +#ifndef UNIT_TEST + uint8_t buf[12]; + hwinfo_get_device_id(buf, sizeof(buf)); + + uint64_t id64 = crc32_ieee(buf, sizeof(buf)); + id64 += ((uint64_t)CONFIG_LIBRE_SOLAR_TYPE_ID) << 32; + + uint64_to_base32(id64, device_id, sizeof(device_id), alphabet_crockford); +#endif + + data_storage_read(); + if (battery_conf_check(&bat_conf_user)) { + battery_conf_overwrite(&bat_conf_user, &bat_conf, &charger); + } + else { + battery_conf_overwrite(&bat_conf, &bat_conf_user); + } +} + +void thingset_auth() +{ + static const char pass_exp[] = CONFIG_THINGSET_EXPERT_PASSWORD; + static const char pass_mkr[] = CONFIG_THINGSET_MAKER_PASSWORD; + + if (strlen(pass_exp) == strlen(auth_password) && + strncmp(auth_password, pass_exp, strlen(pass_exp)) == 0) + { + LOG_INF("Authenticated as expert user."); + ts.set_authentication(TS_EXP_MASK | TS_USR_MASK); + } + else if (strlen(pass_mkr) == strlen(auth_password) && + strncmp(auth_password, pass_mkr, strlen(pass_mkr)) == 0) + { + LOG_INF("Authenticated as maker."); + ts.set_authentication(TS_MKR_MASK | TS_USR_MASK); + } + else { + LOG_INF("Reset authentication."); + ts.set_authentication(TS_USR_MASK); + } +} + +void uint64_to_base32(uint64_t in, char *out, size_t size, const char *alphabet) +{ + // 13 is the maximum number of characters needed to encode 64-bit variable to base32 + int len = (size > 13) ? 13 : size; + + // find out actual length of output string + for (int i = 0; i < len; i++) { + if ((in >> (i * 5)) == 0) { + len = i; + break; + } + } + + for (int i = 0; i < len; i++) { + out[len-i-1] = alphabet[(in >> (i * 5)) % 32]; + } + out[len] = '\0'; +} + +void update_control() +{ + charger.time_last_ctrl_msg = uptime(); +} + +#endif /* CUSTOM_DATA_OBJECTS_FILE */ diff --git a/app/src/data_objects.h b/app/src/data_objects.h new file mode 100644 index 0000000..b8f5c57 --- /dev/null +++ b/app/src/data_objects.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifndef DATA_OBJECTS_H_ +#define DATA_OBJECTS_H_ + +/** @file + * + * @brief Handling of ThingSet data objects + */ + +#include +#include + +/* + * Categories / first layer node IDs + */ +#define ID_ROOT 0x00 +#define ID_INFO 0x01 // read-only device information (e.g. manufacturer, device ID) +#define ID_MEAS 0x02 // output data (e.g. measurement values) +#define ID_STATE 0x03 // recorded data (history-dependent) +#define ID_REC 0x04 // recorded data (history-dependent) +#define ID_INPUT 0x05 // input data (e.g. set-points) +#define ID_CONF 0x06 // configurable settings +#define ID_CAL 0x07 // calibration +#define ID_REPORT 0x0A // reports +#define ID_RPC 0x0E // remote procedure calls +#define ID_DFU 0x0F // device firmware upgrade +#define ID_PUB 0x100 // publication setup +#define ID_CTRL 0x8000 // control functions + +/* + * Subset definitions for statements and publish/subscribe + */ +#define SUBSET_SER (1U << 0) // UART serial +#define SUBSET_CAN (1U << 1) // CAN bus +#define SUBSET_NVM (1U << 2) // data that should be stored in EEPROM +#define SUBSET_CTRL (1U << 3) // control data sent and received via CAN + +/* + * Data object versioning for EEPROM + * + * Increment the version number each time any data object IDs stored in NVM are changed. Otherwise + * data might get corrupted. + */ +#define DATA_OBJECTS_VERSION 05 + +extern bool pub_serial_enable; +extern bool pub_can_enable; + +/** + * Callback function to be called when conf values were changed + */ +void data_objects_update_conf(); + +/** + * Initializes and reads data objects from EEPROM + */ +void data_objects_init(); + +/** + * Callback to provide authentication mechanism via ThingSet + */ +void thingset_auth(); + +/** + * Alphabet used for base32 encoding + * + * https://en.wikipedia.org/wiki/Base32#Crockford's_Base32 + */ +const char alphabet_crockford[] = "0123456789abcdefghjkmnpqrstvwxyz"; + +/** + * Convert numeric device ID to base32 string + */ +void uint64_to_base32(uint64_t in, char *out, size_t size, const char *alphabet); + +/** + * Update control values received via CAN + */ +void update_control(); + +#endif /* DATA_OBJECTS_H */ diff --git a/src/data_storage.cpp b/app/src/data_storage.cpp similarity index 86% rename from src/data_storage.cpp rename to app/src/data_storage.cpp index 852e373..fe4d97d 100644 --- a/src/data_storage.cpp +++ b/app/src/data_storage.cpp @@ -10,18 +10,18 @@ #include "mcu.h" #include "thingset.h" -#include "data_nodes.h" +#include "data_objects.h" #include "helper.h" #include -#ifndef UNIT_TEST +#ifdef CONFIG_SOC_FAMILY_STM32 #include -#include -LOG_MODULE_REGISTER(nvs, CONFIG_DATA_STORAGE_LOG_LEVEL); #include +LOG_MODULE_REGISTER(nvs, CONFIG_DATA_STORAGE_LOG_LEVEL); + K_MUTEX_DEFINE(data_buf_lock); // Buffer used by store and restore functions (must be word-aligned for hardware CRC calculation) @@ -61,7 +61,7 @@ uint32_t _calc_crc(const uint8_t *buf, size_t len) /* * EEPROM header bytes: - * - 0-1: Data nodes version number + * - 0-1: Data objects version number * - 2-3: Number of data bytes * - 4-7: CRC32 * @@ -90,7 +90,7 @@ void data_storage_read() buf_header[0], buf_header[1], buf_header[2], buf_header[3], buf_header[4], buf_header[5], buf_header[6], buf_header[7]); - if (version == DATA_NODES_VERSION && len <= sizeof(buf)) { + if (version == DATA_OBJECTS_VERSION && len <= sizeof(buf)) { k_mutex_lock(&data_buf_lock, K_FOREVER); err = eeprom_read(eeprom_dev, EEPROM_HEADER_SIZE, buf, len); @@ -98,8 +98,8 @@ void data_storage_read() //for (int i = 0; i < len; i++) printf("%.2x ", buf[i]); if (_calc_crc(buf, len) == crc) { - int status = ts.bin_sub(buf, sizeof(buf), TS_WRITE_MASK, PUB_NVM); - LOG_INF("EEPROM read and data nodes updated, ThingSet result: 0x%x", status); + int status = ts.bin_import(buf, sizeof(buf), TS_WRITE_MASK, SUBSET_NVM); + LOG_INF("EEPROM read and data objects updated, ThingSet result: 0x%x", status); } else { LOG_ERR("EEPROM data CRC invalid, expected 0x%x (data_len = %d)", @@ -120,10 +120,10 @@ void data_storage_write() k_mutex_lock(&data_buf_lock, K_FOREVER); - int len = ts.bin_pub(buf + EEPROM_HEADER_SIZE, sizeof(buf) - EEPROM_HEADER_SIZE, PUB_NVM); + int len = ts.bin_export(buf + EEPROM_HEADER_SIZE, sizeof(buf) - EEPROM_HEADER_SIZE, SUBSET_NVM); uint32_t crc = _calc_crc(buf + EEPROM_HEADER_SIZE, len); - *((uint16_t*)&buf[0]) = (uint16_t)DATA_NODES_VERSION; + *((uint16_t*)&buf[0]) = (uint16_t)DATA_OBJECTS_VERSION; *((uint16_t*)&buf[2]) = (uint16_t)(len); *((uint32_t*)&buf[4]) = crc; @@ -156,7 +156,7 @@ void data_storage_write() /* * NVS header bytes: - * - 0-1: Data nodes version number + * - 0-1: Data objects version number * * Data starts from byte 2 */ @@ -208,12 +208,12 @@ void data_storage_read() uint16_t version = *((uint16_t*)&buf[0]); - if (version == DATA_NODES_VERSION) { + if (version == DATA_OBJECTS_VERSION) { k_mutex_lock(&data_buf_lock, K_FOREVER); - int status = ts.bin_sub(buf + NVS_HEADER_SIZE, num_bytes - NVS_HEADER_SIZE, - TS_WRITE_MASK, PUB_NVM); - LOG_INF("NVS read and data nodes updated, ThingSet result: 0x%x", status); + int status = ts.bin_import(buf + NVS_HEADER_SIZE, num_bytes - NVS_HEADER_SIZE, + TS_WRITE_MASK, SUBSET_NVM); + LOG_INF("NVS read and data objects updated, ThingSet result: 0x%x", status); k_mutex_unlock(&data_buf_lock); } @@ -230,9 +230,9 @@ void data_storage_write() k_mutex_lock(&data_buf_lock, K_FOREVER); - *((uint16_t*)&buf[0]) = (uint16_t)DATA_NODES_VERSION; + *((uint16_t*)&buf[0]) = (uint16_t)DATA_OBJECTS_VERSION; - int len = ts.bin_pub(buf + NVS_HEADER_SIZE, sizeof(buf) - NVS_HEADER_SIZE, PUB_NVM); + int len = ts.bin_export(buf + NVS_HEADER_SIZE, sizeof(buf) - NVS_HEADER_SIZE, SUBSET_NVM); if (len == 0) { LOG_ERR("NVS data could not be stored. ThingSet error (len = %d)", len); diff --git a/src/data_storage.h b/app/src/data_storage.h similarity index 100% rename from src/data_storage.h rename to app/src/data_storage.h diff --git a/src/dcdc.cpp b/app/src/dcdc.cpp similarity index 88% rename from src/dcdc.cpp rename to app/src/dcdc.cpp index f8427bf..afd69ef 100644 --- a/src/dcdc.cpp +++ b/app/src/dcdc.cpp @@ -8,14 +8,9 @@ #include -#ifndef UNIT_TEST #include #include -#include -LOG_MODULE_REGISTER(dcdc, CONFIG_DCDC_LOG_LEVEL); -#endif - #include // for fabs function #include // for min/max function #include @@ -26,6 +21,8 @@ LOG_MODULE_REGISTER(dcdc, CONFIG_DCDC_LOG_LEVEL); #include "data_storage.h" #include "setup.h" +LOG_MODULE_REGISTER(dcdc, CONFIG_DCDC_LOG_LEVEL); + extern DeviceStatus dev_stat; #if BOARD_HAS_DCDC @@ -208,20 +205,15 @@ bool Dcdc::check_hs_mosfet_short() bool Dcdc::startup_inhibit(bool reset) { - // wait at least 100 ms for voltages to settle - static const int num_wait_calls = - (CONFIG_CONTROL_FREQUENCY / 10 >= 1) ? (CONFIG_CONTROL_FREQUENCY / 10) : 1; - - static int startup_delay_counter = 0; + static uint32_t inhibit_start; if (reset) { - startup_delay_counter = 0; + inhibit_start = uptime(); + return true; } else { - startup_delay_counter++; + return (uptime() < inhibit_start + DCDC_STARTUP_INHIBIT_TIME); } - - return (startup_delay_counter < num_wait_calls); } __weak void Dcdc::control() @@ -291,27 +283,40 @@ __weak void Dcdc::control() void Dcdc::test() { if (half_bridge_enabled()) { - if (half_bridge_get_duty_cycle() > 0.5) { - half_bridge_set_ccr(half_bridge_get_ccr() - 1); + const char *stop_reason = NULL; + if (lvb->voltage > ls_voltage_max || hvb->voltage > hs_voltage_max) { + stop_reason = "emergency (voltage limits exceeded)"; + } + else if (enable == false) { + stop_reason = "disabled"; + } + else { + if (half_bridge_get_duty_cycle() > 0.50) { + half_bridge_set_ccr(half_bridge_get_ccr() - 1); + } + else { + half_bridge_set_ccr(half_bridge_get_ccr() + 1); + } + } + if (stop_reason != NULL) { + stop(); + printf("DC/DC Stop: %s.\n", stop_reason); } } else { - static int startup_delay_counter = 0; - - // wait at least 100 ms for voltages to settle - static const int num_wait_calls = - (CONFIG_CONTROL_FREQUENCY / 10 >= 1) ? (CONFIG_CONTROL_FREQUENCY / 10) : 1; - - if (startup_delay_counter > num_wait_calls) { - if (check_start_conditions() != DCDC_MODE_OFF) { - half_bridge_set_duty_cycle(lvb->voltage / hvb->voltage); - half_bridge_start(); - printf("DC/DC test mode start (HV: %.2fV, LV: %.2fV, PWM: %.1f).\n", - hvb->voltage, lvb->voltage, half_bridge_get_duty_cycle() * 100); + if (check_start_conditions() != DCDC_MODE_OFF) { + // startup allowed, but we need to wait until voltages settle + if (startup_inhibit()) { + return; } + + half_bridge_set_duty_cycle(lvb->voltage / hvb->voltage); + half_bridge_start(); + printf("DC/DC test mode start (HV: %.2fV, LV: %.2fV, PWM: %.1f).\n", + hvb->voltage, lvb->voltage, half_bridge_get_duty_cycle() * 100); } else { - startup_delay_counter++; + startup_inhibit(true); // reset inhibit counter } } } diff --git a/src/dcdc.h b/app/src/dcdc.h similarity index 98% rename from src/dcdc.h rename to app/src/dcdc.h index 78fff62..bc26367 100644 --- a/src/dcdc.h +++ b/app/src/dcdc.h @@ -20,6 +20,8 @@ #include "power_port.h" +#define DCDC_STARTUP_INHIBIT_TIME 3 // seconds + /** * DC/DC operation mode * @@ -108,7 +110,7 @@ public: void control(); /** - * Test mode for DC/DC, ramping up to 50% duty cycle + * Test mode for DC/DC, ramping up/down to 50% duty cycle */ void test(); diff --git a/src/device_status.cpp b/app/src/device_status.cpp similarity index 100% rename from src/device_status.cpp rename to app/src/device_status.cpp diff --git a/src/device_status.h b/app/src/device_status.h similarity index 100% rename from src/device_status.h rename to app/src/device_status.h diff --git a/src/ext/CMakeLists.txt b/app/src/ext/CMakeLists.txt similarity index 100% rename from src/ext/CMakeLists.txt rename to app/src/ext/CMakeLists.txt diff --git a/src/ext/README.md b/app/src/ext/README.md similarity index 100% rename from src/ext/README.md rename to app/src/ext/README.md diff --git a/app/src/ext/can.cpp b/app/src/ext/can.cpp new file mode 100644 index 0000000..0cec36b --- /dev/null +++ b/app/src/ext/can.cpp @@ -0,0 +1,264 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#if CONFIG_THINGSET_CAN + +#include +#include +#include +#include +#include + +#ifdef CONFIG_ISOTP +#include +#endif + +#include +LOG_MODULE_REGISTER(ext_can, CONFIG_CAN_LOG_LEVEL); + +#include "data_objects.h" +#include "hardware.h" +#include "thingset.h" +#include "bat_charger.h" +#include "helper.h" + +#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), can_en)) +#define CAN_EN_GPIO DT_CHILD(DT_PATH(outputs), can_en) +#endif + +extern ThingSet ts; +extern uint16_t can_node_addr; +extern Charger charger; + +static const struct device *can_dev = DEVICE_DT_GET(DT_NODELABEL(can1)); + +#ifdef CONFIG_ISOTP + +#define RX_THREAD_STACK_SIZE 1024 +#define RX_THREAD_PRIORITY 2 + +const struct isotp_fc_opts fc_opts = { + .bs = 8, // block size + .stmin = 1 // minimum separation time = 100 ms +}; + +struct isotp_msg_id rx_addr = { + .id_type = CAN_EXTENDED_IDENTIFIER, + .use_ext_addr = 0, // Normal ISO-TP addressing (using only CAN ID) + .use_fixed_addr = 1, // enable SAE J1939 compatible addressing +}; + +struct isotp_msg_id tx_addr = { + .id_type = CAN_EXTENDED_IDENTIFIER, + .use_ext_addr = 0, // Normal ISO-TP addressing (using only CAN ID) + .use_fixed_addr = 1, // enable SAE J1939 compatible addressing +}; + +static struct isotp_recv_ctx recv_ctx; +static struct isotp_send_ctx send_ctx; + +void send_complete_cb(int error_nr, void *arg) +{ + ARG_UNUSED(arg); + LOG_DBG("TX complete callback, err: %d", error_nr); +} + +void can_isotp_thread() +{ + int ret, rem_len, resp_len; + unsigned int req_len; + struct net_buf *buf; + static uint8_t rx_buffer[600]; // large enough to receive a 512k flash page for DFU + static uint8_t tx_buffer[1000]; + + if (!device_is_ready(can_dev)) { + return; + } + + while (1) { + /* re-assign address in every loop as it may have been changed via ThingSet */ + rx_addr.ext_id = TS_CAN_BASE_REQRESP | TS_CAN_PRIO_REQRESP | + TS_CAN_TARGET_SET(can_node_addr); + tx_addr.ext_id = TS_CAN_BASE_REQRESP | TS_CAN_PRIO_REQRESP | + TS_CAN_SOURCE_SET(can_node_addr); + + ret = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr, &fc_opts, K_FOREVER); + if (ret != ISOTP_N_OK) { + LOG_DBG("Failed to bind to rx ID %d [%d]", rx_addr.ext_id, ret); + return; + } + + req_len = 0; + do { + rem_len = isotp_recv_net(&recv_ctx, &buf, K_FOREVER); + if (rem_len < 0) { + LOG_DBG("Receiving error [%d]", rem_len); + break; + } + if (req_len + buf->len <= sizeof(rx_buffer)) { + memcpy(&rx_buffer[req_len], buf->data, buf->len); + } + req_len += buf->len; + net_buf_unref(buf); + } while (rem_len); + + // we need to unbind the receive ctx so that control frames are received in the send ctx + isotp_unbind(&recv_ctx); + + if (req_len > sizeof(rx_buffer)) { + LOG_DBG("RX buffer too small"); + tx_buffer[0] = TS_STATUS_REQUEST_TOO_LARGE; + resp_len = 1; + } + else if (req_len > 0 && rem_len == 0) { + LOG_INF("Got %d bytes via ISO-TP. Processing ThingSet message.", req_len); + resp_len = ts.process(rx_buffer, req_len, tx_buffer, sizeof(tx_buffer)); + LOG_DBG("TX buf: %x %x %x %x", tx_buffer[0], tx_buffer[1], tx_buffer[2], tx_buffer[3]); + } + else { + tx_buffer[0] = TS_STATUS_INTERNAL_SERVER_ERR; + resp_len = 1; + } + + if (resp_len > 0) { + ret = isotp_send(&send_ctx, can_dev, tx_buffer, resp_len, + &recv_ctx.tx_addr, &recv_ctx.rx_addr, send_complete_cb, NULL); + if (ret != ISOTP_N_OK) { + LOG_DBG("Error while sending data to ID %d [%d]", tx_addr.ext_id, ret); + } + } + } +} + +K_THREAD_DEFINE(can_isotp, RX_THREAD_STACK_SIZE, can_isotp_thread, NULL, NULL, NULL, + RX_THREAD_PRIORITY, 0, 1500); + +#endif /* CONFIG_ISOTP */ + +// below defines should go into the ThingSet library +#define TS_CAN_SOURCE_GET(id) (((uint32_t)id & TS_CAN_SOURCE_MASK) >> TS_CAN_SOURCE_POS) +#define TS_CAN_DATA_ID_GET(id) (((uint32_t)id & TS_CAN_DATA_ID_MASK) >> TS_CAN_DATA_ID_POS) + +CAN_DEFINE_MSGQ(sub_msgq, 10); + +const struct zcan_filter ctrl_filter = { + .id = TS_CAN_BASE_CONTROL, + .rtr = CAN_DATAFRAME, + .id_type = CAN_EXTENDED_IDENTIFIER, + .id_mask = TS_CAN_TYPE_MASK, + .rtr_mask = 1 +}; + +void can_pub_isr(uint32_t err_flags, void *arg) +{ + // Do nothing. Publication messages are fire and forget. +} + +void can_pub_send(uint32_t can_id, uint8_t can_data[8], uint8_t data_len) +{ + struct zcan_frame frame = {0}; + frame.id_type = CAN_EXTENDED_IDENTIFIER; + frame.rtr = CAN_DATAFRAME; + frame.id = can_id; + memcpy(frame.data, can_data, 8); + + if (data_len >= 0) { + frame.dlc = data_len; + + if (can_send(can_dev, &frame, K_MSEC(10), can_pub_isr, NULL) != CAN_TX_OK) { + LOG_DBG("Error sending CAN frame"); + } + } +} + +void can_pubsub_thread() +{ + int wdt_channel = task_wdt_add(2000, task_wdt_callback, (void *)k_current_get()); + + unsigned int can_id; + uint8_t can_data[8]; + struct zcan_frame rx_frame; + + const struct device *can_en_dev = device_get_binding(DT_GPIO_LABEL(CAN_EN_GPIO, gpios)); + gpio_pin_configure(can_en_dev, DT_GPIO_PIN(CAN_EN_GPIO, gpios), + DT_GPIO_FLAGS(CAN_EN_GPIO, gpios) | GPIO_OUTPUT_ACTIVE); + + if (!device_is_ready(can_dev)) { + return; + } + + int filter_id = can_attach_msgq(can_dev, &sub_msgq, &ctrl_filter); + if (filter_id < 0) { + LOG_ERR("Unable to attach ISR [%d]", filter_id); + return; + } + + int64_t next_pub = k_uptime_get(); + uint32_t count = 0; + + while (1) { + + task_wdt_feed(wdt_channel); + + if (pub_can_enable) { + int data_len = 0; + int start_pos = 0; + while (count % 10 == 0) { + // normal objects: only every second + data_len = ts.bin_pub_can(start_pos, SUBSET_CAN, can_node_addr, can_id, can_data); + if (data_len < 0) { + // finished with all IDs + break; + } + else { + can_pub_send(can_id, can_data, data_len); + } + } + + data_len = 0; + start_pos = 0; + while (true) { + // control objects: every 100 ms + data_len = ts.bin_pub_can(start_pos, SUBSET_CTRL, can_node_addr, can_id, can_data); + if (data_len < 0) { + break; + } + else { + can_pub_send(can_id, can_data, data_len); + } + } + } + + // wait for incoming messages until the next pub message has to be sent out + while (k_msgq_get(&sub_msgq, &rx_frame, K_TIMEOUT_ABS_MS(next_pub)) != -EAGAIN) { + // process message + uint16_t data_id = TS_CAN_DATA_ID_GET(rx_frame.id); + uint8_t sender_addr = TS_CAN_SOURCE_GET(rx_frame.id); + + // control message received? + if (data_id > 0x8000 && sender_addr < can_node_addr) { + uint8_t buf[4 + 8]; // ThingSet bin headers + CAN frame payload + buf[0] = 0xA1; // CBOR: map with 1 element + buf[1] = 0x19; // CBOR: uint16 follows + buf[2] = data_id >> 8; + buf[3] = data_id; + memcpy(&buf[4], rx_frame.data, 8); + + int status = ts.bin_import(buf, 4 + rx_frame.dlc, TS_WRITE_MASK, SUBSET_CTRL); + if (status == TS_STATUS_CHANGED) { + charger.time_last_ctrl_msg = uptime(); + } + } + } + + next_pub += 100; // 100 ms period (currently fixed) + count++; + } +} + +K_THREAD_DEFINE(can_pubsub, 1024, can_pubsub_thread, NULL, NULL, NULL, 6, 0, 1000); + +#endif /* CONFIG_THINGSET_CAN */ diff --git a/src/ext/oled.cpp b/app/src/ext/oled.cpp similarity index 100% rename from src/ext/oled.cpp rename to app/src/ext/oled.cpp diff --git a/app/src/ext/serial.cpp b/app/src/ext/serial.cpp new file mode 100644 index 0000000..eb8cb2e --- /dev/null +++ b/app/src/ext/serial.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#if CONFIG_THINGSET_SERIAL + +#include +#include + +#include +#include +#include +#include + +#include "thingset.h" +#include "hardware.h" +#include "data_objects.h" + +#if CONFIG_UEXT_SERIAL_THINGSET +#define UART_DEVICE_NODE DT_ALIAS(uart_uext) +#elif DT_NODE_EXISTS(DT_ALIAS(uart_dbg)) +#define UART_DEVICE_NODE DT_ALIAS(uart_dbg) +#else +// cppcheck-suppress preprocessorErrorDirective +#error "No UART for ThingSet serial defined." +#endif + +static const struct device *uart_dev = DEVICE_DT_GET(UART_DEVICE_NODE); + +static char tx_buf[CONFIG_THINGSET_SERIAL_TX_BUF_SIZE]; +static char rx_buf[CONFIG_THINGSET_SERIAL_RX_BUF_SIZE]; + +static volatile size_t rx_buf_pos = 0; + +static struct k_sem command_flag; // used as an event to signal a received command +static struct k_sem rx_buf_mutex; // binary semaphore used as mutex in ISR context + +extern ThingSet ts; + +const char serial_subset_path[] = "serial"; +static ThingSetDataObject *serial_subset; + +void serial_pub_msg() +{ + if (pub_serial_enable) { + int len = ts.txt_statement(tx_buf, sizeof(tx_buf), serial_subset); + for (int i = 0; i < len; i++) { + uart_poll_out(uart_dev, tx_buf[i]); + } + uart_poll_out(uart_dev, '\n'); + } +} + +void serial_process_command() +{ + // commands must have 2 or more characters + if (rx_buf_pos > 1) { + printf("Received Request (%d bytes): %s\n", strlen(rx_buf), rx_buf); + + int len = ts.process((uint8_t *)rx_buf, strlen(rx_buf), + (uint8_t *)tx_buf, sizeof(tx_buf)); + + for (int i = 0; i < len; i++) { + uart_poll_out(uart_dev, tx_buf[i]); + } + uart_poll_out(uart_dev, '\n'); + } + + // release buffer and start waiting for new commands + rx_buf_pos = 0; + k_sem_give(&rx_buf_mutex); +} + +/* + * Read characters from stream until line end \n is detected, afterwards signal available command. + */ +void serial_cb(const struct device *dev, void* user_data) +{ + uint8_t c; + + if (!uart_irq_update(uart_dev)) { + return; + } + + while (uart_irq_rx_ready(uart_dev) && k_sem_take(&rx_buf_mutex, K_NO_WAIT) == 0) { + + uart_fifo_read(uart_dev, &c, 1); + + // \r\n and \n are markers for line end, i.e. command end + // we accept this at any time, even if the buffer is 'full', since + // there is always one last character left for the \0 + if (c == '\n') { + if (rx_buf_pos > 0 && rx_buf[rx_buf_pos-1] == '\r') { + rx_buf[rx_buf_pos-1] = '\0'; + } + else { + rx_buf[rx_buf_pos] = '\0'; + } + // start processing command and keep the rx_buf_mutex locked + k_sem_give(&command_flag); + return; + } + // backspace allowed if there is something in the buffer already + else if (rx_buf_pos > 0 && c == '\b') { + rx_buf_pos--; + } + // Fill the buffer up to all but 1 character (the last character is reserved for '\0') + // Characters beyond the size of the buffer are dropped. + else if (rx_buf_pos < (sizeof(rx_buf) - 1)) { + rx_buf[rx_buf_pos++] = c; + } + + k_sem_give(&rx_buf_mutex); + } +} + +void serial_thread() +{ + k_sem_init(&command_flag, 0, 1); + k_sem_init(&rx_buf_mutex, 1, 1); + + __ASSERT_NO_MSG(device_is_ready(uart_dev)); + + uart_irq_callback_user_data_set(uart_dev, serial_cb, NULL); + uart_irq_rx_enable(uart_dev); + + serial_subset = ts.get_endpoint(serial_subset_path, strlen(serial_subset_path)); + + // below process loop should be run at least once per sec, setting watchdog timeout to 1.5s + int wdt_channel = task_wdt_add(1500, task_wdt_callback, (void *)k_current_get()); + + int64_t t_start = k_uptime_get(); + + while (true) { + if (k_sem_take(&command_flag, K_TIMEOUT_ABS_MS(t_start)) == 0) { + serial_process_command(); + } + else { + // semaphore timed out (should happen exactly every 1 second) + t_start += 1000; + serial_pub_msg(); + } + task_wdt_feed(wdt_channel); + } +} + +K_THREAD_DEFINE(serial_thread_id, 1280, serial_thread, NULL, NULL, NULL, 6, 0, 1000); + +#endif /* CONFIG_THINGSET_SERIAL */ diff --git a/src/half_bridge.cpp b/app/src/half_bridge.cpp similarity index 99% rename from src/half_bridge.cpp rename to app/src/half_bridge.cpp index 2c4c8f3..19b1de6 100644 --- a/src/half_bridge.cpp +++ b/app/src/half_bridge.cpp @@ -13,9 +13,9 @@ #include "mcu.h" #include "setup.h" -#ifndef UNIT_TEST +#ifdef CONFIG_SOC_FAMILY_STM32 #include -#include +#include #include #endif @@ -44,7 +44,7 @@ static uint16_t clamp_ccr(uint16_t ccr_target) } } -#ifndef UNIT_TEST +#ifdef CONFIG_SOC_FAMILY_STM32 static const struct soc_gpio_pinctrl tim_pinctrl[] = ST_STM32_DT_INST_PINCTRL(0, 0); diff --git a/src/half_bridge.h b/app/src/half_bridge.h similarity index 100% rename from src/half_bridge.h rename to app/src/half_bridge.h diff --git a/src/hardware.cpp b/app/src/hardware.cpp similarity index 53% rename from src/hardware.cpp rename to app/src/hardware.cpp index 6d9a9b2..465ea5f 100644 --- a/src/hardware.cpp +++ b/app/src/hardware.cpp @@ -8,6 +8,7 @@ #include "mcu.h" #include "load.h" +#include "helper.h" #include "half_bridge.h" #include "leds.h" #include "setup.h" @@ -21,13 +22,11 @@ #include #include -#include LOG_MODULE_REGISTER(hardware, CONFIG_HW_LOG_LEVEL); void start_stm32_bootloader() { #if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), boot0)) - // pin is connected to BOOT0 via resistor and capacitor const struct device *dev = device_get_binding(DT_GPIO_LABEL(BOOT0_GPIO, gpios)); gpio_pin_configure(dev, DT_GPIO_PIN(BOOT0_GPIO, gpios), @@ -35,6 +34,37 @@ void start_stm32_bootloader() k_sleep(K_MSEC(100)); // wait for capacitor at BOOT0 pin to charge up reset_device(); +#elif defined(CONFIG_SOC_SERIES_STM32G4X) + if ((FLASH->CR & FLASH_CR_OPTLOCK) != 0U) { + /* Authorizes the Option Byte register programming */ + FLASH->OPTKEYR = FLASH_OPTKEY1; + FLASH->OPTKEYR = FLASH_OPTKEY2; + } + + // Set proper bits for booting the embedded bootloader (see table + // 5 in section 2.6.1 in document RM0440) + + // nBOOT0: nBOOT0 option bit (equivalent to the BOOT0 pin) + // nSWBOOT0: 0: BOOT0 taken from the option bit nBOOT0 + // nSWBOOT0: 1: BOOT0 taken from PB8/BOOT0 pin + // nBOOT1: Together with the BOOT0 pin, this bit selects boot mode + // from the Flash main memory, SRAM1 or the System memory. + + FLASH->OPTR &= ~(FLASH_OPTR_nSWBOOT0 | FLASH_OPTR_nBOOT0); + FLASH->OPTR |= FLASH_OPTR_nBOOT1; + + // Save the current registers in flash, to be reloaded at reset + FLASH->CR |= FLASH_CR_OPTSTRT; + k_sleep(K_MSEC(20)); + + // Reload the option registers from flash; should trigger a system + // reset. + FLASH->CR |= FLASH_CR_OBL_LAUNCH; + + // If OBL_LAUNCH did not reset (it should), we'll force it by + // first locking back the flash registers and going for a reboot. + FLASH->CR |= FLASH_CR_OPTLOCK; + reset_device(); #endif } diff --git a/src/hardware.h b/app/src/hardware.h similarity index 100% rename from src/hardware.h rename to app/src/hardware.h diff --git a/src/helper.h b/app/src/helper.h similarity index 74% rename from src/helper.h rename to app/src/helper.h index c381feb..66bda2e 100644 --- a/src/helper.h +++ b/app/src/helper.h @@ -17,6 +17,28 @@ #include #include +#ifdef __INTELLISENSE__ +/* + * VS Code intellisense can't cope with all the Zephyr macro layers for logging, so provide it + * with something more simple and make it silent. + */ + +#define LOG_DBG(...) printf(__VA_ARGS__) + +#define LOG_INF(...) printf(__VA_ARGS__) + +#define LOG_WRN(...) printf(__VA_ARGS__) + +#define LOG_ERR(...) printf(__VA_ARGS__) + +#define LOG_MODULE_REGISTER(...) + +#else + +#include + +#endif /* VSCODE_INTELLISENSE_HACK */ + #include #ifdef __cplusplus @@ -30,7 +52,7 @@ extern "C" { */ static inline uint32_t uptime() { -#ifdef __ZEPHYR__ +#ifndef UNIT_TEST return k_uptime_get() / 1000; #else return time(NULL); diff --git a/src/leds.cpp b/app/src/leds.cpp similarity index 99% rename from src/leds.cpp rename to app/src/leds.cpp index beb96d6..6c9bf91 100644 --- a/src/leds.cpp +++ b/app/src/leds.cpp @@ -7,10 +7,8 @@ #include "leds.h" #include -#ifndef UNIT_TEST #include #include -#endif #include "hardware.h" diff --git a/src/leds.h b/app/src/leds.h similarity index 100% rename from src/leds.h rename to app/src/leds.h diff --git a/src/load.cpp b/app/src/load.cpp similarity index 100% rename from src/load.cpp rename to app/src/load.cpp diff --git a/src/load.h b/app/src/load.h similarity index 97% rename from src/load.h rename to app/src/load.h index e0737dc..d46956e 100644 --- a/src/load.h +++ b/app/src/load.h @@ -137,14 +137,14 @@ public: ///< battery is empty or any errors occured) time_t oc_timestamp; ///< Time when last overcurrent event occured - int32_t oc_recovery_delay; ///< Seconds before we attempt to re-enable the load + uint32_t oc_recovery_delay; ///< Seconds before we attempt to re-enable the load ///< after an overcurrent event float disconnect_voltage = 0; ///< Low voltage disconnect (LVD) setpoint float reconnect_voltage = 0; ///< Low voltage reconnect (LVD) setpoint time_t lvd_timestamp; ///< Time when last low voltage disconnect happened - int32_t lvd_recovery_delay; ///< Seconds before we re-enable the load after a low voltage + uint32_t lvd_recovery_delay;///< Seconds before we re-enable the load after a low voltage ///< disconnect float junction_temperature; ///< calculated using thermal model based on current and ambient diff --git a/src/load_driver.c b/app/src/load_driver.c similarity index 93% rename from src/load_driver.c rename to app/src/load_driver.c index 1f805f7..965ea9c 100644 --- a/src/load_driver.c +++ b/app/src/load_driver.c @@ -6,7 +6,7 @@ #include "load.h" -#ifndef UNIT_TEST +#ifdef CONFIG_SOC_FAMILY_STM32 #include #include @@ -180,14 +180,15 @@ void usb_out_set(bool status) #if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), charge_pump)) -#define CP_PWM_CONTROLLER (DT_PWMS_LABEL(DT_CHILD(DT_PATH(outputs), charge_pump))) -#define CP_PWM_PERIOD (DT_PHA(DT_CHILD(DT_PATH(outputs), charge_pump), pwms, period)) -#define CP_PWM_CHANNEL (DT_PHA(DT_CHILD(DT_PATH(outputs), charge_pump), pwms, channel)) +#define CP_PWMS DT_CHILD(DT_PATH(outputs), charge_pump) +#define CP_PWM_CONTROLLER DT_PWMS_CTLR(CP_PWMS) +#define CP_PWM_PERIOD DT_PWMS_PERIOD(CP_PWMS) +#define CP_PWM_CHANNEL DT_PWMS_CHANNEL(CP_PWMS) void load_cp_enable() { - const struct device *pwm_dev = device_get_binding(CP_PWM_CONTROLLER); - if (pwm_dev) { + const struct device *pwm_dev = DEVICE_DT_GET(CP_PWM_CONTROLLER); + if (device_is_ready(pwm_dev)) { // set to 50% duty cycle pwm_pin_set_nsec(pwm_dev, CP_PWM_CHANNEL, CP_PWM_PERIOD, CP_PWM_PERIOD / 2, 0); } @@ -228,7 +229,7 @@ bool pgood_check() #endif } -#else // UNIT_TEST +#else // CONFIG_SOC_FAMILY_STM32 void load_out_init() {;} void usb_out_init() {;} diff --git a/src/main.cpp b/app/src/main.cpp similarity index 93% rename from src/main.cpp rename to app/src/main.cpp index 28319bc..57357ad 100644 --- a/src/main.cpp +++ b/app/src/main.cpp @@ -26,7 +26,7 @@ #include "load.h" // load and USB output management #include "leds.h" // LED switching using charlieplexing #include "device_status.h" // log data (error memory, min/max measurements, etc.) -#include "data_nodes.h" // for access to internal data via ThingSet +#include "data_objects.h" // for access to internal data via ThingSet void main(void) { @@ -54,7 +54,7 @@ void main(void) #endif // read custom configuration from EEPROM - data_nodes_init(); + data_objects_init(); // Data Acquisition (DAQ) setup daq_setup(); @@ -63,13 +63,13 @@ void main(void) charger.init_terminal(&bat_conf); #if BOARD_HAS_LOAD_OUTPUT - load.set_voltage_limits(bat_conf.voltage_load_disconnect, bat_conf.voltage_load_reconnect, - bat_conf.voltage_absolute_max); + load.set_voltage_limits(bat_conf.load_disconnect_voltage, bat_conf.load_reconnect_voltage, + bat_conf.absolute_max_voltage); #endif #if BOARD_HAS_USB_OUTPUT - usb_pwr.set_voltage_limits(bat_conf.voltage_load_disconnect - 0.1, // keep on longer than load - bat_conf.voltage_load_reconnect, bat_conf.voltage_absolute_max); + usb_pwr.set_voltage_limits(bat_conf.load_disconnect_voltage - 0.1, // keep on longer than load + bat_conf.load_reconnect_voltage, bat_conf.absolute_max_voltage); #endif // wait until all threads are spawned before activating the watchdog diff --git a/src/mcu.h b/app/src/mcu.h similarity index 98% rename from src/mcu.h rename to app/src/mcu.h index dbae8d1..c6ac898 100644 --- a/src/mcu.h +++ b/app/src/mcu.h @@ -44,7 +44,7 @@ #define TSENSE_CAL2 (*((uint16_t *)0x1FFF75CA)) #define TSENSE_CAL1_VALUE 30.0 // temperature of first calibration point #define TSENSE_CAL2_VALUE 110.0 // temperature of second calibration point -#elif defined(UNIT_TEST) +#elif !defined(CONFIG_SOC_FAMILY_STM32) #define VREFINT_CAL (4096 * 1.224 / 3.0) // VREFINT @3.0V/25°C #define VREFINT_VALUE 3000 // mV #define TSENSE_CAL1 (4096.0 * (670 - 161) / 3300) // datasheet: slope 1.61 mV/°C diff --git a/src/power_port.cpp b/app/src/power_port.cpp similarity index 100% rename from src/power_port.cpp rename to app/src/power_port.cpp diff --git a/src/power_port.h b/app/src/power_port.h similarity index 96% rename from src/power_port.h rename to app/src/power_port.h index a48fd89..789f220 100644 --- a/src/power_port.h +++ b/app/src/power_port.h @@ -14,6 +14,7 @@ #include #include +#include class PowerPort; // forward-declaration @@ -28,7 +29,7 @@ public: /** * Measured bus voltage */ - float voltage; + float voltage = 0; /** * Filtered bus voltage @@ -53,7 +54,7 @@ public: * This value is the voltage at zero current. Values for other currents are calculated * using the droop resistance. */ - float sink_voltage_intercept; + float sink_voltage_intercept = 0; /** * Lower voltage boundary where this bus may be used to source current. @@ -61,33 +62,33 @@ public: * This value is the voltage at zero current. Values for other currents are calculated * using the droop resistance. */ - float src_voltage_intercept; + float src_voltage_intercept = 0; /** * Droop resistance to adjust voltage bounds for current in sourcing direction * * control voltage = nominal voltage - droop_res * current */ - float src_droop_res; + float src_droop_res = 0; /** * Droop resistance to adjust voltage bounds for current in sinking direction * * control voltage = nominal voltage - droop_res * current */ - float sink_droop_res; + float sink_droop_res = 0; /** * Pointer to current measurement that is used to determine the droop. This is typically the * battery or nanogrid terminal. */ - float *ref_current; + float *ref_current = NULL; /** * Available additional current towards the DC bus until limits of the connected ports are * reached */ - float sink_current_margin; + float sink_current_margin = 0; /** * Available additional current from the DC bus until limits of the connected ports are reached @@ -97,7 +98,7 @@ public: * we still get power via solar, current up to the amount of solar input can be diverted into * the load (until the margin gets 0 and the battery would be discharged). */ - float src_current_margin; + float src_current_margin = 0; /** * Calculate current-compensated src control voltage, considering droop and series multiplier @@ -183,7 +184,7 @@ public: /** * Each power port is connected to a DC bus, containing relevant voltage information */ - DcBus *bus; + DcBus *bus = NULL; /** * Measured current through this port (positive sign = current into the external device) diff --git a/src/pwm_switch.cpp b/app/src/pwm_switch.cpp similarity index 99% rename from src/pwm_switch.cpp rename to app/src/pwm_switch.cpp index 5001701..45f4dfa 100644 --- a/src/pwm_switch.cpp +++ b/app/src/pwm_switch.cpp @@ -8,11 +8,6 @@ #include -#ifndef UNIT_TEST -#include -LOG_MODULE_REGISTER(pwm_switch, CONFIG_PWM_LOG_LEVEL); -#endif - #include #include @@ -21,6 +16,8 @@ LOG_MODULE_REGISTER(pwm_switch, CONFIG_PWM_LOG_LEVEL); #include "helper.h" #include "setup.h" +LOG_MODULE_REGISTER(pwm_switch, CONFIG_PWM_LOG_LEVEL); + #if BOARD_HAS_PWM_PORT #define PWM_CURRENT_MAX (DT_PROP(DT_CHILD(DT_PATH(outputs), pwm_switch), current_max)) diff --git a/src/pwm_switch.h b/app/src/pwm_switch.h similarity index 98% rename from src/pwm_switch.h rename to app/src/pwm_switch.h index 7b8f921..5fc8c45 100644 --- a/src/pwm_switch.h +++ b/app/src/pwm_switch.h @@ -91,7 +91,7 @@ public: * Interval to wait before retrying charging after low solar power cut-off or overvoltage * event (s) */ - int restart_interval = 60; + uint32_t restart_interval = 60; /** * Time when charger was switched off last time diff --git a/src/pwm_switch_driver.c b/app/src/pwm_switch_driver.c similarity index 99% rename from src/pwm_switch_driver.c rename to app/src/pwm_switch_driver.c index e022c36..80d1dd7 100644 --- a/src/pwm_switch_driver.c +++ b/app/src/pwm_switch_driver.c @@ -25,7 +25,7 @@ #include #include -#include +#include #define DT_DRV_COMPAT st_stm32_pwm diff --git a/src/setup.cpp b/app/src/setup.cpp similarity index 97% rename from src/setup.cpp rename to app/src/setup.cpp index 68492ba..70e5a16 100644 --- a/src/setup.cpp +++ b/app/src/setup.cpp @@ -24,7 +24,7 @@ #include "load.h" // load and USB output management #include "leds.h" // LED switching using charlieplexing #include "device_status.h" // log data (error memory, min/max measurements, etc.) -#include "data_nodes.h" // for access to internal data via ThingSet +#include "data_objects.h" // for access to internal data via ThingSet DcBus lv_bus; PowerPort lv_terminal(&lv_bus, true); // low voltage terminal (battery for typical MPPT) diff --git a/src/setup.h b/app/src/setup.h similarity index 100% rename from src/setup.h rename to app/src/setup.h diff --git a/app/west.yml b/app/west.yml new file mode 100644 index 0000000..0e3c45c --- /dev/null +++ b/app/west.yml @@ -0,0 +1,27 @@ +manifest: + remotes: + - name: zephyrproject + url-base: https://github.com/zephyrproject-rtos + - name: libresolar + url-base: https://github.com/LibreSolar + - name: thingset + url-base: https://github.com/ThingSet + - name: throwtheswitch + url-base: https://github.com/ThrowTheSwitch + projects: + - name: zephyr + remote: zephyrproject + revision: v2.7-branch + import: + name-allowlist: + - cmsis + - edtt + - hal_stm32 + - name: thingset-device-library + remote: thingset + revision: 1eaa305a9f1873f676b77b8dd0f9d34f1944ecd1 + path: modules/thingset + - name: unity + path: modules/unity + revision: 74cde089e65c3435ce9aa87d5c69f4f16b7f6ade + remote: throwtheswitch diff --git a/boards/README.md b/boards/README.md deleted file mode 100644 index 6d27284..0000000 --- a/boards/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# Configuration of supported boards - -## Zephyr board definition - -The definitions found in `boards/arm/my-board/` folders are used directly by Zephyr. - -More detiails can be found in Zephyr -[porting guide](https://docs.zephyrproject.org/latest/guides/porting/board_porting.html) and -[Kconfig description](https://docs.zephyrproject.org/latest/guides/kconfig/setting.html#the-initial-configuration). - -- `board.cmake`, `CMakeLists.txt`: CMake definitions for board, normally don't need to be touched. -- `Kconfig.board`: Defines the name of the board as used in DTS config. -- `Kconfig.defconfig`: Configuration of invisible Kconfig symbols, i.e. symbols that should not be adjustable by the user via menuconfig. -- `_defconfig`: Default configuration of the board (can be overwritten by prj.conf) -- `.dts`: Main board device tree specification. -- `.yaml`: -- `pinmux.c`: Defines which pins should be used for peripherals like SPI1, SPI2, SPI3 if selected by the user. - -## PlatformIO configuration - -PlatformIO needs an additional definition file for each board. It is stored as `boards/my-board.json` diff --git a/boards/arm/mppt_1210_hus/mppt_1210_hus.dts b/boards/arm/mppt_1210_hus/mppt_1210_hus.dts index 36d109f..c06aca4 100644 --- a/boards/arm/mppt_1210_hus/mppt_1210_hus.dts +++ b/boards/arm/mppt_1210_hus/mppt_1210_hus.dts @@ -147,18 +147,45 @@ }; }; +&clk_hsi { + status = "okay"; +}; + +&pll { + div = <2>; + mul = <4>; + clocks = <&clk_hsi>; + status = "okay"; +}; + +&rcc { + clocks = <&pll>; + clock-frequency = ; + ahb-prescaler = <1>; + apb1-prescaler = <1>; + apb2-prescaler = <1>; +}; + &usart1 { pinctrl-0 = <&usart1_tx_pa9 &usart1_rx_pa10>; current-speed = <115200>; status = "okay"; }; +&usart1_rx_pa10 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &usart2 { pinctrl-0 = <&usart2_tx_pa2 &usart2_rx_pa3>; current-speed = <115200>; status = "okay"; }; +&usart2_rx_pa3 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &i2c1 { pinctrl-0 = <&i2c1_scl_pb6 &i2c1_sda_pb7>; clock-frequency = ; diff --git a/boards/arm/mppt_1210_hus/mppt_1210_hus_defconfig b/boards/arm/mppt_1210_hus/mppt_1210_hus_defconfig index 363a83f..0f05e44 100644 --- a/boards/arm/mppt_1210_hus/mppt_1210_hus_defconfig +++ b/boards/arm/mppt_1210_hus/mppt_1210_hus_defconfig @@ -3,33 +3,18 @@ CONFIG_SOC_SERIES_STM32L0X=y CONFIG_SOC_STM32L072XX=y -# General Kernel Options -CONFIG_CORTEX_M_SYSTICK=y -CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=32000000 +#CONFIG_ARM_MPU=y + +CONFIG_CLOCK_CONTROL=y + +CONFIG_PINMUX=y + +CONFIG_GPIO=y -# Serial Drivers CONFIG_SERIAL=y -CONFIG_UART_INTERRUPT_DRIVEN=y + CONFIG_CONSOLE=y CONFIG_UART_CONSOLE=y -# Pinmux Driver -CONFIG_PINMUX=y - -# GPIO Controller -CONFIG_GPIO=y - -# Clock configuration -CONFIG_CLOCK_CONTROL=y -# SYSCLK selection -CONFIG_CLOCK_STM32_SYSCLK_SRC_PLL=y - -# PLL configuration -CONFIG_CLOCK_STM32_PLL_SRC_HSI=y -CONFIG_CLOCK_STM32_PLL_MULTIPLIER=4 -CONFIG_CLOCK_STM32_PLL_DIVISOR=2 -CONFIG_CLOCK_STM32_AHB_PRESCALER=1 -CONFIG_CLOCK_STM32_APB1_PRESCALER=1 - CONFIG_EEPROM=y CONFIG_EEPROM_STM32=y diff --git a/boards/arm/mppt_2420_hc/mppt_2420_hc.dts b/boards/arm/mppt_2420_hc/mppt_2420_hc.dts index cd18a2e..dfcc3cc 100644 --- a/boards/arm/mppt_2420_hc/mppt_2420_hc.dts +++ b/boards/arm/mppt_2420_hc/mppt_2420_hc.dts @@ -123,18 +123,48 @@ }; }; +&clk_hsi { + status = "okay"; +}; + +&pll { + div-m = <4>; + mul-n = <75>; + div-p = <7>; + div-q = <2>; + div-r = <2>; + clocks = <&clk_hsi>; + status = "okay"; +}; + +&rcc { + clocks = <&pll>; + clock-frequency = ; + ahb-prescaler = <1>; + apb1-prescaler = <1>; + apb2-prescaler = <1>; +}; + &usart1 { pinctrl-0 = <&usart1_tx_pa9 &usart1_rx_pa10>; current-speed = <115200>; status = "okay"; }; +&usart1_rx_pa10 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &usart2 { pinctrl-0 = <&usart2_tx_pa2 &usart2_rx_pa3>; current-speed = <115200>; status = "okay"; }; +&usart2_rx_pa3 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &i2c1 { pinctrl-0 = <&i2c1_scl_pa15 &i2c1_sda_pb7>; clock-frequency = ; @@ -180,8 +210,8 @@ &can1 { pinctrl-0 = <&fdcan1_rx_pa11 &fdcan1_tx_pa12>; - bus-speed = <250000>; - bus-speed-data = <250000>; + bus-speed = <500000>; + bus-speed-data = <500000>; sjw = <1>; sjw-data = <1>; sample-point = <875>; diff --git a/boards/arm/mppt_2420_hc/mppt_2420_hc_0_2_0.conf b/boards/arm/mppt_2420_hc/mppt_2420_hc_0_2_0.conf index b85a808..a956d33 100644 --- a/boards/arm/mppt_2420_hc/mppt_2420_hc_0_2_0.conf +++ b/boards/arm/mppt_2420_hc/mppt_2420_hc_0_2_0.conf @@ -3,7 +3,6 @@ CONFIG_FLASH=y CONFIG_FLASH_PAGE_LAYOUT=y CONFIG_FLASH_LOG_LEVEL_WRN=y -#CONFIG_MPU_ALLOW_FLASH_WRITE=y CONFIG_SPI=y CONFIG_SPI_NOR=y diff --git a/boards/arm/mppt_2420_hc/mppt_2420_hc_defconfig b/boards/arm/mppt_2420_hc/mppt_2420_hc_defconfig index 352a07d..819d91c 100644 --- a/boards/arm/mppt_2420_hc/mppt_2420_hc_defconfig +++ b/boards/arm/mppt_2420_hc/mppt_2420_hc_defconfig @@ -3,65 +3,23 @@ CONFIG_SOC_SERIES_STM32G4X=y CONFIG_SOC_STM32G431XX=y -# 170MHz system clock only in 'boost power' mode. RM0440, section -# 5.1.5 states that the R1MODE bit must be cleared before system can -# be 170MHz. This requires an update to the stm32 clock control -# driver, so default to 150MHz until then. -# CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=170000000 +CONFIG_ARM_MPU=y +CONFIG_MPU_ALLOW_FLASH_WRITE=y -# 150MHz system clock in 'normal power' mode -CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=150000000 - -# enable uart driver -CONFIG_SERIAL=y - -# enable pinmux -CONFIG_PINMUX=y - -# enable GPIO -CONFIG_GPIO=y - -# clock configuration CONFIG_CLOCK_CONTROL=y -# Use PLLCLK for SYSCLK -CONFIG_CLOCK_STM32_SYSCLK_SRC_PLL=y +CONFIG_PINMUX=y -# Use HSI (16MHz) to feed into PLL -CONFIG_CLOCK_STM32_PLL_SRC_HSI=y +CONFIG_GPIO=y -CONFIG_CLOCK_STM32_PLL_M_DIVISOR=4 -CONFIG_CLOCK_STM32_PLL_P_DIVISOR=7 -CONFIG_CLOCK_STM32_PLL_Q_DIVISOR=2 -CONFIG_CLOCK_STM32_PLL_R_DIVISOR=2 +CONFIG_SERIAL=y -# Produce 150MHz clock at PLLCLK output -CONFIG_CLOCK_STM32_PLL_N_MULTIPLIER=75 - -# Comment out above and uncomment below for 170MHz. Note that you -# must have configured the mcu for boost power mode. -# CONFIG_CLOCK_STM32_PLL_N_MULTIPLIER=85 - -# Produce Max (150MHz or 170MHz) HCLK -CONFIG_CLOCK_STM32_AHB_PRESCALER=1 - -# Produce Max (150MHz or 170MHz) APB1 clocks and APB2 clocks -CONFIG_CLOCK_STM32_APB1_PRESCALER=1 -CONFIG_CLOCK_STM32_APB2_PRESCALER=1 - -# Console CONFIG_CONSOLE=y CONFIG_UART_CONSOLE=y -# Enable MPU -CONFIG_ARM_MPU=y - CONFIG_PWM=y CONFIG_CAN=y CONFIG_THINGSET_CAN=y CONFIG_ISOTP=y -CONFIG_ISOTP_RX_BUF_COUNT=2 -CONFIG_ISOTP_RX_BUF_SIZE=100 -CONFIG_ISOTP_RX_SF_FF_BUF_COUNT=2 diff --git a/boards/arm/mppt_2420_hpx/mppt_2420_hpx.dts b/boards/arm/mppt_2420_hpx/mppt_2420_hpx.dts index ee44f73..433c74c 100644 --- a/boards/arm/mppt_2420_hpx/mppt_2420_hpx.dts +++ b/boards/arm/mppt_2420_hpx/mppt_2420_hpx.dts @@ -144,18 +144,48 @@ }; }; +&clk_hsi{ + status = "okay"; +}; + +&pll { + div-m = <4>; + mul-n = <75>; + div-p = <7>; + div-q = <2>; + div-r = <2>; + clocks = <&clk_hsi>; + status = "okay"; +}; + +&rcc { + clocks = <&pll>; + clock-frequency = ; + ahb-prescaler = <1>; + apb1-prescaler = <1>; + apb2-prescaler = <1>; +}; + &usart1 { pinctrl-0 = <&usart1_tx_pa9 &usart1_rx_pa10>; current-speed = <115200>; status = "okay"; }; +&usart1_rx_pa10 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &usart3 { pinctrl-0 = <&usart3_tx_pc10 &usart3_rx_pc11>; current-speed = <115200>; status = "okay"; }; +&usart3_rx_pc11 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &i2c1 { pinctrl-0 = <&i2c1_scl_pa15 &i2c1_sda_pb7>; status = "okay"; diff --git a/boards/arm/mppt_2420_hpx/mppt_2420_hpx_defconfig b/boards/arm/mppt_2420_hpx/mppt_2420_hpx_defconfig index 7f67e7f..449faa2 100644 --- a/boards/arm/mppt_2420_hpx/mppt_2420_hpx_defconfig +++ b/boards/arm/mppt_2420_hpx/mppt_2420_hpx_defconfig @@ -3,59 +3,19 @@ CONFIG_SOC_SERIES_STM32G4X=y CONFIG_SOC_STM32G431XX=y -# 170MHz system clock only in 'boost power' mode. RM0440, section -# 5.1.5 states that the R1MODE bit must be cleared before system can -# be 170MHz. This requires an update to the stm32 clock control -# driver, so default to 150MHz until then. -# CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=170000000 +CONFIG_ARM_MPU=y -# 150MHz system clock in 'normal power' mode -CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=150000000 - -# enable uart driver -CONFIG_SERIAL=y - -# enable pinmux -CONFIG_PINMUX=y - -# enable GPIO -CONFIG_GPIO=y - -# clock configuration CONFIG_CLOCK_CONTROL=y -# Use PLLCLK for SYSCLK -CONFIG_CLOCK_STM32_SYSCLK_SRC_PLL=y +CONFIG_PINMUX=y -# Use HSI (16MHz) to feed into PLL -CONFIG_CLOCK_STM32_PLL_SRC_HSI=y +CONFIG_GPIO=y -CONFIG_CLOCK_STM32_PLL_M_DIVISOR=4 -CONFIG_CLOCK_STM32_PLL_P_DIVISOR=7 -CONFIG_CLOCK_STM32_PLL_Q_DIVISOR=2 -CONFIG_CLOCK_STM32_PLL_R_DIVISOR=2 +CONFIG_SERIAL=y -# Produce 150MHz clock at PLLCLK output -CONFIG_CLOCK_STM32_PLL_N_MULTIPLIER=75 - -# Comment out above and uncomment below for 170MHz. Note that you -# must have configured the mcu for boost power mode. -# CONFIG_CLOCK_STM32_PLL_N_MULTIPLIER=85 - -# Produce Max (150MHz or 170MHz) HCLK -CONFIG_CLOCK_STM32_AHB_PRESCALER=1 - -# Produce Max (150MHz or 170MHz) APB1 clocks and APB2 clocks -CONFIG_CLOCK_STM32_APB1_PRESCALER=1 -CONFIG_CLOCK_STM32_APB2_PRESCALER=1 - -# Console CONFIG_CONSOLE=y CONFIG_UART_CONSOLE=y -# Enable MPU -CONFIG_ARM_MPU=y - CONFIG_PWM=y CONFIG_I2C=y diff --git a/boards/arm/mppt_2420_lc/mppt_2420_lc.dts b/boards/arm/mppt_2420_lc/mppt_2420_lc.dts index ac655b9..d2222ca 100644 --- a/boards/arm/mppt_2420_lc/mppt_2420_lc.dts +++ b/boards/arm/mppt_2420_lc/mppt_2420_lc.dts @@ -144,18 +144,45 @@ }; }; +&clk_hse { + clock-frequency = ; + status = "okay"; +}; + +&pll { + clocks = <&clk_hse>; + prediv = <1>; + mul = <6>; + status = "okay"; +}; + +&rcc { + clocks = <&pll>; + clock-frequency = ; + ahb-prescaler = <1>; + apb1-prescaler = <2>; +}; + &usart1 { pinctrl-0 = <&usart1_tx_pa9 &usart1_rx_pa10>; current-speed = <115200>; status = "okay"; }; +&usart1_rx_pa10 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &usart2 { pinctrl-0 = <&usart2_tx_pa2 &usart2_rx_pa3>; current-speed = <115200>; status = "okay"; }; +&usart2_rx_pa3 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &i2c1 { status = "okay"; pinctrl-0 = <&i2c1_scl_pb6 &i2c1_sda_pb7>; @@ -205,6 +232,6 @@ &can1 { pinctrl-0 = <&can_rx_pb8 &can_tx_pb9>; - bus-speed = <250000>; + bus-speed = <500000>; status = "okay"; }; diff --git a/boards/arm/mppt_2420_lc/mppt_2420_lc_defconfig b/boards/arm/mppt_2420_lc/mppt_2420_lc_defconfig index 55cc9a1..2c1294a 100644 --- a/boards/arm/mppt_2420_lc/mppt_2420_lc_defconfig +++ b/boards/arm/mppt_2420_lc/mppt_2420_lc_defconfig @@ -3,36 +3,23 @@ CONFIG_SOC_SERIES_STM32F0X=y CONFIG_SOC_STM32F072XB=y -# General Kernel Options -CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=48000000 +#CONFIG_ARM_MPU=y -# Serial Drivers -CONFIG_SERIAL=y -CONFIG_UART_INTERRUPT_DRIVEN=y -CONFIG_CONSOLE=y -CONFIG_UART_CONSOLE=y +CONFIG_CLOCK_CONTROL=y -# Pinmux Driver CONFIG_PINMUX=y -# GPIO Controller CONFIG_GPIO=y -# Clock configuration -CONFIG_CLOCK_CONTROL=y -# SYSCLK selection -CONFIG_CLOCK_STM32_HSE_CLOCK=8000000 -CONFIG_CLOCK_STM32_SYSCLK_SRC_PLL=y -# PLL configuration -CONFIG_CLOCK_STM32_PLL_SRC_HSE=y +CONFIG_SERIAL=y -CONFIG_CLOCK_STM32_PLL_MULTIPLIER=6 -CONFIG_CLOCK_STM32_AHB_PRESCALER=1 -CONFIG_CLOCK_STM32_APB1_PRESCALER=1 - -CONFIG_CAN=y -CONFIG_THINGSET_CAN=y +CONFIG_CONSOLE=y +CONFIG_UART_CONSOLE=y CONFIG_I2C=y CONFIG_EEPROM=y CONFIG_EEPROM_AT24=y + +# too little RAM, can only be enabled if serial is disabled +#CONFIG_CAN=y +#CONFIG_THINGSET_CAN=y diff --git a/boards/arm/mppt_2420_rc/mppt_2420_rc.dts b/boards/arm/mppt_2420_rc/mppt_2420_rc.dts index 2936e98..b6e6954 100644 --- a/boards/arm/mppt_2420_rc/mppt_2420_rc.dts +++ b/boards/arm/mppt_2420_rc/mppt_2420_rc.dts @@ -115,18 +115,48 @@ }; }; +&clk_hsi{ + status = "okay"; +}; + +&pll { + div-m = <4>; + mul-n = <75>; + div-p = <7>; + div-q = <2>; + div-r = <2>; + clocks = <&clk_hsi>; + status = "okay"; +}; + +&rcc { + clocks = <&pll>; + clock-frequency = ; + ahb-prescaler = <1>; + apb1-prescaler = <1>; + apb2-prescaler = <1>; +}; + &usart1 { pinctrl-0 = <&usart1_tx_pa9 &usart1_rx_pa10>; current-speed = <115200>; status = "okay"; }; +&usart1_rx_pa10 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &usart2 { pinctrl-0 = <&usart2_tx_pa2 &usart2_rx_pa3>; current-speed = <115200>; status = "okay"; }; +&usart2_rx_pa3 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &spi1 { pinctrl-0 = <&spi1_sck_pb3 &spi1_miso_pb4 &spi1_mosi_pb5>; cs-gpios = <&gpiob 6 GPIO_ACTIVE_LOW>; @@ -189,8 +219,8 @@ &can1 { pinctrl-0 = <&fdcan1_rx_pa11 &fdcan1_tx_pa12>; - bus-speed = <250000>; - bus-speed-data = <250000>; + bus-speed = <500000>; + bus-speed-data = <500000>; sjw = <1>; sjw-data = <1>; sample-point = <875>; diff --git a/boards/arm/mppt_2420_rc/mppt_2420_rc_defconfig b/boards/arm/mppt_2420_rc/mppt_2420_rc_defconfig index 480413b..89fb9b8 100644 --- a/boards/arm/mppt_2420_rc/mppt_2420_rc_defconfig +++ b/boards/arm/mppt_2420_rc/mppt_2420_rc_defconfig @@ -3,59 +3,19 @@ CONFIG_SOC_SERIES_STM32G4X=y CONFIG_SOC_STM32G431XX=y -# 170MHz system clock only in 'boost power' mode. RM0440, section -# 5.1.5 states that the R1MODE bit must be cleared before system can -# be 170MHz. This requires an update to the stm32 clock control -# driver, so default to 150MHz until then. -# CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=170000000 +CONFIG_ARM_MPU=y -# 150MHz system clock in 'normal power' mode -CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=150000000 - -# enable uart driver -CONFIG_SERIAL=y - -# enable pinmux -CONFIG_PINMUX=y - -# enable GPIO -CONFIG_GPIO=y - -# clock configuration CONFIG_CLOCK_CONTROL=y -# Use PLLCLK for SYSCLK -CONFIG_CLOCK_STM32_SYSCLK_SRC_PLL=y +CONFIG_PINMUX=y -# Use HSI (16MHz) to feed into PLL -CONFIG_CLOCK_STM32_PLL_SRC_HSI=y +CONFIG_GPIO=y -CONFIG_CLOCK_STM32_PLL_M_DIVISOR=4 -CONFIG_CLOCK_STM32_PLL_P_DIVISOR=7 -CONFIG_CLOCK_STM32_PLL_Q_DIVISOR=2 -CONFIG_CLOCK_STM32_PLL_R_DIVISOR=2 +CONFIG_SERIAL=y -# Produce 150MHz clock at PLLCLK output -CONFIG_CLOCK_STM32_PLL_N_MULTIPLIER=75 - -# Comment out above and uncomment below for 170MHz. Note that you -# must have configured the mcu for boost power mode. -# CONFIG_CLOCK_STM32_PLL_N_MULTIPLIER=85 - -# Produce Max (150MHz or 170MHz) HCLK -CONFIG_CLOCK_STM32_AHB_PRESCALER=1 - -# Produce Max (150MHz or 170MHz) APB1 clocks and APB2 clocks -CONFIG_CLOCK_STM32_APB1_PRESCALER=1 -CONFIG_CLOCK_STM32_APB2_PRESCALER=1 - -# Console CONFIG_CONSOLE=y CONFIG_UART_CONSOLE=y -# Enable MPU -CONFIG_ARM_MPU=y - CONFIG_I2C=y CONFIG_EEPROM=y CONFIG_EEPROM_AT24=y @@ -64,6 +24,3 @@ CONFIG_CAN=y CONFIG_THINGSET_CAN=y CONFIG_ISOTP=y -CONFIG_ISOTP_RX_BUF_COUNT=1 -CONFIG_ISOTP_RX_BUF_SIZE=100 -CONFIG_ISOTP_RX_SF_FF_BUF_COUNT=2 diff --git a/boards/arm/nucleo_g474re/nucleo_g474re.dts b/boards/arm/nucleo_g474re/nucleo_g474re.dts index 917770a..374b25b 100644 --- a/boards/arm/nucleo_g474re/nucleo_g474re.dts +++ b/boards/arm/nucleo_g474re/nucleo_g474re.dts @@ -160,18 +160,49 @@ }; }; +&clk_hse { + clock-frequency = ; + status = "okay"; +}; + +&pll { + div-m = <6>; + mul-n = <85>; + div-p = <7>; + div-q = <2>; + div-r = <2>; + clocks = <&clk_hse>; + status = "okay"; +}; + +&rcc { + clocks = <&pll>; + clock-frequency = ; + ahb-prescaler = <1>; + apb1-prescaler = <1>; + apb2-prescaler = <1>; +}; + &usart1 { pinctrl-0 = <&usart1_tx_pc4 &usart1_rx_pc5>; current-speed = <115200>; status = "okay"; }; +&usart1_rx_pc5 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &lpuart1 { pinctrl-0 = <&lpuart1_tx_pa2 &lpuart1_rx_pa3>; current-speed = <115200>; status = "okay"; }; +&lpuart1_rx_pa3 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &i2c1 { pinctrl-0 = <&i2c1_scl_pb8 &i2c1_sda_pb9>; status = "okay"; @@ -245,8 +276,8 @@ &can1 { pinctrl-0 = <&fdcan1_rx_pa11 &fdcan1_tx_pa12>; - bus-speed = <250000>; - bus-speed-data = <250000>; + bus-speed = <500000>; + bus-speed-data = <500000>; sjw = <1>; sjw-data = <1>; sample-point = <875>; diff --git a/boards/arm/nucleo_g474re/nucleo_g474re_defconfig b/boards/arm/nucleo_g474re/nucleo_g474re_defconfig index 86c82bf..49a1284 100644 --- a/boards/arm/nucleo_g474re/nucleo_g474re_defconfig +++ b/boards/arm/nucleo_g474re/nucleo_g474re_defconfig @@ -3,14 +3,6 @@ CONFIG_SOC_SERIES_STM32G4X=y CONFIG_SOC_STM32G474XX=y -# 170MHz system clock only in 'boost power' mode. -# RM0440, section 5.1.5 states that the R1MODE bit -# must be cleared before system can be 170MHz. -CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=170000000 - -# 150MHz system clock in 'normal power' mode -# CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=150000000 - # enable uart driver CONFIG_SERIAL=y @@ -20,35 +12,9 @@ CONFIG_PINMUX=y # enable GPIO CONFIG_GPIO=y -# clock configuration +# Enable Clocks CONFIG_CLOCK_CONTROL=y -# Use PLLCLK for SYSCLK -CONFIG_CLOCK_STM32_SYSCLK_SRC_PLL=y - -# Use HSE (24MHz) to feed into PLL -CONFIG_CLOCK_STM32_PLL_SRC_HSE=y -CONFIG_CLOCK_STM32_HSE_CLOCK=24000000 - -CONFIG_CLOCK_STM32_PLL_P_DIVISOR=7 -CONFIG_CLOCK_STM32_PLL_Q_DIVISOR=2 -CONFIG_CLOCK_STM32_PLL_R_DIVISOR=2 - -# Produce 150MHz clock at PLLCLK output -# CONFIG_CLOCK_STM32_PLL_M_DIVISOR=4 -# CONFIG_CLOCK_STM32_PLL_N_MULTIPLIER=75 - -# Produce 170MHz clock at PLLCLK output -CONFIG_CLOCK_STM32_PLL_M_DIVISOR=6 -CONFIG_CLOCK_STM32_PLL_N_MULTIPLIER=85 - -# Produce Max (150MHz or 170MHz) HCLK -CONFIG_CLOCK_STM32_AHB_PRESCALER=1 - -# Produce Max (150MHz or 170MHz) APB1 clocks and APB2 clocks -CONFIG_CLOCK_STM32_APB1_PRESCALER=1 -CONFIG_CLOCK_STM32_APB2_PRESCALER=1 - # Console CONFIG_CONSOLE=y CONFIG_UART_CONSOLE=y @@ -63,6 +29,3 @@ CONFIG_CAN=y CONFIG_THINGSET_CAN=y CONFIG_ISOTP=y -CONFIG_ISOTP_RX_BUF_COUNT=2 -CONFIG_ISOTP_RX_BUF_SIZE=100 -CONFIG_ISOTP_RX_SF_FF_BUF_COUNT=2 diff --git a/boards/arm/pwm_2420_lus/pwm_2420_lus.dts b/boards/arm/pwm_2420_lus/pwm_2420_lus.dts index 3472a6e..a1d5eb7 100644 --- a/boards/arm/pwm_2420_lus/pwm_2420_lus.dts +++ b/boards/arm/pwm_2420_lus/pwm_2420_lus.dts @@ -167,18 +167,46 @@ }; }; +&clk_hsi { + status = "okay"; +}; + +&pll { + div = <2>; + mul = <4>; + clocks = <&clk_hsi>; + status = "okay"; +}; + +&rcc { + clocks = <&pll>; + clock-frequency = ; + ahb-prescaler = <1>; + apb1-prescaler = <1>; + apb2-prescaler = <1>; +}; + &usart1 { pinctrl-0 = <&usart1_tx_pa9 &usart1_rx_pa10>; current-speed = <115200>; status = "okay"; }; +&usart1_rx_pa10 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + + &usart2 { pinctrl-0 = <&usart2_tx_pa2 &usart2_rx_pa3>; current-speed = <115200>; status = "okay"; }; +&usart2_rx_pa3 { + bias-pull-up; // avoid junk characters if pin is left floating +}; + &i2c1 { pinctrl-0 = <&i2c1_scl_pb6 &i2c1_sda_pb7>; status = "okay"; @@ -186,7 +214,7 @@ }; &spi1 { - pinctrl-0 = <&spi1_sck_pb3 &spi1_miso_pb4 &spi1_mosi_pb5>; + pinctrl-0 = <&spi1_sck_pb3 &spi1_miso_pa11 &spi1_mosi_pa12>; cs-gpios = <&gpioa 15 GPIO_ACTIVE_LOW>; status = "okay"; }; diff --git a/boards/arm/pwm_2420_lus/pwm_2420_lus_defconfig b/boards/arm/pwm_2420_lus/pwm_2420_lus_defconfig index 363a83f..0f05e44 100644 --- a/boards/arm/pwm_2420_lus/pwm_2420_lus_defconfig +++ b/boards/arm/pwm_2420_lus/pwm_2420_lus_defconfig @@ -3,33 +3,18 @@ CONFIG_SOC_SERIES_STM32L0X=y CONFIG_SOC_STM32L072XX=y -# General Kernel Options -CONFIG_CORTEX_M_SYSTICK=y -CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=32000000 +#CONFIG_ARM_MPU=y + +CONFIG_CLOCK_CONTROL=y + +CONFIG_PINMUX=y + +CONFIG_GPIO=y -# Serial Drivers CONFIG_SERIAL=y -CONFIG_UART_INTERRUPT_DRIVEN=y + CONFIG_CONSOLE=y CONFIG_UART_CONSOLE=y -# Pinmux Driver -CONFIG_PINMUX=y - -# GPIO Controller -CONFIG_GPIO=y - -# Clock configuration -CONFIG_CLOCK_CONTROL=y -# SYSCLK selection -CONFIG_CLOCK_STM32_SYSCLK_SRC_PLL=y - -# PLL configuration -CONFIG_CLOCK_STM32_PLL_SRC_HSI=y -CONFIG_CLOCK_STM32_PLL_MULTIPLIER=4 -CONFIG_CLOCK_STM32_PLL_DIVISOR=2 -CONFIG_CLOCK_STM32_AHB_PRESCALER=1 -CONFIG_CLOCK_STM32_APB1_PRESCALER=1 - CONFIG_EEPROM=y CONFIG_EEPROM_STM32=y diff --git a/boards/mppt_1210_hus@0.7.json b/boards/mppt_1210_hus@0.7.json deleted file mode 100644 index b4e2b8f..0000000 --- a/boards/mppt_1210_hus@0.7.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "build": { - "cpu": "cortex-m0plus", - "extra_flags": "-DSTM32L072xx", - "f_cpu": "32000000L", - "framework_extra_flags": { - "arduino": "-D__CORTEX_SC=0" - }, - "mcu": "stm32l072rz", - "variant": "MPPT-1210-HUS" - }, - "debug": { - "default_tools": [ - "stlink" - ], - "jlink_device": "STM32L072RZ", - "onboard_tools": [ - "stlink" - ], - "openocd_board": "st_nucleo_l073rz", - "svd_path": "STM32L07x.svd" - }, - "frameworks": [ - "arduino", - "mbed", - "stm32cube", - "zephyr" - ], - "name": "Libre Solar MPPT 1210 HUS", - "upload": { - "maximum_ram_size": 20480, - "maximum_size": 196608, - "protocol": "stlink", - "protocols": [ - "jlink", - "stlink", - "blackmagic", - "mbed" - ] - }, - "url": "http://libre.solar/", - "vendor": "Libre Solar" -} diff --git a/boards/mppt_2420_hc@0.2.json b/boards/mppt_2420_hc@0.2.json deleted file mode 100644 index bf14c5a..0000000 --- a/boards/mppt_2420_hc@0.2.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "build": { - "cpu": "cortex-m4", - "extra_flags": "-DSTM32G4xx -DSTM32G431xx", - "f_cpu": "150000000L", - "mcu": "stm32g431rb", - "variant": "MPPT-2420-HC" - }, - "connectivity": [ - "can" - ], - "debug": { - "default_tools": [ - "jlink" - ], - "jlink_device": "STM32G431RB", - "onboard_tools": [ - "stlink" - ], - "openocd_board": "st_nucleo_g431rb", - "svd_path": "STM32G431xx.svd" - }, - "frameworks": [ - "arduino", - "stm32cube", - "zephyr" - ], - "name": "Libre Solar MPPT 2420 HC", - "upload": { - "maximum_ram_size": 32768, - "maximum_size": 131072, - "protocol": "jlink", - "protocols": [ - "jlink", - "stlink", - "blackmagic", - "mbed" - ] - }, - "url": "https://libre.solar/", - "vendor": "Libre Solar" -} diff --git a/boards/mppt_2420_hpx.json b/boards/mppt_2420_hpx.json deleted file mode 100644 index f3a9d32..0000000 --- a/boards/mppt_2420_hpx.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "build": { - "cpu": "cortex-m4", - "extra_flags": "-DSTM32G4xx -DSTM32G431xx", - "f_cpu": "150000000L", - "mcu": "stm32g431rb", - "variant": "MPPT-2420-HPX" - }, - "connectivity": [ - "can" - ], - "debug": { - "default_tools": [ - "jlink" - ], - "jlink_device": "STM32G431RB", - "onboard_tools": [ - "stlink" - ], - "openocd_board": "st_nucleo_g431rb", - "svd_path": "STM32G431xx.svd" - }, - "frameworks": [ - "arduino", - "stm32cube", - "zephyr" - ], - "name": "Libre Solar MPPT 2420 HPX", - "upload": { - "maximum_ram_size": 32768, - "maximum_size": 131072, - "protocol": "jlink", - "protocols": [ - "jlink", - "stlink", - "blackmagic", - "mbed" - ] - }, - "url": "http://libre.solar/", - "vendor": "Libre Solar" -} diff --git a/boards/mppt_2420_lc.json b/boards/mppt_2420_lc.json deleted file mode 100644 index a36a753..0000000 --- a/boards/mppt_2420_lc.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "build": { - "cpu": "cortex-m0", - "extra_flags": "-DSTM32F072xB", - "f_cpu": "48000000L", - "mcu": "stm32f072rbt6" - }, - "connectivity": [ - "can" - ], - "debug": { - "default_tools": [ - "stlink" - ], - "jlink_device": "STM32F072RB", - "onboard_tools": [ - "stlink" - ], - "openocd_board": "st_nucleo_f0", - "svd_path": "STM32F072x.svd" - }, - "frameworks": [ - "mbed", - "stm32cube", - "zephyr" - ], - "name": "Libre Solar MPPT 2420 LC", - "upload": { - "maximum_ram_size": 16384, - "maximum_size": 131072, - "protocol": "stlink", - "protocols": [ - "jlink", - "stlink", - "blackmagic", - "mbed" - ] - }, - "url": "http://libre.solar/", - "vendor": "Libre Solar" -} \ No newline at end of file diff --git a/boards/mppt_2420_rc.json b/boards/mppt_2420_rc.json deleted file mode 100644 index 3e8ca81..0000000 --- a/boards/mppt_2420_rc.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "build": { - "cpu": "cortex-m4", - "extra_flags": "-DSTM32G4xx -DSTM32G431xx", - "f_cpu": "150000000L", - "mcu": "stm32g431rb", - "variant": "MPPT-2420-RC" - }, - "connectivity": [ - "can" - ], - "debug": { - "default_tools": [ - "jlink" - ], - "jlink_device": "STM32G431RB", - "onboard_tools": [ - "stlink" - ], - "openocd_board": "st_nucleo_g431rb", - "svd_path": "STM32G431xx.svd" - }, - "frameworks": [ - "arduino", - "stm32cube", - "zephyr" - ], - "name": "Libre Solar MPPT 2420 RC", - "upload": { - "maximum_ram_size": 32768, - "maximum_size": 131072, - "protocol": "jlink", - "protocols": [ - "jlink", - "stlink", - "blackmagic", - "mbed" - ] - }, - "url": "http://libre.solar/", - "vendor": "Libre Solar" -} diff --git a/boards/nucleo_g474re.json b/boards/nucleo_g474re.json deleted file mode 100644 index 90012cd..0000000 --- a/boards/nucleo_g474re.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "build": { - "core": "stm32", - "cpu": "cortex-m4", - "extra_flags": "-DSTM32G4xx -DSTM32G474xx", - "f_cpu": "170000000L", - "mcu": "stm32g474ret6", - "product_line": "STM32G474xx", - "variant": "NUCLEO_G474RE" - }, - "connectivity": [ - "can" - ], - "debug": { - "jlink_device": "STM32G474RE", - "openocd_target": "stm32g4x", - "svd_path": "STM32G474xx.svd" - }, - "frameworks": [ - "arduino", - "cmsis", - "mbed", - "libopencm3", - "stm32cube", - "zephyr" - ], - "name": "Nucleo G474RE", - "upload": { - "maximum_ram_size": 131072, - "maximum_size": 524288, - "protocol": "mbed", - "protocols": [ - "jlink", - "stlink", - "cmsis-dap", - "blackmagic", - "mbed" - ] - }, - "url": "https://www.st.com/en/evaluation-tools/nucleo-g474re.html", - "vendor": "ST" -} diff --git a/boards/pwm_2420_lus@0.3.json b/boards/pwm_2420_lus@0.3.json deleted file mode 100644 index 93daa48..0000000 --- a/boards/pwm_2420_lus@0.3.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "build": { - "cpu": "cortex-m0plus", - "extra_flags": "-DSTM32L072xx", - "f_cpu": "32000000L", - "framework_extra_flags": { - "arduino": "-D__CORTEX_SC=0" - }, - "mcu": "stm32l072rz", - "variant": "PWM-2420-LUS" - }, - "debug": { - "default_tools": [ - "stlink" - ], - "jlink_device": "STM32L072RZ", - "onboard_tools": [ - "stlink" - ], - "openocd_board": "st_nucleo_l073rz", - "svd_path": "STM32L07x.svd" - }, - "frameworks": [ - "arduino", - "mbed", - "stm32cube", - "zephyr" - ], - "name": "Libre Solar PWM 2420 LUS", - "upload": { - "maximum_ram_size": 20480, - "maximum_size": 196608, - "protocol": "stlink", - "protocols": [ - "jlink", - "stlink", - "blackmagic", - "mbed" - ] - }, - "url": "http://libre.solar/", - "vendor": "Libre Solar" -} diff --git a/check.sh b/check.sh deleted file mode 100755 index ff7e07d..0000000 --- a/check.sh +++ /dev/null @@ -1,37 +0,0 @@ -#!/bin/bash -# -# This file performs the same checks as TravisCI and should be run after each commit and before -# pushing the commits -# - -echo "---------- Trailing whitespace check -------------" -# check uncommitted changes -git diff --check HEAD -if [ $? != 0 ]; then - exit 1; -fi -# check all commits starting from initial commit -git diff --check `git rev-list --max-parents=0 HEAD`..HEAD -if [ $? != 0 ]; then - exit 1; -fi - -echo "---------- Running compile check -------------" -platformio run -e mppt_2420_lc -e mppt_1210_hus -e mppt_2420_hc -e pwm_2420_lus -if [ $? != 0 ]; then - exit 1; -fi - -echo "---------- Running unit-tests -------------" -platformio test -e unit_test -if [ $? != 0 ]; then - exit 1; -fi - -echo "---------- Running static code checks -------------" -platformio check -e mppt_1210_hus -e pwm_2420_lus --skip-packages --fail-on-defect high -if [ $? != 0 ]; then - exit 1; -fi - -echo "---------- All tests passed -------------" diff --git a/docs/charger-concepts.md b/docs/charger-concepts.md index 60b7c91..6d12fbe 100644 --- a/docs/charger-concepts.md +++ b/docs/charger-concepts.md @@ -36,8 +36,8 @@ During the topping (sometimes also called boost or absorption) the remaining 30 An additional equalization charging is beneficial for flooded lead-acid batteries only. It can be considered as a periodic controlled overcharge that brings the cells to the same charge level and removes the sulphation by increasing the voltage to a higher value than the peak charge voltage limit. The current during equlization is controlled at a very low value. -### 4. Trickle stage +### 4. Float stage -The trickle or float charging stage is the final phase upon the completion of the absorption or equalization phase which maintains the battery at full charge. During this stage, the charge voltage is reduced and held constant. The current reduces to a very low value. +The float or trickle charging stage is the final phase upon the completion of the absorption or equalization phase which maintains the battery at full charge. During this stage, the charge voltage is reduced and held constant. The current reduces to a very low value. ![Flow-chart of the MPPT charge controller state machine](images/charging-stages.png) diff --git a/zephyr/dts/bindings/adc-inputs.yaml b/dts/bindings/adc-inputs.yaml similarity index 100% rename from zephyr/dts/bindings/adc-inputs.yaml rename to dts/bindings/adc-inputs.yaml diff --git a/zephyr/dts/bindings/charge-controller.yaml b/dts/bindings/charge-controller.yaml similarity index 100% rename from zephyr/dts/bindings/charge-controller.yaml rename to dts/bindings/charge-controller.yaml diff --git a/zephyr/dts/bindings/charlieplexing-leds.yaml b/dts/bindings/charlieplexing-leds.yaml similarity index 100% rename from zephyr/dts/bindings/charlieplexing-leds.yaml rename to dts/bindings/charlieplexing-leds.yaml diff --git a/zephyr/dts/bindings/half-bridge.yaml b/dts/bindings/half-bridge.yaml similarity index 100% rename from zephyr/dts/bindings/half-bridge.yaml rename to dts/bindings/half-bridge.yaml diff --git a/zephyr/dts/bindings/outputs.yaml b/dts/bindings/outputs.yaml similarity index 100% rename from zephyr/dts/bindings/outputs.yaml rename to dts/bindings/outputs.yaml diff --git a/dts/bindings/zephyr,dummy-adc.yaml b/dts/bindings/zephyr,dummy-adc.yaml new file mode 100644 index 0000000..c31ce3e --- /dev/null +++ b/dts/bindings/zephyr,dummy-adc.yaml @@ -0,0 +1,15 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +description: ADC similar to STM32 for unit tests + +compatible: "zephyr,dummy-adc" + +include: adc-controller.yaml + +properties: + "#io-channel-cells": + const: 1 + +io-channel-cells: + - input diff --git a/dts/bindings/zephyr,dummy-pwm.yaml b/dts/bindings/zephyr,dummy-pwm.yaml new file mode 100644 index 0000000..f5fefc6 --- /dev/null +++ b/dts/bindings/zephyr,dummy-pwm.yaml @@ -0,0 +1,21 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +description: PWM similar to STM32 for unit tests + +compatible: "zephyr,dummy-pwm" + +include: [pwm-controller.yaml, base.yaml] + +properties: + label: + required: true + + "#pwm-cells": + const: 3 + +pwm-cells: + - channel +# period in terms of nanoseconds + - period + - flags diff --git a/lib/thingset b/lib/thingset deleted file mode 160000 index 0c39567..0000000 --- a/lib/thingset +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0c39567a0feca1ba8036d4bd74d601cb4f02a7ba diff --git a/platformio-extra.py b/platformio-extra.py deleted file mode 100644 index 3a5d8de..0000000 --- a/platformio-extra.py +++ /dev/null @@ -1,8 +0,0 @@ - -# Custom settings, as referred to as "extra_script" in platformio.ini -# -# See http://docs.platformio.org/en/latest/projectconf.html#extra-script - -Import("env") - -env.Append( CXXFLAGS=[ "-Wno-register -fno-rtti" ] ) diff --git a/platformio.ini b/platformio.ini deleted file mode 100644 index 7f4001e..0000000 --- a/platformio.ini +++ /dev/null @@ -1,103 +0,0 @@ -# -# Project Configuration File -# -# A detailed documentation with the EXAMPLES is located here: -# http://docs.platformio.org/en/latest/projectconf.html -# - -[platformio] - -# Choose one of below charge controller board envs as default, e.g. mppt_2420_hc -default_envs = - -# Or create your own custom.ini file to overwrite settings in this file, e.g. for board selection. -# For further information see here: -# https://docs.platformio.org/en/latest/projectconf/section_platformio.html#extra-configs -extra_configs = - custom.ini - -[env] - -framework = zephyr - -#platform = https://github.com/platformio/platform-ststm32.git -platform = ststm32@~12.0.0 - -# Use customized Zephyr branch from Libre Solar repository -platform_packages = - framework-zephyr@https://github.com/LibreSolar/zephyr#v2.5-branch - -#upload_protocol = mbed -upload_protocol = stlink -#upload_protocol = jlink - -#debug_tool = jlink - -# Custom Serial Monitor baud rate -monitor_speed = 115200 - -# Compiler settings -build_flags = - -std=gnu++17 - -fsingle-precision-constant - -Wl,-Map,memory.map - -# Below flags are only valid for C++ and create warnings for C files, so we add them as -# CXXFLAGS in extra_script. -build_unflags = -Wno-register -fno-rtti -extra_scripts = platformio-extra.py - -check_tool = cppcheck, clangtidy -check_flags = - cppcheck: --enable=warning,style,performance,portability,information,missingInclude -j 7 --inline-suppr -# --addon=addons/misra.py --addon=addons/cert.py - clangtidy: --checks=-*,cert-*,clang-analyzer-*,bugprone-*,misc-*,performance-*,readability-*,-readability-magic-numbers,-cert-err58-cpp - -#### BOARD DEFINITIONS ######################################################## - -# You can specify a specific version by adding e.g. @0.2 to the board name -# (see https://docs.zephyrproject.org/latest/guides/porting/board_porting.html for details) - -# PlatformIO requires a .json file with the same name in boards/ directory. If not existing for -# a particular board revision, just copy it from an existing different revision - -# https://github.com/LibreSolar/mppt-2420-lc -[env:mppt_2420_lc] -board = mppt_2420_lc - -# https://github.com/LibreSolar/mppt-2420-rc -[env:mppt_2420_rc] -board = mppt_2420_rc - -# https://github.com/LibreSolar/mppt-2420-hc -[env:mppt_2420_hc] -board = mppt_2420_hc@0.2 - -# https://github.com/LibreSolar/mppt-1210-hus -[env:mppt_1210_hus] -board = mppt_1210_hus@0.7 - -# https://github.com/LibreSolar/mppt-2420-hpx -[env:mppt_2420_hpx] -board = mppt_2420_hpx - -# https://github.com/LibreSolar/pwm-2420-lus -[env:pwm_2420_lus] -board = pwm_2420_lus@0.3 - -# Nucleo board for testing purposes -[env:nucleo_g474re] -board = nucleo_g474re - -[env:unit_test] -platform = native -framework = -build_flags = - -std=gnu++17 - -Wall - -D UNIT_TEST - -D __STDC_FORMAT_MACROS - -D FIRMWARE_VERSION_ID=\"v20.0-7-gda01bb3\" - -I test -# include src directory (otherwise unit-tests will only include lib directory) -test_build_project_src = true diff --git a/check.bat b/scripts/check.bat similarity index 53% rename from check.bat rename to scripts/check.bat index ed93ed8..e540f96 100644 --- a/check.bat +++ b/scripts/check.bat @@ -1,14 +1,15 @@ @ECHO OFF -:: This batch file performs the same checks as TravisCI and should be run after each commit and -:: before pushing the commits +:: This file performs continuous integration checks and should be run before pushing new commits echo "---------- Trailing whitespace check -------------" + :: check uncommitted changes git diff --check HEAD if errorlevel 1 ( echo Failure Reason is %errorlevel% exit /b %errorlevel% ) + :: check all commits starting from initial commit for /F %i in ('"git rev-list --max-parents=0 HEAD"') do git diff --check %i..HEAD if errorlevel 1 ( @@ -17,24 +18,51 @@ if errorlevel 1 ( ) echo "---------- Running compile check -------------" -platformio run -e mppt_2420_lc -e mppt_1210_hus -e mppt_2420_hc -e pwm_2420_lus + +cd zephyr + +west build -b mppt_2420_hc@0.2 if errorlevel 1 ( echo Failure Reason is %errorlevel% exit /b %errorlevel% ) +west build -b mppt_2420_lc +if errorlevel 1 ( + echo Failure Reason is %errorlevel% + exit /b %errorlevel% +) + +west build -b mppt_1210_hus@0.7 +if errorlevel 1 ( + echo Failure Reason is %errorlevel% + exit /b %errorlevel% +) + +west build -b pwm_2420_lus@0.3 +if errorlevel 1 ( + echo Failure Reason is %errorlevel% + exit /b %errorlevel% +) + +cd .. + echo "---------- Running unit-tests -------------" -platformio test -e unit_test -if errorlevel 1 ( - echo Failure Reason is %errorlevel% - exit /b %errorlevel% -) -echo "---------- Running static code checks -------------" -platformio check -e mppt_1210_hus -e pwm_2420_lus --skip-packages --fail-on-defect high +cd tests +west build -b native_posix -t run if errorlevel 1 ( echo Failure Reason is %errorlevel% exit /b %errorlevel% ) +cd .. + +:: echo "---------- Running static code checks -------------" + +:: platformio check -e mppt_1210_hus -e pwm_2420_lus --skip-packages --fail-on-defect high +:: if errorlevel 1 ( +:: echo Failure Reason is %errorlevel% +:: exit /b %errorlevel% +:: ) echo "---------- All tests passed -------------" diff --git a/scripts/check.sh b/scripts/check.sh new file mode 100755 index 0000000..1de8e66 --- /dev/null +++ b/scripts/check.sh @@ -0,0 +1,39 @@ +#!/bin/bash +# +# This file performs continuous integration checks and should be run before pushing new commits +# + +# exit when any command fails +set -e + +# use board-specific directory +west config build.dir-fmt "build/{board}" + +echo "---------- Trailing whitespace check -------------" + +# check uncommitted changes +git diff --check HEAD + +# check all commits starting from initial commit +git diff --check `git rev-list --max-parents=0 HEAD`..HEAD + +echo "---------- Running compile check -------------" + +cd zephyr +west build -b mppt_2420_hc@0.2 +west build -b mppt_2420_lc +west build -b mppt_1210_hus@0.7 +west build -b pwm_2420_lus@0.3 +cd .. + +echo "---------- Running unit-tests -------------" + +cd tests +west build -b native_posix -t run +cd .. + +#echo "---------- Running static code checks -------------" + +#platformio check -e mppt_1210_hus -e pwm_2420_lus --skip-packages --fail-on-defect high + +echo "---------- All tests passed -------------" diff --git a/scripts/data_objects_parser.py b/scripts/data_objects_parser.py new file mode 100755 index 0000000..4dec845 --- /dev/null +++ b/scripts/data_objects_parser.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# Parser to create JSON file containing data object metadata +# +# TODO +# - Parse nesting in .pub/serial/Enable properly (needs to take parent IDs into account) +# - Also add metadata to groups (using "self" key) + +import json + +output_path = "cc-05.json" # version has to match DATA_OBJECTS_VERSION + +data_objects = {} +id_macros = {} + +# get IDs which are defined as macros +with open("src/data_objects.h", 'r') as fd: + for (num, line) in enumerate(fd, 1): + if "#define ID_" in line: + id_macros[line.split()[1]] = int(line.split()[2], base=16) + continue + +# get actual metadata from data_objects file +with open("src/data_objects.cpp", 'r') as fd: + json_str = "" + group_name = "" + save_lines = False + save_name = False + beginning_line = 0 + for (num, line) in enumerate(fd, 1): + if "TS_GROUP" in line: + group_name = line.strip().split(",")[1].strip(' "') + data_objects[group_name] = {} + continue + + if (line.strip(" \n") == "/*{"): + save_lines = True + beginning_line = num + json_str += "{" + continue + elif (line.strip(" \n") == "}*/"): + json_str += "}" + save_lines = False + save_name = True + continue + + if save_lines: + json_str += line + + if save_name: + try: + name = line.strip().split(",")[1].strip(' "') + data_objects[group_name][name] = {} + obj_id = line.split("(")[1].split(",")[0] + try: + data_objects[group_name][name]["id"] = int(obj_id, base=16) + data_objects[group_name][name]["idx"] = str(obj_id) + except ValueError: + data_objects[group_name][name]["id"] = id_macros[obj_id] + data_objects[group_name][name]["idx"] = hex(id_macros[obj_id]) + data_objects[group_name][name].update(json.loads(json_str)) + except Exception as e: + print("Error while parsing block between lines {} and {}".format(beginning_line, num)) + print(e) + exit(-1) + save_name = False + json_str = "" + +# add missing fields +for category in data_objects: + for item in data_objects[category]: + if not 'unit' in data_objects[category][item]: + data_objects[category][item]['unit'] = None + if not 'min' in data_objects[category][item]: + data_objects[category][item]['min'] = None + if not 'max' in data_objects[category][item]: + data_objects[category][item]['max'] = None + +# save result +with open(output_path, "w", encoding='utf8') as filename: + json.dump(data_objects, filename, indent=4, ensure_ascii=False) + +print("Saved JSON output as: " + output_path) diff --git a/src/data_nodes.cpp b/src/data_nodes.cpp deleted file mode 100644 index 97232b2..0000000 --- a/src/data_nodes.cpp +++ /dev/null @@ -1,573 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "data_nodes.h" - -#ifndef UNIT_TEST -#include -#include -#include -#include -LOG_MODULE_REGISTER(data_nodes, CONFIG_DATA_NODES_LOG_LEVEL); -#endif - -#include -#include - -#include "setup.h" - -// can be used to configure custom data objects in separate file instead -// (e.g. data_nodes_custom.cpp) -#ifndef CONFIG_CUSTOM_DATA_NODES_FILE - -#include "thingset.h" -#include "hardware.h" -#include "dcdc.h" -#include "data_storage.h" - -const char manufacturer[] = "Libre Solar"; -const char device_type[] = DT_PROP(DT_PATH(pcb), type); -const char hardware_version[] = DT_PROP(DT_PATH(pcb), version_str); -const char firmware_version[] = FIRMWARE_VERSION_ID; -char device_id[9]; - -static char auth_password[11]; - -#if CONFIG_LV_TERMINAL_BATTERY -#define bat_bus lv_bus -#elif CONFIG_HV_TERMINAL_BATTERY -#define bat_bus hv_bus -#endif - -#if CONFIG_HV_TERMINAL_SOLAR -#define solar_bus hv_bus -#elif CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR -#define solar_bus lv_bus -#endif - -bool pub_serial_enable = IS_ENABLED(CONFIG_THINGSET_SERIAL_PUB_DEFAULT); - -#if CONFIG_THINGSET_CAN -bool pub_can_enable = IS_ENABLED(CONFIG_THINGSET_CAN_PUB_DEFAULT); -uint16_t can_node_addr = CONFIG_THINGSET_CAN_DEFAULT_NODE_ID; -#endif - -/** - * Data Objects - * - * IDs from 0x00 to 0x17 consume only 1 byte, so they are reserved for output data - * objects communicated very often (to lower the data rate for LoRa and CAN) - * - * Normal priority data objects (consuming 2 or more bytes) start from IDs > 23 = 0x17 - */ -static DataNode data_nodes[] = { - - // DEVICE INFORMATION ///////////////////////////////////////////////////// - // using IDs >= 0x18 - - TS_NODE_PATH(ID_INFO, "info", 0, NULL), - - TS_NODE_STRING(0x19, "DeviceID", device_id, sizeof(device_id), - ID_INFO, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_STRING(0x1A, "Manufacturer", manufacturer, 0, - ID_INFO, TS_ANY_R, 0), - - TS_NODE_STRING(0x1B, "DeviceType", device_type, 0, - ID_INFO, TS_ANY_R, 0), - - TS_NODE_STRING(0x1C, "HardwareVersion", hardware_version, 0, - ID_INFO, TS_ANY_R, 0), - - TS_NODE_STRING(0x1D, "FirmwareVersion", firmware_version, 0, - ID_INFO, TS_ANY_R, 0), - - // CONFIGURATION ////////////////////////////////////////////////////////// - // using IDs >= 0x30 except for high priority data objects - - TS_NODE_PATH(ID_CONF, "conf", 0, &data_nodes_update_conf), - - // battery settings - - TS_NODE_FLOAT(0x31, "BatNom_Ah", &bat_conf_user.nominal_capacity, 1, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x32, "BatRecharge_V", &bat_conf_user.voltage_recharge, 2, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x33, "BatAbsMin_V", &bat_conf_user.voltage_absolute_min, 2, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x34, "BatChgMax_A", &bat_conf_user.charge_current_max, 1, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x35, "Topping_V", &bat_conf_user.topping_voltage, 2, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x36, "ToppingCutoff_A", &bat_conf_user.topping_current_cutoff, 1, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_INT32(0x37, "ToppingCutoff_s", &bat_conf_user.topping_duration, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_BOOL(0x38, "TrickleEn", &bat_conf_user.trickle_enabled, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x39, "Trickle_V", &bat_conf_user.trickle_voltage, 2, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_INT32(0x3A, "TrickleRecharge_s", &bat_conf_user.trickle_recharge_time, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_BOOL(0x3B, "EqlEn", &bat_conf_user.equalization_enabled, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x3C, "Eql_V", &bat_conf_user.equalization_voltage, 2, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x3D, "Eql_A", &bat_conf_user.equalization_current_limit, 2, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_INT32(0x3E, "EqlDuration_s", &bat_conf_user.equalization_duration, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_INT32(0x3F, "EqlInterval_d", &bat_conf_user.equalization_trigger_days, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_INT32(0x40, "EqlDeepDisTrigger", &bat_conf_user.equalization_trigger_deep_cycles, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x41, "BatTempComp_mV-K", &bat_conf_user.temperature_compensation, 3, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x42, "BatInt_Ohm", &bat_conf_user.internal_resistance, 3, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x43, "BatWire_Ohm", &bat_conf_user.wire_resistance, 3, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x44, "BatChgMax_degC", &bat_conf_user.charge_temp_max, 1, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x45, "BatChgMin_degC", &bat_conf_user.charge_temp_min, 1, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x46, "BatDisMax_degC", &bat_conf_user.discharge_temp_max, 1, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x47, "BatDisMin_degC", &bat_conf_user.discharge_temp_min, 1, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - // load settings -#if BOARD_HAS_LOAD_OUTPUT - TS_NODE_BOOL(0x50, "LoadEnDefault", &load.enable, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x51, "LoadDisconnect_V", &bat_conf_user.voltage_load_disconnect, 2, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_FLOAT(0x52, "LoadReconnect_V", &bat_conf_user.voltage_load_reconnect, 2, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_INT32(0x53, "LoadOCRecovery_s", &load.oc_recovery_delay, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_INT32(0x54, "LoadUVRecovery_s", &load.lvd_recovery_delay, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), -#endif - -#if BOARD_HAS_USB_OUTPUT - TS_NODE_BOOL(0x55, "UsbEnDefault", &usb_pwr.enable, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - //TS_NODE_FLOAT(0x56, "UsbDisconnect_V", &bat_conf_user.voltage_load_disconnect, 2, - // ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - //TS_NODE_FLOAT(0x57, "UsbReconnect_V", &bat_conf_user.voltage_load_reconnect, 2, - // ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), - - TS_NODE_INT32(0x58, "UsbUVRecovery_s", &usb_pwr.lvd_recovery_delay, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), -#endif - -#if CONFIG_THINGSET_CAN - TS_NODE_UINT16(0x59, "CanNodeId", &can_node_addr, - ID_CONF, TS_ANY_R | TS_ANY_W, PUB_NVM), -#endif - - // INPUT DATA ///////////////////////////////////////////////////////////// - // using IDs >= 0x60 - - TS_NODE_PATH(ID_INPUT, "input", 0, NULL), - -#if BOARD_HAS_LOAD_OUTPUT - TS_NODE_BOOL(0x61, "LoadEn", &load.enable, - ID_INPUT, TS_ANY_R | TS_ANY_W, 0), -#endif - -#if BOARD_HAS_USB_OUTPUT - TS_NODE_BOOL(0x62, "UsbEn", &usb_pwr.enable, - ID_INPUT, TS_ANY_R | TS_ANY_W, 0), -#endif - -#if BOARD_HAS_DCDC - TS_NODE_BOOL(0x63, "DcdcEn", &dcdc.enable, - ID_INPUT, TS_ANY_R | TS_ANY_W, 0), -#endif - -#if BOARD_HAS_PWM_PORT - TS_NODE_BOOL(0x64, "PwmEn", &pwm_switch.enable, - ID_INPUT, TS_ANY_R | TS_ANY_W, 0), -#endif - -#if CONFIG_HV_TERMINAL_NANOGRID - TS_NODE_FLOAT(0x65, "GridSink_V", &hv_bus.sink_voltage_intercept, 2, - ID_INPUT, TS_ANY_R | TS_ANY_W, 0), - - TS_NODE_FLOAT(0x66, "GridSrc_V", &hv_bus.src_voltage_intercept, 2, - ID_INPUT, TS_ANY_R | TS_ANY_W, 0), -#endif - - // OUTPUT DATA //////////////////////////////////////////////////////////// - // using IDs >= 0x70 except for high priority data objects - - TS_NODE_PATH(ID_OUTPUT, "output", 0, NULL), - - // the timestamp currently reflects the time since last reset and not an actual timestamp - TS_NODE_UINT32(0x01, "Uptime_s", ×tamp, - ID_OUTPUT, TS_ANY_R, PUB_SER), - - // battery related data objects - TS_NODE_FLOAT(0x71, "Bat_V", &bat_bus.voltage, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), - - TS_NODE_FLOAT(0x72, "Bat_A", &bat_terminal.current, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), - - TS_NODE_FLOAT(0x73, "Bat_W", &bat_terminal.power, 2, - ID_OUTPUT, TS_ANY_R, 0), - - TS_NODE_FLOAT(0x74, "Bat_degC", &charger.bat_temperature, 1, - ID_OUTPUT, TS_ANY_R, 0), - - TS_NODE_BOOL(0x75, "BatTempExt", &charger.ext_temp_sensor, - ID_OUTPUT, TS_ANY_R, 0), - - TS_NODE_UINT16(0x76, "SOC_pct", &charger.soc, // output will be uint8_t - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), - - TS_NODE_INT16(0x77, "NumBatteries", &lv_bus.series_multiplier, - ID_OUTPUT, TS_ANY_R, 0), - - TS_NODE_FLOAT(0x78, "Int_degC", &dev_stat.internal_temp, 1, - ID_OUTPUT, TS_ANY_R, 0), - -#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(adc_inputs), temp_fets)) - TS_NODE_FLOAT(0x79, "Mosfet_degC", &dcdc.temp_mosfets, 1, - ID_OUTPUT, TS_ANY_R, 0), -#endif - - TS_NODE_FLOAT(0x7A, "ChgTarget_V", &bat_bus.sink_voltage_intercept, 2, - ID_OUTPUT, TS_ANY_R, 0), - - TS_NODE_FLOAT(0x7B, "ChgTarget_A", &bat_terminal.pos_current_limit, 2, - ID_OUTPUT, TS_ANY_R, 0), - - TS_NODE_UINT32(0x7C, "ChgState", &charger.state, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), - -#if BOARD_HAS_DCDC - TS_NODE_UINT16(0x7D, "DCDCState", &dcdc.state, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), -#endif - -#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR - TS_NODE_FLOAT(0x80, "Solar_V", &solar_bus.voltage, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), -#elif CONFIG_PWM_TERMINAL_SOLAR - TS_NODE_FLOAT(0x80, "Solar_V", &pwm_switch.ext_voltage, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), -#endif - -#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR - TS_NODE_FLOAT(0x81, "Solar_A", &solar_terminal.current, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), -#endif - -#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR - TS_NODE_FLOAT(0x82, "Solar_W", &solar_terminal.power, 2, - ID_OUTPUT, TS_ANY_R, 0), -#endif - -#if BOARD_HAS_LOAD_OUTPUT - TS_NODE_FLOAT(0x89, "Load_A", &load.current, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), - - TS_NODE_FLOAT(0x8A, "Load_W", &load.power, 2, - ID_OUTPUT, TS_ANY_R, 0), - - TS_NODE_INT32(0x8B, "LoadInfo", &load.info, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), -#endif - -#if BOARD_HAS_USB_OUTPUT - TS_NODE_INT32(0x8C, "UsbInfo", &usb_pwr.info, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), -#endif - -#if CONFIG_HV_TERMINAL_NANOGRID - TS_NODE_FLOAT(0x90, "Grid_V", &hv_bus.voltage, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), - - TS_NODE_FLOAT(0x91, "Grid_A", &hv_terminal.current, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), - - TS_NODE_FLOAT(0x92, "Grid_W", &hv_terminal.power, 2, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), -#endif - - TS_NODE_UINT32(0x9F, "ErrorFlags", &dev_stat.error_flags, - ID_OUTPUT, TS_ANY_R, PUB_SER | PUB_CAN), - - // RECORDED DATA /////////////////////////////////////////////////////// - // using IDs >= 0xA0 - - TS_NODE_PATH(ID_REC, "rec", 0, NULL), - - // accumulated data - TS_NODE_UINT32(0x08, "SolarInTotal_Wh", &dev_stat.solar_in_total_Wh, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - -#if BOARD_HAS_LOAD_OUTPUT - TS_NODE_UINT32(0x09, "LoadOutTotal_Wh", &dev_stat.load_out_total_Wh, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), -#endif - -#if CONFIG_HV_TERMINAL_NANOGRID - TS_NODE_UINT32(0xC1, "GridImportTotal_Wh", &dev_stat.grid_import_total_Wh, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_UINT32(0xC2, "GridExportTotal_Wh", &dev_stat.grid_export_total_Wh, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), -#endif - - TS_NODE_UINT32(0x0A, "BatChgTotal_Wh", &dev_stat.bat_chg_total_Wh, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_UINT32(0x0B, "BatDisTotal_Wh", &dev_stat.bat_dis_total_Wh, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_UINT16(0x0C, "FullChgCount", &charger.num_full_charges, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_UINT16(0x0D, "DeepDisCount", &charger.num_deep_discharges, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_SER | PUB_NVM), - - TS_NODE_FLOAT(0x0E, "BatUsable_Ah", &charger.usable_capacity, 1, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_SER | PUB_NVM), - - TS_NODE_UINT16(0x0F, "SolarMaxDay_W", &dev_stat.solar_power_max_day, - ID_REC, TS_ANY_R | TS_MKR_W, 0), - -#if BOARD_HAS_LOAD_OUTPUT - TS_NODE_UINT16(0x10, "LoadMaxDay_W", &dev_stat.load_power_max_day, - ID_REC, TS_ANY_R | TS_MKR_W, 0), -#endif - -#if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR - TS_NODE_FLOAT(0xA1, "SolarInDay_Wh", &solar_terminal.neg_energy_Wh, 2, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_SER | PUB_CAN), -#endif - -#if BOARD_HAS_LOAD_OUTPUT - TS_NODE_FLOAT(0xA2, "LoadOutDay_Wh", &load.pos_energy_Wh, 2, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_SER | PUB_CAN), -#endif - - TS_NODE_FLOAT(0xA3, "BatChgDay_Wh", &bat_terminal.pos_energy_Wh, 2, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_SER | PUB_CAN), - - TS_NODE_FLOAT(0xA4, "BatDisDay_Wh", &bat_terminal.neg_energy_Wh, 2, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_SER | PUB_CAN), - - TS_NODE_FLOAT(0xA5, "Dis_Ah", &charger.discharged_Ah, 0, // coulomb counter - ID_REC, TS_ANY_R | TS_MKR_W, PUB_SER | PUB_CAN), - - TS_NODE_UINT16(0xA6, "SOH_pct", &charger.soh, // output will be uint8_t - ID_REC, TS_ANY_R | TS_MKR_W, 0), - - TS_NODE_UINT32(0xA7, "DayCount", &dev_stat.day_counter, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - // min/max recordings - TS_NODE_UINT16(0xB1, "SolarMaxTotal_W", &dev_stat.solar_power_max_total, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - -#if BOARD_HAS_LOAD_OUTPUT - TS_NODE_UINT16(0xB2, "LoadMaxTotal_W", &dev_stat.load_power_max_total, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), -#endif - - TS_NODE_FLOAT(0xB3, "BatMaxTotal_V", &dev_stat.battery_voltage_max, 2, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_FLOAT(0xB4, "SolarMaxTotal_V", &dev_stat.solar_voltage_max, 2, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_FLOAT(0xB5, "DcdcMaxTotal_A", &dev_stat.dcdc_current_max, 2, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - -#if BOARD_HAS_LOAD_OUTPUT - TS_NODE_FLOAT(0xB6, "LoadMaxTotal_A", &dev_stat.load_current_max, 2, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), -#endif - - TS_NODE_INT16(0xB7, "BatMax_degC", &dev_stat.bat_temp_max, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_INT16(0xB8, "IntMax_degC", &dev_stat.int_temp_max, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_INT16(0xB9, "MosfetMax_degC", &dev_stat.mosfet_temp_max, - ID_REC, TS_ANY_R | TS_MKR_W, PUB_NVM), - - // CALIBRATION DATA /////////////////////////////////////////////////////// - // using IDs >= 0xD0 - - TS_NODE_PATH(ID_CAL, "cal", 0, NULL), - -#if BOARD_HAS_DCDC - TS_NODE_FLOAT(0xD1, "DcdcMin_W", &dcdc.output_power_min, 1, - ID_CAL, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_FLOAT(0xD2, "SolarAbsMax_V", &dcdc.hs_voltage_max, 1, - ID_CAL, TS_ANY_R | TS_MKR_W, PUB_NVM), - - TS_NODE_UINT32(0xD3, "DcdcRestart_s", &dcdc.restart_interval, - ID_CAL, TS_ANY_R | TS_MKR_W, PUB_NVM), -#endif - - // FUNCTION CALLS (EXEC) ////////////////////////////////////////////////// - // using IDs >= 0xE0 - - TS_NODE_PATH(ID_EXEC, "exec", 0, NULL), - - TS_NODE_EXEC(0xE1, "reset", &reset_device, ID_EXEC, TS_ANY_RW), - TS_NODE_EXEC(0xE2, "bootloader-stm", &start_stm32_bootloader, ID_EXEC, TS_ANY_RW), - TS_NODE_EXEC(0xE3, "save-settings", &data_storage_write, ID_EXEC, TS_ANY_RW), - - TS_NODE_EXEC(0xEE, "auth", &thingset_auth, 0, TS_ANY_RW), - TS_NODE_STRING(0xEF, "Password", auth_password, sizeof(auth_password), 0xEE, TS_ANY_RW, 0), - - // PUBLICATION DATA /////////////////////////////////////////////////////// - // using IDs >= 0xF0 - - TS_NODE_PATH(ID_PUB, "pub", 0, NULL), - - TS_NODE_PATH(0xF1, "serial", ID_PUB, NULL), - TS_NODE_BOOL(0xF2, "Enable", &pub_serial_enable, 0xF1, TS_ANY_RW, 0), - TS_NODE_PUBSUB(0xF3, "IDs", PUB_SER, 0xF1, TS_ANY_RW, 0), - -#if CONFIG_THINGSET_CAN - TS_NODE_PATH(0xF5, "can", ID_PUB, NULL), - TS_NODE_BOOL(0xF6, "Enable", &pub_can_enable, 0xF5, TS_ANY_RW, 0), - TS_NODE_PUBSUB(0xF7, "IDs", PUB_CAN, 0xF5, TS_ANY_RW, 0), -#endif -}; - -ThingSet ts(data_nodes, sizeof(data_nodes)/sizeof(DataNode)); - -void data_nodes_update_conf() -{ - bool changed; - if (battery_conf_check(&bat_conf_user)) { - LOG_INF("New config valid and activated."); - battery_conf_overwrite(&bat_conf_user, &bat_conf, &charger); -#if BOARD_HAS_LOAD_OUTPUT - load.set_voltage_limits(bat_conf.voltage_load_disconnect, bat_conf.voltage_load_reconnect, - bat_conf.voltage_absolute_max); -#endif - changed = true; - } - else { - LOG_ERR("Requested config change not valid and rejected."); - battery_conf_overwrite(&bat_conf, &bat_conf_user); - changed = false; - } - - // TODO: check also for changes in Load/USB EnDefault - changed = true; // temporary hack - - if (changed) { - data_storage_write(); - } -} - -void data_nodes_init() -{ -#ifndef UNIT_TEST - uint8_t buf[12]; - hwinfo_get_device_id(buf, sizeof(buf)); - - uint64_t id64 = crc32_ieee(buf, sizeof(buf)); - id64 += ((uint64_t)CONFIG_LIBRE_SOLAR_TYPE_ID) << 32; - - uint64_to_base32(id64, device_id, sizeof(device_id), alphabet_crockford); -#endif - - data_storage_read(); - if (battery_conf_check(&bat_conf_user)) { - battery_conf_overwrite(&bat_conf_user, &bat_conf, &charger); - } - else { - battery_conf_overwrite(&bat_conf, &bat_conf_user); - } -} - -void thingset_auth() -{ - static const char pass_exp[] = CONFIG_THINGSET_EXPERT_PASSWORD; - static const char pass_mkr[] = CONFIG_THINGSET_MAKER_PASSWORD; - - if (strlen(pass_exp) == strlen(auth_password) && - strncmp(auth_password, pass_exp, strlen(pass_exp)) == 0) - { - LOG_INF("Authenticated as expert user."); - ts.set_authentication(TS_EXP_MASK | TS_USR_MASK); - } - else if (strlen(pass_mkr) == strlen(auth_password) && - strncmp(auth_password, pass_mkr, strlen(pass_mkr)) == 0) - { - LOG_INF("Authenticated as maker."); - ts.set_authentication(TS_MKR_MASK | TS_USR_MASK); - } - else { - LOG_INF("Reset authentication."); - ts.set_authentication(TS_USR_MASK); - } -} - -void uint64_to_base32(uint64_t in, char *out, size_t size, const char *alphabet) -{ - // 13 is the maximum number of characters needed to encode 64-bit variable to base32 - int len = (size > 13) ? 13 : size; - - // find out actual length of output string - for (int i = 0; i < len; i++) { - if ((in >> (i * 5)) == 0) { - len = i; - break; - } - } - - for (int i = 0; i < len; i++) { - out[len-i-1] = alphabet[(in >> (i * 5)) % 32]; - } - out[len] = '\0'; -} - - -#endif /* CUSTOM_DATA_NODES_FILE */ diff --git a/src/data_nodes.h b/src/data_nodes.h deleted file mode 100644 index c74de5c..0000000 --- a/src/data_nodes.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#ifndef DATA_NODES_H_ -#define DATA_NODES_H_ - -/** @file - * - * @brief Handling of ThingSet data nodes - */ - -#include -#include - -/* - * Categories / first layer node IDs - */ -#define ID_ROOT 0x00 -#define ID_INFO 0x18 // read-only device information (e.g. manufacturer, device ID) -#define ID_CONF 0x30 // configurable settings -#define ID_INPUT 0x60 // input data (e.g. set-points) -#define ID_OUTPUT 0x70 // output data (e.g. measurement values) -#define ID_REC 0xA0 // recorded data (history-dependent) -#define ID_CAL 0xD0 // calibration -#define ID_EXEC 0xE0 // function call -#define ID_AUTH 0xEA -#define ID_PUB 0xF0 // publication setup -#define ID_SUB 0xF1 // subscription setup -#define ID_LOG 0x100 // access log data - -/* - * Publish/subscribe channels - */ -#define PUB_SER (1U << 0) // UART serial -#define PUB_CAN (1U << 1) // CAN bus -#define PUB_NVM (1U << 2) // data that should be stored in EEPROM - -/* - * Data node versioning for EEPROM - * - * Increment the version number each time any data node IDs stored in NVM are changed. Otherwise - * data might get corrupted. - */ -#define DATA_NODES_VERSION 4 - -extern bool pub_serial_enable; -extern bool pub_can_enable; - -/** - * Callback function to be called when conf values were changed - */ -void data_nodes_update_conf(); - -/** - * Initializes and reads data nodes from EEPROM - */ -void data_nodes_init(); - -/** - * Callback to provide authentication mechanism via ThingSet - */ -void thingset_auth(); - -/** - * Alphabet used for base32 encoding - * - * https://en.wikipedia.org/wiki/Base32#Crockford's_Base32 - */ -const char alphabet_crockford[] = "0123456789abcdefghjkmnpqrstvwxyz"; - -/** - * Convert numeric device ID to base32 string - */ -void uint64_to_base32(uint64_t in, char *out, size_t size, const char *alphabet); - -#endif /* DATA_OBJECTS_H */ diff --git a/src/ext/can.cpp b/src/ext/can.cpp deleted file mode 100644 index 4783655..0000000 --- a/src/ext/can.cpp +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#if CONFIG_THINGSET_CAN - -#include -#include -#include -#include -#include - -#ifdef CONFIG_ISOTP -#include -#endif - -#include -LOG_MODULE_REGISTER(ext_can, CONFIG_CAN_LOG_LEVEL); - -#include "hardware.h" // for software watchdog - -#include "thingset.h" -#include "data_nodes.h" - -#if DT_NODE_EXISTS(DT_CHILD(DT_PATH(outputs), can_en)) -#define CAN_EN_GPIO DT_CHILD(DT_PATH(outputs), can_en) -#endif - -extern ThingSet ts; -extern uint16_t can_node_addr; - -const struct device *can_dev; - -#ifdef CONFIG_ISOTP - -#define RX_THREAD_STACK_SIZE 1024 -#define RX_THREAD_PRIORITY 2 - -const struct isotp_fc_opts fc_opts = {.bs = 8, .stmin = 0}; - -struct isotp_msg_id rx_addr = { - .id_type = CAN_EXTENDED_IDENTIFIER, - .use_ext_addr = 0, // Normal ISO-TP addressing (using only CAN ID) - .use_fixed_addr = 1, // enable SAE J1939 compatible addressing -}; - -struct isotp_msg_id tx_addr = { - .id_type = CAN_EXTENDED_IDENTIFIER, - .use_ext_addr = 0, // Normal ISO-TP addressing (using only CAN ID) - .use_fixed_addr = 1, // enable SAE J1939 compatible addressing -}; - -struct isotp_recv_ctx recv_ctx; - -void send_complette_cb(int error_nr, void *arg) -{ - ARG_UNUSED(arg); - LOG_DBG("TX complete callback, err: %d", error_nr); -} - -void can_rx_thread() -{ - int ret, rem_len; - unsigned int received_len; - struct net_buf *buf; - static uint8_t rx_buffer[100]; - static uint8_t tx_buffer[500]; - - // CAN node ID retrieved from EEPROM --> reset necessary after change via ThingSet serial - rx_addr.ext_id = TS_CAN_BASE_REQRESP | TS_CAN_PRIO_REQRESP | TS_CAN_TARGET_SET(can_node_addr); - tx_addr.ext_id = TS_CAN_BASE_REQRESP | TS_CAN_PRIO_REQRESP | TS_CAN_SOURCE_SET(can_node_addr); - - while (1) { - ret = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr, &fc_opts, K_FOREVER); - if (ret != ISOTP_N_OK) { - LOG_DBG("Failed to bind to rx ID %d [%d]", rx_addr.ext_id, ret); - return; - } - - received_len = 0; - do { - rem_len = isotp_recv_net(&recv_ctx, &buf, K_FOREVER); - if (rem_len < 0) { - LOG_DBG("Receiving error [%d]", rem_len); - break; - } - if (received_len + buf->len <= sizeof(rx_buffer)) { - memcpy(&rx_buffer[received_len], buf->data, buf->len); - received_len += buf->len; - } - else { - LOG_DBG("RX buffer too small"); - break; - } - net_buf_unref(buf); - } while (rem_len); - - // we need to unbind the receive ctx so that control frames are received in the send ctx - isotp_unbind(&recv_ctx); - - if (received_len > 0) { - LOG_DBG("Got %d bytes via ISO-TP. Processing ThingSet message.", received_len); - LOG_DBG("RX buf: %x %x %x %x", rx_buffer[0], rx_buffer[1], rx_buffer[2], rx_buffer[3]); - int resp_len = ts.process(rx_buffer, received_len, tx_buffer, sizeof(tx_buffer)); - LOG_DBG("TX buf: %x %x %x %x", tx_buffer[0], tx_buffer[1], tx_buffer[2], tx_buffer[3]); - - if (resp_len > 0) { - static struct isotp_send_ctx send_ctx; - int ret = isotp_send(&send_ctx, can_dev, tx_buffer, resp_len, - &recv_ctx.tx_addr, &recv_ctx.rx_addr, send_complette_cb, NULL); - if (ret != ISOTP_N_OK) { - LOG_DBG("Error while sending data to ID %d [%d]", tx_addr.ext_id, ret); - } - } - } - } -} - -K_THREAD_DEFINE(can_rx, RX_THREAD_STACK_SIZE, can_rx_thread, NULL, NULL, NULL, - RX_THREAD_PRIORITY, 0, 1500); - -#endif /* CONFIG_ISOTP */ - -void can_pub_isr(uint32_t err_flags, void *arg) -{ - // Do nothing. Publication messages are fire and forget. -} - -void can_pub_thread() -{ - int wdt_channel = task_wdt_add(1100, task_wdt_callback, (void *)k_current_get()); - - unsigned int can_id; - uint8_t can_data[8]; - - const struct device *can_en_dev = device_get_binding(DT_GPIO_LABEL(CAN_EN_GPIO, gpios)); - gpio_pin_configure(can_en_dev, DT_GPIO_PIN(CAN_EN_GPIO, gpios), - DT_GPIO_FLAGS(CAN_EN_GPIO, gpios) | GPIO_OUTPUT_ACTIVE); - - can_dev = device_get_binding("CAN_1"); - - int64_t t_start = k_uptime_get(); - - while (true) { - - task_wdt_feed(wdt_channel); - - if (pub_can_enable) { - int data_len = 0; - int start_pos = 0; - while ((data_len = ts.bin_pub_can(start_pos, PUB_CAN, can_node_addr, can_id, can_data)) - != -1) - { - struct zcan_frame frame = {0}; - frame.id_type = CAN_EXTENDED_IDENTIFIER; - frame.rtr = CAN_DATAFRAME; - frame.id = can_id; - memcpy(frame.data, can_data, 8); - - if (data_len >= 0) { - frame.dlc = data_len; - - if (can_send(can_dev, &frame, K_MSEC(10), can_pub_isr, NULL) != CAN_TX_OK) { - LOG_DBG("Error sending CAN frame"); - } - } - } - } - - t_start += 1000; - k_sleep(K_TIMEOUT_ABS_MS(t_start)); - } -} - -K_THREAD_DEFINE(can_pub, 1024, can_pub_thread, NULL, NULL, NULL, 6, 0, 1000); - -#endif /* CONFIG_THINGSET_CAN */ diff --git a/src/ext/serial.cpp b/src/ext/serial.cpp deleted file mode 100644 index a7a5ba9..0000000 --- a/src/ext/serial.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#if CONFIG_THINGSET_SERIAL - -#include -#include - -#include -#include -#include -#include - -#include "thingset.h" -#include "hardware.h" -#include "data_nodes.h" - -#if CONFIG_UEXT_SERIAL_THINGSET -#define UART_DEVICE_NAME DT_LABEL(DT_ALIAS(uart_uext)) -#elif DT_NODE_EXISTS(DT_ALIAS(uart_dbg)) -#define UART_DEVICE_NAME DT_LABEL(DT_ALIAS(uart_dbg)) -#else -// cppcheck-suppress preprocessorErrorDirective -#error "No UART for ThingSet serial defined." -#endif - -const struct device *uart_dev = device_get_binding(UART_DEVICE_NAME); - -static char buf_resp[CONFIG_THINGSET_SERIAL_TX_BUF_SIZE]; -static char buf_req[CONFIG_THINGSET_SERIAL_RX_BUF_SIZE]; - -static volatile size_t req_pos = 0; -static volatile bool command_flag = false; - -extern ThingSet ts; - -void process_1s() -{ - if (pub_serial_enable) { - int len = ts.txt_pub(buf_resp, sizeof(buf_resp), PUB_SER); - for (int i = 0; i < len; i++) { - uart_poll_out(uart_dev, buf_resp[i]); - } - uart_poll_out(uart_dev, '\n'); - } -} - -void process_asap() -{ - if (command_flag) { - // commands must have 2 or more characters - if (req_pos > 1) { - printf("Received Request (%d bytes): %s\n", strlen(buf_req), buf_req); - - int len = ts.process((uint8_t *)buf_req, strlen(buf_req), - (uint8_t *)buf_resp, sizeof(buf_resp)); - - for (int i = 0; i < len; i++) { - uart_poll_out(uart_dev, buf_resp[i]); - } - uart_poll_out(uart_dev, '\n'); - } - - // start listening for new commands - command_flag = false; - req_pos = 0; - } -} - -/** - * Read characters from stream until line end \n detected, signal command available then - * and wait for processing - */ -void process_input(const struct device *dev, void* user_data) -{ - uint8_t c; - - if (!uart_irq_update(uart_dev)) { - return; - } - - while (uart_irq_rx_ready(uart_dev) && command_flag == false) { - uart_fifo_read(uart_dev, &c, 1); - - // \r\n and \n are markers for line end, i.e. command end - // we accept this at any time, even if the buffer is 'full', since - // there is always one last character left for the \0 - if (c == '\n') { - if (req_pos > 0 && buf_req[req_pos-1] == '\r') { - buf_req[req_pos-1] = '\0'; - } - else { - buf_req[req_pos] = '\0'; - } - // start processing - command_flag = true; - } - // backspace allowed if there is something in the buffer already - else if (req_pos > 0 && c == '\b') { - req_pos--; - } - // Fill the buffer up to all but 1 character (the last character is reserved for '\0') - // Characters beyond the size of the buffer are dropped. - else if (req_pos < (sizeof(buf_req)-1)) { - buf_req[req_pos++] = c; - } - } -} - -void serial_thread() -{ - uint32_t last_call = 0; - - // long watchdog timeout needed for ThingSet conf calls which write to slow EEPROM - int wdt_channel = task_wdt_add(500, task_wdt_callback, (void *)k_current_get()); - - uart_irq_callback_user_data_set(uart_dev, process_input, NULL); - uart_irq_rx_enable(uart_dev); - - while (true) { - task_wdt_feed(wdt_channel); - - uint32_t now = k_uptime_get() / 1000; - - process_asap(); // approx. every millisecond - if (now >= last_call + 1) { - last_call = now; - process_1s(); - } - k_sleep(K_MSEC(10)); - } -} - -K_THREAD_DEFINE(serial_thread_id, 1280, serial_thread, NULL, NULL, NULL, 6, 0, 1000); - -#endif /* CONFIG_THINGSET_SERIAL */ diff --git a/test/autoconf.h b/test/autoconf.h deleted file mode 100644 index 96df341..0000000 --- a/test/autoconf.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -// PWM charge controller -#define CONFIG_PWM_TERMINAL_SOLAR 1 - -// MPPT buck/boost or nanogrid mode -#define CONFIG_HV_TERMINAL_SOLAR 1 -#define CONFIG_HV_TERMINAL_NANOGRID 0 - -// battery always assumed to be at low-voltage terminal (might need to be changed for boost mode) -#define CONFIG_LV_TERMINAL_BATTERY 1 - -#define CONFIG_THINGSET_EXPERT_PASSWORD "expert123" -#define CONFIG_THINGSET_MAKER_PASSWORD "maker456" - -// Values that are otherwise defined by Kconfig -#define CONFIG_CONTROL_FREQUENCY 10 // Hz - -#define CONFIG_BAT_TYPE_GEL 1 -#define CONFIG_BAT_TYPE 2 -#define CONFIG_BAT_CAPACITY_AH 50 -#define CONFIG_BAT_NUM_CELLS 6 -#define CONFIG_CELL_ABS_MAX_VOLTAGE_MV 2450 -#define CONFIG_CELL_TOPPING_VOLTAGE_MV 2400 -#define CONFIG_CELL_RECHARGE_VOLTAGE_MV 2300 -#define CONFIG_CELL_RECONNECT_VOLTAGE_MV 2100 -#define CONFIG_CELL_DISCONNECT_VOLTAGE_MV 1950 -#define CONFIG_CELL_ABS_MIN_VOLTAGE_MV 1600 -#define CONFIG_CELL_OCV_FULL_MV 2150 -#define CONFIG_CELL_OCV_EMPTY_MV 1900 -#define CONFIG_CELL_TRICKLE 1 -#define CONFIG_CELL_TRICKLE_VOLTAGE_MV 2300 -#define CONFIG_CELL_TRICKLE_RECHARGE_TIME 1800 -#define CONFIG_CELL_EQUALIZATION_VOLTAGE_MV 2450 -#define CONFIG_CELL_EQUALIZATION_DURATION 3600 -#define CONFIG_CELL_EQUALIZATION_TRIGGER_DAYS 60 -#define CONFIG_CELL_EQUALIZATION_TRIGGER_DEEP_CYCLES 10 -#define CONFIG_CELL_TEMP_COMPENSATION_MV_K -3 -#define CONFIG_CELL_INTERNAL_RESISTANCE_MOHM 5 -#define CONFIG_BAT_CHARGE_TEMP_MAX 50 -#define CONFIG_BAT_CHARGE_TEMP_MIN 0 -#define CONFIG_BAT_DISCHARGE_TEMP_MAX 50 -#define CONFIG_BAT_DISCHARGE_TEMP_MIN -10 -#define CONFIG_LOAD_OC_RECOVERY_DELAY 300 -#define CONFIG_LOAD_LVD_RECOVERY_DELAY 300 diff --git a/test/devicetree.h b/test/devicetree.h deleted file mode 100644 index 4463874..0000000 --- a/test/devicetree.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Macros copied from devicetree.h and util.h - */ - -#define DT_NODE_EXISTS(node_id) DT_CAT(node_id, _EXISTS) - -#define DT_PROP(node_id, prop) DT_CAT(node_id, _P_##prop) -#define DT_PROP_LEN(node_id, prop) DT_PROP(node_id, prop##_LEN) - -#define DT_CHILD(node_id, child) UTIL_CAT(node_id, DT_S_PREFIX(child)) - -#define DT_CAT(node_id, prop_suffix) node_id##prop_suffix - -#define DT_S_PREFIX(name) _S_##name - -#define UTIL_CAT(a, ...) UTIL_PRIMITIVE_CAT(a, __VA_ARGS__) -#define UTIL_PRIMITIVE_CAT(a, ...) a##__VA_ARGS__ - -#define DT_FOREACH_CHILD(node_id, fn) \ - DT_CAT(node_id, _FOREACH_CHILD)(fn) - -#define DT_PHA_BY_IDX(node_id, pha, idx, cell) \ - DT_PROP(node_id, pha##_IDX_##idx##_VAL_##cell) - -#define DT_PHA(node_id, pha, cell) DT_PHA_BY_IDX(node_id, pha, 0, cell) - -#define DT_PHANDLE_BY_IDX(node_id, prop, idx) \ - DT_PROP(node_id, prop##_IDX_##idx##_PH) - -#define DT_PROP_BY_PHANDLE_IDX(node_id, phs, idx, prop) \ - DT_PROP(DT_PHANDLE_BY_IDX(node_id, phs, idx), prop) - -#define DT_PROP_BY_PHANDLE(node_id, ph, prop) \ - DT_PROP_BY_PHANDLE_IDX(node_id, ph, 0, prop) - -#define DT_HAS_COMPAT_STATUS_OKAY(compat) \ - IS_ENABLED(DT_CAT(DT_COMPAT_HAS_OKAY_, compat)) - -/* - * Simplified mocks for certain macros from devicetree.h - */ - -#define DT_INST(inst, compat) UTIL_CAT(DT_N_INST_, UTIL_CAT(inst, UTIL_CAT(_, compat))) - -#define DT_PATH(node) UTIL_CAT(DT_N_S_, node) diff --git a/test/devicetree_unfixed.h b/test/devicetree_unfixed.h deleted file mode 100644 index 547b3a0..0000000 --- a/test/devicetree_unfixed.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -/* - * Needed defines that are normally generated by Zephyr build system - */ - -#define DT_N_S_pcb_P_type "TEST-PCB" -#define DT_N_S_pcb_P_version_str "v0.1" - -#define DT_N_S_pcb_P_hs_voltage_max 80 -#define DT_N_S_pcb_P_ls_voltage_max 32 - -#define DT_N_S_pcb_P_internal_tref_max 50 -#define DT_N_S_pcb_P_mosfets_tj_max 120 -#define DT_N_S_pcb_P_mosfets_tau_ja 5 - -#define DT_N_S_pcb_P_dcdc_current_max 20 -#define DT_N_S_pcb_P_dcdc_current_max_EXISTS 1 - -#define DT_COMPAT_HAS_OKAY_half_bridge 1 -#define DT_N_INST_0_half_bridge DT_N_S_soc_S_timers_40016800_S_halfbridge -#define DT_N_S_soc_S_timers_40016800_S_halfbridge_P_frequency 70000 -#define DT_N_S_soc_S_timers_40016800_S_halfbridge_P_deadtime 300 - -#define DT_N_S_outputs_S_pwm_switch_EXISTS 1 -#define DT_N_S_outputs_S_pwm_switch_P_current_max 20 -#define DT_N_S_outputs_S_pwm_switch_P_pwms_IDX_0_VAL_period 20000000 - -#define DT_N_S_outputs_S_load_EXISTS 1 -#define DT_N_S_outputs_S_load_P_current_max 20 - -#define DT_N_S_outputs_S_usb_pwr_EXISTS 1 - -/* - * ADC - */ -#define DT_N_S_adc_inputs_S_temp_bat_EXISTS 1 -#define DT_N_S_adc_inputs_S_temp_bat_P_multiplier 10000 -#define DT_N_S_adc_inputs_S_temp_bat_P_divider 1 -#define DT_N_S_adc_inputs_S_temp_bat_P_filter_const 5 - -#define DT_N_S_adc_inputs_S_v_high_P_multiplier 102800 -#define DT_N_S_adc_inputs_S_v_high_P_divider 2800 -#define DT_N_S_adc_inputs_S_v_high_P_filter_const 5 - -#define DT_N_S_adc_inputs_S_v_low_P_multiplier 105600 -#define DT_N_S_adc_inputs_S_v_low_P_divider 5600 -#define DT_N_S_adc_inputs_S_v_low_P_filter_const 5 - -#define DT_N_S_adc_inputs_S_v_pwm_P_multiplier 25224 // see pwm_2420_lus.dts -#define DT_N_S_adc_inputs_S_v_pwm_P_divider 984 -#define DT_N_S_adc_inputs_S_v_pwm_P_offset 2338 -#define DT_N_S_adc_inputs_S_v_pwm_P_filter_const 5 - -// amp gain: 50, resistor: 4 mOhm -#define DT_N_S_adc_inputs_S_i_load_P_multiplier 1000 -#define DT_N_S_adc_inputs_S_i_load_P_divider (4 * 50) -#define DT_N_S_adc_inputs_S_i_load_P_filter_const 5 - -#define DT_N_S_adc_inputs_S_i_dcdc_P_multiplier 1000 -#define DT_N_S_adc_inputs_S_i_dcdc_P_divider (4 * 50) -#define DT_N_S_adc_inputs_S_i_dcdc_P_filter_const 5 - -#define DT_N_S_adc_inputs_S_i_pwm_P_multiplier 1000 -#define DT_N_S_adc_inputs_S_i_pwm_P_divider (4 * 50) -#define DT_N_S_adc_inputs_S_i_pwm_P_filter_const 5 - -#define DT_N_S_adc_inputs_S_vref_mcu_P_filter_const 5 - -#define DT_N_S_adc_inputs_S_temp_mcu_P_filter_const 5 - -#define DT_N_S_adc_inputs_FOREACH_CHILD(fn) \ - fn(DT_N_S_adc_inputs_S_v_low) \ - fn(DT_N_S_adc_inputs_S_v_high) \ - fn(DT_N_S_adc_inputs_S_v_pwm) \ - fn(DT_N_S_adc_inputs_S_i_dcdc) \ - fn(DT_N_S_adc_inputs_S_i_load) \ - fn(DT_N_S_adc_inputs_S_i_pwm) \ - fn(DT_N_S_adc_inputs_S_temp_bat) \ - fn(DT_N_S_adc_inputs_S_vref_mcu) \ - fn(DT_N_S_adc_inputs_S_temp_mcu) - -/* - * LEDs - */ -#define DT_N_S_leds_FOREACH_CHILD(fn) \ - fn(DT_N_S_leds_S_pwr) - -#define DT_N_S_leds_P_gpios_IDX_0_PH DT_N_S_soc_S_pin_controller_48000000_S_gpio_48000800 -#define DT_N_S_leds_P_gpios_IDX_0_VAL_pin 15 -#define DT_N_S_leds_P_gpios_IDX_0_VAL_flags 0 -#define DT_N_S_leds_P_gpios_LEN 1 - -#define DT_N_S_soc_S_pin_controller_48000000_S_gpio_48000800_P_label "GPIOC" - -#define DT_N_S_leds_S_pwr_EXISTS 1 -#define DT_N_S_leds_S_pwr_P_states {1 /* 0x1 */} diff --git a/test/main.cpp b/test/main.cpp deleted file mode 100644 index 21172db..0000000 --- a/test/main.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "tests.h" - -#ifdef __WIN32__ - -// The below lines are added to fix unit test compilation error in PIO. -// The Unit Test Framework uses these functions like a constructor/destructor. -// We can just define two empty functions with these names. -void setUp (void) {} -void tearDown (void) {} - -#endif - -int main() -{ - daq_tests(); - bat_charger_tests(); - power_port_tests(); - half_bridge_tests(); - dcdc_tests(); - device_status_tests(); - load_tests(); - -#ifdef CUSTOM_TESTS - custom_tests(); -#endif -} diff --git a/test/tests.h b/test/tests.h deleted file mode 100644 index 27e50e9..0000000 --- a/test/tests.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include -#include - -void bat_charger_tests(); - -void daq_tests(); - -void power_port_tests(); - -void half_bridge_tests(); - -void dcdc_tests(); - -void device_status_tests(); - -void load_tests(); - -// activate this via build_flags in platformio.ini or custom.ini -#ifdef CUSTOM_TESTS -void custom_tests(); -#endif diff --git a/test/zephyr.h b/test/zephyr.h deleted file mode 100644 index a36c4c6..0000000 --- a/test/zephyr.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright (c) The Libre Solar Project Contributors - * - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * @file - * - * @brief Mock necessary functions and generated Devicetree or Kconfig defines from Zephyr - * for unit tests - */ - -#include "devicetree.h" -#include "devicetree_unfixed.h" -#include "autoconf.h" -#include "stdint.h" - -#ifndef __deprecated -#define __deprecated __attribute__((deprecated)) -#endif -#ifndef __weak -#define __weak __attribute__((__weak__)) -#endif - -#define printk printf - -#define CONFIG_LOG_DEFAULT_LEVEL 2 // errors and warnings only - -#define LOG_ERR(fmt, ...) \ - if (CONFIG_LOG_DEFAULT_LEVEL & (1 << 0)) { printf(fmt, ##__VA_ARGS__); printf("\n"); } - -#define LOG_WRN(fmt, ...) \ - if (CONFIG_LOG_DEFAULT_LEVEL & (1 << 1)) { printf(fmt, ##__VA_ARGS__); printf("\n"); } - -#define LOG_INF(fmt, ...) \ - if (CONFIG_LOG_DEFAULT_LEVEL & (1 << 2)) { printf(fmt, ##__VA_ARGS__); printf("\n"); } - -#define LOG_DBG(fmt, ...) \ - if (CONFIG_LOG_DEFAULT_LEVEL & (1 << 3)) { printf(fmt, ##__VA_ARGS__); printf("\n"); } - -// dummy -#define LOG_MODULE_REGISTER(a, b) - - -/* from gpio.h */ - -typedef uint8_t gpio_pin_t; - -typedef uint32_t gpio_flags_t; - - -/* crazy functions from Zephyr's util.h */ - -/** - * @brief Check for macro definition in compiler-visible expressions - * - * This trick was pioneered in Linux as the config_enabled() macro. It - * has the effect of taking a macro value that may be defined to "1" - * or may not be defined at all and turning it into a literal - * expression that can be handled by the C compiler instead of just - * the preprocessor. It is often used with a @p CONFIG_FOO macro which - * may be defined to 1 via Kconfig, or left undefined. - * - * That is, it works similarly to \#if defined(CONFIG_FOO) - * except that its expansion is a C expression. Thus, much \#ifdef - * usage can be replaced with equivalents like: - * - * if (IS_ENABLED(CONFIG_FOO)) { - * do_something_with_foo - * } - * - * This is cleaner since the compiler can generate errors and warnings - * for @p do_something_with_foo even when @p CONFIG_FOO is undefined. - * - * @param config_macro Macro to check - * @return 1 if @p config_macro is defined to 1, 0 otherwise (including - * if @p config_macro is not defined) - */ -#define IS_ENABLED(config_macro) Z_IS_ENABLED1(config_macro) - -/* This is called from IS_ENABLED(), and sticks on a "_XXXX" prefix, - * it will now be "_XXXX1" if config_macro is "1", or just "_XXXX" if it's - * undefined. - * ENABLED: Z_IS_ENABLED2(_XXXX1) - * DISABLED Z_IS_ENABLED2(_XXXX) - */ -#define Z_IS_ENABLED1(config_macro) Z_IS_ENABLED2(_XXXX##config_macro) - -/* Here's the core trick, we map "_XXXX1" to "_YYYY," (i.e. a string - * with a trailing comma), so it has the effect of making this a - * two-argument tuple to the preprocessor only in the case where the - * value is defined to "1" - * ENABLED: _YYYY, <--- note comma! - * DISABLED: _XXXX - */ -#define _XXXX1 _YYYY, - -/* Then we append an extra argument to fool the gcc preprocessor into - * accepting it as a varargs macro. - * arg1 arg2 arg3 - * ENABLED: Z_IS_ENABLED3(_YYYY, 1, 0) - * DISABLED Z_IS_ENABLED3(_XXXX 1, 0) - */ -#define Z_IS_ENABLED2(one_or_two_args) Z_IS_ENABLED3(one_or_two_args 1, 0) - -/* And our second argument is thus now cooked to be 1 in the case - * where the value is defined to 1, and 0 if not: - */ -#define Z_IS_ENABLED3(ignore_this, val, ...) val diff --git a/tests/.gitignore b/tests/.gitignore new file mode 100644 index 0000000..378eac2 --- /dev/null +++ b/tests/.gitignore @@ -0,0 +1 @@ +build diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..cf20571 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,47 @@ +# Copyright (c) The Libre Solar Project Contributors +# SPDX-License-Identifier: Apache-2.0 + +set(BOARD_ROOT ${CMAKE_SOURCE_DIR}/..) +set(DTS_ROOT ${CMAKE_SOURCE_DIR}/..) + +#set(BOARD "native_posix") +#set(ZEPHYR_TOOLCHAIN_VARIANT "host") + +cmake_minimum_required(VERSION 3.13.1) +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) + +project(libre_solar_charge_controller) +add_definitions(-DUNIT_TEST=1) +add_definitions(-DUNITY_OUTPUT_COLOR) +add_definitions(-DUNITY_EXCLUDE_SETJMP) + +add_subdirectory(../app/src build/app) + +zephyr_include_directories(./src) +zephyr_include_directories(../app/src) +zephyr_include_directories(../modules/thingset/src) +zephyr_include_directories(../modules/unity/src) + +target_sources(app PRIVATE + ../modules/unity/src/unity.c + src/main.cpp + src/tests_bat_charger.cpp + src/tests_daq.cpp + src/tests_dcdc.cpp + src/tests_device_status.cpp + src/tests_half_bridge.cpp + src/tests_load.cpp + src/tests_power_port.cpp +) + +# determine git tag and commit hash for automatic firmware versioning +find_package(Git) +if(GIT_FOUND) + execute_process( + COMMAND ${GIT_EXECUTABLE} describe --long --dirty --tags + OUTPUT_VARIABLE FIRMWARE_VERSION_ID + OUTPUT_STRIP_TRAILING_WHITESPACE) +else() + set(FIRMWARE_VERSION_ID "unknown") +endif() +add_definitions(-DFIRMWARE_VERSION_ID="${FIRMWARE_VERSION_ID}") diff --git a/tests/Kconfig b/tests/Kconfig new file mode 100644 index 0000000..6669869 --- /dev/null +++ b/tests/Kconfig @@ -0,0 +1,2 @@ + +rsource "../app/Kconfig" diff --git a/tests/boards/native_posix.overlay b/tests/boards/native_posix.overlay new file mode 100644 index 0000000..ebc8de8 --- /dev/null +++ b/tests/boards/native_posix.overlay @@ -0,0 +1,163 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/ { + /* delete conflicting nodes from Zephyr native_posix board */ + /delete-node/ leds; + /delete-node/ aliases; + + pcb { + compatible = "charge-controller"; + + type = "Native POSIX dummy"; + version-str = "v0.1"; + version-num = <1>; + + hs-voltage-max = <80>; + ls-voltage-max = <32>; + dcdc-current-max = <20>; + }; + + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + zephyr,flash = &flash0; + }; + + leds { + compatible = "charlieplexing-leds"; + gpios = <&gpio0 6 GPIO_ACTIVE_LOW>, /* chg red */ + <&gpio0 14 GPIO_ACTIVE_LOW>, /* chg green */ + <&gpio0 9 GPIO_ACTIVE_LOW>, /* dis red */ + <&gpio0 15 GPIO_ACTIVE_LOW>; /* dis green */ + + pwr { + states = <0 1 0 0>; + }; + + load { + states = <0 0 0 1>; + }; + }; + + outputs { + compatible = "outputs"; + + pwm_switch { + label = "PWM power switch (solar panel)"; + pwms = <&pwm3 2 (20*1000*1000) 0>; /* 20 ms period = 50 Hz */ + current-max = <20>; + kconfig-flag; /* make node visible in Kconfig */ + }; + + load { + label = "Load output"; + gpios = <&gpio0 2 GPIO_ACTIVE_LOW>; + current-max = <20>; + kconfig-flag; /* make node visible in Kconfig */ + }; + + can_en { + label = "CAN disable / standby"; + gpios = <&gpio0 11 GPIO_ACTIVE_LOW>; + }; + }; + + adc1: adc1 { + compatible = "zephyr,dummy-adc"; + label = "ADC_1"; + #io-channel-cells = <1>; + }; + + adc-inputs { + compatible = "adc-inputs"; + + v-low { + io-channels = <&adc1 12>; + multiplier = <105600>; + divider = <5600>; + }; + + v-high { + io-channels = <&adc1 15>; + multiplier = <102200>; + divider = <2200>; + }; + + v-pwm { + io-channels = <&adc1 4>; + multiplier = <25224>; // (12*8.2 + 120*8.2 + 120*12) * 10 + divider = <984>; // (8.2*12) * 10 + offset = <37414>; // 65536 / (1 + 8.2/120 + 8.2/12) + }; + + temp-fets { + io-channels = <&adc1 11>; + multiplier = <10000>; // 10k NTC series resistor + divider = <1>; + }; + + vref-mcu { + io-channels = <&adc1 18>; + multiplier = <1>; + divider = <1>; + }; + + temp-mcu { + io-channels = <&adc1 16>; + multiplier = <1>; + divider = <1>; + }; + + i-dcdc { + io-channels = <&adc1 1>; + // amp gain: 25, resistor: 2 mOhm + multiplier = <1000>; // 1000 + divider = <50>; // 2*25 + }; + + i-load { + io-channels = <&adc1 2>; + // amp gain: 25, resistor: 2 mOhm + multiplier = <1000>; // 1000 + divider = <50>; // 2*25 + }; + + i-pwm { + io-channels = <&adc1 5>; + // amp gain: 68/2.2, resistor: 2 mOhm + multiplier = <2200>; // 1000*2.2 + divider = <136>; // 2*68 + }; + }; + + timers1: timers1 { + status = "okay"; + + halfbridge { + compatible = "half-bridge"; + frequency = <70000>; + deadtime = <300>; + }; + }; + + timers3: timers { + status = "okay"; + + pwm3: pwm3 { + compatible = "zephyr,dummy-pwm"; + label = "PWM_3"; + #pwm-cells = <3>; + }; + }; + + aliases { + uart-dbg = &uart0; + uart-uext = &uart0; +// spi-uext = &spi1; +// i2c-uext = &i2c1; + }; +}; diff --git a/tests/prj.conf b/tests/prj.conf new file mode 100644 index 0000000..344a95f --- /dev/null +++ b/tests/prj.conf @@ -0,0 +1,40 @@ +# Main application configuration (overrides board-specific settings) + +# only very small heap necessary for malloc in printf statements with %f +CONFIG_HEAP_MEM_POOL_SIZE=256 + +CONFIG_CPLUSPLUS=y +CONFIG_LIB_CPLUSPLUS=y + +#CONFIG_WATCHDOG=y +#CONFIG_WDT_DISABLE_AT_BOOT=y +CONFIG_TASK_WDT=y +CONFIG_THREAD_NAME=y + +CONFIG_REBOOT=y + +CONFIG_HWINFO=y + +CONFIG_CONSOLE_SUBSYS=y + +CONFIG_LOG=y + +CONFIG_THINGSET=y + +# ThingSet protocol interface via UART serial +CONFIG_THINGSET_SERIAL=n + +# Uncomment to disable regular data publication on ThingSet serial at startup +CONFIG_THINGSET_SERIAL_PUB_DEFAULT=n + +# Uncomment to use LS.one or debug RX/TX connector instead of UEXT serial for ThingSet +CONFIG_UEXT_SERIAL_THINGSET=n + +# Uncomment to enable I2C OLED display in UEXT connector +#CONFIG_UEXT_OLED_DISPLAY=y + +# Select initial battery configuration: GEL (default), FLOODED, AGM, LFP, NMC or NMC_HV +#CONFIG_BAT_TYPE_???=y + +# Change number of cells considering selected type (12V/24V battery by default if not set) +#CONFIG_BAT_NUM_CELLS=? diff --git a/test/daq_stub.h b/tests/src/daq_stub.h similarity index 100% rename from test/daq_stub.h rename to tests/src/daq_stub.h diff --git a/tests/src/main.cpp b/tests/src/main.cpp new file mode 100644 index 0000000..637683e --- /dev/null +++ b/tests/src/main.cpp @@ -0,0 +1,45 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include "unity.h" + +#include +#include + +#ifdef CONFIG_ARCH_POSIX +#include "posix_board_if.h" +#endif + +#include "tests.h" + +extern "C" { + +void setUp (void) {} +void tearDown (void) {} + +} /* extern "C" */ + +void main() +{ + int err = 0; + + err += daq_tests(); + err += bat_charger_tests(); + err += power_port_tests(); + err += half_bridge_tests(); + err += dcdc_tests(); + err += device_status_tests(); + err += load_tests(); + +#ifdef CONFIG_CUSTOM_TESTS + err += custom_tests(); +#endif + +#ifdef CONFIG_ARCH_POSIX + posix_exit(err); +#endif +} diff --git a/tests/src/tests.h b/tests/src/tests.h new file mode 100644 index 0000000..8ebea20 --- /dev/null +++ b/tests/src/tests.h @@ -0,0 +1,26 @@ +/* + * Copyright (c) The Libre Solar Project Contributors + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include + +int bat_charger_tests(); + +int daq_tests(); + +int power_port_tests(); + +int half_bridge_tests(); + +int dcdc_tests(); + +int device_status_tests(); + +int load_tests(); + +#ifdef CONFIG_CUSTOM_TESTS +int custom_tests(); +#endif diff --git a/test/tests_bat_charger.cpp b/tests/src/tests_bat_charger.cpp similarity index 83% rename from test/tests_bat_charger.cpp rename to tests/src/tests_bat_charger.cpp index 1ae377e..0807df8 100644 --- a/test/tests_bat_charger.cpp +++ b/tests/src/tests_bat_charger.cpp @@ -25,7 +25,7 @@ static void init_structs() void no_start_at_high_voltage() { init_structs(); - bat_terminal.bus->voltage = bat_conf.voltage_recharge + 0.1; + bat_terminal.bus->voltage = bat_conf.recharge_voltage + 0.1; charger.charge_control(&bat_conf); TEST_ASSERT_EQUAL(CHG_STATE_IDLE, charger.state); } @@ -34,7 +34,7 @@ void no_start_after_short_rest() { init_structs(); charger.time_state_changed = time(NULL) - bat_conf.time_limit_recharge + 1; - bat_terminal.bus->voltage = bat_conf.voltage_recharge - 0.1; + bat_terminal.bus->voltage = bat_conf.recharge_voltage - 0.1; charger.charge_control(&bat_conf); TEST_ASSERT_EQUAL(CHG_STATE_IDLE, charger.state); } @@ -43,7 +43,7 @@ void no_start_outside_temperature_limits() { init_structs(); charger.bat_temperature = bat_conf.charge_temp_max + 1; - bat_terminal.bus->voltage = bat_conf.voltage_recharge - 0.1; + bat_terminal.bus->voltage = bat_conf.recharge_voltage - 0.1; charger.charge_control(&bat_conf); TEST_ASSERT_EQUAL(CHG_STATE_IDLE, charger.state); @@ -56,7 +56,7 @@ void start_if_everything_just_fine() { init_structs(); charger.time_state_changed = time(NULL) - bat_conf.time_limit_recharge - 1; - bat_terminal.bus->voltage = bat_conf.voltage_recharge - 0.1; + bat_terminal.bus->voltage = bat_conf.recharge_voltage - 0.1; charger.charge_control(&bat_conf); TEST_ASSERT_EQUAL(CHG_STATE_BULK, charger.state); } @@ -65,7 +65,7 @@ void enter_topping_at_voltage_setpoint() { init_structs(); charger.time_state_changed = time(NULL) - bat_conf.time_limit_recharge - 1; - bat_terminal.bus->voltage = bat_conf.voltage_recharge - 0.1; + bat_terminal.bus->voltage = bat_conf.recharge_voltage - 0.1; bat_terminal.bus->voltage_filtered = bat_terminal.bus->voltage; charger.charge_control(&bat_conf); TEST_ASSERT_EQUAL(CHG_STATE_BULK, charger.state); @@ -82,7 +82,7 @@ void topping_to_bulk_after_8h_low_power() charger.time_state_changed = time(NULL) - 8 * 60 * 60 + 1; bat_terminal.bus->voltage = bat_conf.topping_voltage - 0.1; bat_terminal.bus->voltage_filtered = bat_terminal.bus->voltage; - bat_terminal.current = bat_conf.topping_current_cutoff + 0.1; + bat_terminal.current = bat_conf.topping_cutoff_current + 0.1; bat_terminal.current_filtered = bat_terminal.current; charger.charge_control(&bat_conf); @@ -98,7 +98,7 @@ void stop_topping_after_time_limit() enter_topping_at_voltage_setpoint(); charger.target_voltage_timer = bat_conf.topping_duration - 1; - bat_terminal.current = bat_conf.topping_current_cutoff + 0.1; + bat_terminal.current = bat_conf.topping_cutoff_current + 0.1; bat_terminal.current_filtered = bat_terminal.current; bat_terminal.bus->voltage = bat_conf.topping_voltage - bat_terminal.current * bat_terminal.bus->sink_droop_res + 0.1; @@ -109,7 +109,7 @@ void stop_topping_after_time_limit() charger.target_voltage_timer = bat_conf.topping_duration + 1; charger.charge_control(&bat_conf); - TEST_ASSERT_EQUAL(CHG_STATE_TRICKLE, charger.state); + TEST_ASSERT_EQUAL(CHG_STATE_FLOAT, charger.state); } void stop_topping_at_cutoff_current() @@ -117,22 +117,22 @@ void stop_topping_at_cutoff_current() enter_topping_at_voltage_setpoint(); charger.target_voltage_timer = 0; - bat_terminal.current = bat_conf.topping_current_cutoff - 0.1; + bat_terminal.current = bat_conf.topping_cutoff_current - 0.1; bat_terminal.current_filtered = bat_terminal.current; bat_terminal.bus->voltage = bat_conf.topping_voltage - bat_terminal.current * bat_terminal.bus->sink_droop_res + 0.1; bat_terminal.bus->voltage_filtered = bat_terminal.bus->voltage; charger.charge_control(&bat_conf); - TEST_ASSERT_EQUAL(CHG_STATE_TRICKLE, charger.state); + TEST_ASSERT_EQUAL(CHG_STATE_FLOAT, charger.state); } -void trickle_to_idle_for_li_ion() +void float_to_idle_for_li_ion() { enter_topping_at_voltage_setpoint(); battery_conf_init(&bat_conf, BAT_TYPE_LFP, 4, 100); charger.time_state_changed = time(NULL) - 1; - bat_terminal.current = bat_conf.topping_current_cutoff - 0.1; + bat_terminal.current = bat_conf.topping_cutoff_current - 0.1; bat_terminal.bus->voltage = bat_conf.topping_voltage - bat_terminal.current * bat_terminal.bus->sink_droop_res + 0.1; charger.charge_control(&bat_conf); @@ -152,7 +152,7 @@ void no_equalization_if_disabled() charger.time_state_changed = time(NULL) - 1; bat_terminal.bus->voltage = bat_conf.topping_voltage + 0.1; - bat_terminal.current = bat_conf.topping_current_cutoff - 0.1; + bat_terminal.current = bat_conf.topping_cutoff_current - 0.1; charger.charge_control(&bat_conf); TEST_ASSERT_NOT_EQUAL(CHG_STATE_EQUALIZATION, charger.state); } @@ -170,12 +170,12 @@ void no_equalization_if_limits_not_reached() charger.time_state_changed = time(NULL) - 1; bat_terminal.bus->voltage = bat_conf.topping_voltage + 0.1; - bat_terminal.current = bat_conf.topping_current_cutoff - 0.1; + bat_terminal.current = bat_conf.topping_cutoff_current - 0.1; charger.charge_control(&bat_conf); TEST_ASSERT_NOT_EQUAL(CHG_STATE_EQUALIZATION, charger.state); } -void trickle_to_equalization_if_enabled_and_time_limit_reached() +void float_to_equalization_if_enabled_and_time_limit_reached() { enter_topping_at_voltage_setpoint(); bat_conf.equalization_enabled = true; @@ -183,7 +183,7 @@ void trickle_to_equalization_if_enabled_and_time_limit_reached() time(NULL) - bat_conf.equalization_trigger_days * 24*60*60; charger.time_state_changed = time(NULL) - 1; - bat_terminal.current = bat_conf.topping_current_cutoff - 0.1; + bat_terminal.current = bat_conf.topping_cutoff_current - 0.1; bat_terminal.bus->voltage = bat_conf.topping_voltage - bat_terminal.current * bat_terminal.bus->sink_droop_res + 0.1; charger.charge_control(&bat_conf); @@ -191,7 +191,7 @@ void trickle_to_equalization_if_enabled_and_time_limit_reached() } -void trickle_to_equalization_if_enabled_and_deep_dis_limit_reached() +void float_to_equalization_if_enabled_and_deep_dis_limit_reached() { enter_topping_at_voltage_setpoint(); bat_conf.equalization_enabled = true; @@ -199,7 +199,7 @@ void trickle_to_equalization_if_enabled_and_deep_dis_limit_reached() charger.num_deep_discharges - bat_conf.equalization_trigger_deep_cycles; charger.time_state_changed = time(NULL) - 1; - bat_terminal.current = bat_conf.topping_current_cutoff - 0.1; + bat_terminal.current = bat_conf.topping_cutoff_current - 0.1; bat_terminal.bus->voltage = bat_conf.topping_voltage - bat_terminal.current * bat_terminal.bus->sink_droop_res + 0.1; charger.charge_control(&bat_conf); @@ -209,7 +209,7 @@ void trickle_to_equalization_if_enabled_and_deep_dis_limit_reached() void stop_equalization_after_time_limit() { - trickle_to_equalization_if_enabled_and_time_limit_reached(); + float_to_equalization_if_enabled_and_time_limit_reached(); charger.time_state_changed = time(NULL) - bat_conf.equalization_duration + 1; bat_terminal.bus->voltage = bat_conf.equalization_voltage - @@ -220,10 +220,10 @@ void stop_equalization_after_time_limit() charger.time_state_changed = time(NULL) - bat_conf.topping_duration - 1; charger.charge_control(&bat_conf); - TEST_ASSERT_EQUAL(CHG_STATE_TRICKLE, charger.state); + TEST_ASSERT_EQUAL(CHG_STATE_FLOAT, charger.state); } -void restart_bulk_from_trickle_if_voltage_drops() +void restart_bulk_from_float_if_voltage_drops() { TEST_ASSERT(0); } @@ -236,7 +236,7 @@ void stop_discharge_at_low_voltage() charger.discharge_control(&bat_conf); TEST_ASSERT_LESS_THAN(0, bat_terminal.neg_current_limit); - bat_terminal.bus->voltage = bat_conf.voltage_absolute_min - 0.1; + bat_terminal.bus->voltage = bat_conf.absolute_min_voltage - 0.1; charger.discharge_control(&bat_conf); TEST_ASSERT_EQUAL(0, bat_terminal.neg_current_limit); } @@ -266,17 +266,17 @@ void restart_discharge_if_allowed() init_structs(); // stop because of undervoltage - bat_terminal.bus->voltage = bat_conf.voltage_absolute_min - 0.1; + bat_terminal.bus->voltage = bat_conf.absolute_min_voltage - 0.1; charger.discharge_control(&bat_conf); TEST_ASSERT_EQUAL(0, bat_terminal.neg_current_limit); // increase voltage slightly above absolute minimum - bat_terminal.bus->voltage = bat_conf.voltage_absolute_min + 0.05; + bat_terminal.bus->voltage = bat_conf.absolute_min_voltage + 0.05; charger.discharge_control(&bat_conf); TEST_ASSERT_EQUAL(0, bat_terminal.neg_current_limit); // increase voltage above hysteresis voltage - bat_terminal.bus->voltage = bat_conf.voltage_absolute_min + 0.15; + bat_terminal.bus->voltage = bat_conf.absolute_min_voltage + 0.15; charger.discharge_control(&bat_conf); TEST_ASSERT_LESS_THAN(0, bat_terminal.neg_current_limit); } @@ -296,7 +296,7 @@ void no_soc_below_0() TEST_ASSERT(0); } -void bat_charger_tests() +int bat_charger_tests() { UNITY_BEGIN(); @@ -312,17 +312,17 @@ void bat_charger_tests() RUN_TEST(stop_topping_after_time_limit); RUN_TEST(stop_topping_at_cutoff_current); - // trickle - RUN_TEST(trickle_to_idle_for_li_ion); + // float + RUN_TEST(float_to_idle_for_li_ion); // equalization RUN_TEST(no_equalization_if_disabled); RUN_TEST(no_equalization_if_limits_not_reached); - RUN_TEST(trickle_to_equalization_if_enabled_and_time_limit_reached); - RUN_TEST(trickle_to_equalization_if_enabled_and_deep_dis_limit_reached); + RUN_TEST(float_to_equalization_if_enabled_and_time_limit_reached); + RUN_TEST(float_to_equalization_if_enabled_and_deep_dis_limit_reached); RUN_TEST(stop_equalization_after_time_limit); - //RUN_TEST(restart_bulk_from_trickle_if_voltage_drops); + //RUN_TEST(restart_bulk_from_float_if_voltage_drops); // TODO: temperature compensation // TODO: current compensation @@ -338,5 +338,5 @@ void bat_charger_tests() //RUN_TEST(no_soc_above_100); //RUN_TEST(no_soc_below_0); - UNITY_END(); + return UNITY_END(); } diff --git a/test/tests_daq.cpp b/tests/src/tests_daq.cpp similarity index 93% rename from test/tests_daq.cpp rename to tests/src/tests_daq.cpp index dd901be..a12765d 100644 --- a/test/tests_daq.cpp +++ b/tests/src/tests_daq.cpp @@ -95,12 +95,12 @@ void adc_alert_lv_undervoltage_triggering() { dev_stat.clear_error(ERR_ANY_ERROR); battery_conf_init(&bat_conf, BAT_TYPE_LFP, 4, 100); - daq_set_lv_limits(bat_conf.voltage_absolute_max, bat_conf.voltage_absolute_min); + daq_set_lv_limits(bat_conf.absolute_max_voltage, bat_conf.absolute_min_voltage); prepare_adc_filtered(); adc_update_value(ADC_POS(v_low)); // undervoltage test - adcval.battery_voltage = bat_conf.voltage_absolute_min - 0.1; + adcval.battery_voltage = bat_conf.absolute_min_voltage - 0.1; prepare_adc_readings(adcval); adc_update_value(ADC_POS(v_low)); TEST_ASSERT_EQUAL(false, dev_stat.has_error(ERR_LOAD_VOLTAGE_DIP)); @@ -123,20 +123,20 @@ void adc_alert_lv_overvoltage_triggering() { dev_stat.clear_error(ERR_ANY_ERROR); battery_conf_init(&bat_conf, BAT_TYPE_LFP, 4, 100); - daq_set_lv_limits(bat_conf.voltage_absolute_max, bat_conf.voltage_absolute_min); + daq_set_lv_limits(bat_conf.absolute_max_voltage, bat_conf.absolute_min_voltage); prepare_adc_filtered(); adc_update_value(ADC_POS(v_low)); dcdc.state = DCDC_CONTROL_MPPT; // overvoltage test - adcval.battery_voltage = bat_conf.voltage_absolute_max + 0.1; + adcval.battery_voltage = bat_conf.absolute_max_voltage + 0.1; prepare_adc_readings(adcval); adc_update_value(ADC_POS(v_low)); TEST_ASSERT_EQUAL(false, dev_stat.has_error(ERR_BAT_OVERVOLTAGE)); adc_update_value(ADC_POS(v_low)); TEST_ASSERT_EQUAL(true, dev_stat.has_error(ERR_BAT_OVERVOLTAGE)); - TEST_ASSERT_EQUAL(false, pwm_switch.active()); + //TEST_ASSERT_EQUAL(false, pwm_switch.active()); TEST_ASSERT_EQUAL(DCDC_CONTROL_OFF, dcdc.state); // reset values @@ -179,7 +179,7 @@ void adc_alert_overflow_prevention() * Purpose: Check if raw data from 2 voltage and 2 current measurements are converted * to calculated voltage/current measurements of different DC buses */ -void daq_tests() +int daq_tests() { adcval.bat_temperature = 25; adcval.battery_voltage = 12; @@ -210,5 +210,5 @@ void daq_tests() RUN_TEST(adc_alert_hv_overvoltage_triggering); RUN_TEST(adc_alert_overflow_prevention); - UNITY_END(); + return UNITY_END(); } diff --git a/test/tests_dcdc.cpp b/tests/src/tests_dcdc.cpp similarity index 99% rename from test/tests_dcdc.cpp rename to tests/src/tests_dcdc.cpp index 78f92da..a0d4f48 100644 --- a/test/tests_dcdc.cpp +++ b/tests/src/tests_dcdc.cpp @@ -413,7 +413,7 @@ void boost_correct_mppt_operation() TEST_ASSERT(pwm3 > pwm2); } -void dcdc_tests() +int dcdc_tests() { UNITY_BEGIN(); @@ -472,5 +472,5 @@ void dcdc_tests() RUN_TEST(boost_stop_high_voltage_emergency); RUN_TEST(boost_correct_mppt_operation); - UNITY_END(); + return UNITY_END(); } diff --git a/test/tests_device_status.cpp b/tests/src/tests_device_status.cpp similarity index 98% rename from test/tests_device_status.cpp rename to tests/src/tests_device_status.cpp index 6fd5fd8..0d9e67e 100644 --- a/test/tests_device_status.cpp +++ b/tests/src/tests_device_status.cpp @@ -119,7 +119,7 @@ void dev_stat_new_int_temp_max() TEST_ASSERT_EQUAL(22, dev_stat.int_temp_max); } -void device_status_tests() +int device_status_tests() { UNITY_BEGIN(); @@ -135,5 +135,5 @@ void device_status_tests() RUN_TEST(dev_stat_new_bat_temp_max); RUN_TEST(dev_stat_new_int_temp_max); - UNITY_END(); + return UNITY_END(); } diff --git a/test/tests_half_bridge.cpp b/tests/src/tests_half_bridge.cpp similarity index 97% rename from test/tests_half_bridge.cpp rename to tests/src/tests_half_bridge.cpp index ad914a1..ff16f36 100644 --- a/test/tests_half_bridge.cpp +++ b/tests/src/tests_half_bridge.cpp @@ -71,7 +71,7 @@ void half_bridge_ccr_limits_not_violated() TEST_ASSERT_FLOAT_WITHIN(duty_epsilon, MIN_PWM_DUTY, half_bridge_get_duty_cycle()); } -void half_bridge_tests() +int half_bridge_tests() { init_structs(); @@ -84,5 +84,5 @@ void half_bridge_tests() RUN_TEST(half_bridge_duty_limits_not_violated); RUN_TEST(half_bridge_ccr_limits_not_violated); - UNITY_END(); + return UNITY_END(); } diff --git a/test/tests_load.cpp b/tests/src/tests_load.cpp similarity index 99% rename from test/tests_load.cpp rename to tests/src/tests_load.cpp index 5474209..209132d 100644 --- a/test/tests_load.cpp +++ b/tests/src/tests_load.cpp @@ -288,7 +288,7 @@ void control_off_short_circuit_flag_reset() TEST_ASSERT_EQUAL(LOAD_STATE_ON, load_out.state); } -void load_tests() +int load_tests() { UNITY_BEGIN(); @@ -311,5 +311,5 @@ void load_tests() // ToDo: What to do if port current is above the limit, but the hardware can still handle it? - UNITY_END(); + return UNITY_END(); } diff --git a/test/tests_power_port.cpp b/tests/src/tests_power_port.cpp similarity index 98% rename from test/tests_power_port.cpp rename to tests/src/tests_power_port.cpp index 7d84af2..af2a6bb 100644 --- a/test/tests_power_port.cpp +++ b/tests/src/tests_power_port.cpp @@ -91,7 +91,7 @@ void load_output_energy_calculation_valid() TEST_ASSERT_EQUAL_FLOAT(round((sun_hours + night_hours) * lv_terminal.bus->voltage * adcval.load_current), round(load.pos_energy_Wh)); } -void power_port_tests() +int power_port_tests() { energy_calculation_init(); @@ -103,5 +103,5 @@ void power_port_tests() RUN_TEST(solar_input_energy_calculation_valid); RUN_TEST(load_output_energy_calculation_valid); - UNITY_END(); + return UNITY_END(); } diff --git a/zephyr/west.yml b/zephyr/west.yml deleted file mode 100644 index dec5167..0000000 --- a/zephyr/west.yml +++ /dev/null @@ -1,20 +0,0 @@ -manifest: - remotes: - - name: zephyrproject-rtos - url-base: https://github.com/zephyrproject-rtos - - name: libresolar - url-base: https://github.com/LibreSolar - projects: - - name: zephyr - remote: libresolar - revision: v2.5-branch - # path must be something else than zephyr as we get a Kconfig include recursion otherwise - path: rtos - import: - # main zephyr modules should be placed in here into zephyr subdirectory - path-prefix: zephyr - # only get modules we actually need - name-whitelist: - - cmsis - - edtt - - hal_stm32