πŸ“Ά BaseWifi API Reference

🌟 Overview

BaseWifi is the abstract base class for all WiFi implementations in the HardFOC system. It provides a unified interface for wireless networking operations including station mode (client), access point mode (hotspot), network scanning, security configuration, and comprehensive connection management.

✨ Features

  • πŸ“‘ Station Mode - Connect to existing WiFi networks as a client
  • πŸ”₯ Access Point Mode - Create WiFi hotspots for device configuration
  • πŸ” Network Scanning - Discover available wireless networks
  • πŸ”’ Security Support - WPA/WPA2/WPA3 and enterprise authentication
  • πŸ“Š Connection Management - Automatic reconnection and signal monitoring
  • ⚑ Event System - Comprehensive callback system for network events
  • πŸ”§ Power Management - Energy-efficient WiFi operation modes
  • πŸ“ˆ Signal Monitoring - Real-time RSSI and connection quality tracking

πŸ“ Header File

1
#include "inc/base/BaseWifi.h"

🎯 Type Definitions

🚨 Error Codes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
enum class hf_wifi_err_t : hf_u8_t {
    WIFI_SUCCESS = 0,                   // βœ… Success
    WIFI_ERR_FAILURE = 1,               // ❌ General failure
    WIFI_ERR_INVALID_PARAM = 2,         // 🚫 Invalid parameter
    WIFI_ERR_NOT_INITIALIZED = 3,       // ⚠️ WiFi not initialized
    WIFI_ERR_ALREADY_INITIALIZED = 4,   // ⚠️ WiFi already initialized
    WIFI_ERR_NOT_CONNECTED = 5,         // πŸ“Ά WiFi not connected
    WIFI_ERR_ALREADY_CONNECTED = 6,     // πŸ“Ά WiFi already connected
    WIFI_ERR_CONNECTION_FAILED = 7,     // ❌ Connection failed
    WIFI_ERR_DISCONNECTION_FAILED = 8,  // ❌ Disconnection failed
    WIFI_ERR_SCAN_FAILED = 9,           // πŸ” Network scan failed
    WIFI_ERR_AP_START_FAILED = 10,      // πŸ”₯ Access Point start failed
    WIFI_ERR_AP_STOP_FAILED = 11,       // πŸ”₯ Access Point stop failed
    WIFI_ERR_TIMEOUT = 12,              // ⏰ Operation timeout
    WIFI_ERR_NO_MEMORY = 13,            // πŸ’Ύ Insufficient memory
    WIFI_ERR_INVALID_SSID = 14,         // πŸ“‘ Invalid SSID
    WIFI_ERR_INVALID_PASSWORD = 15,     // πŸ” Invalid password
    WIFI_ERR_WEAK_SIGNAL = 16,          // πŸ“‰ Weak signal strength
    WIFI_ERR_AUTHENTICATION_FAILED = 17, // πŸ” Authentication failed
    WIFI_ERR_ASSOCIATION_FAILED = 18,   // πŸ”— Association failed
    WIFI_ERR_HANDSHAKE_FAILED = 19,     // 🀝 4-way handshake failed
    WIFI_ERR_INIT_FAILED = 20,          // πŸš€ WiFi initialization failed
    WIFI_ERR_CONFIG_INVALID = 21,       // βš™οΈ Invalid configuration
    WIFI_ERR_ENTERPRISE_FAILED = 22,    // 🏒 Enterprise authentication failed
    WIFI_ERR_WPA3_NOT_SUPPORTED = 23,   // πŸ”’ WPA3 not supported
    WIFI_ERR_MESH_FAILED = 24           // πŸ•ΈοΈ Mesh operation failed
};

🌐 WiFi Modes

1
2
3
4
5
6
enum class hf_wifi_mode_t : hf_u8_t {
    WIFI_MODE_NULL = 0,     // 🚫 WiFi disabled
    WIFI_MODE_STA = 1,      // πŸ“± Station mode (client)
    WIFI_MODE_AP = 2,       // πŸ”₯ Access Point mode
    WIFI_MODE_APSTA = 3     // πŸ”„ Combined AP+STA mode
};

πŸ”’ Security Types

