esp-idf/components/lwip/port/esp32/netif/dhcp_state.c

74 lines
1.7 KiB
C
Raw Normal View History

2022-03-23 14:20:06 -04:00
/*
* SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "nvs.h"
#include "lwip/dhcp.h"
#include "lwip/netif.h"
#include "netif/dhcp_state.h"
#define DHCP_NAMESPACE "dhcp_state"
2022-03-23 14:20:06 -04:00
#define IF_KEY_SIZE 3
2022-03-23 14:20:06 -04:00
/*
* As a NVS key, use string representation of the interface index number
*/
static inline char *gen_if_key(struct netif *netif, char *name)
{
lwip_itoa(name, IF_KEY_SIZE, netif->num);
return name;
}
2022-03-23 14:20:06 -04:00
bool dhcp_ip_addr_restore(struct netif *netif)
{
nvs_handle_t nvs;
2022-03-23 14:20:06 -04:00
char if_key[IF_KEY_SIZE];
bool err = false;
if (netif == NULL) {
return false;
}
2022-03-23 14:20:06 -04:00
struct dhcp *dhcp = netif_dhcp_data(netif);
2022-03-23 14:20:06 -04:00
uint32_t *ip_addr = &dhcp->offered_ip_addr.addr;
if (nvs_open(DHCP_NAMESPACE, NVS_READONLY, &nvs) == ESP_OK) {
if (nvs_get_u32(nvs, gen_if_key(netif, if_key), ip_addr) == ESP_OK) {
err = true;
}
2022-03-23 14:20:06 -04:00
nvs_close(nvs);
}
return err;
}
2022-03-23 14:20:06 -04:00
void dhcp_ip_addr_store(struct netif *netif)
{
nvs_handle_t nvs;
2022-03-23 14:20:06 -04:00
char if_key[IF_KEY_SIZE];
if (netif == NULL) {
return;
}
2022-03-23 14:20:06 -04:00
struct dhcp *dhcp = netif_dhcp_data(netif);
uint32_t ip_addr = dhcp->offered_ip_addr.addr;
2022-03-23 14:20:06 -04:00
if (nvs_open(DHCP_NAMESPACE, NVS_READWRITE, &nvs) == ESP_OK) {
nvs_set_u32(nvs, gen_if_key(netif, if_key), ip_addr);
nvs_commit(nvs);
nvs_close(nvs);
}
}
2022-03-23 14:20:06 -04:00
void dhcp_ip_addr_erase(struct netif *netif)
{
nvs_handle_t nvs;
2022-03-23 14:20:06 -04:00
char if_key[IF_KEY_SIZE];
if (netif == NULL) {
return;
}
2022-03-23 14:20:06 -04:00
if (nvs_open(DHCP_NAMESPACE, NVS_READWRITE, &nvs) == ESP_OK) {
nvs_erase_key(nvs, gen_if_key(netif, if_key));
nvs_commit(nvs);
nvs_close(nvs);
}
}