1/*
2 * esp32 / esp-idf NV settings shim
3 *
4 * Copyright (C) 2019 - 2020 Andy Green <andy@warmcat.com>
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to
8 * deal in the Software without restriction, including without limitation the
9 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 * sell copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 * IN THE SOFTWARE.
23 */
24
25#include <private-lib-core.h>
26
27#include <nvs_flash.h>
28
29int
30lws_settings_plat_get(lws_settings_instance_t *si, const char *name,
31		      uint8_t *dest, size_t *max_actual)
32{
33	int n;
34
35	n = nvs_flash_init_partition((const char *)si->opaque_plat);
36
37	lwsl_notice("%s: init partition %d\n", __func__, n);
38	if (n == ESP_ERR_NOT_FOUND)
39		return 1;
40
41	if (nvs_open_from_partition((const char *)si->opaque_plat,
42				    "_lws_settings", NVS_READONLY,
43				    (nvs_handle_t *)&si->handle_plat))
44		return 1;
45
46	n = nvs_get_blob((nvs_handle_t)si->handle_plat,
47			 name, dest, max_actual);
48
49	nvs_close((nvs_handle_t)si->handle_plat);
50
51	return !!n;
52}
53
54int
55lws_settings_plat_set(lws_settings_instance_t *si, const char *name,
56		      const uint8_t *src, size_t len)
57{
58	int n = nvs_flash_init_partition((const char *)si->opaque_plat);
59
60	lwsl_notice("%s: init partition %d\n", __func__, n);
61	if (n == ESP_ERR_NOT_FOUND)
62		return 1;
63
64	if (nvs_open_from_partition((const char *)si->opaque_plat,
65				    "_lws_settings", NVS_READWRITE,
66				    (nvs_handle_t *)&si->handle_plat))
67		return 1;
68
69	n = nvs_set_blob((nvs_handle_t)si->handle_plat, name, src, len);
70
71	nvs_commit((nvs_handle_t)si->handle_plat);
72	nvs_close((nvs_handle_t)si->handle_plat);
73
74	return 0;
75}
76