diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index a1d037c..3cc0808 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -37,7 +37,16 @@ jobs: custom: dvjcodec - target: esp32c3 display: cu2 - custom: supermini + custom: tesla.10Ah + - target: esp32c3 + display: cu2 + custom: tesla.15Ah + - target: esp32c3 + display: cu2 + custom: tesla.20Ah + - target: esp32c3 + display: cu3 + custom: teslatour.15Ah steps: - name: Checkout repo uses: actions/checkout@v3 diff --git a/.gitmodules b/.gitmodules index dab1ef7..8664b7b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -10,6 +10,3 @@ [submodule "components/esp32-button"] path = components/esp32-button url = https://github.com/void-spark/esp32-button.git -[submodule "components/littlefs"] - path = components/littlefs - url = https://github.com/joltwallet/esp_littlefs.git diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json index 72c25a2..c6eeaca 100644 --- a/.vscode/c_cpp_properties.json +++ b/.vscode/c_cpp_properties.json @@ -98,7 +98,6 @@ "${workspaceFolder}/sdk/idf/components/soc/esp32/include", "${workspaceFolder}/sdk/idf/components/soc/include", "${workspaceFolder}/sdk/idf/components/spi_flash/include", - "${workspaceFolder}/sdk/idf/components/littlefs/include", "${workspaceFolder}/sdk/idf/components/tcp_transport/include", "${workspaceFolder}/sdk/idf/components/ulp/ulp_common/include", "${workspaceFolder}/sdk/idf/components/ulp/ulp_common/include/esp32", diff --git a/components/littlefs b/components/littlefs deleted file mode 160000 index 8274371..0000000 --- a/components/littlefs +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 8274371dc5912196f66ac3e71dbb6291760cb8b0 diff --git a/main/CMakeLists.txt b/main/CMakeLists.txt index d98875c..99d4c7c 100644 --- a/main/CMakeLists.txt +++ b/main/CMakeLists.txt @@ -1,4 +1,4 @@ idf_component_register(SRC_DIRS "." "states" INCLUDE_DIRS "." - REQUIRES esp32-button driver littlefs esp_timer nvs_flash esp_adc + REQUIRES esp32-button driver esp_timer nvs_flash esp_adc ) \ No newline at end of file diff --git a/main/Kconfig.projbuild b/main/Kconfig.projbuild index b942e2e..1f67316 100644 --- a/main/Kconfig.projbuild +++ b/main/Kconfig.projbuild @@ -87,6 +87,18 @@ menu "Sparta Ion Config" int "The actual battery voltage in mv for full (=100%). For example 42000mv for a 10s battery" default 42000 + config ION_CURR_ADC + bool "Enable ADC for current measurement" + default n + + config ION_CURR_ADC_CHAN + int "ADC channel to use for current measurement" + default 6 + + config ION_BAT_CHARGE + int "Full battery charge in mAh." + default 10000 + config ION_KEEPALIVE bool "Enable keepalive heartbeat. Will reset the ESP32 when main loop is stuck for more than a minute." default n diff --git a/main/bat.cpp b/main/bat.cpp index f700a53..cd9c50a 100644 --- a/main/bat.cpp +++ b/main/bat.cpp @@ -7,6 +7,8 @@ static const char *TAG = "bat"; +static uint32_t chargeFullMah = (CONFIG_ION_BAT_CHARGE * 3); + // ADC Attenuation // 11DB = 3.55 voltage gain, reference voltage should be around 1100mv, // so max theoretical measurement would be 3905mv, actual/recommended(?) is a lot lower. @@ -16,12 +18,18 @@ static bool cali_enable = false; static adc_oneshot_unit_handle_t adc1_handle = NULL; static adc_cali_handle_t adc1_cali_handle = NULL; -// Use a fake value of 27.6v when we don't have ADC. +// Batterij en stroomwaarden +// Use a fake value of CONFIG_ION_ADC_FULL_MVv when we don't have ADC. static uint32_t batMv = 27600; +static uint32_t batMa = 0; +static uint32_t historyMa = 0; static uint32_t history; static uint8_t batPercentage; +// Get lower/upper limit from configuration +static uint32_t emptyMv = CONFIG_ION_ADC_EMPTY_MV; +static uint32_t fullMv = CONFIG_ION_ADC_FULL_MV; static void adc_calibration_init(adc_unit_t unit, adc_atten_t atten) { esp_err_t ret = ESP_FAIL; @@ -83,8 +91,12 @@ void adc_init() { config.atten = ADC_ATTEN; config.bitwidth = ADC_BITWIDTH_DEFAULT; + // Voltage channel ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, (adc_channel_t)CONFIG_ION_ADC_CHAN, &config)); + // Current Channel + ESP_ERROR_CHECK(adc_oneshot_config_channel(adc1_handle, (adc_channel_t)CONFIG_ION_CURR_ADC_CHAN, &config)); + adc_calibration_init(ADC_UNIT_1, ADC_ATTEN); } @@ -104,20 +116,30 @@ uint32_t measureBatMv() { return (adcVoltageMv * CONFIG_ION_DIVIDER_SCALE) / 1000; } -static uint8_t batMvToPercentage(uint32_t batMv) { +uint32_t measureCurrentMv() { + int adc_raw = 0; + ESP_ERROR_CHECK(adc_oneshot_read(adc1_handle, (adc_channel_t)CONFIG_ION_CURR_ADC_CHAN, &adc_raw)); + int adcCurrentMv = 0; + if (cali_enable) { + ESP_ERROR_CHECK(adc_cali_raw_to_voltage(adc1_cali_handle, adc_raw, &adcCurrentMv)); + } else { + adcCurrentMv = (adc_raw * 3550) / (1 << SOC_ADC_RTC_MAX_BITWIDTH); + } + historyMa += adcCurrentMv; + uint32_t avg = historyMa >> 5; + historyMa -= avg; - // Get lower/upper limit from configuration - uint32_t emptyMv = CONFIG_ION_ADC_EMPTY_MV; - uint32_t fullMv = CONFIG_ION_ADC_FULL_MV; + return avg; +} + +static uint8_t batMvToPercentage(uint32_t batMv) { // Calculate the percentage uint32_t percentage = (batMv < emptyMv) ? 0 : ((batMv - emptyMv) * 100) / (fullMv - emptyMv); // Limit to 0-100 uint8_t batterypercentage = 0; - if (percentage < 0) { - batterypercentage = 0; - } else if (percentage > 100) { + if (percentage > 100) { batterypercentage = 100; } else { batterypercentage = (uint8_t)percentage; @@ -138,7 +160,11 @@ void measureBat() { uint32_t avg = history >> 7; history -= avg; - batPercentage = batMvToPercentage(avg); + batPercentage = batMvToPercentage(avg); +} + +void measureCurrent() { + batMa = measureCurrentMv(); } uint32_t getBatMv() { @@ -146,7 +172,7 @@ uint32_t getBatMv() { } uint8_t getBatPercentage() { - if(batPercentage == 0) { + if(batMv == 0) { // Use a fake value of 50% when we don't have ADC. return 50; } @@ -154,6 +180,10 @@ uint8_t getBatPercentage() { return batPercentage; } +uint32_t getBatMa() { + return batMa; +} + void adc_teardown() { // Tear Down diff --git a/main/bat.h b/main/bat.h index 3e94de6..18dafcb 100644 --- a/main/bat.h +++ b/main/bat.h @@ -1,7 +1,15 @@ #pragma once +// Initialisatie en teardown void adc_init(); +void adc_teardown(); + +// Voltage measurement void measureBat(); uint32_t getBatMv(); uint8_t getBatPercentage(); -void adc_teardown(); + +// Current Measurement +void measureCurrent(); +uint32_t getBatMa(); +uint32_t getBatMah(); \ No newline at end of file diff --git a/main/charge.cpp b/main/charge.cpp new file mode 100644 index 0000000..a5fa5fc --- /dev/null +++ b/main/charge.cpp @@ -0,0 +1,55 @@ +#include "sdkconfig.h" +#include "storage.h" +#include "charge.h" + +static struct batData *bat; + +static uint32_t chargeFullMah = (CONFIG_ION_BAT_CHARGE * 1800); // increase * 1800 to conform to the relative current measurement. + +bool full = true; + +uint8_t getChargePercentage() { + + uint8_t percentageUsed = (uint8_t)(((float)bat->mah / (float)chargeFullMah) * 100.0f); + if (percentageUsed > 100) percentageUsed = 100; + + uint8_t percentage = 100 - percentageUsed; + + if (percentage != bat->percentage) { + bat->percentage = percentage; + batDataSave(); + } + + return bat->percentage; +} + +uint32_t getMv() { + return bat->mv; +} + +uint32_t getMah() { + return bat->mah; +} + +void chargeUpdate(uint32_t mv, uint32_t ma) { + bat->mv = mv; + bat->mah += ma; +} + +void loadCharge() { + bat = batDataGet(); + + if (!batDataLoad()) { + // Defaults als er nog geen data in NVS staat + bat->percentage = 100; + bat->mv = 0; + bat->mah = 0; + } +} + +void resetCharge() { + bat->percentage = 100; + bat->mv = 0; + bat->mah = 0; + batDataSave(); +} diff --git a/main/charge.h b/main/charge.h new file mode 100644 index 0000000..e246ea2 --- /dev/null +++ b/main/charge.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +uint8_t getChargePercentage(void); + +uint32_t getMv(void); + +uint32_t getMah(void); + +void chargeUpdate(uint32_t mv, uint32_t mah); + +void loadCharge(void); + +void resetCharge(void); diff --git a/main/display.cpp b/main/display.cpp index 6f61d9f..6192098 100644 --- a/main/display.cpp +++ b/main/display.cpp @@ -3,6 +3,7 @@ #include "freertos/timers.h" #include "states/states.h" #include "trip.h" +#include "charge.h" #include "relays.h" #include "bat.h" #include "cu2.h" @@ -41,7 +42,12 @@ void stopDisplayUpdates() { static void displayUpdate(ion_state * state) { #if CONFIG_ION_CU2 uint16_t numTop = digits(state->speed, 3, 2); + // uint16_t numTop = digits(getChargePercentage(), 3, 2); + //uint16_t numTop = digits(getBatMv(), 3, 2); uint32_t numBottom = digits(getTrip1() / 100, 5, 1); + // uint32_t numBottom = digits(getBatMa(), 5, 1); + // uint32_t numBottom = digits(getMah() / 1000, 5, 1); + uint8_t batPercentage = getChargePercentage(); displayUpdateCu2(false, // setDefault (assist_level)state->level, // assistLevel BLNK_SOLID, // assistBlink @@ -55,7 +61,7 @@ static void displayUpdate(ion_state * state) { BLNK_SOLID, // top BLNK_SOLID, // bottom false, // miles - getBatPercentage(), // batPercentage + batPercentage, // batPercentage numTop, // topVal numBottom); // bottomVal #elif CONFIG_ION_CU3 diff --git a/main/main.cpp b/main/main.cpp index 6319f05..b1a336f 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -31,6 +31,7 @@ #include "motor.h" #include "relays.h" #include "trip.h" +#include "charge.h" #include "states/states.h" #include "storage.h" @@ -53,14 +54,14 @@ static const char *TAG = "app"; #define CHARGE_PIN ((gpio_num_t)CONFIG_ION_CHARGE_PIN) #endif -static const int BUTTON_MODE_SHORT_PRESS_BIT = BIT0; -static const int BUTTON_MODE_LONG_PRESS_BIT = BIT1; -static const int BUTTON_LIGHT_SHORT_PRESS_BIT = BIT2; -static const int BUTTON_LIGHT_LONG_PRESS_BIT = BIT3; -static const int IGNORE_HELD_BIT = BIT4; -static const int WAKEUP_BIT = BIT5; -static const int CALIBRATE_BIT = BIT6; -static const int MEASURE_BAT_BIT = BIT7; +static const int BUTTON_MODE_SHORT_PRESS_BIT = BIT0; +static const int BUTTON_MODE_LONG_PRESS_BIT = BIT1; +static const int BUTTON_LIGHT_SHORT_PRESS_BIT = BIT2; +static const int BUTTON_LIGHT_LONG_PRESS_BIT = BIT3; +static const int IGNORE_HELD_BIT = BIT4; +static const int WAKEUP_BIT = BIT5; +static const int CALIBRATE_BIT = BIT6; +static const int MEASURE_BAT_BIT = BIT7; static EventGroupHandle_t controlEventGroup; @@ -83,6 +84,8 @@ TimerHandle_t healthCheckTimer ; static void checkMyTaskHealth(TimerHandle_t xTimer) { if (!myTaskAlive) { + batDataSave(); + batDataSave(); esp_restart(); } myTaskAlive = false; // Reset voor volgende check @@ -147,21 +150,8 @@ static messageHandlingResult handleMotorMessage(ion_state * state) { writeMessage(cmdResp(message.source, MSG_BMS, message.command, payload, sizeof(payload))); return CONTROL_TO_SENDER; } else if(message.type == MSG_CMD_REQ && message.payloadSize == 4 && message.command == CMD_GET_DATA && message.payload[1] == 0x38 && message.payload[3] == 0x3a) { - // GET DATA 9438283a 14:38(Calibration A) 28:3a(Calibration B) - uint8_t payload[] = {0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // Data (last 10 bytes) to be replaced - - if(calibrationFileExists()) { - if(!readCalibrationData(payload + 1)) { - return CONTROL_TO_SENDER; - } - } else { - // Backup data - // Gold small test: 94 38 4b 13 28 3a 3e 98 ed f3 - uint8_t data[] = {0x94, 0x38, 0x4b, 0x15, 0x28, 0x3a, 0x3e, 0x91, 0x79, 0x50}; // This needs to be good calibration data! - memcpy(payload + 1, data, 10); - } - - writeMessage(cmdResp(message.source, MSG_BMS, message.command, payload, sizeof(payload))); + uint8_t *payload = calibrationLoad(); + writeMessage(cmdResp(message.source, MSG_BMS, message.command, payload, 11)); return CONTROL_TO_SENDER; } else if(message.type == MSG_CMD_REQ && message.payloadSize == 10 && message.command == CMD_PUT_DATA && message.payload[1] == 0xc0 && message.payload[5] == 0xc1) { // PUT DATA c0/c1 @@ -174,7 +164,7 @@ static messageHandlingResult handleMotorMessage(ion_state * state) { return CONTROL_TO_SENDER; } else if(message.type == MSG_CMD_REQ && message.payloadSize == 10 && message.command == CMD_PUT_DATA && message.payload[1] == 0x38 && message.payload[5] == 0x3a) { // PUT DATA 38/3a - if(!writeCalibrationData(message.payload)) { + if(!calibrationSave(message.payload)) { return CONTROL_TO_SENDER; } @@ -242,11 +232,12 @@ static void my_task(void *pvParameter) { adc_init(); #endif - init_littlefs(); + storageInit(); initUart(); loadDistances(); + loadCharge(); #if CONFIG_ION_CU2 initCu2(controlEventGroup, @@ -306,12 +297,12 @@ static void my_task(void *pvParameter) { #endif EventBits_t buttonBits = xEventGroupWaitBits(controlEventGroup, BUTTON_MODE_SHORT_PRESS_BIT | BUTTON_MODE_LONG_PRESS_BIT | BUTTON_LIGHT_SHORT_PRESS_BIT | BUTTON_LIGHT_LONG_PRESS_BIT | WAKEUP_BIT | CALIBRATE_BIT, true, false, 0); - const bool modeShortPress = (buttonBits & BUTTON_MODE_SHORT_PRESS_BIT) != 0; - const bool modeLongPress = (buttonBits & BUTTON_MODE_LONG_PRESS_BIT) != 0; + const bool modeShortPress = (buttonBits & BUTTON_MODE_SHORT_PRESS_BIT) != 0; + const bool modeLongPress = (buttonBits & BUTTON_MODE_LONG_PRESS_BIT) != 0; const bool lightShortPress = (buttonBits & BUTTON_LIGHT_SHORT_PRESS_BIT) != 0; - const bool lightLongPress = (buttonBits & BUTTON_LIGHT_LONG_PRESS_BIT) != 0; - const bool wakeup = (buttonBits & WAKEUP_BIT) != 0; - const bool calibrate = (buttonBits & CALIBRATE_BIT) != 0; + const bool lightLongPress = (buttonBits & BUTTON_LIGHT_LONG_PRESS_BIT) != 0; + const bool wakeup = (buttonBits & WAKEUP_BIT) != 0; + const bool calibrate = (buttonBits & CALIBRATE_BIT) != 0; if(lightShortPress) { toggleLight(); @@ -320,6 +311,7 @@ static void my_task(void *pvParameter) { if(modeLongPress) { resetTrip1(0); + resetCharge(); requestDisplayUpdate(); } @@ -328,7 +320,15 @@ static void my_task(void *pvParameter) { EventBits_t bits = xEventGroupWaitBits(controlEventGroup, bitsToCheck, false, false, 0); if((bits & MEASURE_BAT_BIT) != 0) { xEventGroupClearBits(controlEventGroup, MEASURE_BAT_BIT); + + // Batterij meten measureBat(); + +#if CONFIG_ION_CURR_ADC + // Stroom meten tegelijk + measureCurrent(); + chargeUpdate(getBatMv(), getBatMa()); +#endif } else #endif if(handleDisplayUpdate(&state)) { @@ -402,4 +402,4 @@ extern "C" void app_main() { } } #endif -} +} \ No newline at end of file diff --git a/main/states/calibrate.cpp b/main/states/calibrate.cpp index 50147c1..56858c6 100644 --- a/main/states/calibrate.cpp +++ b/main/states/calibrate.cpp @@ -2,6 +2,8 @@ #include "freertos/event_groups.h" #include "esp_log.h" #include "blink.h" +#include "display.h" +#include "cu2.h" #include "cmds.h" #include "bow.h" #include "states.h" @@ -22,6 +24,11 @@ void handleCalibrateState(ion_state * state) { // >> cal: almost directly after cal cmd (35) // XXX handoffs later DP(CU3) pings motor, and starts to include it in handoffs // Motor does get data 2a +#if CONFIG_ION_CU2 + displayUpdateCu2(false, ASS_OFF, BLNK_SOLID, BLNK_OFF, BLNK_OFF, BLNK_OFF, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_SOLID, BLNK_SOLID, false, 0, 0xccc, 0xa0a0a); + requestDisplayUpdate(); + vTaskDelay(pdMS_TO_TICKS(1000)); +#endif if(state->step == 0) { exchange(cmdReq(MSG_MOTOR, MSG_BMS, CMD_CALIBRATE)); } else if (state->step == 1) { diff --git a/main/states/motor_off.cpp b/main/states/motor_off.cpp index 364e2e0..32e65f2 100644 --- a/main/states/motor_off.cpp +++ b/main/states/motor_off.cpp @@ -3,14 +3,14 @@ #include "freertos/event_groups.h" #include "esp_log.h" #include "blink.h" -#include "trip.h" +#include "storage.h" #include "states.h" void toMotorOffState(ion_state * state) { queueBlink(4, 100, 300); - saveDistances(); + batDataSave(); state->state = MOTOR_OFF; state->step = 0; diff --git a/main/states/turn_motor_on.cpp b/main/states/turn_motor_on.cpp index 03e0f25..b943df1 100644 --- a/main/states/turn_motor_on.cpp +++ b/main/states/turn_motor_on.cpp @@ -11,6 +11,8 @@ #include "cu3.h" #include "motor.h" #include "states.h" +#include "trip.h" +#include "charge.h" static const char *TAG = "turn_motor_on_state"; @@ -56,7 +58,8 @@ void handleTurnMotorOnState(ion_state * state) { readResult result = exchange(cmdReq(MSG_DISPLAY, MSG_BMS, CMD_BUTTON_POLL, payload, sizeof(payload)), &message, 225 / portTICK_PERIOD_MS ); } else if(state->step == 1) { // Update display - displayUpdateCu2(false, ASS_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_SOLID, BLNK_SOLID, true, 25, 0xccc, 0xccccc); + // assistLevel assistBlink wrench total trip light bars comma km top bottom miles batPercentage topVal bottomVal + displayUpdateCu2(false, ASS_OFF, BLNK_SOLID, BLNK_OFF, BLNK_OFF, BLNK_OFF, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_SOLID, BLNK_SOLID, false, getChargePercentage(), 0xccc, digits(getTotal() / 100, 5, 1)); } else if(state->step == 2) { // Unknown command which is always the same and always sent to the // display at this point. @@ -69,7 +72,9 @@ void handleTurnMotorOnState(ion_state * state) { startButtonCheck(); } else if(state->step == 4) { // Set default display, which is shown if the display isn't updated for a bit (?) - displayUpdateCu2(true, ASS_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, false, 10, 0xccc, 0xccccc); + // setDefault assistLevel assistBlink wrench total trip light bars comma km top bottom miles batPercentage topVal bottomVal + // displayUpdateCu2(f, ASS_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_SOLID, BLNK_SOLID, true, 100, 0xccc, 0xccccc); + displayUpdateCu2(true, ASS_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, BLNK_OFF, BLNK_SOLID, false, getChargePercentage(), 0xccc, digits(getTotal() / 100, 5, 1)); } else #else const uint8_t nextStep = 0; diff --git a/main/storage.cpp b/main/storage.cpp index 8a6c2b9..83983d3 100644 --- a/main/storage.cpp +++ b/main/storage.cpp @@ -1,87 +1,132 @@ -#include -#include "esp_log.h" -#include "esp_littlefs.h" #include "storage.h" +#include "nvs_flash.h" +#include "nvs.h" +#include "esp_log.h" +#include // <-- toegevoegd voor memcpy() static const char *TAG = "storage"; -#define CALIBRATION_FILE "/littlefs/calibration.bin" +#define NVS_NAMESPACE "storage" +#define NVS_KEY_BATDATA "batdata" +#define NVS_KEY_CALIB "calibration" -void init_littlefs() { - ESP_LOGI(TAG, "Initializing LittleFS"); - - esp_vfs_littlefs_conf_t conf = { - .base_path = "/littlefs", - .partition_label = "littlefs", // moet overeenkomen met je partitions.csv - .partition = NULL, - .format_if_mount_failed = true, - .read_only = false, - .dont_mount = false, - .grow_on_mount = true - }; +// Centrale instantie van batData +static struct batData bat; - ESP_ERROR_CHECK(esp_vfs_littlefs_register(&conf)); +// ----------------------------------------------------------------------------- +// Initialisatie +// ----------------------------------------------------------------------------- - size_t total = 0, used = 0; - esp_err_t ret = esp_littlefs_info(conf.partition_label, &total, &used); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to get LittleFS partition information (%s)", esp_err_to_name(ret)); - } else { - ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used); +void storageInit(void) +{ + // NVS init + esp_err_t err = nvs_flash_init(); + if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { + nvs_flash_erase(); + nvs_flash_init(); } - - struct stat st; - if(stat(CALIBRATION_FILE, &st) == 0) { - FILE *fp = fopen(CALIBRATION_FILE, "r"); - if(fp == NULL) { - ESP_LOGE(TAG, "Failed to open calibration file for reading"); - } else { - uint8_t data[10]; - size_t read = fread(data, 1, sizeof(data), fp); - fclose(fp); - ESP_LOGI(TAG, "Calibration file found. Size: %lu, content:", st.st_size); - ESP_LOG_BUFFER_HEX(TAG, data, read); - } - } -} -bool calibrationFileExists() { - return fileExists(CALIBRATION_FILE); -} + // Defaults voor batData + bat.trip1 = 0; + bat.trip2 = 0; + bat.total = 0; -bool readCalibrationData(uint8_t * target) { - return readData(CALIBRATION_FILE, target, 10); + bat.percentage = 0; + bat.mv = 0; + bat.mah = 0; + + ESP_LOGI(TAG, "Storage initialized"); } -bool writeCalibrationData(uint8_t * source){ - return writeData(CALIBRATION_FILE, source, 10); +// ----------------------------------------------------------------------------- +// batData API +// ----------------------------------------------------------------------------- + +struct batData *batDataGet(void) +{ + return &bat; } -bool fileExists(const char * path) { - struct stat st; - return stat(path, &st) == 0; +bool batDataLoad(void) +{ + nvs_handle_t handle; + if (nvs_open(NVS_NAMESPACE, NVS_READONLY, &handle) != ESP_OK) + return false; + + size_t size = sizeof(bat); + esp_err_t err = nvs_get_blob(handle, NVS_KEY_BATDATA, &bat, &size); + nvs_close(handle); + + return (err == ESP_OK); } -bool readData(const char * path, void * target, size_t size) { - FILE *fp = fopen(path, "r"); - if(fp == NULL) { - ESP_LOGE(TAG, "Failed to open file %s for reading", path); +bool batDataSave(void) +{ + nvs_handle_t handle; + if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &handle) != ESP_OK) + return false; + + esp_err_t err = nvs_set_blob(handle, NVS_KEY_BATDATA, &bat, sizeof(bat)); + if (err != ESP_OK) { + nvs_close(handle); return false; } - fread(target, 1, size, fp); - fclose(fp); - return true; + err = nvs_commit(handle); + nvs_close(handle); + + return (err == ESP_OK); } -bool writeData(const char * path, void * source, size_t size) { - FILE *fp = fopen(path, "w"); - if(fp == NULL) { - ESP_LOGE(TAG, "Failed to open file %s for writing", path); +// ----------------------------------------------------------------------------- +// Calibration API +// ----------------------------------------------------------------------------- + +uint8_t *calibrationLoad(void) +{ + static uint8_t payload[11]; + + // Byte 0 is altijd 0x00 + payload[0] = 0x00; + + // Fallback calibratie (10 bytes) + static const uint8_t fallback[10] = { + 0x94, 0x38, 0x4b, 0x15, 0x28, 0x3a, 0x3e, 0x91, 0x79, 0x50 + }; + + // Probeer calibratie uit NVS te lezen + nvs_handle_t handle; + esp_err_t err = nvs_open(NVS_NAMESPACE, NVS_READONLY, &handle); + + if (err == ESP_OK) { + size_t size = 10; + err = nvs_get_blob(handle, NVS_KEY_CALIB, payload + 1, &size); + nvs_close(handle); + + if (err == ESP_OK) { + return payload; // Succesvol geladen + } + } + + // Geen calibratie ? fallback + memcpy(payload + 1, fallback, 10); + return payload; +} + +bool calibrationSave(uint8_t *source) +{ + nvs_handle_t handle; + if (nvs_open(NVS_NAMESPACE, NVS_READWRITE, &handle) != ESP_OK) + return false; + + esp_err_t err = nvs_set_blob(handle, NVS_KEY_CALIB, source, 10); + if (err != ESP_OK) { + nvs_close(handle); return false; } - fwrite(source, 1, size, fp); - fclose(fp); - return true; + err = nvs_commit(handle); + nvs_close(handle); + + return (err == ESP_OK); } \ No newline at end of file diff --git a/main/storage.h b/main/storage.h index 0734089..495e03c 100644 --- a/main/storage.h +++ b/main/storage.h @@ -1,18 +1,25 @@ #pragma once +#include +#include -#include +struct batData { + uint32_t trip1; + uint32_t trip2; + uint32_t total; -void init_littlefs(); + uint8_t percentage; + uint32_t mv; + uint32_t mah; +}; -// Is a calibration file stored? -bool calibrationFileExists(); +// Init NVS + defaults +void storageInit(void); -// Reads calibration data to the given buffer, data is 10 bytes long -bool readCalibrationData(uint8_t * target); +// batData API +struct batData *batDataGet(void); +bool batDataLoad(void); +bool batDataSave(void); -// Writes calibration data from the given buffer, data is 10 bytes long -bool writeCalibrationData(uint8_t * source); - -bool fileExists(const char * path); -bool readData(const char * path, void * target, size_t size); -bool writeData(const char * path, void * source, size_t size); +// calibration API +uint8_t *calibrationLoad(void); +bool calibrationSave(uint8_t *source); diff --git a/main/trip.cpp b/main/trip.cpp index 3fc266c..0f4dfcc 100644 --- a/main/trip.cpp +++ b/main/trip.cpp @@ -1,62 +1,49 @@ #include "storage.h" #include "trip.h" -#define DISTANCE_FILE "/littlefs/distance.bin" - -struct distancesStruct { - // Trip-1 in 10m increments - uint32_t trip1; - - // Trip-2 in 10m increments - uint32_t trip2; - - // Total in 10m increments - uint32_t total; -}; - -static distancesStruct distances; +static struct batData *bat; static uint32_t lastDistance = 0; void resetTrip1(uint32_t distance) { - distances.trip1 = distance; + bat->trip1 = distance; } uint32_t getTrip1() { - return distances.trip1; + return bat->trip1; } uint32_t getTrip2() { - return distances.trip2; + return bat->trip2; } uint32_t getTotal() { - return distances.total; + return bat->total; } void distanceUpdate(uint32_t distance) { - if(distance < lastDistance) { - // We expect this only happens when the motor reset (powered off and on). - // Which means the motor started at 0 again. - // We could reset when we know we power off the motor instead, but what if we don't have a relay (or it's broken)? + + if (distance < lastDistance) { + // Motor is opnieuw opgestart → teller terug naar 0 lastDistance = 0; } uint32_t delta = distance - lastDistance; - distances.trip1 += delta; - distances.trip2 += delta; - distances.total += delta; + bat->trip1 += delta; + bat->trip2 += delta; + bat->total += delta; lastDistance = distance; } void loadDistances() { - if(fileExists(DISTANCE_FILE)) { - readData(DISTANCE_FILE, &distances, sizeof(distances)); - } -} + bat = batDataGet(); -void saveDistances() { - writeData(DISTANCE_FILE, &distances, sizeof(distances)); + if (!batDataLoad()) { + // Defaults als er nog geen data in NVS staat + bat->trip1 = 0; + bat->trip2 = 0; + bat->total = 0; + } } diff --git a/main/trip.h b/main/trip.h index 2506aed..b75bd52 100644 --- a/main/trip.h +++ b/main/trip.h @@ -1,24 +1,21 @@ #pragma once -#include +#include -// To reset on long press mode button +// Reset Trip-1 (bijv. op long-press van mode-knop) void resetTrip1(uint32_t distance); // Trip-1 in 10m increments -uint32_t getTrip1(); +uint32_t getTrip1(void); // Trip-2 in 10m increments -uint32_t getTrip2(); +uint32_t getTrip2(void); // Total in 10m increments -uint32_t getTotal(); +uint32_t getTotal(void); -// Distance update from the motor, distance since motor power on in 10m increments +// Distance update vanuit de motor (afstand sinds motor power-on) void distanceUpdate(uint32_t distance); -// Load distances from flash -void loadDistances(); - -// Write distances to flash -void saveDistances(); +// Laad trip-data uit NVS (via batData) +void loadDistances(void); diff --git a/partitions.csv b/partitions.csv index 6f1bbda..1a85d02 100644 --- a/partitions.csv +++ b/partitions.csv @@ -1,5 +1,4 @@ -# Name, Type, SubType, Offset, Size, Flags -nvs, data, nvs, , 0x4000, -phy_init, data, phy, , 0x1000, -factory, app, factory, , 1M, -littlefs, data, littlefs, , 1M, \ No newline at end of file +# Name, Type, SubType, Offset, Size, Flags +nvs, data, nvs, , 0x10000, +phy_init, data, phy, , 0x1000, +factory, app, factory, , 1M, diff --git a/sdkconfig.defaults b/sdkconfig.defaults index 260dfe5..9a07c8f 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -4,7 +4,7 @@ CONFIG_ION_CU3=y # My chips are 4MB flash, once you use OTA this settings matters CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y -# Set up partitions for littlefs +# Set up partitions CONFIG_PARTITION_TABLE_CUSTOM=y CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" diff --git a/sdkconfig.defaults.esp32c3 b/sdkconfig.defaults.esp32c3 index 1a90b98..e5bd942 100644 --- a/sdkconfig.defaults.esp32c3 +++ b/sdkconfig.defaults.esp32c3 @@ -11,7 +11,6 @@ # 7(--) - RST - RST # 8(--) - VCC - 3.3V - CONFIG_ION_BUTTON=n CONFIG_ION_LED_PIN=3 CONFIG_ION_UART=1 diff --git a/sdkconfig.supermini b/sdkconfig.tesla.10Ah similarity index 64% rename from sdkconfig.supermini rename to sdkconfig.tesla.10Ah index e640b4c..6c4d2c7 100644 --- a/sdkconfig.supermini +++ b/sdkconfig.tesla.10Ah @@ -20,29 +20,46 @@ CONFIG_ION_UART=1 CONFIG_ION_RXD=20 CONFIG_ION_TXD=21 -CONFIG_ION_LIGHT=n -CONFIG_ION_LIGHT_PIN=1 -CONFIG_ION_LIGHT_PIN_INVERTED=n - CONFIG_ION_RELAY=y CONFIG_ION_RELAY_PIN=0 CONFIG_ION_RELAY_PIN_INVERTED=n +CONFIG_ION_LIGHT=y +CONFIG_ION_LIGHT_PIN=3 +CONFIG_ION_LIGHT_PIN_INVERTED=n + CONFIG_ESP32C3_DEFAULT_CPU_FREQ_160=y +# --- ADC measuring --- +# For ESP32-C3 +# ADC channel 0 is pin 0 +# ADC channel 1 is pin 1 +# ADC channel 2 is pin 2 +# ADC channel 3 is pin 3 +# ADC channel 4 is pin 4 CONFIG_ION_ADC=y +# --- Voltage measuring --- # ADC channel 1 is pin 2 CONFIG_ION_ADC_CHAN=2 # The scale of the divider, times 1000, from APM power module CONFIG_ION_DIVIDER_SCALE=10829 -# Consider 18V (3.0V/cell for 6s) empty -CONFIG_ION_ADC_EMPTY_MV=18000 +# Consider 23V (2,875V/cell for 8s LiFePo4) empty +CONFIG_ION_ADC_EMPTY_MV=23000 + +# Consider 27V (3,375V/cell for 8s LiFePo4) full +CONFIG_ION_ADC_FULL_MV=27000 + +# --- Current measuring --- +CONFIG_ION_CURR_ADC=y + +# ADC channel 2 is pin 1 +CONFIG_ION_CURR_ADC_CHAN=1 -# Consider 25.2V (4.2V/cell for 6s) full -CONFIG_ION_ADC_FULL_MV=25200 +# Full battery charge in mAh. +CONFIG_ION_BAT_CHARGE=10000 # keepalive CONFIG_ION_KEEPALIVE=y diff --git a/sdkconfig.tesla.15Ah b/sdkconfig.tesla.15Ah new file mode 100644 index 0000000..c6ffe83 --- /dev/null +++ b/sdkconfig.tesla.15Ah @@ -0,0 +1,65 @@ +# Configuration for use with ESP32 C3 supermini and APM power module +# https://nl.aliexpress.com/item/1005006170575141.html +# https://nl.aliexpress.com/item/1005005831224524.html + +# Pins: +# 1(06) - GND - GND +# 2(04) - GP4 - IO4 > Optional ADC use for battery level, voltage +# 3(06) - GP5 - IO5 > Optional ADC use for battery level, current +# 4(00) - GP0 - IO0 > Motor on/off (active low) +# 5(01) - GP1 - IO1 > Light on/off (active high) + jumper for debug +# 6(20) - RXD - RX > Bus send +# 7(21) - TXD - TX > Bus receive +# 8(07) - VCC - 5V + + +CONFIG_ION_BUTTON=n +CONFIG_ION_LED_PIN=8 + +CONFIG_ION_UART=1 +CONFIG_ION_RXD=20 +CONFIG_ION_TXD=21 + +CONFIG_ION_RELAY=y +CONFIG_ION_RELAY_PIN=0 +CONFIG_ION_RELAY_PIN_INVERTED=n + +CONFIG_ION_LIGHT=y +CONFIG_ION_LIGHT_PIN=3 +CONFIG_ION_LIGHT_PIN_INVERTED=n + +CONFIG_ESP32C3_DEFAULT_CPU_FREQ_160=y + +# --- ADC measuring --- +# For ESP32-C3 +# ADC channel 0 is pin 0 +# ADC channel 1 is pin 1 +# ADC channel 2 is pin 2 +# ADC channel 3 is pin 3 +# ADC channel 4 is pin 4 +CONFIG_ION_ADC=y + +# --- Voltage measuring --- +# ADC channel 1 is pin 2 +CONFIG_ION_ADC_CHAN=2 + +# The scale of the divider, times 1000, from APM power module +CONFIG_ION_DIVIDER_SCALE=10829 + +# Consider 23V (2,875V/cell for 8s LiFePo4) empty +CONFIG_ION_ADC_EMPTY_MV=23000 + +# Consider 27V (3,375V/cell for 8s LiFePo4) full +CONFIG_ION_ADC_FULL_MV=27000 + +# --- Current measuring --- +CONFIG_ION_CURR_ADC=y + +# ADC channel 2 is pin 1 +CONFIG_ION_CURR_ADC_CHAN=1 + +# Full battery charge in mAh. +CONFIG_ION_BAT_CHARGE=15000 + +# keepalive +CONFIG_ION_KEEPALIVE=y diff --git a/sdkconfig.tesla.20Ah b/sdkconfig.tesla.20Ah new file mode 100644 index 0000000..33b4881 --- /dev/null +++ b/sdkconfig.tesla.20Ah @@ -0,0 +1,65 @@ +# Configuration for use with ESP32 C3 supermini and APM power module +# https://nl.aliexpress.com/item/1005006170575141.html +# https://nl.aliexpress.com/item/1005005831224524.html + +# Pins: +# 1(06) - GND - GND +# 2(04) - GP4 - IO4 > Optional ADC use for battery level, voltage +# 3(06) - GP5 - IO5 > Optional ADC use for battery level, current +# 4(00) - GP0 - IO0 > Motor on/off (active low) +# 5(01) - GP1 - IO1 > Light on/off (active high) + jumper for debug +# 6(20) - RXD - RX > Bus send +# 7(21) - TXD - TX > Bus receive +# 8(07) - VCC - 5V + + +CONFIG_ION_BUTTON=n +CONFIG_ION_LED_PIN=8 + +CONFIG_ION_UART=1 +CONFIG_ION_RXD=20 +CONFIG_ION_TXD=21 + +CONFIG_ION_RELAY=y +CONFIG_ION_RELAY_PIN=0 +CONFIG_ION_RELAY_PIN_INVERTED=n + +CONFIG_ION_LIGHT=y +CONFIG_ION_LIGHT_PIN=3 +CONFIG_ION_LIGHT_PIN_INVERTED=n + +CONFIG_ESP32C3_DEFAULT_CPU_FREQ_160=y + +# --- ADC measuring --- +# For ESP32-C3 +# ADC channel 0 is pin 0 +# ADC channel 1 is pin 1 +# ADC channel 2 is pin 2 +# ADC channel 3 is pin 3 +# ADC channel 4 is pin 4 +CONFIG_ION_ADC=y + +# --- Voltage measuring --- +# ADC channel 1 is pin 2 +CONFIG_ION_ADC_CHAN=2 + +# The scale of the divider, times 1000, from APM power module +CONFIG_ION_DIVIDER_SCALE=10829 + +# Consider 23V (2,875V/cell for 8s LiFePo4) empty +CONFIG_ION_ADC_EMPTY_MV=23000 + +# Consider 27V (3,375V/cell for 8s LiFePo4) full +CONFIG_ION_ADC_FULL_MV=27000 + +# --- Current measuring --- +CONFIG_ION_CURR_ADC=y + +# ADC channel 2 is pin 1 +CONFIG_ION_CURR_ADC_CHAN=1 + +# Full battery charge in mAh. +CONFIG_ION_BAT_CHARGE=20000 + +# keepalive +CONFIG_ION_KEEPALIVE=y diff --git a/sdkconfig.teslatour.15Ah b/sdkconfig.teslatour.15Ah new file mode 100644 index 0000000..c6ffe83 --- /dev/null +++ b/sdkconfig.teslatour.15Ah @@ -0,0 +1,65 @@ +# Configuration for use with ESP32 C3 supermini and APM power module +# https://nl.aliexpress.com/item/1005006170575141.html +# https://nl.aliexpress.com/item/1005005831224524.html + +# Pins: +# 1(06) - GND - GND +# 2(04) - GP4 - IO4 > Optional ADC use for battery level, voltage +# 3(06) - GP5 - IO5 > Optional ADC use for battery level, current +# 4(00) - GP0 - IO0 > Motor on/off (active low) +# 5(01) - GP1 - IO1 > Light on/off (active high) + jumper for debug +# 6(20) - RXD - RX > Bus send +# 7(21) - TXD - TX > Bus receive +# 8(07) - VCC - 5V + + +CONFIG_ION_BUTTON=n +CONFIG_ION_LED_PIN=8 + +CONFIG_ION_UART=1 +CONFIG_ION_RXD=20 +CONFIG_ION_TXD=21 + +CONFIG_ION_RELAY=y +CONFIG_ION_RELAY_PIN=0 +CONFIG_ION_RELAY_PIN_INVERTED=n + +CONFIG_ION_LIGHT=y +CONFIG_ION_LIGHT_PIN=3 +CONFIG_ION_LIGHT_PIN_INVERTED=n + +CONFIG_ESP32C3_DEFAULT_CPU_FREQ_160=y + +# --- ADC measuring --- +# For ESP32-C3 +# ADC channel 0 is pin 0 +# ADC channel 1 is pin 1 +# ADC channel 2 is pin 2 +# ADC channel 3 is pin 3 +# ADC channel 4 is pin 4 +CONFIG_ION_ADC=y + +# --- Voltage measuring --- +# ADC channel 1 is pin 2 +CONFIG_ION_ADC_CHAN=2 + +# The scale of the divider, times 1000, from APM power module +CONFIG_ION_DIVIDER_SCALE=10829 + +# Consider 23V (2,875V/cell for 8s LiFePo4) empty +CONFIG_ION_ADC_EMPTY_MV=23000 + +# Consider 27V (3,375V/cell for 8s LiFePo4) full +CONFIG_ION_ADC_FULL_MV=27000 + +# --- Current measuring --- +CONFIG_ION_CURR_ADC=y + +# ADC channel 2 is pin 1 +CONFIG_ION_CURR_ADC_CHAN=1 + +# Full battery charge in mAh. +CONFIG_ION_BAT_CHARGE=15000 + +# keepalive +CONFIG_ION_KEEPALIVE=y