1
2
3
4
5
6
7
8
9
10
enum class hf_wifi_security_t : hf_u8_t {
    WIFI_AUTH_OPEN = 0,         // πŸ”“ Open network (no security)
    WIFI_AUTH_WEP = 1,          // πŸ” WEP (deprecated)
    WIFI_AUTH_WPA_PSK = 2,      // πŸ”’ WPA-PSK
    WIFI_AUTH_WPA2_PSK = 3,     // πŸ”’ WPA2-PSK (most common)
    WIFI_AUTH_WPA_WPA2_PSK = 4, // πŸ”’ WPA/WPA2-PSK mixed
    WIFI_AUTH_WPA2_ENTERPRISE = 5, // 🏒 WPA2-Enterprise
    WIFI_AUTH_WPA3_PSK = 6,     // πŸ›‘οΈ WPA3-PSK (latest)
    WIFI_AUTH_WPA2_WPA3_PSK = 7 // πŸ›‘οΈ WPA2/WPA3-PSK mixed
};

πŸ“Š Event Types

1
2
3
4
5
6
7
8
9
10
11
12
13
enum class hf_wifi_event_t : hf_u8_t {
    WIFI_EVENT_STA_START = 0,       // πŸš€ Station started
    WIFI_EVENT_STA_STOP = 1,        // πŸ›‘ Station stopped
    WIFI_EVENT_STA_CONNECTED = 2,   // βœ… Connected to AP
    WIFI_EVENT_STA_DISCONNECTED = 3, // ❌ Disconnected from AP
    WIFI_EVENT_STA_GOT_IP = 4,      // 🌐 Got IP address
    WIFI_EVENT_STA_LOST_IP = 5,     // 🌐 Lost IP address
    WIFI_EVENT_AP_START = 6,        // πŸ”₯ AP started
    WIFI_EVENT_AP_STOP = 7,         // πŸ”₯ AP stopped
    WIFI_EVENT_AP_STA_CONNECTED = 8, // πŸ‘€ Client connected to AP
    WIFI_EVENT_AP_STA_DISCONNECTED = 9, // πŸ‘€ Client disconnected from AP
    WIFI_EVENT_SCAN_DONE = 10       // πŸ” Network scan completed
};

βš™οΈ Configuration Structures

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
struct hf_wifi_station_config_t {
    std::string ssid;                      // πŸ“‘ Network SSID
    std::string password;                  // πŸ” Network password
    uint8_t bssid[6];                     // πŸ†” Target BSSID (optional)
    bool bssid_set;                       // 🎯 Use specific BSSID
    uint8_t channel;                      // πŸ“» WiFi channel (0 = auto)
    uint16_t listen_interval;             // ⏰ Listen interval
    hf_wifi_security_t threshold_authmode; // πŸ”’ Minimum security level
    int16_t threshold_rssi;               // πŸ“Ά Minimum signal strength
};

struct hf_wifi_ap_config_t {
    std::string ssid;            // πŸ“‘ AP SSID
    std::string password;        // πŸ” AP password
    uint8_t ssid_len;           // πŸ“ SSID length (0 for auto)
    uint8_t channel;            // πŸ“» WiFi channel
    hf_wifi_security_t authmode; // πŸ”’ Authentication mode
    uint8_t ssid_hidden;        // πŸ‘» Hide SSID (0 = visible, 1 = hidden)
    uint8_t max_connection;     // πŸ‘₯ Maximum concurrent connections
    uint16_t beacon_interval;   // πŸ“‘ Beacon interval (ms)
};

struct hf_wifi_scan_result_t {
    std::string ssid;              // πŸ“‘ Network SSID
    uint8_t bssid[6];             // πŸ†” Network BSSID
    uint8_t primary_channel;       // πŸ“» Primary channel
    uint8_t secondary_channel;     // πŸ“» Secondary channel
    int8_t rssi;                  // πŸ“Ά Signal strength (dBm)
    hf_wifi_security_t authmode;   // πŸ”’ Authentication mode
    uint32_t phy_11b:1;           // πŸ“Š 802.11b support
    uint32_t phy_11g:1;           // πŸ“Š 802.11g support
    uint32_t phy_11n:1;           // πŸ“Š 802.11n support
    uint32_t wps:1;               // πŸ”§ WPS support
};

