EIS-BLE-S3/main/wifi_cfg.c

119 lines
3.1 KiB
C

#include "wifi_cfg.h"
#include <string.h>
#include <stdio.h>
#include "nvs_flash.h"
#include "nvs.h"
#define NVS_NS "wifi_prov"
#define KEY_STA_SSID "sta_ssid"
#define KEY_STA_PASS "sta_pass"
#define KEY_AP_SSID "ap_ssid"
#define KEY_AP_PASS "ap_pass"
#define DEFAULT_AP_SSID "EIS4"
#define DEFAULT_AP_PASS "eis4data"
static char sta_ssid[WIFI_CFG_SSID_MAX];
static char sta_pass[WIFI_CFG_PASS_MAX];
static char ap_ssid[WIFI_CFG_SSID_MAX];
static char ap_pass[WIFI_CFG_PASS_MAX];
esp_err_t wifi_cfg_init(void)
{
memset(sta_ssid, 0, sizeof(sta_ssid));
memset(sta_pass, 0, sizeof(sta_pass));
strncpy(ap_ssid, DEFAULT_AP_SSID, sizeof(ap_ssid) - 1);
strncpy(ap_pass, DEFAULT_AP_PASS, sizeof(ap_pass) - 1);
nvs_handle_t h;
esp_err_t err = nvs_open(NVS_NS, NVS_READONLY, &h);
if (err == ESP_ERR_NVS_NOT_FOUND)
return ESP_OK;
if (err != ESP_OK)
return err;
size_t len;
len = sizeof(sta_ssid);
nvs_get_str(h, KEY_STA_SSID, sta_ssid, &len);
len = sizeof(sta_pass);
nvs_get_str(h, KEY_STA_PASS, sta_pass, &len);
len = sizeof(ap_ssid);
if (nvs_get_str(h, KEY_AP_SSID, ap_ssid, &len) != ESP_OK) {
strncpy(ap_ssid, DEFAULT_AP_SSID, sizeof(ap_ssid) - 1);
}
len = sizeof(ap_pass);
if (nvs_get_str(h, KEY_AP_PASS, ap_pass, &len) != ESP_OK) {
strncpy(ap_pass, DEFAULT_AP_PASS, sizeof(ap_pass) - 1);
}
nvs_close(h);
if (sta_ssid[0])
printf("WiFi cfg: STA \"%s\"\n", sta_ssid);
printf("WiFi cfg: AP \"%s\"\n", ap_ssid);
return ESP_OK;
}
bool wifi_cfg_has_sta(void)
{
return sta_ssid[0] != '\0';
}
esp_err_t wifi_cfg_get_sta(char *ssid, size_t ssid_sz, char *pass, size_t pass_sz)
{
if (!sta_ssid[0])
return ESP_ERR_NOT_FOUND;
strncpy(ssid, sta_ssid, ssid_sz - 1);
ssid[ssid_sz - 1] = '\0';
strncpy(pass, sta_pass, pass_sz - 1);
pass[pass_sz - 1] = '\0';
return ESP_OK;
}
esp_err_t wifi_cfg_set_sta(const char *ssid, const char *pass)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NVS_NS, NVS_READWRITE, &h);
if (err != ESP_OK) return err;
nvs_set_str(h, KEY_STA_SSID, ssid);
nvs_set_str(h, KEY_STA_PASS, pass);
nvs_commit(h);
nvs_close(h);
strncpy(sta_ssid, ssid, sizeof(sta_ssid) - 1);
sta_ssid[sizeof(sta_ssid) - 1] = '\0';
strncpy(sta_pass, pass, sizeof(sta_pass) - 1);
sta_pass[sizeof(sta_pass) - 1] = '\0';
return ESP_OK;
}
esp_err_t wifi_cfg_get_ap(char *ssid, size_t ssid_sz, char *pass, size_t pass_sz)
{
strncpy(ssid, ap_ssid, ssid_sz - 1);
ssid[ssid_sz - 1] = '\0';
strncpy(pass, ap_pass, pass_sz - 1);
pass[pass_sz - 1] = '\0';
return ESP_OK;
}
esp_err_t wifi_cfg_set_ap(const char *ssid, const char *pass)
{
nvs_handle_t h;
esp_err_t err = nvs_open(NVS_NS, NVS_READWRITE, &h);
if (err != ESP_OK) return err;
nvs_set_str(h, KEY_AP_SSID, ssid);
nvs_set_str(h, KEY_AP_PASS, pass);
nvs_commit(h);
nvs_close(h);
strncpy(ap_ssid, ssid, sizeof(ap_ssid) - 1);
ap_ssid[sizeof(ap_ssid) - 1] = '\0';
strncpy(ap_pass, pass, sizeof(ap_pass) - 1);
ap_pass[sizeof(ap_pass) - 1] = '\0';
return ESP_OK;
}