1 // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 #include "nvs_partition_manager.hpp"
15 #include "nvs_handle.hpp"
16 #include "nvs_handle_simple.hpp"
17 #include "nvs_handle_locked.hpp"
18 #include "nvs_platform.hpp"
19 
20 namespace nvs {
21 
open_nvs_handle_from_partition(const char * partition_name,const char * ns_name,nvs_open_mode_t open_mode,esp_err_t * err)22 std::unique_ptr<NVSHandle> open_nvs_handle_from_partition(const char *partition_name,
23         const char *ns_name,
24         nvs_open_mode_t open_mode,
25         esp_err_t *err)
26 {
27     if (partition_name == nullptr || ns_name == nullptr) {
28         if (err) {
29             *err = ESP_ERR_INVALID_ARG;
30         }
31         return nullptr;
32     }
33 
34     esp_err_t lock_result = Lock::init();
35     if (lock_result != ESP_OK) {
36         if (err != nullptr) {
37             *err = lock_result;
38         }
39         return nullptr;
40     }
41 
42     Lock lock;
43 
44     NVSHandleSimple *handle_simple;
45     esp_err_t result = nvs::NVSPartitionManager::get_instance()->
46             open_handle(partition_name, ns_name, open_mode, &handle_simple);
47 
48     if (err) {
49         *err = result;
50     }
51 
52     if (result != ESP_OK) {
53         return nullptr;
54     }
55 
56     NVSHandleLocked *locked_handle = new (nothrow) NVSHandleLocked(handle_simple);
57 
58     if (!locked_handle) {
59         if (err) {
60             *err = ESP_ERR_NO_MEM;
61         }
62         delete handle_simple;
63         return nullptr;
64     }
65 
66     return std::unique_ptr<NVSHandleLocked>(locked_handle);
67 }
68 
open_nvs_handle(const char * ns_name,nvs_open_mode_t open_mode,esp_err_t * err)69 std::unique_ptr<NVSHandle> open_nvs_handle(const char *ns_name,
70         nvs_open_mode_t open_mode,
71         esp_err_t *err)
72 {
73     return open_nvs_handle_from_partition(NVS_DEFAULT_PART_NAME, ns_name, open_mode, err);
74 }
75 
76 } // namespace nvs
77