πŸ—οΈ Class Interface

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class BaseWifi {
public:
    // πŸ”§ Lifecycle management
    virtual ~BaseWifi() = default;
    virtual hf_wifi_err_t Initialize(hf_wifi_mode_t mode) = 0;
    virtual hf_wifi_err_t Deinitialize() = 0;
    virtual bool IsInitialized() const = 0;
    virtual hf_wifi_err_t SetMode(hf_wifi_mode_t mode) = 0;
    virtual hf_wifi_mode_t GetMode() const = 0;

    // πŸ“± Station mode operations
    virtual hf_wifi_err_t ConfigureStation(const hf_wifi_station_config_t& config) = 0;
    virtual hf_wifi_err_t ConnectStation(hf_timeout_ms_t timeout_ms = 0) = 0;
    virtual hf_wifi_err_t DisconnectStation() = 0;
    virtual bool IsStationConnected() const = 0;
    virtual hf_wifi_err_t GetStationInfo(hf_wifi_station_info_t& info) const = 0;

    // πŸ”₯ Access Point operations
    virtual hf_wifi_err_t ConfigureAP(const hf_wifi_ap_config_t& config) = 0;
    virtual hf_wifi_err_t StartAP() = 0;
    virtual hf_wifi_err_t StopAP() = 0;
    virtual bool IsAPStarted() const = 0;
    virtual hf_wifi_err_t GetAPInfo(hf_wifi_ap_info_t& info) const = 0;

    // πŸ” Network scanning
    virtual hf_wifi_err_t StartScan(const hf_wifi_scan_config_t& config = {}) = 0;
    virtual hf_wifi_err_t GetScanResults(hf_wifi_scan_result_t* results, uint16_t& count) = 0;
    virtual bool IsScanInProgress() const = 0;

    // πŸ“Š Network information
    virtual hf_wifi_err_t GetIPInfo(hf_wifi_ip_info_t& ip_info) const = 0;
    virtual int8_t GetRSSI() const = 0;
    virtual hf_wifi_err_t GetMACAddress(uint8_t mac[6]) const = 0;

    // 🎯 Event management
    virtual hf_wifi_err_t SetEventCallback(hf_wifi_event_callback_t callback) = 0;
    virtual hf_wifi_err_t ClearEventCallback() = 0;

    // πŸ”§ Power management
    virtual hf_wifi_err_t SetPowerSaveMode(hf_wifi_power_save_t mode) = 0;
    virtual hf_wifi_power_save_t GetPowerSaveMode() const = 0;
};

🎯 Core Methods

πŸ”§ Initialization

1
hf_wifi_err_t Initialize(hf_wifi_mode_t mode);

Purpose: πŸš€ Initialize WiFi subsystem with specified mode
Parameters: WiFi operating mode (STA, AP, or APSTA)
Returns: Error code indicating success or failure

πŸ“± Station Mode Operations

1
2
3
4
hf_wifi_err_t ConfigureStation(const hf_wifi_station_config_t& config);
hf_wifi_err_t ConnectStation(hf_timeout_ms_t timeout_ms = 0);
hf_wifi_err_t DisconnectStation();
bool IsStationConnected() const;

Purpose: πŸ“‘ Connect to existing WiFi networks as a client
Parameters: Network credentials, timeout values
Returns: Connection status and error codes

πŸ”₯ Access Point Operations

1
2
3
4
hf_wifi_err_t ConfigureAP(const hf_wifi_ap_config_t& config);
hf_wifi_err_t StartAP();
hf_wifi_err_t StopAP();
bool IsAPStarted() const;

Purpose: πŸ”₯ Create and manage WiFi hotspots
Parameters: AP configuration (SSID, password, security)
Returns: AP status and error codes

πŸ” Network Scanning

1
2
3
hf_wifi_err_t StartScan(const hf_wifi_scan_config_t& config = {});
hf_wifi_err_t GetScanResults(hf_wifi_scan_result_t* results, uint16_t& count);
bool IsScanInProgress() const;

Purpose: πŸ” Discover and analyze available WiFi networks
Parameters: Scan configuration and result buffers
Returns: Available networks with signal strength and security info

πŸ’‘ Usage Examples

πŸ“± WiFi Station (Client) Mode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#include "inc/mcu/esp32/EspWifi.h"

class WiFiClient {
private:
    EspWifi wifi*;
    bool connected*;
    
public:
    WiFiClient() : connected*(false) {}
    
    bool initialize() {
        // πŸš€ Initialize WiFi in station mode
        hf_wifi_err_t result = wifi*.Initialize(hf_wifi_mode_t::WIFI_MODE_STA);
        if (result != hf_wifi_err_t::WIFI_SUCCESS) {
            printf("❌ Failed to initialize WiFi: %s\n", HfWifiErrToString(result).data());
            return false;
        }
        
        // πŸ“‘ Set up event callback for connection monitoring
        wifi*.SetEventCallback([this](hf_wifi_event_t event, void* data) {
            handle_wifi_event(event, data);
        });
        
        printf("βœ… WiFi initialized in station mode\n");
        return true;
    }
    
