/* * SPDX-License-Identifier: AGPL-3.0-only * Copyright (c) Camden Dixie O'Brien */ #include "system_utils.h" #include "fatal.h" #include "time_storage.h" #include "esp_log.h" #include "esp_system.h" #include "nvs_flash.h" #define TAG "System utils" #define NVS_NAMESPACE "system-utils" #define BOOTED_FLAG_KEY "booted" static bool first_boot; static void test_first_boot(void) { esp_err_t error; nvs_handle_t handle; error = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &handle); if (error != ESP_OK) { ESP_LOGE(TAG, "Error opening NVS store namespace: %02x", error); first_boot = false; return; } uint8_t tmp; error = nvs_get_u8(handle, BOOTED_FLAG_KEY, &tmp); if (error == ESP_OK) { first_boot = false; } else if (error == ESP_ERR_NVS_NOT_FOUND) { ESP_LOGI(TAG, "First boot of system"); first_boot = true; error = nvs_set_u8(handle, BOOTED_FLAG_KEY, 1); if (error != ESP_OK) ESP_LOGE(TAG, "Error setting booted flag: %02x", error); } else { ESP_LOGE(TAG, "Error getting booted flag: %02x", error); first_boot = false; } nvs_close(handle); } void early_init() { esp_err_t error = nvs_flash_init(); if (error == ESP_ERR_NVS_NO_FREE_PAGES || error == ESP_ERR_NVS_NEW_VERSION_FOUND) { ESP_LOGI(TAG, "NVS partition full or outdated; erasing"); (void)nvs_flash_erase(); error = nvs_flash_init(); } if (error != ESP_OK) { ESP_LOGE(TAG, "Error initializing NVS store: %04x", error); FATAL(); } test_first_boot(); } bool is_first_boot() { return first_boot; } void reboot() { ESP_LOGI(TAG, "Rebooting system"); time_storage_save(); esp_restart(); }