Files
ink-board/main/network/wifi_handler.h

60 lines
2.1 KiB
C++

#pragma once
#include "io/io.h"
#include "esp_wifi.h"
#include "freertos/event_groups.h"
#define WIFI_STARTED_BIT (1 << 0)
#define WIFI_CONNECTED_BIT (1 << 1)
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
std::unique_ptr<KVStorageHandler> kvs
);
~WifiHandler();
esp_err_t init();
esp_err_t connect(const std::string& ssid, const std::string& password);
esp_err_t connect(const std::string& 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;
// prevent moving
WifiHandler(WifiHandler&& other) = delete;
WifiHandler& operator=(WifiHandler&& other) = delete;
void store_wifi_credentials(const std::string& ssid, const std::string& password);
void get_wifi_credentials(std::string& out_ssid, std::string& out_password);
bool initialized = false;
std::unique_ptr<KVStorageHandler> kvs = nullptr;
EventGroupHandle_t s_wifi_event_group = 0;
SemaphoreHandle_t scan_mutex = nullptr;
SemaphoreHandle_t connection_mutex = nullptr;
SemaphoreHandle_t credential_mutex = nullptr;
// current connected / preferred SSID
std::string current_ssid;
// current password (temporarily stored for successful connection event)
std::string current_password;
// prevent auto-reconnect on expected disconnection, e.g. when user calls disconnect()
// should be reset to false after connect()
bool expect_disconnected = false;
};