    bool connect_to_network(const std::string& ssid, const std::string& password) {
        // βš™οΈ Configure station parameters
        hf_wifi_station_config_t config;
        config.ssid = ssid;
        config.password = password;
        config.bssid_set = false;  // Don't target specific BSSID
        config.channel = 0;        // Auto-select channel
        config.threshold_authmode = hf_wifi_security_t::WIFI_AUTH_WPA2_PSK;
        config.threshold_rssi = -80; // Minimum -80dBm signal strength
        
        hf_wifi_err_t result = wifi*.ConfigureStation(config);
        if (result != hf_wifi_err_t::WIFI_SUCCESS) {
            printf("❌ Failed to configure station: %s\n", HfWifiErrToString(result).data());
            return false;
        }
        
        // πŸ”— Attempt connection with 30 second timeout
        printf("πŸ”— Connecting to network '%s'...\n", ssid.c_str());
        result = wifi*.ConnectStation(30000);
        
        if (result == hf_wifi_err_t::WIFI_SUCCESS) {
            printf("βœ… Connected to WiFi network\n");
            return true;
        } else {
            printf("❌ Connection failed: %s\n", HfWifiErrToString(result).data());
            return false;
        }
    }
    
    void disconnect() {
        if (connected*) {
            hf_wifi_err_t result = wifi*.DisconnectStation();
            if (result == hf_wifi_err_t::WIFI_SUCCESS) {
                printf("βœ… Disconnected from WiFi\n");
            } else {
                printf("❌ Disconnect failed: %s\n", HfWifiErrToString(result).data());
            }
        }
    }
    
    void print_connection_info() {
        if (!connected*) {
            printf("❌ Not connected to WiFi\n");
            return;
        }
        
        // πŸ“Š Get IP information
        hf_wifi_ip_info_t ip_info;
        if (wifi*.GetIPInfo(ip_info) == hf_wifi_err_t::WIFI_SUCCESS) {
            printf("🌐 IP Address: %d.%d.%d.%d\n",
                   (ip_info.ip >> 0) & 0xFF,
                   (ip_info.ip >> 8) & 0xFF,
                   (ip_info.ip >> 16) & 0xFF,
                   (ip_info.ip >> 24) & 0xFF);
            printf("🌐 Gateway: %d.%d.%d.%d\n",
                   (ip_info.gateway >> 0) & 0xFF,
                   (ip_info.gateway >> 8) & 0xFF,
                   (ip_info.gateway >> 16) & 0xFF,
                   (ip_info.gateway >> 24) & 0xFF);
        }
        
        // πŸ“Ά Get signal strength
        int8_t rssi = wifi*.GetRSSI();
        printf("πŸ“Ά Signal Strength: %d dBm", rssi);
        if (rssi > -50) {
            printf(" (Excellent)\n");
        } else if (rssi > -60) {
            printf(" (Good)\n");
        } else if (rssi > -70) {
            printf(" (Fair)\n");
        } else {
            printf(" (Poor)\n");
        }
        
        // πŸ†” Get MAC address
        uint8_t mac[6];
        if (wifi*.GetMACAddress(mac) == hf_wifi_err_t::WIFI_SUCCESS) {
            printf("πŸ†” MAC Address: %02X:%02X:%02X:%02X:%02X:%02X\n",
                   mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        }
    }
    
    void handle_wifi_event(hf_wifi_event_t event, void* data) {
        switch (event) {
            case hf_wifi_event_t::WIFI_EVENT_STA_START:
                printf("πŸ“‘ WiFi station started\n");
                break;
                
            case hf_wifi_event_t::WIFI_EVENT_STA_CONNECTED:
                printf("βœ… Connected to access point\n");
                break;
                
            case hf_wifi_event_t::WIFI_EVENT_STA_GOT_IP:
                printf("🌐 Got IP address\n");
                connected* = true;
                print_connection_info();
                break;
                
            case hf_wifi_event_t::WIFI_EVENT_STA_DISCONNECTED:
                printf("❌ Disconnected from access point\n");
                connected* = false;
                break;
                
            case hf_wifi_event_t::WIFI_EVENT_STA_LOST_IP:
                printf("🌐 Lost IP address\n");
                connected* = false;
                break;
                
            default:
                printf("πŸ“‘ WiFi event: %d\n", static_cast<int>(event));
                break;
        }
    }
    
    bool is_connected() const {
        return connected* && wifi*.IsStationConnected();
    }
};

void wifi_client_demo() {
    WiFiClient client;
    
    if (!client.initialize()) {
        printf("❌ WiFi client initialization failed\n");
        return;
    }
    
    // πŸ”— Connect to your WiFi network
    if (client.connect_to_network("YourWiFiSSID", "YourPassword")) {
        printf("πŸŽ‰ Successfully connected to WiFi!\n");
        
        // πŸ“Š Monitor connection
        for (int i = 0; i < 60; i++) {  // Monitor for 1 minute
            if (client.is_connected()) {
                printf("πŸ“Ά WiFi connected (check %d/60)\n", i + 1);
            } else {
                printf("❌ WiFi disconnected\n");
                break;
            }
            vTaskDelay(pdMS_TO_TICKS(1000));
        }
        
        client.disconnect();
    }
}

πŸ”₯ WiFi Access Point (Hotspot) Mode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
class WiFiHotspot {
private:
    EspWifi wifi*;
    bool ap_started*;
    uint8_t connected_clients*;
    
public:
    WiFiHotspot() : ap_started*(false), connected_clients*(0) {}
    
