|
| 1 | +//User Setting in Flash (USF) module |
| 2 | +//This module is used to store the user settings in flash memory |
| 3 | +//The user settings are: the beacon ID |
| 4 | +//The beacon ID is a 1-byte value that is used to identify the beacon |
| 5 | +//The beacon ID is stored in flash memory and is loaded at startup |
| 6 | +//The beacon ID is written to flash memory when the user changes it |
| 7 | +//The beacon ID is used in the advertising data |
| 8 | + |
| 9 | +#include <zephyr/kernel.h> |
| 10 | +#include <zephyr/device.h> |
| 11 | +#include <zephyr/devicetree.h> |
| 12 | +#include <zephyr/drivers/sensor.h> |
| 13 | + |
| 14 | +#include <zephyr/drivers/flash.h> |
| 15 | +#include <zephyr/storage/flash_map.h> |
| 16 | +#include <zephyr/fs/nvs.h> |
| 17 | +#include "usf.h" |
| 18 | + |
| 19 | +static struct nvs_fs fs; |
| 20 | + |
| 21 | +#define NVS_PARTITION storage_partition |
| 22 | +#define NVS_PARTITION_DEVICE FIXED_PARTITION_DEVICE(NVS_PARTITION) |
| 23 | +#define NVS_PARTITION_OFFSET FIXED_PARTITION_OFFSET(NVS_PARTITION) |
| 24 | + |
| 25 | +#define BEACONID_ID 1 |
| 26 | +//#define KEY_ID 2 |
| 27 | + |
| 28 | +int usf_init(void) { |
| 29 | + int rc = 0; |
| 30 | + |
| 31 | + struct flash_pages_info info; |
| 32 | + /* define the nvs file system by settings with: |
| 33 | + * sector_size equal to the pagesize, |
| 34 | + * 3 sectors |
| 35 | + * starting at NVS_PARTITION_OFFSET |
| 36 | + */ |
| 37 | + fs.flash_device = NVS_PARTITION_DEVICE; |
| 38 | + if (!device_is_ready(fs.flash_device)) { |
| 39 | + printk("Flash device %s is not ready\n", fs.flash_device->name); |
| 40 | + return 0; |
| 41 | + } |
| 42 | + fs.offset = NVS_PARTITION_OFFSET; |
| 43 | + rc = flash_get_page_info_by_offs(fs.flash_device, fs.offset, &info); |
| 44 | + if (rc) { |
| 45 | + printk("Unable to get page info\n"); |
| 46 | + return 0; |
| 47 | + } |
| 48 | + fs.sector_size = info.size; |
| 49 | + fs.sector_count = 3U; |
| 50 | + |
| 51 | + rc = nvs_mount(&fs); |
| 52 | + if (rc) { |
| 53 | + printk("Flash Init failed\n"); |
| 54 | + return 0; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +//Load the user settings from flash |
| 59 | +int usf_load(void) |
| 60 | +{ |
| 61 | + int ret; |
| 62 | + uint8_t beacon_id; |
| 63 | + |
| 64 | + ret = nvs_read(&fs, BEACONID_ID, &beacon_id, sizeof(beacon_id)); |
| 65 | + if (ret > 0) { /* item was found, show it */ |
| 66 | + printk("Id: %d, Address: %s\n", BEACONID_ID, beacon_id); |
| 67 | + //TODO: load the read value into the beacon ID array from the adv data in main.c |
| 68 | + } else {/* item was not found*/ |
| 69 | + printk("Id: %d, not found\n", BEACONID_ID); |
| 70 | + //TODO: Set the default value for the beacon ID outside this function |
| 71 | + } |
| 72 | + |
| 73 | +} |
| 74 | + |
| 75 | +int usf_write_beacon_id(uint8_t value) { |
| 76 | + |
| 77 | + (void)nvs_write(&fs, BEACONID_ID, &value,sizeof(value)); |
| 78 | + |
| 79 | +} |
| 80 | + |
0 commit comments