#pragma once #include "io/io.h" #include "esp_wifi.h" #include "freertos/event_groups.h" #define WIFI_CONNECTED_BIT (1 << 0) class WifiHandler { public: WifiHandler( // this handler is used to store/retrieve WiFi credentials // should have a unique namespace for WiFi credentials // it will be owned by WifiHandler and deleted in its destructor KVStorageHandler* kvs ); ~WifiHandler(); // move semantics WifiHandler(WifiHandler&& other) noexcept; void init(); esp_err_t connect(const char* ssid, const char* password); esp_err_t connect(const char* ssid); // connect using stored password esp_err_t reconnect(); // reconnect to current SSID void disconnect(); EventBits_t wait_for_connection(TickType_t ticks_to_wait); // returns list of available networks, caller is responsible for freeing the returned memory // returns nullptr if scan failed esp_err_t scan_networks( wifi_ap_record_t*& ap_records, uint16_t& ap_count ); static void wifi_event_handler(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data); private: // prevent copying WifiHandler(const WifiHandler&) = delete; WifiHandler& operator=(const WifiHandler&) = delete; char* build_password_key(const char* ssid); void get_wifi_credentials(char*& ssid, char*& password); bool initialized = false; KVStorageHandler* kvs = nullptr; EventGroupHandle_t s_wifi_event_group = 0; SemaphoreHandle_t scan_mutex = nullptr; SemaphoreHandle_t connection_mutex = nullptr; // current connected / preferred SSID char* current_ssid = nullptr; // prevent auto-reconnect on expected disconnection, e.g. when user calls disconnect() // should be reset to false after connect() bool expect_disconnected = false; };