    bool initialize() {
        // πŸš€ Initialize WiFi in AP mode
        hf_wifi_err_t result = wifi*.Initialize(hf_wifi_mode_t::WIFI_MODE_AP);
        if (result != hf_wifi_err_t::WIFI_SUCCESS) {
            printf("❌ Failed to initialize WiFi AP: %s\n", HfWifiErrToString(result).data());
            return false;
        }
        
        // πŸ“‘ Set up event callback for client monitoring
        wifi*.SetEventCallback([this](hf_wifi_event_t event, void* data) {
            handle_ap_event(event, data);
        });
        
        printf("βœ… WiFi initialized in AP mode\n");
        return true;
    }
    
    bool start_hotspot(const std::string& ssid, const std::string& password, 
                      uint8_t max_clients = 4) {
        // βš™οΈ Configure access point
        hf_wifi_ap_config_t config;
        config.ssid = ssid;
        config.password = password;
        config.ssid_len = 0;  // Auto-calculate length
        config.channel = 1;   // Channel 1 (2.4GHz)
        config.authmode = password.empty() ? 
            hf_wifi_security_t::WIFI_AUTH_OPEN : 
            hf_wifi_security_t::WIFI_AUTH_WPA2_PSK;
        config.ssid_hidden = 0;  // Broadcast SSID
        config.max_connection = max_clients;
        config.beacon_interval = 100;  // 100ms beacon interval
        
        hf_wifi_err_t result = wifi*.ConfigureAP(config);
        if (result != hf_wifi_err_t::WIFI_SUCCESS) {
            printf("❌ Failed to configure AP: %s\n", HfWifiErrToString(result).data());
            return false;
        }
        
        // πŸ”₯ Start the access point
        result = wifi*.StartAP();
        if (result == hf_wifi_err_t::WIFI_SUCCESS) {
            printf("πŸ”₯ WiFi hotspot '%s' started successfully\n", ssid.c_str());
            printf("πŸ‘₯ Maximum clients: %u\n", max_clients);
            if (!password.empty()) {
                printf("πŸ”’ Security: WPA2-PSK\n");
            } else {
                printf("πŸ”“ Security: Open (no password)\n");
            }
            return true;
        } else {
            printf("❌ Failed to start AP: %s\n", HfWifiErrToString(result).data());
            return false;
        }
    }
    
    void stop_hotspot() {
        if (ap_started*) {
            hf_wifi_err_t result = wifi*.StopAP();
            if (result == hf_wifi_err_t::WIFI_SUCCESS) {
                printf("πŸ”₯ WiFi hotspot stopped\n");
            } else {
                printf("❌ Failed to stop hotspot: %s\n", HfWifiErrToString(result).data());
            }
        }
    }
    
