wifi.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * SPDX-FileCopyrightText: 2022 Helmut Pozimski <helmut@pozimski.eu>
  3. *
  4. * SPDX-License-Identifier: GPL-2.0-only
  5. */
  6. #include <stdint.h>
  7. #include <esp_wifi.h>
  8. #include <esp_err.h>
  9. #include <string.h>
  10. #include <freertos/FreeRTOS.h>
  11. #include <freertos/task.h>
  12. #include <freertos/event_groups.h>
  13. #include "configuration.h"
  14. #define WIFI_CONNECTED_BIT BIT0
  15. #define WIFI_FAIL_BIT BIT1
  16. static EventGroupHandle_t wifi_event_group;
  17. static void wifi_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) {
  18. if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
  19. esp_wifi_connect();
  20. } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
  21. xEventGroupSetBits(wifi_event_group, WIFI_FAIL_BIT);
  22. } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
  23. xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
  24. }
  25. }
  26. void wifi_init() {
  27. wifi_event_group = xEventGroupCreate();
  28. tcpip_adapter_init();
  29. ESP_ERROR_CHECK(esp_event_loop_create_default());
  30. wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
  31. ESP_ERROR_CHECK(esp_wifi_init(&cfg));
  32. ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL));
  33. ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL));
  34. wifi_config_t wifi_config = {
  35. .sta = {
  36. .ssid = WIFI_ESSID,
  37. .password = WIFI_PASSWORD
  38. },
  39. };
  40. wifi_config.sta.threshold.authmode = WIFI_AUTH_WPA2_PSK;
  41. ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
  42. ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
  43. }
  44. uint8_t wifi_start() {
  45. ESP_ERROR_CHECK(esp_wifi_start());
  46. xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
  47. pdFALSE, pdFALSE, portMAX_DELAY);
  48. EventBits_t event_bits = xEventGroupGetBits(wifi_event_group);
  49. ESP_ERROR_CHECK(esp_event_handler_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler));
  50. ESP_ERROR_CHECK(esp_event_handler_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler));
  51. vEventGroupDelete(wifi_event_group);
  52. return event_bits & WIFI_CONNECTED_BIT;
  53. }
  54. void wifi_stop() {
  55. esp_wifi_disconnect();
  56. esp_wifi_stop();
  57. }