diff --git a/README.md b/README.md index 512282c..88c819b 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ![build badge](https://travis-ci.com/LibreSolar/charge-controller-firmware.svg?branch=master) -This repository contains the firmware for the different Libre Solar Charge Controllers. Originally, the firmware was based on [ARM Mbed OS](https://www.mbed.com). The current version also supports using [Zephyr RTOS](https://www.zephyrproject.org/) for some boards. +This repository contains the firmware for the different Libre Solar Charge Controllers based on [Zephyr RTOS](https://www.zephyrproject.org/). Coding style is described [here](https://github.com/LibreSolar/coding-style). @@ -10,7 +10,7 @@ Coding style is described [here](https://github.com/LibreSolar/coding-style). ## Supported devices -The software is configurable to support different charge controller PCBs with either STM32F072 (including CAN support) or low-power STM32L072/3 MCUs. +The software is configurable to support different charge controller PCBs with STM32F072, low-power STM32L072/3 or most recent STM32G431 MCUs: - [Libre Solar MPPT 12/24V 20A with CAN](https://github.com/LibreSolar/MPPT-2420-LC) - [Libre Solar MPPT 12V 10A with USB](https://github.com/LibreSolar/MPPT-1210-HUS) @@ -26,7 +26,7 @@ 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`. -### ARM Mbed OS +### PlatfrormIO It is suggested to use Visual Studio Code and PlatformIO for firmware development, as it simplifies compiling and uploading the code a lot: @@ -40,15 +40,28 @@ It is suggested to use Visual Studio Code and PlatformIO for firmware developmen 5. Press the upload button at the bottom left corner in VS Code. -### Zephyr +### Native Zephyr environment -Support for Zephyr was recently added to PlatformIO. You may need to run `pio upgrade` and `pio update` to get the most recent version. +You can also use the Zephyr build system directly for advanced configuration using `menuconfig` or if you need more recently added features. -After that, you should be able to compile and flash Zephyr for supported boards (-zephyr suffix in platformio.ini) in the same way as explained above for Mbed. +The CMake entry point is in the `zephyr` subfolder, so you need to run `west` command in that directory. -As the build system in PlatformIO is not the same as the native Zephyr build system, there might still be some issues. Generally, also `west build` and `west flash` should work if called from within the zephyr subdirectory. +Initial board selection (see `boards subfolder for correct names): -**Important:** For the STM32G4 we require several bug fixes that were introduced in Zephyr v2.2. The PlatformIO package is currently based on v2.1, so it is required to use native Zephyr build system until PlatformIO package is updated. + west build -b + +Flash with specific debug probe (runner), e.g. J-Link: + + west flash -r jlink + +User configuration using menuconfig: + + west build -t menuconfig + +Report of used memory (RAM and flash): + + west build -t rom_report + west build -t ram_report ### Troubleshooting @@ -58,11 +71,9 @@ The standard OpenOCD settings sometimes fail to flash firmware to this MCU, whic Try one of these workarounds: -1. Change OpenOCD settings to `set WORKAREASIZE 0x1000` in the file `~/.platformio/packages/tool-openocd/scripts/board/st_nucleo_l073rz.cfg`. +1. Change OpenOCD settings to `adapter_khz 500` in line 70 in `~/.platformio/packages/tool-openocd/scripts/target/stm32l0.cfg`. -2. Use ST-Link tools. For Windows there is a GUI tool. Under Linux, uncomment the `upload_command` line in `platformio.ini`. - -3. Use other debuggers and tools, e.g. Segger J-Link. +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 @@ -97,9 +108,10 @@ 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 each pull-request) use the script `check.sh`: +the same tests locally (recommended before each pull-request) use the script `check.sh` or ` check.bat`: - bash check.sh + bash check.sh # Linux + cmd check.bat # Windows ### Unit-tests diff --git a/STM32L073XZ.ld.link_script.ld b/boards/STM32L073XZ.ld.link_script.ld similarity index 100% rename from STM32L073XZ.ld.link_script.ld rename to boards/STM32L073XZ.ld.link_script.ld diff --git a/linker_flags_newlib-nano.py b/linker_flags_newlib-nano.py deleted file mode 100644 index 75cf321..0000000 --- a/linker_flags_newlib-nano.py +++ /dev/null @@ -1,18 +0,0 @@ -# Custom settings, as referred to as "extra_script" in platformio.ini -# -# See http://docs.platformio.org/en/latest/projectconf.html#extra-script -# and https://docs.platformio.org/en/latest/projectconf/advanced_scripting.html#extra-linker-flags-without-wl-prefix -# -# We are setting the required linker flags for use of newlib-nano - - -Import("env") - -env.Append( - LINKFLAGS=[ - "-Wl,-u,_printf_float", - "--specs=nano.specs", - "--specs=nosys.specs" - ]) - -env.Append( CXXFLAGS=[ "-Wno-register" ] ) diff --git a/mbed_app.json b/mbed_app.json deleted file mode 100644 index c2bb077..0000000 --- a/mbed_app.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "config": { - "enable-led-control-example": true, - "LED": "NC", - "BUTTON": "NC", - "BUTTON_MODE": "PullUp" - }, - "target_overrides": { - "NUCLEO_L073RZ": { - "target.lse_available" : 0, - "target.clock_source" : "USE_PLL_HSI", - "target.stdio_uart_tx" : "PA_9", - "target.stdio_uart_rx" : "PA_10" - }, - "NUCLEO_F072RB": { - "target.lse_available" : 0, - "target.clock_source" : "USE_PLL_HSE_XTAL|USE_PLL_HSI", - "target.stdio_uart_tx" : "PA_9", - "target.stdio_uart_rx" : "PA_10" - } - } -} diff --git a/platformio.ini b/platformio.ini index 07dd907..6930809 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,18 +10,10 @@ # Select the charge controller hardware by uncommenting one of the following lines default_envs = # mppt-2420-lc-v0.10 -# mppt-2420-lc-v0.10-zephyr -# mppt-2420-hpx-v0.1-zephyr -# mppt-1210-hus-v0.2 +# mppt-2420-hpx-v0.1 # mppt-1210-hus-v0.4 -# mppt-1210-hus-v0.6 # mppt-1210-hus-v0.7 -# mppt-1210-hus-v0.4-zephyr -# mppt-1210-hus-v0.7-zephyr -# pwm-2420-lus-v0.2 # pwm-2420-lus-v0.3 -# pwm-2420-lus-v0.3-bl -# pwm-2420-lus-v0.3-zephyr # unit-test-native # Or create your own custom.ini file to overwrite settings in this file, e.g. for board selection. @@ -33,10 +25,10 @@ extra_configs = [env] # select specific stm32 version, as automatic updates of mbed could break compatibility -platform = ststm32@~5.3.0 -#platform = https://github.com/platformio/platform-ststm32.git +platform = https://github.com/platformio/platform-ststm32.git +#platform = ststm32@~5.3.0 -framework = mbed +framework = zephyr #upload_protocol = mbed upload_protocol = stlink @@ -44,10 +36,6 @@ upload_protocol = stlink #debug_tool = jlink -# Custom upload tools (overwrites upload_protocol) -#upload_command = st-flash write $SOURCE 0x8000000 -#upload_command = dfu-util -d 0483:df11 -a 0 -s 0x08000000:leave -D $SOURCE - # Custom Serial Monitor baud rate monitor_speed = 115200 @@ -56,16 +44,13 @@ build_flags = -std=gnu++17 -fsingle-precision-constant -Wl,-Map,memory.map - -D TURN_OFF_MBED_DEPRECATED_WARNING - -D DEBUG_PRINT_FLAGS=0x7 - -D MBED_BUILD_PROFILE_RELEASE -# -D MBED_BUILD_PROFILE_DEBUG build_unflags = -std=gnu++98 -std=gnu++14 extra_scripts = - pre:linker_flags_newlib-nano.py generate_version_file.py +lib_ignore = ESP32 + check_tool = cppcheck, clangtidy check_flags = cppcheck: --enable=warning,style,performance,portability,information,missingInclude -j 7 @@ -76,106 +61,28 @@ check_flags = # https://github.com/LibreSolar/MPPT-2420-LC/tree/5bc39183c8 [env:mppt-2420-lc-v0.10] -board = nucleo_f072rb -build_flags = ${env.build_flags} - -D CONFIG_BOARD_MPPT_2420_LC_0V10 - -[env:mppt-2420-lc-v0.10-zephyr] board = mppt_2420_lc_0v10 -framework = zephyr -build_flags = - -std=gnu++17 - -fsingle-precision-constant - -Wl,-Map,memory.map -platform = https://github.com/platformio/platform-ststm32.git -lib_ignore = ESP32 -extra_scripts = generate_version_file.py - -# https://github.com/LibreSolar/MPPT-1210-HUS/tree/586626f3d8 -[env:mppt-1210-hus-v0.2] -board = nucleo_f072rb -build_flags = ${env.build_flags} - -D CONFIG_BOARD_MPPT_1210_HUS_0V2 # https://github.com/LibreSolar/MPPT-1210-HUS/tree/63e5842671 [env:mppt-1210-hus-v0.4] -board = nucleo_l073rz -build_flags = ${env.build_flags} - -D CONFIG_BOARD_MPPT_1210_HUS_0V4 - -# https://github.com/LibreSolar/mppt-1210-hus/releases/tag/v0.6 -[env:mppt-1210-hus-v0.6] -board = nucleo_l073rz -build_flags = ${env.build_flags} - -D CONFIG_BOARD_MPPT_1210_HUS_0V7 +board = mppt_1210_hus_0v4 # https://github.com/LibreSolar/MPPT-1210-HUS [env:mppt-1210-hus-v0.7] -board = nucleo_l073rz -build_flags = ${env.build_flags} - -D CONFIG_BOARD_MPPT_1210_HUS_0V7 - -[env:mppt-1210-hus-v0.4-zephyr] -board = mppt_1210_hus_0v4 -framework = zephyr -build_flags = - -std=gnu++17 - -fsingle-precision-constant - -Wl,-Map,memory.map -platform = https://github.com/platformio/platform-ststm32.git -lib_ignore = ESP32 -extra_scripts = generate_version_file.py - -[env:mppt-1210-hus-v0.7-zephyr] board = mppt_1210_hus_0v7 -framework = zephyr -build_flags = - -std=gnu++17 - -fsingle-precision-constant - -Wl,-Map,memory.map -platform = https://github.com/platformio/platform-ststm32.git -lib_ignore = ESP32 -extra_scripts = generate_version_file.py -[env:mppt-2420-hpx-v0.1-zephyr] +[env:mppt-2420-hpx-v0.1] board = mppt_2420_hpx -framework = zephyr -build_flags = - -std=gnu++17 - -fsingle-precision-constant - -Wl,-Map,memory.map -platform = https://github.com/platformio/platform-ststm32.git -lib_ignore = ESP32 -extra_scripts = generate_version_file.py # https://github.com/LibreSolar/PWM-2420-LUS -[env:pwm-2420-lus-v0.2] -board = nucleo_l073rz -build_flags = ${env.build_flags} - -D CONFIG_BOARD_PWM_2420_LUS_0V2 - [env:pwm-2420-lus-v0.3] -board = nucleo_l073rz -build_flags = ${env.build_flags} - -D CONFIG_BOARD_PWM_2420_LUS_0V3 - -[env:pwm-2420-lus-v0.3-zephyr] board = pwm_2420_lus_0v3 -framework = zephyr -build_flags = - -std=gnu++17 - -fsingle-precision-constant - -Wl,-Map,memory.map -platform = https://github.com/platformio/platform-ststm32.git -lib_ignore = ESP32 -extra_scripts = generate_version_file.py [env:pwm-2420-lus-v0.3-bl] -board = nucleo_l073rz +board = pwm_2420_lus_0v3 build_flags = ${env.build_flags} - -D CONFIG_BOARD_PWM_2420_LUS_0V3 -D BOOTLOADER_ENABLED - -Wl,-T'"$PROJECT_DIR\STM32L073XZ.ld.link_script.ld"',-v + -Wl,-T'"$PROJECT_DIR/boards/STM32L073XZ.ld.link_script.ld"',-v [env:unit-test-native] platform = native @@ -189,5 +96,4 @@ build_flags = -D DEBUG_PRINT_FLAGS=0xF # include src directory (otherwise unit-tests will only include lib directory) test_build_project_src = true -lib_ignore = ESP32 extra_scripts = diff --git a/src/config.h_template b/src/config.h_template index d170a08..e644f26 100644 --- a/src/config.h_template +++ b/src/config.h_template @@ -7,6 +7,8 @@ #ifndef CONFIG_H #define CONFIG_H +#ifndef __ZEPHYR__ + #include "pcb.h" /** @file @@ -88,4 +90,6 @@ #define MQTT_PUBLISH_TOPIC "nodes2server/report" #define MQTT_SUBSCRIBE_TOPIC "server2node/state-req" +#endif + #endif /* CONFIG_H */ diff --git a/src/daq_zephyr.c b/src/daq_driver.c similarity index 100% rename from src/daq_zephyr.c rename to src/daq_driver.c diff --git a/src/daq_mbed.cpp b/src/daq_mbed.cpp deleted file mode 100644 index e882551..0000000 --- a/src/daq_mbed.cpp +++ /dev/null @@ -1,235 +0,0 @@ -/* - * Copyright (c) 2016 Martin Jäger / Libre Solar - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#include "daq.h" - -#if defined(__MBED__) - -#include // log for thermistor calculation -#include - -#include "mbed.h" - -#include "mcu.h" -#include "setup.h" -#include "debug.h" -#include "pcb.h" // contains defines for pins - -// for ADC and DMA -extern uint16_t adc_readings[]; -extern AnalogOut ref_i_dcdc; - -void dma_setup() -{ - //__HAL_RCC_DMA1_CLK_ENABLE(); - - /* Enable the peripheral clock on DMA */ - RCC->AHBENR |= RCC_AHBENR_DMA1EN; - - /* Enable DMA transfer on ADC and circular mode */ - ADC1->CFGR1 |= ADC_CFGR1_DMAEN | ADC_CFGR1_DMACFG; - - /* Configure the peripheral data register address */ - DMA1_Channel1->CPAR = (uint32_t)(&(ADC1->DR)); - - /* Configure the memory address */ - DMA1_Channel1->CMAR = (uint32_t)(&(adc_readings[0])); - - /* Configure the number of DMA tranfer to be performed on DMA channel 1 */ - DMA1_Channel1->CNDTR = NUM_ADC_CH; - - /* Configure increment, size, interrupts and circular mode */ - DMA1_Channel1->CCR = - DMA_CCR_MINC | /* memory increment mode enabled */ - DMA_CCR_MSIZE_0 | /* memory size 16-bit */ - DMA_CCR_PSIZE_0 | /* peripheral size 16-bit */ - DMA_CCR_TEIE | /* transfer error interrupt enable */ - DMA_CCR_TCIE | /* transfer complete interrupt enable */ - DMA_CCR_CIRC; /* circular mode enable */ - /* DIR = 0: read from peripheral */ - - /* Enable DMA Channel 1 */ - DMA1_Channel1->CCR |= DMA_CCR_EN; - - /* Configure NVIC for DMA (priority 2: second-lowest value for STM32L0/F0) */ - NVIC_SetPriority(DMA1_Channel1_IRQn, 2); - NVIC_EnableIRQ(DMA1_Channel1_IRQn); - - // Trigger ADC conversions - ADC1->CR |= ADC_CR_ADSTART; -} - -extern "C" void DMA1_Channel1_IRQHandler(void) -{ - if ((DMA1->ISR & DMA_ISR_TCIF1) != 0) // Test if transfer completed on DMA channel 1 - { - for (unsigned int i = 0; i < NUM_ADC_CH; i++) { - adc_update_value(i); - } - } - DMA1->IFCR |= 0x0FFFFFFF; // clear all interrupt registers -} - -void dac_setup() -{ -#ifdef PIN_REF_I_DCDC - ref_i_dcdc = 0.1; // reference voltage for zero current (0.1 for buck, 0.9 for boost, 0.5 for bi-directional) -#endif -} - -void adc_setup() -{ -#ifdef PIN_V_SOLAR_EN - DigitalOut solar_en(PIN_V_SOLAR_EN); - solar_en = 1; -#endif - - ADC_HandleTypeDef hadc = {0}; - ADC_ChannelConfTypeDef sConfig = {0}; - - __HAL_RCC_ADC1_CLK_ENABLE(); - - // Configure ADC object structures - hadc.Instance = ADC1; - hadc.State = HAL_ADC_STATE_RESET; - hadc.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; - hadc.Init.Resolution = ADC_RESOLUTION_12B; - hadc.Init.DataAlign = ADC_DATAALIGN_LEFT; // for exponential moving average filter - hadc.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD; - hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV; - hadc.Init.LowPowerAutoWait = DISABLE; - hadc.Init.LowPowerAutoPowerOff = DISABLE; - hadc.Init.ContinuousConvMode = DISABLE; - hadc.Init.DiscontinuousConvMode = DISABLE; - hadc.Init.ExternalTrigConv = ADC_SOFTWARE_START; - hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; - hadc.Init.DMAContinuousRequests = ENABLE; //DISABLE; - hadc.Init.Overrun = ADC_OVR_DATA_OVERWRITTEN; - - if (HAL_ADC_Init(&hadc) != HAL_OK) { - error("Cannot initialize ADC"); - } - -#if defined(STM32L0) - HAL_ADCEx_Calibration_Start(&hadc, ADC_SINGLE_ENDED); -#else - HAL_ADCEx_Calibration_Start(&hadc); -#endif - - // Configure ADC channel - sConfig.Channel = ADC_CHANNEL_0; // can be any channel for initialization - sConfig.Rank = ADC_RANK_CHANNEL_NUMBER; - - // Clear all channels as it is not done in HAL_ADC_ConfigChannel() - hadc.Instance->CHSELR = 0; - - if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK) { - error("Cannot initialize ADC"); - } - - HAL_ADC_Start(&hadc); // Start conversion - - // Read out value one time to finish ADC configuration - if (HAL_ADC_PollForConversion(&hadc, 10) == HAL_OK) { - HAL_ADC_GetValue(&hadc); - } - - // ADC sampling time register - // 000: 1.5 ADC clock cycles - // 001: 7.5 ADC clock cycles - // 010: 13.5 ADC clock cycles - // 011: 28.5 ADC clock cycles - // 100: 41.5 ADC clock cycles - // 101: 55.5 ADC clock cycles - // 110: 71.5 ADC clock cycles - // 111: 239.5 ADC clock cycles - //ADC1->SMPR = ADC_SMPR_SMP_1; // for normal ADC OK - ADC1->SMPR |= ADC_SMPR_SMP_0 | ADC_SMPR_SMP_1 | ADC_SMPR_SMP_2; // necessary for internal reference and temperature - - // Select ADC channels based on setup in config.h - ADC1->CHSELR = ADC_CHSEL; - - // Enable internal voltage reference and temperature sensor - // ToDo check sample rate - ADC->CCR |= ADC_CCR_TSEN | ADC_CCR_VREFEN; -} - -#if defined(STM32F0) - -void adc_timer_start(int freq_Hz) // max. 10 kHz -{ - // Enable TIM15 clock - RCC->APB2ENR |= RCC_APB2ENR_TIM15EN; - - // Set timer clock to 10 kHz - TIM15->PSC = SystemCoreClock / 10000 - 1; - - // Interrupt on timer update - TIM15->DIER |= TIM_DIER_UIE; - - // Auto Reload Register sets interrupt frequency - TIM15->ARR = 10000 / freq_Hz - 1; - - // 2 = second-lowest priority of STM32L0/F0 - NVIC_SetPriority(TIM15_IRQn, 2); - NVIC_EnableIRQ(TIM15_IRQn); - - // Control Register 1 - // TIM_CR1_CEN = 1: Counter enable - TIM15->CR1 |= TIM_CR1_CEN; -} - -extern "C" void TIM15_IRQHandler(void) -{ - TIM15->SR &= ~(1 << 0); - ADC1->CR |= ADC_CR_ADSTART; -} - -#elif defined(STM32L0) - -void adc_timer_start(int freq_Hz) // max. 10 kHz -{ - // Enable TIM6 clock - RCC->APB1ENR |= RCC_APB1ENR_TIM6EN; - - // Set timer clock to 10 kHz - TIM6->PSC = SystemCoreClock / 10000 - 1; - - // Interrupt on timer update - TIM6->DIER |= TIM_DIER_UIE; - - // Auto Reload Register sets interrupt frequency - TIM6->ARR = 10000 / freq_Hz - 1; - - // 2 = second-lowest priority of STM32L0/F0 - NVIC_SetPriority(TIM6_IRQn, 2); - NVIC_EnableIRQ(TIM6_IRQn); - - // Control Register 1 - // TIM_CR1_CEN = 1: Counter enable - TIM6->CR1 |= TIM_CR1_CEN; -} - -extern "C" void TIM6_IRQHandler(void) -{ - TIM6->SR &= ~(1 << 0); - ADC1->CR |= ADC_CR_ADSTART; -} - -#endif - -void daq_setup() -{ - dac_setup(); // for current sensor references - adc_setup(); - dma_setup(); - adc_timer_start(1000); // 1 kHz - wait(0.5); // wait for ADC to collect some measurement values - daq_update(); - calibrate_current_sensors(); -} - -#endif /* __MBED__ */ \ No newline at end of file diff --git a/src/ext/can.cpp b/src/ext/can.cpp index d1bb852..3d5ae21 100644 --- a/src/ext/can.cpp +++ b/src/ext/can.cpp @@ -139,7 +139,7 @@ ThingSetCAN::ThingSetCAN(uint8_t can_node_id, const unsigned int c): void ThingSetCAN::enable() { - gpio_pin_write(gpio_stb_dev, DT_SWITCH_CAN_GPIOS_PIN, 1); + gpio_pin_set(can_en_dev, DT_SWITCH_CAN_GPIOS_PIN, 1); } #endif diff --git a/src/ext/oled.cpp b/src/ext/oled.cpp index e176750..1ba0430 100644 --- a/src/ext/oled.cpp +++ b/src/ext/oled.cpp @@ -15,11 +15,9 @@ #include #include -#if defined(__ZEPHYR__) #include #include #include -#endif #include "setup.h" #include "half_bridge.h" @@ -56,32 +54,18 @@ const unsigned char bmp_disconnected [] = { 0x08, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; -#if defined(__MBED__) -I2C i2c_dev(PIN_UEXT_SDA, PIN_UEXT_SCL); -OledSSD1306 oled(i2c_dev); -#elif defined(__ZEPHYR__) const char i2c_dev[] = DT_ALIAS_I2C_UEXT_LABEL; OledSSD1306 oled(i2c_dev); -#endif void ExtOled::enable() { -#if defined(PIN_UEXT_DIS) && defined(__MBED__) - DigitalOut uext_dis(PIN_UEXT_DIS); - uext_dis = 0; -#endif - #ifdef DT_SWITCH_UEXT_GPIOS_CONTROLLER struct device *dev_uext_dis = device_get_binding(DT_SWITCH_UEXT_GPIOS_CONTROLLER); gpio_pin_configure(dev_uext_dis, DT_SWITCH_UEXT_GPIOS_PIN, DT_SWITCH_UEXT_GPIOS_FLAGS | GPIO_OUTPUT_ACTIVE); #endif -#ifdef OLED_BRIGHTNESS - oled.init(OLED_BRIGHTNESS); -#else - oled.init(); // use default (lowest brightness) -#endif + oled.init(CONFIG_EXT_OLED_BRIGHTNESS); } void ExtOled::process_1s() diff --git a/src/ext/serial.cpp b/src/ext/serial.cpp index ea37472..eea0804 100644 --- a/src/ext/serial.cpp +++ b/src/ext/serial.cpp @@ -12,56 +12,33 @@ #include "ext.h" -#ifdef __MBED__ -#include "mbed.h" -#elif defined(__ZEPHYR__) #include #include #include #include #include -#endif /* MBED or ZEPHYR */ #include "thingset.h" -#ifdef __ZEPHYR__ #define TX_BUF_SIZE CONFIG_EXT_THINGSET_SERIAL_TX_BUF_SIZE #define RX_BUF_SIZE CONFIG_EXT_THINGSET_SERIAL_RX_BUF_SIZE #define UART_DEVICE_NAME DT_ALIAS_UART_DBG_LABEL struct device *uart_dev = device_get_binding(UART_DEVICE_NAME); -#else -#define TX_BUF_SIZE 1000 -#define RX_BUF_SIZE 500 -#endif class ThingSetStream: public ExtInterface { public: -#ifdef __MBED__ - ThingSetStream(Stream& s, const unsigned int c): channel(c), stream(&s) {}; -#elif defined(__ZEPHYR__) ThingSetStream(const unsigned int c): channel(c){}; -#endif virtual void process_asap(); virtual void process_1s(); protected: -#ifdef __MBED__ - virtual void process_input(); // this is called from the ISR typically -#elif defined (__ZEPHYR__) static void process_input(void*); -#endif const unsigned int channel; -#ifdef __MBED__ - virtual bool readable() - { - return stream->readable(); - } -#elif defined (__ZEPHYR__) static bool readable() { // Start processing interrupts in ISR. @@ -85,43 +62,14 @@ protected: // But static functions dont have access to the class members. // Hence these members are passed as a structure of pointers. DataStreamStruct data_stream = {buf_req, &req_pos, &command_flag}; -#endif /* MBED */ private: -#ifdef __MBED__ - Stream* stream; -#endif /* MBED */ - char buf_resp[TX_BUF_SIZE]; char buf_req[RX_BUF_SIZE]; size_t req_pos = 0; bool command_flag = false; }; -#ifdef __MBED__ - -template class ThingSetSerial: public ThingSetStream -{ -public: - ThingSetSerial(T& s, const unsigned int c): ThingSetStream(s,c), ser(s) {} - - void enable() { - Callback cb([this]() -> void { this->process_input();}); - ser.attach(cb); - } - -private: - bool readable() - { - return ser.readable(); - } - -private: - T& ser; -}; - -#elif defined(__ZEPHYR__) - class ThingSetSerial: public ThingSetStream { public: @@ -138,8 +86,6 @@ public: } }; -#endif /* MBED or ZEPHYR*/ - /* * Construct all global ExtInterfaces here. * All of these are added to the list of devices @@ -150,12 +96,7 @@ public: extern const int pub_channel_serial; -#ifdef __MBED__ -extern Serial serial; -ThingSetSerial ts_uart(serial, pub_channel_serial); -#elif defined(__ZEPHYR__) ThingSetSerial ts_uart(pub_channel_serial); -#endif /* MBED or ZEPHYR */ #endif /* CONFIG_EXT_THINGSET_SERIAL */ @@ -164,17 +105,11 @@ extern ThingSet ts; void ThingSetStream::process_1s() { if (ts.get_pub_channel(channel)->enabled) { -#ifdef __MBED__ - ts.pub_msg_json(buf_resp, sizeof(buf_resp), channel); - stream->puts(buf_resp); - stream->putc('\n'); -#elif defined(__ZEPHYR__) int len = ts.pub_msg_json(buf_resp, sizeof(buf_resp), channel); for (int i = 0; i < len; i++) { uart_poll_out(uart_dev, buf_resp[i]); } uart_poll_out(uart_dev, '\n'); -#endif /* MBED or ZREPHYR */ } } @@ -183,20 +118,12 @@ void ThingSetStream::process_asap() if (command_flag) { // commands must have 2 or more characters if (req_pos > 1) { -#ifdef __MBED__ - stream->printf("Received Request (%d bytes): %s\n", strlen(buf_req), buf_req); - ts.process((uint8_t *)buf_req, strlen(buf_req), (uint8_t *)buf_resp, sizeof(buf_resp)); - stream->puts(buf_resp); - stream->putc('\n'); - fflush(*stream); -#elif defined(__ZEPHYR__) 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'); -#endif /* MBED or ZEPHYR */ } // start listening for new commands @@ -209,26 +136,16 @@ void ThingSetStream::process_asap() * Read characters from stream until line end \n detected, signal command available then * and wait for processing */ -#ifdef __MBED__ -void ThingSetStream::process_input() -#elif defined (__ZEPHYR__) void ThingSetStream::process_input(void* user_data) -#endif /* MBED or ZEPHYR */ { -#ifdef __ZEPHYR__ u8_t c; DataStreamStruct *data_stream_ptr = (DataStreamStruct *)user_data; bool command_flag = *(data_stream_ptr->command_flag_ptr); char *buf_req = data_stream_ptr->buf_req_ptr; size_t req_pos = *(data_stream_ptr->req_pos_ptr); -#endif /* __ZEPHYR__ */ while (readable() && command_flag == false) { -#ifdef __MBED__ - int c = stream->getc(); -#elif defined(__ZEPHYR__) uart_fifo_read(uart_dev, &c, 1); -#endif /* MBED */ // \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 @@ -257,10 +174,8 @@ void ThingSetStream::process_input(void* user_data) buf_req[req_pos++] = c; } -#ifdef __ZEPHYR__ *(data_stream_ptr->command_flag_ptr) = command_flag; *(data_stream_ptr->req_pos_ptr) = req_pos; -#endif } } diff --git a/src/half_bridge.cpp b/src/half_bridge.cpp index eafee1e..b0df139 100644 --- a/src/half_bridge.cpp +++ b/src/half_bridge.cpp @@ -38,13 +38,8 @@ class PWM_TIM3 GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODE1)) | GPIO_MODER_MODE1_1; // Select AF2 on PB0 and PB1 -#ifdef __MBED__ - GPIOB->AFR[0] |= 0x2 << GPIO_AFRL_AFRL0_Pos; - GPIOB->AFR[0] |= 0x2 << GPIO_AFRL_AFRL1_Pos; -#else GPIOB->AFR[0] |= 0x2 << GPIO_AFRL_AFSEL0_Pos; GPIOB->AFR[0] |= 0x2 << GPIO_AFRL_AFSEL1_Pos; -#endif // No prescaler --> timer frequency == SystemClock TIM3->PSC = 0; diff --git a/src/hardware.cpp b/src/hardware.cpp index 27c2ee7..dca24b0 100644 --- a/src/hardware.cpp +++ b/src/hardware.cpp @@ -24,202 +24,7 @@ #define MAGIC_CODE_ADDR (SRAM_END - 0xF) // where the magic code is stored -#if defined(__MBED__) - -#include "mbed.h" - -#if defined(STM32F0) - -void control_timer_start(int freq_Hz) // max. 10 kHz -{ - // Enable TIM16 clock - RCC->APB2ENR |= RCC_APB2ENR_TIM16EN; - - // Set timer clock to 10 kHz - TIM16->PSC = SystemCoreClock / 10000 - 1; - - // Interrupt on timer update - TIM16->DIER |= TIM_DIER_UIE; - - // Auto Reload Register sets interrupt frequency - TIM16->ARR = 10000 / freq_Hz - 1; - - // 1 = second-highest priority of STM32L0/F0 - NVIC_SetPriority(TIM16_IRQn, 1); - NVIC_EnableIRQ(TIM16_IRQn); - - // Control Register 1 - // TIM_CR1_CEN = 1: Counter enable - TIM16->CR1 |= TIM_CR1_CEN; -} - -extern "C" void TIM16_IRQHandler(void) -{ - TIM16->SR &= ~TIM_SR_UIF; // clear update interrupt flag to restart timer - system_control(); -} - -#elif defined(STM32L0) - -void control_timer_start(int freq_Hz) // max. 10 kHz -{ - // Enable TIM7 clock - RCC->APB1ENR |= RCC_APB1ENR_TIM7EN; - - // Set timer clock to 10 kHz - TIM7->PSC = SystemCoreClock / 10000 - 1; - - // Interrupt on timer update - TIM7->DIER |= TIM_DIER_UIE; - - // Auto Reload Register sets interrupt frequency - TIM7->ARR = 10000 / freq_Hz - 1; - - // 1 = second-highest priority of STM32L0/F0 - NVIC_SetPriority(TIM7_IRQn, 1); - NVIC_EnableIRQ(TIM7_IRQn); - - // Control Register 1 - // TIM_CR1_CEN = 1: Counter enable - TIM7->CR1 |= TIM_CR1_CEN; -} - -extern "C" void TIM7_IRQHandler(void) -{ - TIM7->SR &= ~(1 << 0); - system_control(); -} - -#endif - - -// Reset the watchdog timer -void feed_the_dog() -{ - IWDG->KR = 0xAAAA; -} - -// configures IWDG (timeout in seconds) -void init_watchdog(float timeout) { - - // TODO for STM32L0 - #define LSI_FREQ 40000 // approx. 40 kHz according to RM0091 - - uint16_t prescaler; - - IWDG->KR = 0x5555; // Disable write protection of IWDG registers - - // set prescaler - if ((timeout * (LSI_FREQ/4)) < 0x7FF) { - IWDG->PR = IWDG_PRESCALER_4; - prescaler = 4; - } - else if ((timeout * (LSI_FREQ/8)) < 0xFF0) { - IWDG->PR = IWDG_PRESCALER_8; - prescaler = 8; - } - else if ((timeout * (LSI_FREQ/16)) < 0xFF0) { - IWDG->PR = IWDG_PRESCALER_16; - prescaler = 16; - } - else if ((timeout * (LSI_FREQ/32)) < 0xFF0) { - IWDG->PR = IWDG_PRESCALER_32; - prescaler = 32; - } - else if ((timeout * (LSI_FREQ/64)) < 0xFF0) { - IWDG->PR = IWDG_PRESCALER_64; - prescaler = 64; - } - else if ((timeout * (LSI_FREQ/128)) < 0xFF0) { - IWDG->PR = IWDG_PRESCALER_128; - prescaler = 128; - } - else { - IWDG->PR = IWDG_PRESCALER_256; - prescaler = 256; - } - - // set reload value (between 0 and 0x0FFF) - IWDG->RLR = (uint32_t)(timeout * (LSI_FREQ/prescaler)); - - //float calculated_timeout = ((float)(prescaler * IWDG->RLR)) / LSI_FREQ; - //printf("WATCHDOG set with prescaler:%d reload value: 0x%X - timeout:%f\n", prescaler, (unsigned int)IWDG->RLR, calculated_timeout); - - IWDG->KR = 0xAAAA; // reload - IWDG->KR = 0xCCCC; // start - - feed_the_dog(); -} - -// this function is called by mbed if a serious error occured: error() function called -void mbed_die(void) -{ - half_bridge_stop(); - load.stop(); - -#if CONFIG_HAS_USB_PWR_OUTPUT - usb_pwr.stop(); -#endif - - leds_init(false); - - while (1) { - - leds_toggle_error(); - wait_ms(100); - - // stay here to indicate something was wrong - feed_the_dog(); - } -} - -void start_stm32_bootloader() -{ -#ifdef PIN_BOOT0_EN - // pin is connected to BOOT0 via resistor and capacitor - DigitalOut boot0_en(PIN_BOOT0_EN); - - boot0_en = 1; - wait_ms(100); // wait for capacitor at BOOT0 pin to charge up - - NVIC_SystemReset(); -#elif defined (STM32F0) - // place magic code at end of RAM and initiate reset - *((uint32_t *)(MAGIC_CODE_ADDR)) = 0xDEADBEEF; - NVIC_SystemReset(); -#endif -} - -// This function should be called at the beginning of SystemInit in system_clock.c (mbed target directory) -// As mbed does not provide this functionality, you have to patch the file manually -extern "C" void system_init_hook() -{ - if (*((uint32_t *)(MAGIC_CODE_ADDR)) == 0xDEADBEEF) { - - uint32_t jump_address; - - *((uint32_t *)(MAGIC_CODE_ADDR)) = 0x00000000; // reset the trigger - - jump_address = (*((uint32_t *) (SYS_MEM_START + 4))); - - // reinitialize stack pointer - __set_MSP(SYS_MEM_START); - - // jump to specified address - void (*jump)(void); - jump = (void (*)(void)) jump_address; - jump(); - - while (42); // should never be reached - } -} - -void reset_device() -{ - NVIC_SystemReset(); -} - -#elif defined(__ZEPHYR__) +#ifndef UNIT_TEST #include #include diff --git a/src/helper.cpp b/src/helper.cpp index 3dae563..eb84da5 100644 --- a/src/helper.cpp +++ b/src/helper.cpp @@ -8,15 +8,13 @@ #include -#ifdef __MBED__ -#include "mbed.h" -#elif defined(__ZEPHYR__) +#ifndef UNIT_TEST #include #endif uint32_t uptime() { -#ifdef __ZEPHYR__ +#ifndef UNIT_TEST return k_uptime_get() / 1000; #else return time(NULL); diff --git a/src/leds.cpp b/src/leds.cpp index 6e0eca8..7ddec33 100644 --- a/src/leds.cpp +++ b/src/leds.cpp @@ -15,124 +15,7 @@ static int blink_state = 1; // global state of all blinking static bool charging = false; -#ifdef __MBED__ - -#include "mbed.h" - -static void charlieplexing() -{ - static int led_count = 0; - static int flicker_count = 0; - static bool flicker_state = 1; - - // could be increased to value >NUM_LEDS to reduce on-time - if (led_count >= NUM_LEDS) { - led_count = 0; - } - - if (flicker_count > 30) { - flicker_count = 0; - flicker_state = !flicker_state; - } - - if (led_count < NUM_LEDS && ( - led_states[led_count] == LED_STATE_ON || - (led_states[led_count] == LED_STATE_FLICKER && flicker_state == 1) || - (led_states[led_count] == LED_STATE_BLINK && blink_state == 1) - )) { - for (int pin_number = 0; pin_number < NUM_LED_PINS; pin_number++) { - DigitalInOut pin(led_pins[pin_number]); - switch (led_pin_setup[led_count][pin_number]) { - case PIN_HIGH: - pin.output(); - pin = 1; - break; - case PIN_LOW: - pin.output(); - pin = 0; - break; - case PIN_FLOAT: - pin.input(); - break; - } - } - } - else { - // all pins floating - for (int pin_number = 0; pin_number < NUM_LED_PINS; pin_number++) { - DigitalIn pin(led_pins[pin_number]); - } - } - - led_count++; - flicker_count++; -} - -#if defined(STM32F0) - -static void timer_start(int freq_Hz) // max. 10 kHz -{ - // Enable TIM17 clock - RCC->APB2ENR |= RCC_APB2ENR_TIM17EN; - - // Set timer clock to 10 kHz - TIM17->PSC = SystemCoreClock / 10000 - 1; - - // Interrupt on timer update - TIM17->DIER |= TIM_DIER_UIE; - - // Auto Reload Register sets interrupt frequency - TIM17->ARR = 10000 / freq_Hz - 1; - - // 3 = lowest priority of STM32L0/F0 - NVIC_SetPriority(TIM17_IRQn, 3); - NVIC_EnableIRQ(TIM17_IRQn); - - // Control Register 1 - // TIM_CR1_CEN = 1: Counter enable - TIM17->CR1 |= TIM_CR1_CEN; -} - -extern "C" void TIM17_IRQHandler(void) -{ - TIM17->SR &= ~TIM_SR_UIF; // clear update interrupt flag to restart timer - charlieplexing(); -} - -#elif defined(STM32L0) - -static void timer_start(int freq_Hz) // max. 10 kHz -{ - // Enable TIM22 clock - RCC->APB2ENR |= RCC_APB2ENR_TIM22EN; - - // Set timer clock to 10 kHz - TIM22->PSC = SystemCoreClock / 10000 - 1; - - // Interrupt on timer update - TIM22->DIER |= TIM_DIER_UIE; - - // Auto Reload Register sets interrupt frequency - TIM22->ARR = 10000 / freq_Hz - 1; - - // 3 = lowest priority of STM32L0/F0 - NVIC_SetPriority(TIM22_IRQn, 3); - NVIC_EnableIRQ(TIM22_IRQn); - - // Control Register 1 - // TIM_CR1_CEN = 1: Counter enable - TIM22->CR1 |= TIM_CR1_CEN; -} - -extern "C" void TIM22_IRQHandler(void) -{ - TIM22->SR &= ~(1 << 0); - charlieplexing(); -} - -#endif // STM32 - -#elif defined(__ZEPHYR__) +#ifndef UNIT_TEST #include #include @@ -199,7 +82,7 @@ void leds_update_thread() } } -#endif // ZEPHYR or MBED +#endif // UNIT_TEST void leds_init(bool enabled) { @@ -213,9 +96,6 @@ void leds_init(bool enabled) trigger_timeout[led] = -1; } } -#ifdef __MBED__ - timer_start(NUM_LEDS * 60); // 60 Hz -#endif } void leds_set_charging(bool enabled) diff --git a/src/leds.h b/src/leds.h index 5a527bc..8a098cc 100644 --- a/src/leds.h +++ b/src/leds.h @@ -28,11 +28,9 @@ enum LedState { */ void leds_init(bool enabled = true); -#ifdef __ZEPHYR__ /** Main thread for LED control in Zephyr, performs pin initializations and charlieplexing at 60 Hz */ void leds_update_thread(); -#endif /** Enables/disables dedicated charging LED if existing or * blinks SOC LED when solar power is coming in. diff --git a/src/load_drv.cpp b/src/load_drv.cpp index 0b02d3f..ea7a080 100644 --- a/src/load_drv.cpp +++ b/src/load_drv.cpp @@ -8,7 +8,7 @@ #include // for PRIu32 in printf statements -#if defined(__ZEPHYR__) +#ifndef UNIT_TEST #include #include @@ -27,7 +27,7 @@ static struct device *dev_load; static struct device *dev_usb; #endif -#endif // __ZEPHYR__ +#endif // UNIT_TEST #include "pcb.h" #include "config.h" @@ -51,11 +51,7 @@ static void lptim_init() GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODE2)) | GPIO_MODER_MODE2_1; // Select AF2 (LPTIM_OUT) on PB2 -#ifdef __MBED__ // older version of STM32 Cube - GPIOB->AFR[0] |= 0x2U << GPIO_AFRL_AFRL2_Pos; -#else GPIOB->AFR[0] |= 0x2U << GPIO_AFRL_AFSEL2_Pos; -#endif // Set prescaler to 32 (resulting in 1 MHz timer frequency) LPTIM1->CFGR |= 0x5U << LPTIM_CFGR_PRESC_Pos; @@ -96,10 +92,6 @@ void short_circuit_comp_init() { #if defined(PIN_I_LOAD_COMP) -#ifdef __MBED__ - MBED_ASSERT(PIN_I_LOAD_COMP == PB_4); -#endif - // set GPIO pin to analog RCC->IOPENR |= RCC_IOPENR_GPIOBEN; GPIOB->MODER &= ~(GPIO_MODER_MODE4); @@ -167,30 +159,6 @@ void load_out_set(bool status) leds_set(LED_LOAD, status); #endif -#if defined(__MBED__) && defined(PIN_LOAD_EN) - DigitalOut load_enable(PIN_LOAD_EN); - if (status == true) { - load_enable = 1; - } - else { - load_enable = 0; - } -#endif - -#if defined(__MBED__) && defined(PIN_LOAD_DIS) - DigitalOut load_disable(PIN_LOAD_DIS); - if (status == true) { - #ifdef PIN_I_LOAD_COMP - lptim_init(); - #else - load_disable = 0; - #endif - } - else { - load_disable = 1; - } -#endif - #ifdef DT_SWITCH_LOAD_GPIOS_CONTROLLER gpio_pin_configure(dev_load, DT_SWITCH_LOAD_GPIOS_PIN, DT_SWITCH_LOAD_GPIOS_FLAGS | GPIO_OUTPUT_INACTIVE); @@ -209,17 +177,6 @@ void load_out_set(bool status) void usb_out_set(bool status) { -#if defined(__MBED__) && defined(PIN_USB_PWR_EN) - DigitalOut usb_pwr_en(PIN_USB_PWR_EN); - if (status == true) usb_pwr_en = 1; - else usb_pwr_en = 0; -#endif -#if defined(__MBED__) && defined(PIN_USB_PWR_DIS) - DigitalOut usb_pwr_dis(PIN_USB_PWR_DIS); - if (status == true) usb_pwr_dis = 0; - else usb_pwr_dis = 1; -#endif - #ifdef DT_SWITCH_USB_PWR_GPIOS_CONTROLLER gpio_pin_configure(dev_usb, DT_SWITCH_USB_PWR_GPIOS_PIN, DT_SWITCH_USB_PWR_GPIOS_FLAGS | GPIO_OUTPUT_INACTIVE); diff --git a/src/main_zephyr.cpp b/src/main.cpp similarity index 99% rename from src/main_zephyr.cpp rename to src/main.cpp index 903f698..cdc5323 100644 --- a/src/main_zephyr.cpp +++ b/src/main.cpp @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -#ifdef __ZEPHYR__ +#ifndef UNIT_TEST #include #include @@ -168,4 +168,4 @@ K_THREAD_DEFINE(leds_thread, 256, leds_update_thread, NULL, NULL, NULL, 4, 0, K_ K_THREAD_DEFINE(ext_thread, 1024, ext_mgr_thread, NULL, NULL, NULL, 6, 0, 1000); -#endif // __ZEPHYR__ +#endif // UNIT_TEST diff --git a/src/main_mbed.cpp b/src/main_mbed.cpp deleted file mode 100644 index 82ca43d..0000000 --- a/src/main_mbed.cpp +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright (c) 2016 Martin Jäger / Libre Solar - * - * SPDX-License-Identifier: Apache-2.0 - */ - -#ifdef __MBED__ - -/** @file - * - * @brief Entry point of charge controller firmware - */ - -#include "mbed.h" - -#include "thingset.h" // handles access to internal data via communication interfaces -#include "pcb.h" // hardware-specific settings -#include "config.h" // user-specific configuration -#include "setup.h" -#include "helper.h" - -#include "half_bridge.h" // PWM generation for DC/DC converter -#include "hardware.h" // hardware-related functions like watchdog, etc. -#include "dcdc.h" // DC/DC converter control (hardware independent) -#include "pwm_switch.h" // PWM charge controller -#include "bat_charger.h" // battery settings and charger state machine -#include "daq.h" // ADC using DMA and conversion to measurement values -#include "ext/ext.h" // communication interfaces, displays, etc. in UEXT connector -#include "eeprom.h" // external I2C EEPROM -#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_objects.h" // for access to internal data via ThingSet -#include "bl_support.h" // Bootloader support from the application side - -Serial serial(PIN_SWD_TX, PIN_SWD_RX, "serial", 115200); - -/** Main function including initialization and continuous loop - */ -int main() -{ - #ifdef BOOTLOADER_ENABLED - check_bootloader(); // Update the bootloader status in flash to a stable state. - #endif - - leds_init(); - - battery_conf_init(&bat_conf, BATTERY_TYPE, BATTERY_NUM_CELLS, BATTERY_CAPACITY); - battery_conf_overwrite(&bat_conf, &bat_conf_user); // initialize conf_user with same values - - // Configuration from EEPROM - data_objects_read_eeprom(); - ts.set_conf_callback(data_objects_update_conf); // after each configuration change, data should be written back to EEPROM - ts.set_user_password(THINGSET_USER_PASSWORD); // passwords defined in config.h (see template) - ts.set_maker_password(THINGSET_MAKER_PASSWORD); - - // Data Acquisition (DAQ) setup - daq_setup(); - - // initialize all extensions and external communication interfaces - ext_mgr.enable_all(); - - init_watchdog(10); // 10s should be enough for communication ports - - #if CONFIG_HV_TERMINAL_SOLAR || CONFIG_LV_TERMINAL_SOLAR || CONFIG_PWM_TERMINAL_SOLAR - solar_terminal.init_solar(); - #endif - - #if CONFIG_HV_TERMINAL_NANOGRID - grid_terminal.init_nanogrid(); - #endif - - charger.detect_num_batteries(&bat_conf); // check if we have 24V instead of 12V system - charger.init_terminal(&bat_conf); - load.set_voltage_limits(bat_conf.voltage_load_disconnect, bat_conf.voltage_load_reconnect, - bat_conf.voltage_absolute_max); - - #if CONFIG_HAS_USB_PWR_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); - #endif - - wait(2); // safety feature: be able to re-flash before starting - control_timer_start(CONTROL_FREQUENCY); - wait(0.1); // necessary to prevent MCU from randomly getting stuck here if PV panel is connected before battery - - // The Mbed Serial class calls sleep_manager_lock_deep_sleep() internally during attach. If no - // Serial is enabled, sleep does not always return in STM32F072, so we lock deep sleep manually - sleep_manager_lock_deep_sleep(); - - // the main loop is suitable for slow tasks like communication (even blocking wait allowed) - time_t last_call = timestamp; - while (1) { - - ext_mgr.process_asap(); - - time_t now = timestamp; - if (now >= last_call + 1 || now < last_call) { - // called once per second (or slower if blocking wait occured somewhere) - - charger.discharge_control(&bat_conf); - charger.charge_control(&bat_conf); - - eeprom_update(); - - leds_update_1s(); - leds_update_soc(charger.soc, flags_check(&load.error_flags, ERR_LOAD_SHEDDING)); - - ext_mgr.process_1s(); - - #if CONFIG_HS_MOSFET_FAIL_SAFE_PROTECTION && CONFIG_HAS_DCDC_CONVERTER - if (dev_stat.has_error(ERR_DCDC_HS_MOSFET_SHORT)) { - dcdc.fuse_destruction(); - } - #endif - - last_call = now; - } - feed_the_dog(); - sleep(); // wake-up by timer interrupts - } -} - -/** High priority function for DC/DC / PWM control and safety functions - * - * Called by control timer with 10 Hz frequency (see hardware.cpp). - */ -void system_control() -{ - static int counter = 0; - - // convert ADC readings to meaningful measurement values - daq_update(); - - // alerts should trigger only for transients, so update based on actual voltage - daq_set_lv_alerts(lv_terminal.bus->voltage * 1.2, lv_terminal.bus->voltage * 0.8); - - bat_terminal.update_bus_current_margins(); - - #if CONFIG_HAS_PWM_SWITCH - pwm_switch.control(); - leds_set_charging(pwm_switch.active()); - #endif - - #if CONFIG_HAS_DCDC_CONVERTER - hv_terminal.update_bus_current_margins(); - dcdc.control(); // control of DC/DC including MPPT algorithm - leds_set_charging(half_bridge_enabled()); - #endif - - load.control(); - - #if CONFIG_HAS_USB_PWR_OUTPUT - usb_pwr.control(); - #endif - - if (counter % CONTROL_FREQUENCY == 0) { - // called once per second (this timer is much more accurate than time(NULL) based on LSI) - // see also here: https://github.com/ARMmbed/mbed-os/issues/9065 - timestamp++; - counter = 0; - - // energy + soc calculation must be called exactly once per second - #if CONFIG_HAS_DCDC_CONVERTER - hv_terminal.energy_balance(); - #endif - - #if CONFIG_HAS_PWM_SWITCH - pwm_switch.energy_balance(); - #endif - - lv_terminal.energy_balance(); - load.energy_balance(); - dev_stat.update_energy(); - dev_stat.update_min_max_values(); - charger.update_soc(&bat_conf); - } - counter++; -} - -#endif // __MBED__ diff --git a/src/setup.cpp b/src/setup.cpp index 0068ea2..b6dda97 100644 --- a/src/setup.cpp +++ b/src/setup.cpp @@ -83,7 +83,7 @@ DeviceStatus dev_stat; // uint32_t considered large enough, so we avoid 64-bit math (overflow in year 2106) uint32_t timestamp; -#ifdef __ZEPHYR__ +#ifndef UNIT_TEST #include diff --git a/test/main.cpp b/test/main.cpp index b0cc49b..61c3120 100644 --- a/test/main.cpp +++ b/test/main.cpp @@ -6,12 +6,16 @@ #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(); diff --git a/zephyr/CMakeLists.txt b/zephyr/CMakeLists.txt index 7fd9e48..82e9b9d 100644 --- a/zephyr/CMakeLists.txt +++ b/zephyr/CMakeLists.txt @@ -12,28 +12,31 @@ add_definitions(-D__ZEPHYR__ -DDEBUG_PRINT_FLAGS=7) include_directories(../src) -target_sources(app PRIVATE ../src/bat_charger.cpp) -target_sources(app PRIVATE ../src/data_objects.cpp) -target_sources(app PRIVATE ../src/daq.cpp) -target_sources(app PRIVATE ../src/daq_zephyr.c) -target_sources(app PRIVATE ../src/device_status.cpp) -target_sources(app PRIVATE ../src/dcdc.cpp) -target_sources(app PRIVATE ../src/eeprom.cpp) -target_sources(app PRIVATE ../src/half_bridge.cpp) -target_sources(app PRIVATE ../src/hardware.cpp) -target_sources(app PRIVATE ../src/helper.cpp) -target_sources(app PRIVATE ../src/leds.cpp) -target_sources(app PRIVATE ../src/load.cpp) -target_sources(app PRIVATE ../src/load_drv.cpp) -target_sources(app PRIVATE ../src/main_zephyr.cpp) -target_sources(app PRIVATE ../src/power_port.cpp) -target_sources(app PRIVATE ../src/pwm_switch.cpp) -target_sources(app PRIVATE ../src/setup.cpp) -target_sources(app PRIVATE ../src/ext/ext.cpp) -target_sources(app PRIVATE ../src/ext/oled.cpp) -target_sources(app PRIVATE ../src/ext/serial.cpp) -target_sources(app PRIVATE ../src/ext/can.cpp) -target_sources(app PRIVATE ../src/ext/can_msg_queue.cpp) +target_sources(app PRIVATE + ../src/bat_charger.cpp + ../src/data_objects.cpp + ../src/daq.cpp + ../src/daq_driver.c + ../src/device_status.cpp + ../src/dcdc.cpp + ../src/eeprom.cpp + ../src/half_bridge.cpp + ../src/hardware.cpp + ../src/helper.cpp + ../src/leds.cpp + ../src/load.cpp + ../src/load_drv.cpp + ../src/main.cpp + ../src/power_port.cpp + ../src/pwm_switch.cpp + ../src/setup.cpp + ../src/ext/ext.cpp + ../src/ext/oled.cpp + ../src/ext/serial.cpp + ../src/ext/can.cpp + ../src/ext/can_msg_queue.cpp +) add_subdirectory(../lib/thingset build/thingset) add_subdirectory(../lib/oled-display build/oled-display) +#add_subdirectory_ifdef(CONFIG_EXT_OLED_DISPLAY ../lib/oled-display)