|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Purva Yeshi <[email protected]> |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include <zephyr/kernel.h> |
| 8 | +#include <zephyr/sys/reboot.h> |
| 9 | +#include <zephyr/device.h> |
| 10 | +#include <string.h> |
| 11 | +#include <zephyr/drivers/flash.h> |
| 12 | +#include <zephyr/storage/flash_map.h> |
| 13 | +#include <zephyr/fs/nvs.h> |
| 14 | +#include <zephyr/logging/log.h> |
| 15 | + |
| 16 | +#include "EEPROM.h" |
| 17 | + |
| 18 | +static struct nvs_fs fs; |
| 19 | + |
| 20 | +#define NVS_PARTITION storage_partition |
| 21 | +#define NVS_PARTITION_DEVICE FIXED_PARTITION_DEVICE(NVS_PARTITION) |
| 22 | +#define NVS_PARTITION_OFFSET FIXED_PARTITION_OFFSET(NVS_PARTITION) |
| 23 | + |
| 24 | +/* Register a module for logging */ |
| 25 | +LOG_MODULE_REGISTER(eeprom, LOG_LEVEL_INF); |
| 26 | + |
| 27 | +int arduino::ZephyrEEPROM::nvs_init(void) |
| 28 | +{ |
| 29 | + int rc = 0; |
| 30 | + |
| 31 | + struct flash_pages_info info; |
| 32 | + |
| 33 | + fs.flash_device = NVS_PARTITION_DEVICE; |
| 34 | + if (!device_is_ready(fs.flash_device)) { |
| 35 | + LOG_ERR("Flash device %s is not ready", fs.flash_device->name); |
| 36 | + return -ENODEV; |
| 37 | + } |
| 38 | + |
| 39 | + fs.offset = NVS_PARTITION_OFFSET; |
| 40 | + |
| 41 | + rc = flash_get_page_info_by_offs(fs.flash_device, fs.offset, &info); |
| 42 | + if (rc) { |
| 43 | + LOG_ERR("Unable to get page info"); |
| 44 | + return rc; |
| 45 | + } |
| 46 | + |
| 47 | + fs.sector_size = info.size; |
| 48 | + fs.sector_count = 3U; |
| 49 | + |
| 50 | + rc = nvs_mount(&fs); |
| 51 | + if (rc) { |
| 52 | + LOG_ERR("Flash Init failed"); |
| 53 | + return rc; |
| 54 | + } |
| 55 | + |
| 56 | + LOG_INF("NVS initialized successfully"); |
| 57 | + return 0; |
| 58 | +} |
| 59 | + |
| 60 | +int arduino::ZephyrEEPROM::read_data(uint16_t id, void *data, size_t max_len) |
| 61 | +{ |
| 62 | + /* Correctly pass data and max_len */ |
| 63 | + int rc = nvs_read(&fs, id, data, max_len); |
| 64 | + if (rc > 0) { |
| 65 | + /* Data successfully read */ |
| 66 | + return rc; |
| 67 | + } else if (rc == 0) { |
| 68 | + LOG_ERR("Data not found for ID: %d", id); |
| 69 | + } else { |
| 70 | + LOG_ERR("Error reading data for ID: %d, Error: %d", id, rc); |
| 71 | + } |
| 72 | + /* Return the result code, which can indicate an error or success */ |
| 73 | + return rc; |
| 74 | +} |
| 75 | + |
| 76 | +int arduino::ZephyrEEPROM::write_data(uint16_t id, const void *data, size_t data_len) |
| 77 | +{ |
| 78 | + /* Pass data directly */ |
| 79 | + int rc = nvs_write(&fs, id, data, data_len); |
| 80 | + if (rc < 0) { |
| 81 | + LOG_ERR("Error writing data for ID: %d, Error: %d", id, rc); |
| 82 | + } |
| 83 | + return rc; |
| 84 | +} |
| 85 | + |
| 86 | +arduino::ZephyrEEPROM EEPROM; |
0 commit comments