Files
Hodor/main/wifi.c
T

87 lines
2.8 KiB
C

#include "sdkconfig.h"
#include <esp_log.h>
#include <esp_system.h>
#include "esp_http_server.h"
#include <nvs_flash.h>
#include <sys/param.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_netif.h"
#include "esp_http_server.h"
#include "lwip/sockets.h"
#include <netinet/tcp.h>
#include "board.h"
static const char *TAG = "WIFI:";
static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
ESP_LOGW(TAG, "Wi-Fi disconnected. Retrying...");
esp_wifi_connect();
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(TAG, "SUCCESS! Got IP: " IPSTR, IP2STR(&event->ip_info.ip));
}
}
void start_wifi_and_server(void) {
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
nvs_flash_erase();
nvs_flash_init();
}
esp_netif_init();
esp_event_loop_create_default();
esp_netif_create_default_wifi_sta();
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
esp_wifi_init(&cfg);
wifi_config_t wifi_config = {
.sta = {
.ssid = "viratak-lte",
.password = "mydlinkviratak",
},
};
esp_wifi_set_mode(WIFI_MODE_STA);
esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL, NULL);
esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL, NULL);
esp_wifi_start();
esp_wifi_set_ps(WIFI_PS_NONE);
esp_wifi_connect();
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
httpd_handle_t server = NULL;
if (httpd_start(&server, &config) == ESP_OK) {
httpd_uri_t uri_capture = {
.uri = "/pic",
.method = HTTP_GET,
.handler = capture_handler,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &uri_capture);
httpd_uri_t uri_stream = {
.uri = "/stream",
.method = HTTP_GET,
.handler = stream_handler,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &uri_stream);
httpd_uri_t uri_audio_ws = {
.uri = "/audio",
.method = HTTP_GET,
.handler = audio_ws_handler,
.is_websocket = true
};
httpd_register_uri_handler(server, &uri_audio_ws);
}
}