    void print_ap_info() {
        if (!ap_started*) {
            printf("❌ Access point not started\n");
            return;
        }
        
        // πŸ“Š Get AP information
        hf_wifi_ap_info_t ap_info;
        if (wifi*.GetAPInfo(ap_info) == hf_wifi_err_t::WIFI_SUCCESS) {
            printf("πŸ“‘ AP SSID: %s\n", ap_info.ssid.c_str());
            printf("πŸ“» Channel: %u\n", ap_info.channel);
            printf("πŸ‘₯ Connected Clients: %u/%u\n", 
                   connected_clients*, ap_info.max_connection);
        }
        
        // 🌐 Get IP information
        hf_wifi_ip_info_t ip_info;
        if (wifi*.GetIPInfo(ip_info) == hf_wifi_err_t::WIFI_SUCCESS) {
            printf("🌐 AP IP Address: %d.%d.%d.%d\n",
                   (ip_info.ip >> 0) & 0xFF,
                   (ip_info.ip >> 8) & 0xFF,
                   (ip_info.ip >> 16) & 0xFF,
                   (ip_info.ip >> 24) & 0xFF);
        }
        
        // πŸ†” Get MAC address
        uint8_t mac[6];
        if (wifi*.GetMACAddress(mac) == hf_wifi_err_t::WIFI_SUCCESS) {
            printf("πŸ†” AP MAC Address: %02X:%02X:%02X:%02X:%02X:%02X\n",
                   mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        }
    }
    
    void handle_ap_event(hf_wifi_event_t event, void* data) {
        switch (event) {
            case hf_wifi_event_t::WIFI_EVENT_AP_START:
                printf("πŸ”₯ Access point started\n");
                ap_started* = true;
                print_ap_info();
                break;
                
            case hf_wifi_event_t::WIFI_EVENT_AP_STOP:
                printf("πŸ”₯ Access point stopped\n");
                ap_started* = false;
                connected_clients* = 0;
                break;
                
            case hf_wifi_event_t::WIFI_EVENT_AP_STA_CONNECTED:
                connected_clients*++;
                printf("πŸ‘€ Client connected (total: %u)\n", connected_clients*);
                break;
                
            case hf_wifi_event_t::WIFI_EVENT_AP_STA_DISCONNECTED:
                if (connected_clients* > 0) connected_clients*--;
                printf("πŸ‘€ Client disconnected (total: %u)\n", connected_clients*);
                break;
                
            default:
                printf("πŸ“‘ AP event: %d\n", static_cast<int>(event));
                break;
        }
    }
    
    bool is_running() const {
        return ap_started* && wifi*.IsAPStarted();
    }
    
    uint8_t get_client_count() const {
        return connected_clients*;
    }
};

void wifi_hotspot_demo() {
    WiFiHotspot hotspot;
    
    if (!hotspot.initialize()) {
        printf("❌ WiFi hotspot initialization failed\n");
        return;
    }
    
    // πŸ”₯ Start hotspot with custom settings
    if (hotspot.start_hotspot("HardFOC-Config", "hardfoc123", 8)) {
        printf("πŸŽ‰ WiFi hotspot started successfully!\n");
        
        // πŸ“Š Monitor hotspot for 5 minutes
        for (int i = 0; i < 300; i++) {  // 5 minutes = 300 seconds
            if (hotspot.is_running()) {
                printf("πŸ”₯ Hotspot running - %u clients connected (time: %ds)\n", 
                       hotspot.get_client_count(), i + 1);
            } else {
                printf("❌ Hotspot stopped unexpectedly\n");
                break;
            }
            vTaskDelay(pdMS_TO_TICKS(1000));
        }
        
        hotspot.stop_hotspot();
    }
}

πŸ” WiFi Network Scanner

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class WiFiScanner {
private:
    EspWifi wifi*;
    std::vector<hf_wifi_scan_result_t> scan_results*;
    
public:
    bool initialize() {
        // πŸš€ Initialize WiFi for scanning (station mode)
        hf_wifi_err_t result = wifi*.Initialize(hf_wifi_mode_t::WIFI_MODE_STA);
        if (result != hf_wifi_err_t::WIFI_SUCCESS) {
            printf("❌ Failed to initialize WiFi scanner: %s\n", HfWifiErrToString(result).data());
            return false;
        }
        
        printf("βœ… WiFi scanner initialized\n");
        return true;
    }
    
    bool scan_networks(bool show_hidden = false) {
        printf("πŸ” Scanning for WiFi networks...\n");
        
        // βš™οΈ Configure scan parameters
        hf_wifi_scan_config_t config;
        config.ssid = "";           // Scan all SSIDs
        config.bssid = nullptr;     // Scan all BSSIDs
        config.channel = 0;         // Scan all channels
        config.show_hidden = show_hidden;
        config.scan_type = hf_wifi_scan_type_t::WIFI_SCAN_TYPE_ACTIVE;
        config.scan_time.active.min = 120;  // Min scan time per channel (ms)
        config.scan_time.active.max = 150;  // Max scan time per channel (ms)
        
        // πŸ” Start the scan
        hf_wifi_err_t result = wifi*.StartScan(config);
        if (result != hf_wifi_err_t::WIFI_SUCCESS) {
            printf("❌ Failed to start scan: %s\n", HfWifiErrToString(result).data());
            return false;
        }
        
        // ⏰ Wait for scan to complete (with timeout)
        int timeout_count = 0;
        while (wifi*.IsScanInProgress() && timeout_count < 60) {  // 6 second timeout
            vTaskDelay(pdMS_TO_TICKS(100));
            timeout_count++;
        }
        
        if (wifi*.IsScanInProgress()) {
            printf("⏰ Scan timeout - may be incomplete\n");
            return false;
        }
        
        // πŸ“Š Get scan results
        scan_results*.clear();
        scan_results*.resize(50);  // Prepare for up to 50 networks
        uint16_t count = scan_results*.size();
        
        result = wifi*.GetScanResults(scan_results*.data(), count);
        if (result != hf_wifi_err_t::WIFI_SUCCESS) {
            printf("❌ Failed to get scan results: %s\n", HfWifiErrToString(result).data());
            return false;
        }
        
        // πŸ“ Resize to actual count
        scan_results*.resize(count);
        
        printf("βœ… Scan completed - found %u networks\n", count);
        return true;
    }
    
    void print_scan_results() {
        if (scan_results*.empty()) {
            printf("❌ No scan results available\n");
            return;
        }
        
        printf("\nπŸ“Š WiFi Network Scan Results:\n");
        printf("═══════════════════════════════════════════════════════════════════════\n");
        printf("β”‚ %-32s β”‚ πŸ“Ά RSSI β”‚ πŸ“» Ch β”‚ πŸ”’ Security         β”‚\n", "SSID");
        printf("β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€\n");
        
        // πŸ“Š Sort by signal strength (strongest first)
        std::sort(scan_results*.begin(), scan_results*.end(),
                  [](const hf_wifi_scan_result_t& a, const hf_wifi_scan_result_t& b) {
                      return a.rssi > b.rssi;
                  });
        
        for (const auto& result : scan_results*) {
            std::string ssid = result.ssid.empty() ? "<Hidden Network>" : result.ssid;
            if (ssid.length() > 32) {
                ssid = ssid.substr(0, 29) + "...";
            }
            
            std::string signal_bar = get_signal_bars(result.rssi);
            std::string security = get_security_string(result.authmode);
            
            printf("β”‚ %-32s β”‚ %3d dBm β”‚  %2u   β”‚ %-19s β”‚\n",
                   ssid.c_str(), result.rssi, result.primary_channel, security.c_str());
        }
        
        printf("β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜\n");
        
        print_scan_statistics();
    }
    
    void print_scan_statistics() {
        if (scan_results*.empty()) return;
        
        printf("\nπŸ“ˆ Scan Statistics:\n");
        
        // πŸ“Š Count by security type
        std::map<hf_wifi_security_t, int> security_counts;
        std::map<uint8_t, int> channel_counts;
        int strong_signals = 0, weak_signals = 0;
        
        for (const auto& result : scan_results*) {
            security_counts[result.authmode]++;
            channel_counts[result.primary_channel]++;
            
            if (result.rssi > -60) {
                strong_signals++;
            } else if (result.rssi < -80) {
                weak_signals++;
            }
        }
        
        printf("   πŸ”’ Security Distribution:\n");
        for (const auto& [auth, count] : security_counts) {
            printf("      %s: %d networks\n", get_security_string(auth).c_str(), count);
        }
        
        printf("   πŸ“» Popular Channels:\n");
        auto top_channels = get_top_channels(channel_counts, 3);
        for (const auto& [channel, count] : top_channels) {
            printf("      Channel %u: %d networks\n", channel, count);
        }
        
        printf("   πŸ“Ά Signal Quality:\n");
        printf("      Strong (>-60dBm): %d networks\n", strong_signals);
        printf("      Weak (<-80dBm): %d networks\n", weak_signals);
    }
    
private:
    std::string get_signal_bars(int8_t rssi) {
        if (rssi > -50) return "β–ˆβ–ˆβ–ˆβ–ˆ";      // Excellent
        else if (rssi > -60) return "β–ˆβ–ˆβ–ˆ ";  // Good
        else if (rssi > -70) return "β–ˆβ–ˆ  ";  // Fair
        else if (rssi > -80) return "β–ˆ   ";  // Poor
        else return "    ";                  // Very poor
    }
    
    std::string get_security_string(hf_wifi_security_t auth) {
        switch (auth) {
            case hf_wifi_security_t::WIFI_AUTH_OPEN: return "πŸ”“ Open";
            case hf_wifi_security_t::WIFI_AUTH_WEP: return "πŸ” WEP";
            case hf_wifi_security_t::WIFI_AUTH_WPA_PSK: return "πŸ”’ WPA";
            case hf_wifi_security_t::WIFI_AUTH_WPA2_PSK: return "πŸ”’ WPA2";
            case hf_wifi_security_t::WIFI_AUTH_WPA_WPA2_PSK: return "πŸ”’ WPA/WPA2";
            case hf_wifi_security_t::WIFI_AUTH_WPA2_ENTERPRISE: return "🏒 WPA2-Enterprise";
            case hf_wifi_security_t::WIFI_AUTH_WPA3_PSK: return "πŸ›‘οΈ WPA3";
            case hf_wifi_security_t::WIFI_AUTH_WPA2_WPA3_PSK: return "πŸ›‘οΈ WPA2/WPA3";
            default: return "❓ Unknown";
        }
    }
    
    std::vector<std::pair<uint8_t, int>> get_top_channels(
        const std::map<uint8_t, int>& channel_counts, int limit) {
        std::vector<std::pair<uint8_t, int>> sorted_channels(
            channel_counts.begin(), channel_counts.end());
        
        std::sort(sorted_channels.begin(), sorted_channels.end(),
                  [](const auto& a, const auto& b) { return a.second > b.second; });
        
        if (sorted_channels.size() > limit) {
            sorted_channels.resize(limit);
        }
        
        return sorted_channels;
    }
};

void wifi_scanner_demo() {
    WiFiScanner scanner;
    
    if (!scanner.initialize()) {
        printf("❌ WiFi scanner initialization failed\n");
        return;
    }
    
    // πŸ” Perform network scan
    if (scanner.scan_networks(true)) {  // Include hidden networks
        scanner.print_scan_results();
    } else {
        printf("❌ Network scan failed\n");
    }
}

🏎️ Performance Considerations

⚑ Optimization Tips

