1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- /*
- * SPDX-FileCopyrightText: 2022 Helmut Pozimski <helmut@pozimski.eu>
- *
- * SPDX-License-Identifier: GPL-2.0-only
- */
- #include <stdint.h>
- #include <esp_wifi.h>
- #include <esp_err.h>
- #include <string.h>
- #include <freertos/FreeRTOS.h>
- #include <freertos/task.h>
- #include <freertos/event_groups.h>
- #include "configuration.h"
- #define WIFI_CONNECTED_BIT BIT0
- #define WIFI_FAIL_BIT BIT1
- static EventGroupHandle_t wifi_event_group;
- 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) {
- xEventGroupSetBits(wifi_event_group, WIFI_FAIL_BIT);
- } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
- xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
- }
- }
- void wifi_init() {
- wifi_event_group = xEventGroupCreate();
- tcpip_adapter_init();
- ESP_ERROR_CHECK(esp_event_loop_create_default());
- wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
- ESP_ERROR_CHECK(esp_wifi_init(&cfg));
- ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
- ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));
- wifi_config_t wifi_config = {
- .sta = {
- .ssid = WIFI_ESSID,
- .password = WIFI_PASSWORD
- },
- };
- wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
- ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
- ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
- }
- uint8_t wifi_start() {
- ESP_ERROR_CHECK(esp_wifi_start());
- xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
- pdFALSE, pdFALSE, portMAX_DELAY);
- EventBits_t event_bits = xEventGroupGetBits(wifi_event_group);
- ESP_ERROR_CHECK(esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler));
- ESP_ERROR_CHECK(esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler));
- vEventGroupDelete(wifi_event_group);
- return event_bits & WIFI_CONNECTED_BIT;
- }
- void wifi_stop() {
- esp_wifi_disconnect();
- esp_wifi_stop();
- }
|