Skip to content

Commit

Permalink
improved WiFi STA connection robustness. To be used with libesphttpd/…
Browse files Browse the repository at this point in the history
…pull/85

Also formatted with VS-Code.
  • Loading branch information
pabbott-lumitec committed Jul 27, 2022
1 parent 4aa7a75 commit 0683a5f
Showing 1 changed file with 54 additions and 46 deletions.
100 changes: 54 additions & 46 deletions main/user_main.c
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ char my_hostname[16] = "esphttpd";

#define TAG "user_main"

#define LISTEN_PORT 80u
#define LISTEN_PORT 80u
#define MAX_CONNECTIONS 32u

static char connectionMemory[sizeof(RtosConnType) * MAX_CONNECTIONS];
Expand All @@ -86,12 +86,14 @@ static HttpdFreertosInstance httpdFreertosInstance;
//Function that tells the authentication system what users/passwords live on the system.
//This is disabled in the default build; if you want to try it, enable the authBasic line in
//the builtInUrls below.
int myPassFn(HttpdConnData *connData, int no, char *user, int userLen, char *pass, int passLen) {
if (no==0) {
int myPassFn(HttpdConnData *connData, int no, char *user, int userLen, char *pass, int passLen)
{
if (no == 0)
{
strcpy(user, "admin");
strcpy(pass, "s3cr3t");
return 1;
//Add more users this way. Check against incrementing no for each user added.
//Add more users this way. Check against incrementing no for each user added.
// } else if (no==1) {
// strcpy(user, "user1");
// strcpy(pass, "something");
Expand All @@ -100,64 +102,68 @@ int myPassFn(HttpdConnData *connData, int no, char *user, int userLen, char *pas
return 0;
}


//Broadcast the uptime in seconds every second over connected websockets
static void websocketBcast(void *arg) {
static int ctr=0;
static void websocketBcast(void *arg)
{
static int ctr = 0;
char buff[128];
while(1) {
while (1)
{
ctr++;
sprintf(buff, "Up for %d minutes %d seconds!\n", ctr/60, ctr%60);
sprintf(buff, "Up for %d minutes %d seconds!\n", ctr / 60, ctr % 60);
cgiWebsockBroadcast(&httpdFreertosInstance.httpdInstance,
"/websocket/ws.cgi", buff, strlen(buff),
WEBSOCK_FLAG_NONE);

vTaskDelay(1000/portTICK_RATE_MS);
vTaskDelay(1000 / portTICK_RATE_MS);
}
}

//On reception of a message, send "You sent: " plus whatever the other side sent
static void myWebsocketRecv(Websock *ws, char *data, int len, int flags) {
static void myWebsocketRecv(Websock *ws, char *data, int len, int flags)
{
int i;
char buff[128];
sprintf(buff, "You sent: ");
for (i=0; i<len; i++) buff[i+10]=data[i];
buff[i+10]=0;
for (i = 0; i < len; i++)
buff[i + 10] = data[i];
buff[i + 10] = 0;
cgiWebsocketSend(&httpdFreertosInstance.httpdInstance,
ws, buff, strlen(buff), WEBSOCK_FLAG_NONE);
}

//Websocket connected. Install reception handler and send welcome message.
static void myWebsocketConnect(Websock *ws) {
ws->recvCb=myWebsocketRecv;
static void myWebsocketConnect(Websock *ws)
{
ws->recvCb = myWebsocketRecv;
cgiWebsocketSend(&httpdFreertosInstance.httpdInstance,
ws, "Hi, Websocket!", 14, WEBSOCK_FLAG_NONE);
}

//On reception of a message, echo it back verbatim
void myEchoWebsocketRecv(Websock *ws, char *data, int len, int flags) {
void myEchoWebsocketRecv(Websock *ws, char *data, int len, int flags)
{
printf("EchoWs: echo, len=%d\n", len);
cgiWebsocketSend(&httpdFreertosInstance.httpdInstance,
ws, data, len, flags);
}

//Echo websocket connected. Install reception handler.
void myEchoWebsocketConnect(Websock *ws) {
void myEchoWebsocketConnect(Websock *ws)
{
printf("EchoWs: connect\n");
ws->recvCb=myEchoWebsocketRecv;
ws->recvCb = myEchoWebsocketRecv;
}

#define OTA_FLASH_SIZE_K 1024
#define OTA_TAGNAME "generic"

CgiUploadFlashDef uploadParams={
.type=CGIFLASH_TYPE_FW,
.fw1Pos=0x1000,
.fw2Pos=((OTA_FLASH_SIZE_K*1024)/2)+0x1000,
.fwSize=((OTA_FLASH_SIZE_K*1024)/2)-0x1000,
.tagName=OTA_TAGNAME
};

CgiUploadFlashDef uploadParams = {
.type = CGIFLASH_TYPE_FW,
.fw1Pos = 0x1000,
.fw2Pos = ((OTA_FLASH_SIZE_K * 1024) / 2) + 0x1000,
.fwSize = ((OTA_FLASH_SIZE_K * 1024) / 2) - 0x1000,
.tagName = OTA_TAGNAME};

static void customHeaders_cacheForever(HttpdConnData *connData)
{
Expand Down Expand Up @@ -224,9 +230,7 @@ HttpdBuiltInUrl builtInUrls[] = {

ROUTE_FILESYSTEM(),

ROUTE_END()
};

ROUTE_END()};

#ifdef ESP32

Expand Down Expand Up @@ -289,7 +293,7 @@ static void app_event_handler(void *arg, esp_event_base_t event_base,
printf("GW:" IPSTR "\n", IP2STR(&event->ip_info.gw));
printf("~~~~~~~~~~~~~\n");

}
}

if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED)
{
Expand Down Expand Up @@ -327,7 +331,6 @@ static void app_event_handler(void *arg, esp_event_base_t event_base,
printf("GW:" IPSTR "\n", IP2STR(&ap_ip_info.gw));
}
printf("~~~~~~~~~~~~\n");
set_status_ind_wifi(WIFI_STATE_IDLE);
}

if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED)
Expand Down Expand Up @@ -358,32 +361,35 @@ void init_wifi(bool factory_defaults)

wifi_mode_t old_mode;
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK( esp_wifi_init(&cfg) );
ESP_ERROR_CHECK(esp_wifi_init(&cfg));

// Try to get WiFi configuration from NVS?
#if defined(CONFIG_STORE_WIFI_TO_NVS)
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_FLASH)); // WIFI_STORAGE_FLASH or WIFI_STORAGE_RAM
#else // don't save WiFi config to NVS
ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) );
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
#endif
ESP_ERROR_CHECK(esp_wifi_get_mode(&old_mode));

if (factory_defaults)
{
old_mode = DEFAULT_WIFI_MODE;
esp_wifi_set_mode(old_mode);
}

if (old_mode == WIFI_MODE_APSTA || old_mode == WIFI_MODE_STA)
{
ESP_ERROR_CHECK(esp_wifi_set_bandwidth(WIFI_IF_STA, WIFI_BW_HT20)); // set 20MHz bandwidth, for better range
//// STA settings
wifi_config_t factory_sta_config = {
.sta = {
.ssid = DEFAULT_WIFI_STA_SSID,
.password = DEFAULT_WIFI_STA_PASS,
}};
.sort_method = WIFI_CONNECT_AP_BY_SIGNAL}};
wifi_config_t sta_stored_config;
//esp_wifi_set_mode(WIFI_MODE_APSTA); // must enable modes before trying esp_wifi_get_config()

ESP_ERROR_CHECK(esp_wifi_get_config(ESP_IF_WIFI_STA, &sta_stored_config));
sta_stored_config.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL;

if (factory_defaults && strlen((char *)factory_sta_config.sta.ssid) != 0)
{
Expand All @@ -408,6 +414,7 @@ void init_wifi(bool factory_defaults)

if (old_mode == WIFI_MODE_APSTA || old_mode == WIFI_MODE_AP)
{
ESP_ERROR_CHECK(esp_wifi_set_bandwidth(WIFI_IF_AP, WIFI_BW_HT20)); // set 20MHz bandwidth, for better range
//// AP settings
wifi_config_t factory_ap_config;
{
Expand All @@ -425,7 +432,6 @@ void init_wifi(bool factory_defaults)

if (factory_defaults && strlen((char *)factory_ap_config.ap.ssid) != 0)
{

// load factory default STA config
ESP_LOGI(TAG, "Using factory-default WiFi AP configuration, ssid: %s", factory_ap_config.ap.ssid);
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_AP, &factory_ap_config));
Expand All @@ -445,15 +451,17 @@ void init_wifi(bool factory_defaults)
}
}

ESP_ERROR_CHECK( esp_wifi_start() );
ESP_ERROR_CHECK(esp_wifi_start());
}
#endif

//Main routine. Initialize stdout, the I/O, filesystem and the webserver and we're done.
#if ESP32
void app_main(void) {
void app_main(void)
{
#else
void user_init(void) {
void user_init(void)
{
#endif

#ifndef ESP32
Expand All @@ -470,12 +478,13 @@ void user_init(void) {
{
// NVS partition was truncated and needs to be erased
// Retry nvs_flash_init
ESP_LOGW(TAG, "NVS invalid, reformatting... ");
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
ESP_ERROR_CHECK(err); // will reboot if error!

uint32_t net_configured = 0; // value will default to 0, if not set yet in NVS
uint32_t net_configured = 0; // value will default to 0, if not set yet in NVS
ESP_LOGI(TAG, "Opening NVS handle ");
err = nvs_open(NVS_NAMESPACE, NVS_READWRITE, &my_nvs_handle);
if (err != ESP_OK)
Expand Down Expand Up @@ -525,10 +534,9 @@ void user_init(void) {
HTTPD_FLAG_NONE);
httpdFreertosStart(&httpdFreertosInstance);


xTaskCreate(websocketBcast, "wsbcast", 3000, NULL, 3, NULL);

ESP_ERROR_CHECK(initCgiWifi()); // Initialise wifi configuration CGI
initCgiWifi(); // Initialise wifi configuration CGI

ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
ESP_EVENT_ANY_ID,
Expand All @@ -541,12 +549,12 @@ void user_init(void) {
NULL,
NULL));

#ifdef ETHERNET_ENABLE
init_wifi(!net_configured); // Start Wifi, restore factory wifi settings if not initialized
startCgiWifi(); // will try to restore STA connection on boot
#ifdef MY_ETH_ENABLE
init_ethernet();
#endif

init_wifi(!net_configured); // Start Wifi, restore factory wifi settings if not initialized

if (!net_configured)
{ // If wasn't initialized, now we are initialized. Write it to NVS.
net_configured = 1;
Expand Down

0 comments on commit 0683a5f

Please sign in to comment.