  • πŸ“Ά Signal Strength - Maintain RSSI above -70dBm for reliable operation
  • πŸ“» Channel Selection - Use channels 1, 6, or 11 for 2.4GHz to avoid interference
  • πŸ”‹ Power Management - Use power save modes for battery-powered applications
  • πŸ”„ Reconnection Logic - Implement automatic reconnection for critical applications
  • πŸ“Š Connection Monitoring - Monitor signal quality and implement roaming logic

πŸ“Š Typical Performance Ranges

WiFi Standard Max Speed Range Power Consumption

|β€”β€”β€”β€”β€”β€”-|β€”β€”β€”β€”β€”|———–|β€”β€”β€”β€”β€”β€”β€”-|

802.11b 11 Mbps ~150m outdoor Low
802.11g 54 Mbps ~150m outdoor Medium
802.11n 300 Mbps ~250m outdoor Medium-High

πŸ›‘οΈ Security Best Practices

πŸ”’ Secure WiFi Implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// βœ… Use strong security protocols
config.authmode = hf_wifi_security_t::WIFI_AUTH_WPA3_PSK;  // Prefer WPA3

// βœ… Set minimum security thresholds
config.threshold_authmode = hf_wifi_security_t::WIFI_AUTH_WPA2_PSK;

// βœ… Use strong passwords
config.password = "YourSecurePassword123!@#";  // Strong password example

// βœ… Monitor security events
wifi.SetEventCallback([](hf_wifi_event_t event, void* data) {
    if (event == hf_wifi_event_t::WIFI_EVENT_STA_DISCONNECTED) {
        // Log security events
        printf("πŸ”’ Security: Connection lost - investigating...\n");
    }
});

🧡 Thread Safety

The BaseWifi class is not inherently thread-safe. For concurrent access from multiple tasks, use appropriate synchronization mechanisms.