#include <zephyr/kernel.h>
#include <zephyr/logging/log.h>
#include <zephyr/drivers/watchdog.h>
#include <zephyr/drivers/flash.h>
#include <zephyr/storage/flash_map.h>
#include <zephyr/fs/nvs.h>


#define NVS_PARTITION			storage_partition
#define NVS_PARTITION_DEVICE	FIXED_PARTITION_DEVICE(NVS_PARTITION)
#define NVS_PARTITION_OFFSET	FIXED_PARTITION_OFFSET(NVS_PARTITION)
#define NVS_SETTINGS_ADDR		2

#define LOG_MODULE_NAME app
LOG_MODULE_REGISTER(LOG_MODULE_NAME);



uint32_t nv_save()
{
	int rc;
	uint8_t testdata[100] = {0x55};
	struct nvs_fs fs;
	struct flash_pages_info info;

	fs.flash_device = NVS_PARTITION_DEVICE; 

	if (!device_is_ready(fs.flash_device)) {
		printk("Flash device %s is not ready\n", fs.flash_device->name);
		return 1;
	}

	fs.offset = NVS_PARTITION_OFFSET; //0xfd000 matches storage in ram report
	rc = flash_get_page_info_by_offs(fs.flash_device, fs.offset, &info);

	if (rc) {
		printk("Unable to get page info, rc=%d\n", rc);
		return rc;
	}

	fs.sector_size = info.size;
	fs.sector_count = 3U;
	rc = nvs_mount(&fs);

	if (rc) {
		printk("Flash Init failed, rc=%d\n", rc);
		return rc;
	}

	printk("FS nvs mount rc %d\n",rc);
	printk("Writing data %d byte\n", sizeof(testdata));
	rc = nvs_write(&fs, 1, &testdata, sizeof(testdata));
	printk("NVS write rc %d\n",rc);

	return rc;
}


 /************************************ Main ***************************************/
 int main(void)
 {
	uint32_t rc;
	printk("***START\n");
	rc = nv_save();
	for (;;) 
	{
		k_sleep(K_MSEC(1));

	 }
 }