1 // Copyright 2018 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
15 #include <stdio.h>
16 #include <assert.h>
17 #include "nvs.h"
18 #include "lwip/opt.h"
19 #include "lwip/dhcp.h"
20 #include "lwip/netif.h"
21 #include "esp_interface.h"
22 #include "esp_netif.h"
23 #include "esp_netif_net_stack.h"
24 #include "netif/dhcp_state.h"
25
26 #define DHCP_NAMESPACE "dhcp_state"
27
28 // DHCP_Client has to be enabled for this netif
29 #define VALID_NETIF_ID(netif) (ESP_NETIF_DHCP_CLIENT&esp_netif_get_flags(netif))
30
dhcp_ip_addr_restore(void * netif)31 bool dhcp_ip_addr_restore(void *netif)
32 {
33 nvs_handle_t nvs;
34 bool err = false;
35 struct netif *net = (struct netif *)netif;
36 struct dhcp *dhcp = netif_dhcp_data(net);
37 esp_netif_t *esp_netif = esp_netif_get_handle_from_netif_impl(netif);
38
39 if(VALID_NETIF_ID(esp_netif)) {
40 uint32_t *ip_addr = &dhcp->offered_ip_addr.addr;
41 if (nvs_open(DHCP_NAMESPACE, NVS_READONLY, &nvs) == ESP_OK) {
42 if (nvs_get_u32(nvs, esp_netif_get_ifkey(esp_netif), ip_addr) == ESP_OK) {
43 err = true;
44 }
45 nvs_close(nvs);
46 }
47 }
48 return err;
49 }
50
dhcp_ip_addr_store(void * netif)51 void dhcp_ip_addr_store(void *netif)
52 {
53 nvs_handle_t nvs;
54 struct netif *net = (struct netif *)netif;
55 struct dhcp *dhcp = netif_dhcp_data(net);
56 uint32_t ip_addr = dhcp->offered_ip_addr.addr;
57 esp_netif_t *esp_netif = esp_netif_get_handle_from_netif_impl(netif);
58
59 if(VALID_NETIF_ID(esp_netif)) {
60 if (nvs_open(DHCP_NAMESPACE, NVS_READWRITE, &nvs) == ESP_OK) {
61 nvs_set_u32(nvs,esp_netif_get_ifkey(esp_netif), ip_addr);
62 nvs_commit(nvs);
63 nvs_close(nvs);
64 }
65 }
66 }
67
dhcp_ip_addr_erase(void * esp_netif)68 void dhcp_ip_addr_erase(void *esp_netif)
69 {
70 nvs_handle_t nvs;
71
72 if(VALID_NETIF_ID(esp_netif)) {
73 if (nvs_open(DHCP_NAMESPACE, NVS_READWRITE, &nvs) == ESP_OK) {
74 nvs_erase_key(nvs, esp_netif_get_ifkey(esp_netif));
75 nvs_commit(nvs);
76 nvs_close(nvs);
77 }
78 }
79 }
80