85 lines
2.3 KiB
C
85 lines
2.3 KiB
C
#include <freertos/FreeRTOS.h>
|
|
#include <freertos/task.h>
|
|
#include <esp_log.h>
|
|
#include <esp_wifi.h>
|
|
//#include <esp_http_client.h>
|
|
//#include "esp_netif.h"
|
|
#include "functions.h"
|
|
#include "wifi.h"
|
|
#include "leds.h"
|
|
|
|
static const char * TAG = "wifi.c";
|
|
|
|
esp_err_t wifi_init() {
|
|
ESP_ERROR_CHECK(esp_event_loop_create_default());
|
|
// Init IP Stack
|
|
tcpip_adapter_init();
|
|
return ESP_OK;
|
|
}
|
|
|
|
static bool wait_for_connected() {
|
|
tcpip_adapter_ip_info_t ip_info;
|
|
|
|
unsigned repeats = 15;
|
|
for(unsigned i = 0; i < repeats; ++i)
|
|
{
|
|
if ( tcpip_adapter_get_ip_info( TCPIP_ADAPTER_IF_STA, &ip_info ) == ESP_OK && ip_info.ip.addr != 0 ) {
|
|
ESP_LOGI(TAG, "IP Address: " IPSTR, IP2STR(&ip_info.ip));
|
|
return ESP_OK;
|
|
}
|
|
vTaskDelay(1000 / portTICK_RATE_MS);
|
|
}
|
|
ESP_LOGE(TAG, "Timedout waiting for ip address from dhcp server.");
|
|
return ESP_FAIL;
|
|
}
|
|
|
|
// Function to turn on WiFi
|
|
esp_err_t wifi_on() {
|
|
// Init wifi
|
|
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
|
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
|
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
|
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
|
// Configure Wifi AP settings
|
|
wifi_config_t sta_config = {
|
|
.sta = {
|
|
.ssid = CONFIG_ESP_WIFI_SSID,
|
|
.password = CONFIG_ESP_WIFI_PASSWORD,
|
|
},
|
|
};
|
|
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &sta_config));
|
|
|
|
// Enable power saving
|
|
//ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_MIN_MODEM));
|
|
//ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_MAX_MODEM));
|
|
ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
|
|
|
|
ESP_LOGI(TAG, "Turning WiFi ON...");
|
|
esp_wifi_start(); // Start WiFi
|
|
ESP_LOGI(TAG, "WiFi is ON and connecting...");
|
|
esp_wifi_connect();
|
|
led1_on();
|
|
ESP_LOGI(TAG, "WiFi is ON and connected to AP.");
|
|
if (wait_for_connected() == ESP_OK) {
|
|
led2_on();
|
|
return ESP_OK;
|
|
}
|
|
else {
|
|
wifi_off();
|
|
return ESP_FAIL;
|
|
}
|
|
}
|
|
|
|
// Function to turn off WiFi
|
|
esp_err_t wifi_off() {
|
|
ESP_LOGI(TAG, "Disconnecting from AP and turning off WiFi...");
|
|
esp_wifi_disconnect();
|
|
ESP_LOGI(TAG, "WiFi disconnected. Turning WiFi OFF...");
|
|
esp_wifi_stop(); // Stop WiFi
|
|
esp_wifi_deinit();
|
|
led1_off();
|
|
led2_off();
|
|
ESP_LOGI(TAG, "WiFi is OFF.");
|
|
return ESP_OK;
|
|
}
|