WiFiGeneric.cpp 53.4 KB
Newer Older
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
/*
 ESP8266WiFiGeneric.cpp - WiFi library for esp8266

 Copyright (c) 2014 Ivan Grokhotkov. All rights reserved.
 This file is part of the esp8266 core for Arduino environment.

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

 Reworked on 28 Dec 2015 by Markus Sattler

 */

#include "WiFi.h"
#include "WiFiGeneric.h"

extern "C" {
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
#include <string.h>

#include <esp_err.h>
#include <esp_wifi.h>
38
#include <esp_event.h>
39 40 41 42
#include "lwip/ip_addr.h"
#include "lwip/opt.h"
#include "lwip/err.h"
#include "lwip/dns.h"
43
#include "dhcpserver/dhcpserver_options.h"
44 45 46

} //extern "C"

47
#include "esp32-hal.h"
48 49 50
#include <vector>
#include "sdkconfig.h"

51
#define _byte_swap32(num) (((num>>24)&0xff) | ((num<<8)&0xff0000) | ((num>>8)&0xff00) | ((num<<24)&0xff000000))
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
ESP_EVENT_DEFINE_BASE(ARDUINO_EVENTS);
/*
 * Private (exposable) methods
 * */
static esp_netif_t* esp_netifs[ESP_IF_MAX] = {NULL, NULL, NULL};
esp_interface_t get_esp_netif_interface(esp_netif_t* esp_netif){
	for(int i=0; i<ESP_IF_MAX; i++){
		if(esp_netifs[i] != NULL && esp_netifs[i] == esp_netif){
			return (esp_interface_t)i;
		}
	}
	return ESP_IF_MAX;
}

void add_esp_interface_netif(esp_interface_t interface, esp_netif_t* esp_netif){
	if(interface < ESP_IF_MAX){
		esp_netifs[interface] = esp_netif;
	}
}

esp_netif_t* get_esp_interface_netif(esp_interface_t interface){
	if(interface < ESP_IF_MAX){
		return esp_netifs[interface];
	}
	return NULL;
}

esp_err_t set_esp_interface_hostname(esp_interface_t interface, const char * hostname){
	if(interface < ESP_IF_MAX){
		return esp_netif_set_hostname(esp_netifs[interface], hostname);
	}
	return ESP_FAIL;
}
85

86
esp_err_t set_esp_interface_ip(esp_interface_t interface, IPAddress local_ip=IPAddress(), IPAddress gateway=IPAddress(), IPAddress subnet=IPAddress(), IPAddress dhcp_lease_start=INADDR_NONE){
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
	esp_netif_t *esp_netif = esp_netifs[interface];
	esp_netif_dhcp_status_t status = ESP_NETIF_DHCP_INIT;
	esp_netif_ip_info_t info;
    info.ip.addr = static_cast<uint32_t>(local_ip);
    info.gw.addr = static_cast<uint32_t>(gateway);
    info.netmask.addr = static_cast<uint32_t>(subnet);

    log_v("Configuring %s static IP: " IPSTR ", MASK: " IPSTR ", GW: " IPSTR,
          interface == ESP_IF_WIFI_STA ? "Station" :
          interface == ESP_IF_WIFI_AP ? "SoftAP" : "Ethernet",
          IP2STR(&info.ip), IP2STR(&info.netmask), IP2STR(&info.gw));

    esp_err_t err = ESP_OK;
    if(interface != ESP_IF_WIFI_AP){
    	err = esp_netif_dhcpc_get_status(esp_netif, &status);
        if(err){
        	log_e("DHCPC Get Status Failed! 0x%04x", err);
        	return err;
        }
		err = esp_netif_dhcpc_stop(esp_netif);
		if(err && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED){
			log_e("DHCPC Stop Failed! 0x%04x", err);
			return err;
		}
        err = esp_netif_set_ip_info(esp_netif, &info);
        if(err){
        	log_e("Netif Set IP Failed! 0x%04x", err);
        	return err;
        }
    	if(info.ip.addr == 0){
    		err = esp_netif_dhcpc_start(esp_netif);
    		if(err){
            	log_e("DHCPC Start Failed! 0x%04x", err);
            	return err;
            }
    	}
    } else {
    	err = esp_netif_dhcps_get_status(esp_netif, &status);
        if(err){
        	log_e("DHCPS Get Status Failed! 0x%04x", err);
        	return err;
        }
		err = esp_netif_dhcps_stop(esp_netif);
		if(err && err != ESP_ERR_ESP_NETIF_DHCP_ALREADY_STOPPED){
			log_e("DHCPS Stop Failed! 0x%04x", err);
			return err;
		}
        err = esp_netif_set_ip_info(esp_netif, &info);
        if(err){
        	log_e("Netif Set IP Failed! 0x%04x", err);
        	return err;
        }

        dhcps_lease_t lease;
        lease.enable = true;
142 143 144 145 146 147 148 149
        uint8_t CIDR = WiFiGenericClass::calculateSubnetCIDR(subnet);
        log_v("SoftAP: %s | Gateway: %s | DHCP Start: %s | Netmask: %s", local_ip.toString().c_str(), gateway.toString().c_str(), dhcp_lease_start.toString().c_str(), subnet.toString().c_str());
        // netmask must have room for at least 12 IP addresses (AP + GW + 10 DHCP Leasing addresses)
        // netmask also must be limited to the last 8 bits of IPv4, otherwise this function won't work
        // IDF NETIF checks netmask for the 3rd byte: https://github.com/espressif/esp-idf/blob/master/components/esp_netif/lwip/esp_netif_lwip.c#L1857-L1862
        if (CIDR > 28 || CIDR < 24) {
            log_e("Bad netmask. It must be from /24 to /28 (255.255.255. 0<->240)");
            return ESP_FAIL; //  ESP_FAIL if initializing failed
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
        // The code below is ready for any netmask, not limited to 255.255.255.0
        uint32_t netmask = _byte_swap32(info.netmask.addr);
        uint32_t ap_ipaddr = _byte_swap32(info.ip.addr);
        uint32_t dhcp_ipaddr = _byte_swap32(static_cast<uint32_t>(dhcp_lease_start));
        dhcp_ipaddr = dhcp_ipaddr == 0 ? ap_ipaddr + 1 : dhcp_ipaddr;
        uint32_t leaseStartMax = ~netmask - 10;
        // there will be 10 addresses for DHCP to lease
        lease.start_ip.addr = dhcp_ipaddr;
        lease.end_ip.addr = lease.start_ip.addr + 10;
        // Check if local_ip is in the same subnet as the dhcp leasing range initial address
        if ((ap_ipaddr & netmask) != (dhcp_ipaddr & netmask)) {
            log_e("The AP IP address (%s) and the DHCP start address (%s) must be in the same subnet", 
                local_ip.toString().c_str(), IPAddress(_byte_swap32(dhcp_ipaddr)).toString().c_str());
            return ESP_FAIL; //  ESP_FAIL if initializing failed
        }
        // prevents DHCP lease range to overflow subnet range
        if ((dhcp_ipaddr & ~netmask) >= leaseStartMax) {
            // make first DHCP lease addr stay in the begining of the netmask range
            lease.start_ip.addr = (dhcp_ipaddr & netmask) + 1;
            lease.end_ip.addr = lease.start_ip.addr + 10;
            log_w("DHCP Lease out of range - Changing DHCP leasing start to %s", IPAddress(_byte_swap32(lease.start_ip.addr)).toString().c_str());
        }
        // Check if local_ip is within DHCP range
        if (ap_ipaddr >= lease.start_ip.addr && ap_ipaddr <= lease.end_ip.addr) {
            log_e("The AP IP address (%s) can't be within the DHCP range (%s -- %s)", 
                local_ip.toString().c_str(), IPAddress(_byte_swap32(lease.start_ip.addr)).toString().c_str(), IPAddress(_byte_swap32(lease.end_ip.addr)).toString().c_str());
            return ESP_FAIL; //  ESP_FAIL if initializing failed
        }
        // Check if gateway is within DHCP range
        uint32_t gw_ipaddr = _byte_swap32(info.gw.addr);
        bool gw_in_same_subnet = (gw_ipaddr & netmask) == (ap_ipaddr & netmask);
        if (gw_in_same_subnet && gw_ipaddr >= lease.start_ip.addr && gw_ipaddr <= lease.end_ip.addr) {
            log_e("The GatewayP address (%s) can't be within the DHCP range (%s -- %s)", 
                gateway.toString().c_str(), IPAddress(_byte_swap32(lease.start_ip.addr)).toString().c_str(), IPAddress(_byte_swap32(lease.end_ip.addr)).toString().c_str());
            return ESP_FAIL; //  ESP_FAIL if initializing failed
        }
        // all done, just revert back byte order of DHCP lease range
        lease.start_ip.addr = _byte_swap32(lease.start_ip.addr);
        lease.end_ip.addr = _byte_swap32(lease.end_ip.addr);
190
        log_v("DHCP Server Range: %s to %s", IPAddress(lease.start_ip.addr).toString().c_str(), IPAddress(lease.end_ip.addr).toString().c_str());
191 192 193 194 195 196 197 198 199
        err = tcpip_adapter_dhcps_option(
            (tcpip_adapter_dhcp_option_mode_t)TCPIP_ADAPTER_OP_SET,
            (tcpip_adapter_dhcp_option_id_t)ESP_NETIF_SUBNET_MASK,
            (void*)&info.netmask.addr, sizeof(info.netmask.addr)
        );
		if(err){
        	log_e("DHCPS Set Netmask Failed! 0x%04x", err);
        	return err;
        }
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        err = tcpip_adapter_dhcps_option(
            (tcpip_adapter_dhcp_option_mode_t)TCPIP_ADAPTER_OP_SET,
            (tcpip_adapter_dhcp_option_id_t)REQUESTED_IP_ADDRESS,
            (void*)&lease, sizeof(dhcps_lease_t)
        );
		if(err){
        	log_e("DHCPS Set Lease Failed! 0x%04x", err);
        	return err;
        }
		err = esp_netif_dhcps_start(esp_netif);
		if(err){
        	log_e("DHCPS Start Failed! 0x%04x", err);
        	return err;
        }
    }
	return err;
}

esp_err_t set_esp_interface_dns(esp_interface_t interface, IPAddress main_dns=IPAddress(), IPAddress backup_dns=IPAddress(), IPAddress fallback_dns=IPAddress()){
	esp_netif_t *esp_netif = esp_netifs[interface];
	esp_netif_dns_info_t dns;
	dns.ip.type = ESP_IPADDR_TYPE_V4;
	dns.ip.u_addr.ip4.addr = static_cast<uint32_t>(main_dns);
	if(dns.ip.u_addr.ip4.addr && esp_netif_set_dns_info(esp_netif, ESP_NETIF_DNS_MAIN, &dns) != ESP_OK){
    	log_e("Set Main DNS Failed!");
    	return ESP_FAIL;
    }
	if(interface != ESP_IF_WIFI_AP){
		dns.ip.u_addr.ip4.addr = static_cast<uint32_t>(backup_dns);
		if(dns.ip.u_addr.ip4.addr && esp_netif_set_dns_info(esp_netif, ESP_NETIF_DNS_BACKUP, &dns) != ESP_OK){
	    	log_e("Set Backup DNS Failed!");
	    	return ESP_FAIL;
	    }
		dns.ip.u_addr.ip4.addr = static_cast<uint32_t>(fallback_dns);
		if(dns.ip.u_addr.ip4.addr && esp_netif_set_dns_info(esp_netif, ESP_NETIF_DNS_FALLBACK, &dns) != ESP_OK){
	    	log_e("Set Fallback DNS Failed!");
	    	return ESP_FAIL;
	    }
	}
	return ESP_OK;
}

242
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
243
static const char * auth_mode_str(int authmode)
244
{
245 246 247 248 249 250 251 252
    switch (authmode) {
    case WIFI_AUTH_OPEN:
    	return ("OPEN");
        break;
    case WIFI_AUTH_WEP:
    	return ("WEP");
        break;
    case WIFI_AUTH_WPA_PSK:
253
    	return ("WPA_PSK");
254 255 256 257 258 259 260 261 262 263
        break;
    case WIFI_AUTH_WPA2_PSK:
    	return ("WPA2_PSK");
        break;
    case WIFI_AUTH_WPA_WPA2_PSK:
    	return ("WPA_WPA2_PSK");
        break;
    case WIFI_AUTH_WPA2_ENTERPRISE:
    	return ("WPA2_ENTERPRISE");
        break;
264 265 266 267 268 269 270 271 272
    case WIFI_AUTH_WPA3_PSK:
    	return ("WPA3_PSK");
        break;
    case WIFI_AUTH_WPA2_WPA3_PSK:
    	return ("WPA2_WPA3_PSK");
        break;
    case WIFI_AUTH_WAPI_PSK:
    	return ("WPAPI_PSK");
        break;
273 274
    default:
        break;
275
    }
276 277
	return ("UNKNOWN");
}
278
#endif
279 280 281 282 283 284 285 286 287 288 289 290 291 292

static char default_hostname[32] = {0,};
static const char * get_esp_netif_hostname(){
	if(default_hostname[0] == 0){
	    uint8_t eth_mac[6];
	    esp_wifi_get_mac((wifi_interface_t)WIFI_IF_STA, eth_mac);
	    snprintf(default_hostname, 32, "%s%02X%02X%02X", CONFIG_IDF_TARGET "-", eth_mac[3], eth_mac[4], eth_mac[5]);
	}
	return (const char *)default_hostname;
}
static void set_esp_netif_hostname(const char * name){
	if(name){
		snprintf(default_hostname, 32, "%s", name);
	}
293 294
}

295 296 297 298 299 300
static xQueueHandle _arduino_event_queue;
static TaskHandle_t _arduino_event_task_handle = NULL;
static EventGroupHandle_t _arduino_event_group = NULL;

static void _arduino_event_task(void * arg){
	arduino_event_t *data = NULL;
301
    for (;;) {
302 303
        if(xQueueReceive(_arduino_event_queue, &data, portMAX_DELAY) == pdTRUE){
            WiFiGenericClass::_eventCallback(data);
304
            free(data);
305 306
            data = NULL;
        }
307 308
    }
    vTaskDelete(NULL);
309
    _arduino_event_task_handle = NULL;
310 311
}

312 313 314
esp_err_t postArduinoEvent(arduino_event_t *data)
{
	if(data == NULL){
315
        return ESP_FAIL;
316 317 318 319 320 321 322 323 324
	}
	arduino_event_t * event = (arduino_event_t*)malloc(sizeof(arduino_event_t));
	if(event == NULL){
        log_e("Arduino Event Malloc Failed!");
        return ESP_FAIL;
	}
	memcpy(event, data, sizeof(arduino_event_t));
    if (xQueueSend(_arduino_event_queue, &event, portMAX_DELAY) != pdPASS) {
        log_e("Arduino Event Send Failed!");
325 326 327 328 329
        return ESP_FAIL;
    }
    return ESP_OK;
}

330 331 332 333 334 335 336 337 338 339 340 341 342 343
static void _arduino_event_cb(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data) {
	arduino_event_t arduino_event;
	arduino_event.event_id = ARDUINO_EVENT_MAX;

	/*
	 * STA
	 * */
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
    	log_v("STA Started");
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_STA_START;
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_STOP) {
    	log_v("STA Stopped");
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_STA_STOP;
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_AUTHMODE_CHANGE) {
344 345 346 347
    	#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            wifi_event_sta_authmode_change_t * event = (wifi_event_sta_authmode_change_t*)event_data;
    	    log_v("STA Auth Mode Changed: From: %s, To: %s", auth_mode_str(event->old_mode), auth_mode_str(event->new_mode));
        #endif
348 349 350
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE;
    	memcpy(&arduino_event.event_info.wifi_sta_authmode_change, event_data, sizeof(wifi_event_sta_authmode_change_t));
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_CONNECTED) {
351 352 353 354
    	#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            wifi_event_sta_connected_t * event = (wifi_event_sta_connected_t*)event_data;
    	    log_v("STA Connected: SSID: %s, BSSID: " MACSTR ", Channel: %u, Auth: %s", event->ssid, MAC2STR(event->bssid), event->channel, auth_mode_str(event->authmode));
        #endif
355 356 357
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_STA_CONNECTED;
    	memcpy(&arduino_event.event_info.wifi_sta_connected, event_data, sizeof(wifi_event_sta_connected_t));
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
358 359 360 361
    	#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            wifi_event_sta_disconnected_t * event = (wifi_event_sta_disconnected_t*)event_data;
    	    log_v("STA Disconnected: SSID: %s, BSSID: " MACSTR ", Reason: %u", event->ssid, MAC2STR(event->bssid), event->reason);
        #endif
362 363 364
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_STA_DISCONNECTED;
    	memcpy(&arduino_event.event_info.wifi_sta_disconnected, event_data, sizeof(wifi_event_sta_disconnected_t));
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
365 366 367 368 369
        #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
            log_v("STA Got %sIP:" IPSTR, event->ip_changed?"New ":"Same ", IP2STR(&event->ip_info.ip));
    	#endif
        arduino_event.event_id = ARDUINO_EVENT_WIFI_STA_GOT_IP;
370 371 372 373 374 375 376 377 378
    	memcpy(&arduino_event.event_info.got_ip, event_data, sizeof(ip_event_got_ip_t));
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_LOST_IP) {
    	log_v("STA IP Lost");
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_STA_LOST_IP;

	/*
	 * SCAN
	 * */
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_SCAN_DONE) {
379 380 381 382
        #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
    	   wifi_event_sta_scan_done_t * event = (wifi_event_sta_scan_done_t*)event_data;
    	   log_v("SCAN Done: ID: %u, Status: %u, Results: %u", event->scan_id, event->status, event->number);
        #endif
383 384 385 386 387 388 389 390 391 392 393 394 395
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_SCAN_DONE;
    	memcpy(&arduino_event.event_info.wifi_scan_done, event_data, sizeof(wifi_event_sta_scan_done_t));

	/*
	 * AP
	 * */
	} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_START) {
		log_v("AP Started");
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_START;
	} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STOP) {
		log_v("AP Stopped");
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_STOP;
	} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_PROBEREQRECVED) {
396 397 398 399 400
		#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            wifi_event_ap_probe_req_rx_t * event = (wifi_event_ap_probe_req_rx_t*)event_data;
		    log_v("AP Probe Request: RSSI: %d, MAC: " MACSTR, event->rssi, MAC2STR(event->mac));
    	#endif
        arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED;
401 402
    	memcpy(&arduino_event.event_info.wifi_ap_probereqrecved, event_data, sizeof(wifi_event_ap_probe_req_rx_t));
	} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STACONNECTED) {
403 404 405 406 407
		#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            wifi_event_ap_staconnected_t* event = (wifi_event_ap_staconnected_t*) event_data;
		    log_v("AP Station Connected: MAC: " MACSTR ", AID: %d", MAC2STR(event->mac), event->aid);
    	#endif
        arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_STACONNECTED;
408 409
    	memcpy(&arduino_event.event_info.wifi_ap_staconnected, event_data, sizeof(wifi_event_ap_staconnected_t));
	} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_AP_STADISCONNECTED) {
410 411 412 413
		#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            wifi_event_ap_stadisconnected_t* event = (wifi_event_ap_stadisconnected_t*) event_data;
		    log_v("AP Station Disconnected: MAC: " MACSTR ", AID: %d", MAC2STR(event->mac), event->aid);
        #endif
414 415 416
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_STADISCONNECTED;
    	memcpy(&arduino_event.event_info.wifi_ap_stadisconnected, event_data, sizeof(wifi_event_ap_stadisconnected_t));
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_AP_STAIPASSIGNED) {
417 418 419 420 421
    	#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
           ip_event_ap_staipassigned_t * event = (ip_event_ap_staipassigned_t*)event_data;
    	   log_v("AP Station IP Assigned:" IPSTR, IP2STR(&event->ip));
    	#endif
        arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED;
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
    	memcpy(&arduino_event.event_info.wifi_ap_staipassigned, event_data, sizeof(ip_event_ap_staipassigned_t));

	/*
	 * ETH
	 * */
	} else if (event_base == ETH_EVENT && event_id == ETHERNET_EVENT_CONNECTED) {
		log_v("Ethernet Link Up");
    	arduino_event.event_id = ARDUINO_EVENT_ETH_CONNECTED;
    	memcpy(&arduino_event.event_info.eth_connected, event_data, sizeof(esp_eth_handle_t));
	} else if (event_base == ETH_EVENT && event_id == ETHERNET_EVENT_DISCONNECTED) {
		log_v("Ethernet Link Down");
    	arduino_event.event_id = ARDUINO_EVENT_ETH_DISCONNECTED;
	} else if (event_base == ETH_EVENT && event_id == ETHERNET_EVENT_START) {
		log_v("Ethernet Started");
    	arduino_event.event_id = ARDUINO_EVENT_ETH_START;
	} else if (event_base == ETH_EVENT && event_id == ETHERNET_EVENT_STOP) {
		log_v("Ethernet Stopped");
    	arduino_event.event_id = ARDUINO_EVENT_ETH_STOP;
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_ETH_GOT_IP) {
441 442 443 444 445
        #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
            log_v("Ethernet got %sip:" IPSTR, event->ip_changed?"new":"", IP2STR(&event->ip_info.ip));
    	#endif
        arduino_event.event_id = ARDUINO_EVENT_ETH_GOT_IP;
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    	memcpy(&arduino_event.event_info.got_ip, event_data, sizeof(ip_event_got_ip_t));

	/*
	 * IPv6
	 * */
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_GOT_IP6) {
    	ip_event_got_ip6_t * event = (ip_event_got_ip6_t*)event_data;
    	esp_interface_t iface = get_esp_netif_interface(event->esp_netif);
    	log_v("IF[%d] Got IPv6: IP Index: %d, Zone: %d, " IPV6STR, iface, event->ip_index, event->ip6_info.ip.zone, IPV62STR(event->ip6_info.ip));
    	memcpy(&arduino_event.event_info.got_ip6, event_data, sizeof(ip_event_got_ip6_t));
    	if(iface == ESP_IF_WIFI_STA){
        	arduino_event.event_id = ARDUINO_EVENT_WIFI_STA_GOT_IP6;
    	} else if(iface == ESP_IF_WIFI_AP){
        	arduino_event.event_id = ARDUINO_EVENT_WIFI_AP_GOT_IP6;
    	} else if(iface == ESP_IF_ETH){
        	arduino_event.event_id = ARDUINO_EVENT_ETH_GOT_IP6;
    	}

	/*
	 * WPS
	 * */
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_WPS_ER_SUCCESS) {
    	arduino_event.event_id = ARDUINO_EVENT_WPS_ER_SUCCESS;
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_WPS_ER_FAILED) {
    	arduino_event.event_id = ARDUINO_EVENT_WPS_ER_FAILED;
    	memcpy(&arduino_event.event_info.wps_fail_reason, event_data, sizeof(wifi_event_sta_wps_fail_reason_t));
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_WPS_ER_TIMEOUT) {
    	arduino_event.event_id = ARDUINO_EVENT_WPS_ER_TIMEOUT;
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_WPS_ER_PIN) {
    	arduino_event.event_id = ARDUINO_EVENT_WPS_ER_PIN;
    	memcpy(&arduino_event.event_info.wps_er_pin, event_data, sizeof(wifi_event_sta_wps_er_pin_t));
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_WPS_ER_PBC_OVERLAP) {
    	arduino_event.event_id = ARDUINO_EVENT_WPS_ER_PBC_OVERLAP;

M
Me No Dev 已提交
480 481 482 483 484 485 486
	/*
	 * FTM
	 * */
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_FTM_REPORT) {
    	arduino_event.event_id = ARDUINO_EVENT_WIFI_FTM_REPORT;
    	memcpy(&arduino_event.event_info.wifi_ftm_report, event_data, sizeof(wifi_event_ftm_report_t));

487 488 489 490 491 492 493 494 495 496 497

	/*
	 * SMART CONFIG
	 * */
	} else if (event_base == SC_EVENT && event_id == SC_EVENT_SCAN_DONE) {
		log_v("SC Scan Done");
    	arduino_event.event_id = ARDUINO_EVENT_SC_SCAN_DONE;
    } else if (event_base == SC_EVENT && event_id == SC_EVENT_FOUND_CHANNEL) {
    	log_v("SC Found Channel");
    	arduino_event.event_id = ARDUINO_EVENT_SC_FOUND_CHANNEL;
    } else if (event_base == SC_EVENT && event_id == SC_EVENT_GOT_SSID_PSWD) {
498
        #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
499 500 501
            smartconfig_event_got_ssid_pswd_t *event = (smartconfig_event_got_ssid_pswd_t *)event_data;
            log_v("SC: SSID: %s, Password: %s", (const char *)event->ssid, (const char *)event->password);
        #endif
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    	arduino_event.event_id = ARDUINO_EVENT_SC_GOT_SSID_PSWD;
    	memcpy(&arduino_event.event_info.sc_got_ssid_pswd, event_data, sizeof(smartconfig_event_got_ssid_pswd_t));

    } else if (event_base == SC_EVENT && event_id == SC_EVENT_SEND_ACK_DONE) {
    	log_v("SC Send Ack Done");
    	arduino_event.event_id = ARDUINO_EVENT_SC_SEND_ACK_DONE;

	/*
	 * Provisioning
	 * */
	} else if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_INIT) {
		log_v("Provisioning Initialized!");
    	arduino_event.event_id = ARDUINO_EVENT_PROV_INIT;
	} else if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_DEINIT) {
		log_v("Provisioning Uninitialized!");
    	arduino_event.event_id = ARDUINO_EVENT_PROV_DEINIT;
	} else if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_START) {
		log_v("Provisioning Start!");
    	arduino_event.event_id = ARDUINO_EVENT_PROV_START;
	} else if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_END) {
		log_v("Provisioning End!");
		wifi_prov_mgr_deinit();
    	arduino_event.event_id = ARDUINO_EVENT_PROV_END;
	} else if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_CRED_RECV) {
526 527 528 529
        #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_VERBOSE
            wifi_sta_config_t *event = (wifi_sta_config_t *)event_data;
            log_v("Provisioned Credentials: SSID: %s, Password: %s", (const char *) event->ssid, (const char *) event->password);
        #endif
530 531 532
    	arduino_event.event_id = ARDUINO_EVENT_PROV_CRED_RECV;
    	memcpy(&arduino_event.event_info.prov_cred_recv, event_data, sizeof(wifi_sta_config_t));
	} else if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_CRED_FAIL) {
533 534 535 536
        #if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_ERROR
            wifi_prov_sta_fail_reason_t *reason = (wifi_prov_sta_fail_reason_t *)event_data;
            log_e("Provisioning Failed: Reason : %s", (*reason == WIFI_PROV_STA_AUTH_ERROR)?"Authentication Failed":"AP Not Found");
        #endif
537 538 539 540 541 542 543 544 545 546 547 548
    	arduino_event.event_id = ARDUINO_EVENT_PROV_CRED_FAIL;
    	memcpy(&arduino_event.event_info.prov_fail_reason, event_data, sizeof(wifi_prov_sta_fail_reason_t));
	} else if (event_base == WIFI_PROV_EVENT && event_id == WIFI_PROV_CRED_SUCCESS) {
		log_v("Provisioning Success!");
    	arduino_event.event_id = ARDUINO_EVENT_PROV_CRED_SUCCESS;
    }
    
	if(arduino_event.event_id < ARDUINO_EVENT_MAX){
		postArduinoEvent(&arduino_event);
	}
}

M
Me No Dev 已提交
549
static bool _start_network_event_task(){
550 551 552
    if(!_arduino_event_group){
        _arduino_event_group = xEventGroupCreate();
        if(!_arduino_event_group){
M
Me No Dev 已提交
553 554 555
            log_e("Network Event Group Create Failed!");
            return false;
        }
556
        xEventGroupSetBits(_arduino_event_group, WIFI_DNS_IDLE_BIT);
M
Me No Dev 已提交
557
    }
558 559 560
    if(!_arduino_event_queue){
    	_arduino_event_queue = xQueueCreate(32, sizeof(arduino_event_t*));
        if(!_arduino_event_queue){
561
            log_e("Network Event Queue Create Failed!");
M
Me No Dev 已提交
562
            return false;
563 564
        }
    }
565 566 567 568 569 570 571 572 573 574

    esp_err_t err = esp_event_loop_create_default();
    if (err != ESP_OK && err != ESP_ERR_INVALID_STATE) {
    	log_e("esp_event_loop_create_default failed!");
        return err;
    }

    if(!_arduino_event_task_handle){
        xTaskCreateUniversal(_arduino_event_task, "arduino_events", 4096, NULL, ESP_TASKD_EVENT_PRIO - 1, &_arduino_event_task_handle, ARDUINO_EVENT_RUNNING_CORE);
        if(!_arduino_event_task_handle){
575
            log_e("Network Event Task Start Failed!");
M
Me No Dev 已提交
576
            return false;
577 578
        }
    }
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605

    if(esp_event_handler_instance_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &_arduino_event_cb, NULL, NULL)){
        log_e("event_handler_instance_register for WIFI_EVENT Failed!");
        return false;
    }

    if(esp_event_handler_instance_register(IP_EVENT, ESP_EVENT_ANY_ID, &_arduino_event_cb, NULL, NULL)){
        log_e("event_handler_instance_register for IP_EVENT Failed!");
        return false;
    }

    if(esp_event_handler_instance_register(SC_EVENT, ESP_EVENT_ANY_ID, &_arduino_event_cb, NULL, NULL)){
        log_e("event_handler_instance_register for SC_EVENT Failed!");
        return false;
    }

    if(esp_event_handler_instance_register(ETH_EVENT, ESP_EVENT_ANY_ID, &_arduino_event_cb, NULL, NULL)){
        log_e("event_handler_instance_register for ETH_EVENT Failed!");
        return false;
    }

    if(esp_event_handler_instance_register(WIFI_PROV_EVENT, ESP_EVENT_ANY_ID, &_arduino_event_cb, NULL, NULL)){
        log_e("event_handler_instance_register for WIFI_PROV_EVENT Failed!");
        return false;
    }

    return true;
606 607
}

608
bool tcpipInit(){
609
    static bool initialized = false;
610
    if(!initialized){
611
        initialized = true;
612 613 614 615 616 617 618 619 620 621 622 623
#if CONFIG_IDF_TARGET_ESP32
        uint8_t mac[8];
        if(esp_efuse_mac_get_default(mac) == ESP_OK){
            esp_base_mac_addr_set(mac);
        }
#endif
        initialized = esp_netif_init() == ESP_OK;
        if(initialized){
        	initialized = _start_network_event_task();
        } else {
        	log_e("esp_netif_init failed!");
        }
624
    }
625
    return initialized;
626 627
}

628 629 630 631
/*
 * WiFi INIT
 * */

M
Me No Dev 已提交
632
static bool lowLevelInitDone = false;
633 634 635 636 637 638 639 640 641 642 643 644 645
bool WiFiGenericClass::_wifiUseStaticBuffers = false;

bool WiFiGenericClass::useStaticBuffers(){
    return _wifiUseStaticBuffers;
}

void WiFiGenericClass::useStaticBuffers(bool bufferMode){
    if (lowLevelInitDone) {
        log_w("WiFi already started. Call WiFi.mode(WIFI_MODE_NULL) before setting Static Buffer Mode.");
    } 
    _wifiUseStaticBuffers = bufferMode;
}

646 647 648 649
// Temporary fix to ensure that CDC+JTAG stay on on ESP32-C3
#if CONFIG_IDF_TARGET_ESP32C3
extern "C" void phy_bbpll_en_usb(bool en);
#endif
650

651
bool wifiLowLevelInit(bool persistent){
652
    if(!lowLevelInitDone){
653 654 655 656 657 658 659 660 661 662 663 664
        lowLevelInitDone = true;
        if(!tcpipInit()){
        	lowLevelInitDone = false;
        	return lowLevelInitDone;
        }
        if(esp_netifs[ESP_IF_WIFI_AP] == NULL){
            esp_netifs[ESP_IF_WIFI_AP] = esp_netif_create_default_wifi_ap();
        }
        if(esp_netifs[ESP_IF_WIFI_STA] == NULL){
            esp_netifs[ESP_IF_WIFI_STA] = esp_netif_create_default_wifi_sta();
        }

665
        wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
666 667 668 669 670

	if(!WiFiGenericClass::useStaticBuffers()) {
	    cfg.static_tx_buf_num = 0;
            cfg.dynamic_tx_buf_num = 32;
	    cfg.tx_buf_type = 1;
Z
ZYJ 已提交
671
            cfg.cache_tx_buf_num = 4;  // can't be zero!
672 673 674 675
	    cfg.static_rx_buf_num = 4;
            cfg.dynamic_rx_buf_num = 32;
        }

676 677 678
        esp_err_t err = esp_wifi_init(&cfg);
        if(err){
            log_e("esp_wifi_init %d", err);
679 680
        	lowLevelInitDone = false;
        	return lowLevelInitDone;
681
        }
682 683 684 685
// Temporary fix to ensure that CDC+JTAG stay on on ESP32-C3
#if CONFIG_IDF_TARGET_ESP32C3
	phy_bbpll_en_usb(true);
#endif
686
        if(!persistent){
687
        	lowLevelInitDone = esp_wifi_set_storage(WIFI_STORAGE_RAM) == ESP_OK;
688
        }
M
Me No Dev 已提交
689 690 691 692 693
        if(lowLevelInitDone){
			arduino_event_t arduino_event;
			arduino_event.event_id = ARDUINO_EVENT_WIFI_READY;
			postArduinoEvent(&arduino_event);
        }
694
    }
695
    return lowLevelInitDone;
696 697 698
}

static bool wifiLowLevelDeinit(){
699
    if(lowLevelInitDone){
M
me-no-dev 已提交
700
    	lowLevelInitDone = !(esp_wifi_deinit() == ESP_OK);
701
    }
M
me-no-dev 已提交
702
    return !lowLevelInitDone;
703 704 705 706
}

static bool _esp_wifi_started = false;

707
static bool espWiFiStart(){
708 709 710
    if(_esp_wifi_started){
        return true;
    }
711
    _esp_wifi_started = true;
712 713
    esp_err_t err = esp_wifi_start();
    if (err != ESP_OK) {
714
        _esp_wifi_started = false;
715
        log_e("esp_wifi_start %d", err);
716
        return _esp_wifi_started;
717
    }
718
    return _esp_wifi_started;
719 720 721 722 723 724 725
}

static bool espWiFiStop(){
    esp_err_t err;
    if(!_esp_wifi_started){
        return true;
    }
M
Me No Dev 已提交
726
    _esp_wifi_started = false;
727 728
    err = esp_wifi_stop();
    if(err){
zhaoyanbai's avatar
zhaoyanbai 已提交
729
        log_e("Could not stop WiFi! %d", err);
M
Me No Dev 已提交
730
        _esp_wifi_started = true;
731 732 733 734 735 736 737 738 739
        return false;
    }
    return wifiLowLevelDeinit();
}

// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------- Generic WiFi function -----------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------

740 741 742
typedef struct WiFiEventCbList {
    static wifi_event_id_t current_id;
    wifi_event_id_t id;
743
    WiFiEventCb cb;
744
    WiFiEventFuncCb fcb;
745
    WiFiEventSysCb scb;
746
    arduino_event_id_t event;
747

748
    WiFiEventCbList() : id(current_id++), cb(NULL), fcb(NULL), scb(NULL), event(ARDUINO_EVENT_WIFI_READY) {}
749
} WiFiEventCbList_t;
750 751
wifi_event_id_t WiFiEventCbList::current_id = 1;

752 753 754 755 756

// arduino dont like std::vectors move static here
static std::vector<WiFiEventCbList_t> cbEventList;

bool WiFiGenericClass::_persistent = true;
757
bool WiFiGenericClass::_long_range = false;
758
wifi_mode_t WiFiGenericClass::_forceSleepLastMode = WIFI_MODE_NULL;
759 760 761 762 763
#if CONFIG_IDF_TARGET_ESP32S2
wifi_ps_type_t WiFiGenericClass::_sleepEnabled = WIFI_PS_NONE;
#else
wifi_ps_type_t WiFiGenericClass::_sleepEnabled = WIFI_PS_MIN_MODEM;
#endif
764

765
WiFiGenericClass::WiFiGenericClass() 
766 767 768
{
}

769 770 771 772 773 774 775 776 777 778 779
const char * WiFiGenericClass::getHostname()
{
    return get_esp_netif_hostname();
}

bool WiFiGenericClass::setHostname(const char * hostname)
{
    set_esp_netif_hostname(hostname);
    return true;
}

M
Me No Dev 已提交
780
int WiFiGenericClass::setStatusBits(int bits){
781
    if(!_arduino_event_group){
M
Me No Dev 已提交
782 783
        return 0;
    }
784
    return xEventGroupSetBits(_arduino_event_group, bits);
M
Me No Dev 已提交
785 786 787
}

int WiFiGenericClass::clearStatusBits(int bits){
788
    if(!_arduino_event_group){
M
Me No Dev 已提交
789 790
        return 0;
    }
791
    return xEventGroupClearBits(_arduino_event_group, bits);
M
Me No Dev 已提交
792 793 794
}

int WiFiGenericClass::getStatusBits(){
795
    if(!_arduino_event_group){
M
Me No Dev 已提交
796 797
        return 0;
    }
798
    return xEventGroupGetBits(_arduino_event_group);
M
Me No Dev 已提交
799 800 801
}

int WiFiGenericClass::waitStatusBits(int bits, uint32_t timeout_ms){
802
    if(!_arduino_event_group){
M
Me No Dev 已提交
803 804 805
        return 0;
    }
    return xEventGroupWaitBits(
806
        _arduino_event_group,    // The event group being tested.
M
Me No Dev 已提交
807 808 809 810 811 812
        bits,  // The bits within the event group to wait for.
        pdFALSE,         // BIT_0 and BIT_4 should be cleared before returning.
        pdTRUE,        // Don't wait for both bits, either bit will do.
        timeout_ms / portTICK_PERIOD_MS ) & bits; // Wait a maximum of 100ms for either bit to be set.
}

813 814 815 816 817
/**
 * set callback function
 * @param cbEvent WiFiEventCb
 * @param event optional filter (WIFI_EVENT_MAX is all events)
 */
818
wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventCb cbEvent, arduino_event_id_t event)
819 820
{
    if(!cbEvent) {
821
        return 0;
822 823 824 825 826 827 828
    }
    WiFiEventCbList_t newEventHandler;
    newEventHandler.cb = cbEvent;
    newEventHandler.fcb = NULL;
    newEventHandler.scb = NULL;
    newEventHandler.event = event;
    cbEventList.push_back(newEventHandler);
829
    return newEventHandler.id;
830 831
}

832
wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventFuncCb cbEvent, arduino_event_id_t event)
833 834
{
    if(!cbEvent) {
835
        return 0;
836 837 838 839 840 841 842
    }
    WiFiEventCbList_t newEventHandler;
    newEventHandler.cb = NULL;
    newEventHandler.fcb = cbEvent;
    newEventHandler.scb = NULL;
    newEventHandler.event = event;
    cbEventList.push_back(newEventHandler);
843
    return newEventHandler.id;
844 845
}

846
wifi_event_id_t WiFiGenericClass::onEvent(WiFiEventSysCb cbEvent, arduino_event_id_t event)
847 848
{
    if(!cbEvent) {
849
        return 0;
850 851 852 853 854 855 856
    }
    WiFiEventCbList_t newEventHandler;
    newEventHandler.cb = NULL;
    newEventHandler.fcb = NULL;
    newEventHandler.scb = cbEvent;
    newEventHandler.event = event;
    cbEventList.push_back(newEventHandler);
857
    return newEventHandler.id;
858 859 860 861 862 863 864
}

/**
 * removes a callback form event handler
 * @param cbEvent WiFiEventCb
 * @param event optional filter (WIFI_EVENT_MAX is all events)
 */
865
void WiFiGenericClass::removeEvent(WiFiEventCb cbEvent, arduino_event_id_t event)
866 867 868 869 870 871 872 873 874 875 876 877 878
{
    if(!cbEvent) {
        return;
    }

    for(uint32_t i = 0; i < cbEventList.size(); i++) {
        WiFiEventCbList_t entry = cbEventList[i];
        if(entry.cb == cbEvent && entry.event == event) {
            cbEventList.erase(cbEventList.begin() + i);
        }
    }
}

879
void WiFiGenericClass::removeEvent(WiFiEventSysCb cbEvent, arduino_event_id_t event)
880 881 882 883 884 885 886
{
    if(!cbEvent) {
        return;
    }

    for(uint32_t i = 0; i < cbEventList.size(); i++) {
        WiFiEventCbList_t entry = cbEventList[i];
887
        if(entry.scb == cbEvent && entry.event == event) {
888 889 890 891 892
            cbEventList.erase(cbEventList.begin() + i);
        }
    }
}

893
void WiFiGenericClass::removeEvent(wifi_event_id_t id)
894 895 896
{
    for(uint32_t i = 0; i < cbEventList.size(); i++) {
        WiFiEventCbList_t entry = cbEventList[i];
897
        if(entry.id == id) {
898 899 900 901 902 903 904 905 906 907
            cbEventList.erase(cbEventList.begin() + i);
        }
    }
}

/**
 * callback for WiFi events
 * @param arg
 */
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
908 909 910 911
const char * arduino_event_names[] = {
		"WIFI_READY",
		"SCAN_DONE",
		"STA_START", "STA_STOP", "STA_CONNECTED", "STA_DISCONNECTED", "STA_AUTHMODE_CHANGE", "STA_GOT_IP", "STA_GOT_IP6", "STA_LOST_IP",
M
Me No Dev 已提交
912 913
		"AP_START", "AP_STOP", "AP_STACONNECTED", "AP_STADISCONNECTED", "AP_STAIPASSIGNED", "AP_PROBEREQRECVED", "AP_GOT_IP6", 
		"FTM_REPORT",
914 915 916 917 918
		"ETH_START", "ETH_STOP", "ETH_CONNECTED", "ETH_DISCONNECTED", "ETH_GOT_IP", "ETH_GOT_IP6",
		"WPS_ER_SUCCESS", "WPS_ER_FAILED", "WPS_ER_TIMEOUT", "WPS_ER_PIN", "WPS_ER_PBC_OVERLAP",
		"SC_SCAN_DONE", "SC_FOUND_CHANNEL", "SC_GOT_SSID_PSWD", "SC_SEND_ACK_DONE",
		"PROV_INIT", "PROV_DEINIT", "PROV_START", "PROV_END", "PROV_CRED_RECV", "PROV_CRED_FAIL", "PROV_CRED_SUCCESS"
};
919 920
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN
921
const char * system_event_reasons[] = { "UNSPECIFIED", "AUTH_EXPIRE", "AUTH_LEAVE", "ASSOC_EXPIRE", "ASSOC_TOOMANY", "NOT_AUTHED", "NOT_ASSOCED", "ASSOC_LEAVE", "ASSOC_NOT_AUTHED", "DISASSOC_PWRCAP_BAD", "DISASSOC_SUPCHAN_BAD", "UNSPECIFIED", "IE_INVALID", "MIC_FAILURE", "4WAY_HANDSHAKE_TIMEOUT", "GROUP_KEY_UPDATE_TIMEOUT", "IE_IN_4WAY_DIFFERS", "GROUP_CIPHER_INVALID", "PAIRWISE_CIPHER_INVALID", "AKMP_INVALID", "UNSUPP_RSN_IE_VERSION", "INVALID_RSN_IE_CAP", "802_1X_AUTH_FAILED", "CIPHER_SUITE_REJECTED", "BEACON_TIMEOUT", "NO_AP_FOUND", "AUTH_FAIL", "ASSOC_FAIL", "HANDSHAKE_TIMEOUT", "CONNECTION_FAIL" };
922
#define reason2str(r) ((r>176)?system_event_reasons[r-176]:system_event_reasons[r-1])
923
#endif
924
esp_err_t WiFiGenericClass::_eventCallback(arduino_event_t *event)
925
{
926 927
    static bool first_connect = true;

928 929
    if(event->event_id < ARDUINO_EVENT_MAX) {
        log_d("Arduino Event: %d - %s", event->event_id, arduino_event_names[event->event_id]);
930
    }
931
    if(event->event_id == ARDUINO_EVENT_WIFI_SCAN_DONE) {
932
        WiFiScanClass::_scanDone();
M
Me No Dev 已提交
933

934
    } else if(event->event_id == ARDUINO_EVENT_WIFI_STA_START) {
M
Me No Dev 已提交
935 936
        WiFiSTAClass::_setStatus(WL_DISCONNECTED);
        setStatusBits(STA_STARTED_BIT);
937 938 939 940
        if(esp_wifi_set_ps(_sleepEnabled) != ESP_OK){
            log_e("esp_wifi_set_ps failed");
        }
    } else if(event->event_id == ARDUINO_EVENT_WIFI_STA_STOP) {
M
Me No Dev 已提交
941 942
        WiFiSTAClass::_setStatus(WL_NO_SHIELD);
        clearStatusBits(STA_STARTED_BIT | STA_CONNECTED_BIT | STA_HAS_IP_BIT | STA_HAS_IP6_BIT);
943
    } else if(event->event_id == ARDUINO_EVENT_WIFI_STA_CONNECTED) {
M
Me No Dev 已提交
944 945
        WiFiSTAClass::_setStatus(WL_IDLE_STATUS);
        setStatusBits(STA_CONNECTED_BIT);
946 947 948 949

        //esp_netif_create_ip6_linklocal(esp_netifs[ESP_IF_WIFI_STA]);
    } else if(event->event_id == ARDUINO_EVENT_WIFI_STA_DISCONNECTED) {
        uint8_t reason = event->event_info.wifi_sta_disconnected.reason;
950 951 952
        log_w("Reason: %u - %s", reason, reason2str(reason));
        if(reason == WIFI_REASON_NO_AP_FOUND) {
            WiFiSTAClass::_setStatus(WL_NO_SSID_AVAIL);
953
        } else if((reason == WIFI_REASON_AUTH_FAIL) && !first_connect){
954 955 956 957
            WiFiSTAClass::_setStatus(WL_CONNECT_FAILED);
        } else if(reason == WIFI_REASON_BEACON_TIMEOUT || reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
            WiFiSTAClass::_setStatus(WL_CONNECTION_LOST);
        } else if(reason == WIFI_REASON_AUTH_EXPIRE) {
958

959 960 961
        } else {
            WiFiSTAClass::_setStatus(WL_DISCONNECTED);
        }
M
Me No Dev 已提交
962
        clearStatusBits(STA_CONNECTED_BIT | STA_HAS_IP_BIT | STA_HAS_IP6_BIT);
963 964 965 966 967 968 969 970 971
        if(first_connect && ((reason == WIFI_REASON_AUTH_EXPIRE) ||
        (reason >= WIFI_REASON_BEACON_TIMEOUT)))
        {
            log_d("WiFi Reconnect Running");
            WiFi.disconnect();
            WiFi.begin();
            first_connect = false;
        }
        else if(WiFi.getAutoReconnect()){
S
Shawn A 已提交
972 973 974 975 976 977 978 979 980 981
            if((reason == WIFI_REASON_AUTH_EXPIRE) ||
            (reason >= WIFI_REASON_BEACON_TIMEOUT && reason != WIFI_REASON_AUTH_FAIL))
            {
                log_d("WiFi AutoReconnect Running");
                WiFi.disconnect();
                WiFi.begin();
            }
        }
        else if (reason == WIFI_REASON_ASSOC_FAIL){
            WiFiSTAClass::_setStatus(WL_CONNECT_FAILED);
M
Me No Dev 已提交
982
        }
983
    } else if(event->event_id == ARDUINO_EVENT_WIFI_STA_GOT_IP) {
984 985 986 987 988 989 990 991 992
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
        uint8_t * ip = (uint8_t *)&(event->event_info.got_ip.ip_info.ip.addr);
        uint8_t * mask = (uint8_t *)&(event->event_info.got_ip.ip_info.netmask.addr);
        uint8_t * gw = (uint8_t *)&(event->event_info.got_ip.ip_info.gw.addr);
        log_d("STA IP: %u.%u.%u.%u, MASK: %u.%u.%u.%u, GW: %u.%u.%u.%u",
            ip[0], ip[1], ip[2], ip[3],
            mask[0], mask[1], mask[2], mask[3],
            gw[0], gw[1], gw[2], gw[3]);
#endif
M
Me No Dev 已提交
993 994
        WiFiSTAClass::_setStatus(WL_CONNECTED);
        setStatusBits(STA_HAS_IP_BIT | STA_CONNECTED_BIT);
995
    } else if(event->event_id == ARDUINO_EVENT_WIFI_STA_LOST_IP) {
M
Me No Dev 已提交
996 997 998
        WiFiSTAClass::_setStatus(WL_IDLE_STATUS);
        clearStatusBits(STA_HAS_IP_BIT);

999
    } else if(event->event_id == ARDUINO_EVENT_WIFI_AP_START) {
M
Me No Dev 已提交
1000
        setStatusBits(AP_STARTED_BIT);
1001
    } else if(event->event_id == ARDUINO_EVENT_WIFI_AP_STOP) {
M
Me No Dev 已提交
1002
        clearStatusBits(AP_STARTED_BIT | AP_HAS_CLIENT_BIT);
1003
    } else if(event->event_id == ARDUINO_EVENT_WIFI_AP_STACONNECTED) {
M
Me No Dev 已提交
1004
        setStatusBits(AP_HAS_CLIENT_BIT);
1005
    } else if(event->event_id == ARDUINO_EVENT_WIFI_AP_STADISCONNECTED) {
M
Me No Dev 已提交
1006 1007 1008 1009 1010
        wifi_sta_list_t clients;
        if(esp_wifi_ap_get_sta_list(&clients) != ESP_OK || !clients.num){
            clearStatusBits(AP_HAS_CLIENT_BIT);
        }

1011
    } else if(event->event_id == ARDUINO_EVENT_ETH_START) {
M
Me No Dev 已提交
1012
        setStatusBits(ETH_STARTED_BIT);
1013
    } else if(event->event_id == ARDUINO_EVENT_ETH_STOP) {
M
Me No Dev 已提交
1014
        clearStatusBits(ETH_STARTED_BIT | ETH_CONNECTED_BIT | ETH_HAS_IP_BIT | ETH_HAS_IP6_BIT);
1015
    } else if(event->event_id == ARDUINO_EVENT_ETH_CONNECTED) {
M
Me No Dev 已提交
1016
        setStatusBits(ETH_CONNECTED_BIT);
1017
    } else if(event->event_id == ARDUINO_EVENT_ETH_DISCONNECTED) {
M
Me No Dev 已提交
1018
        clearStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP_BIT | ETH_HAS_IP6_BIT);
1019
    } else if(event->event_id == ARDUINO_EVENT_ETH_GOT_IP) {
1020 1021 1022 1023 1024 1025 1026 1027 1028
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
        uint8_t * ip = (uint8_t *)&(event->event_info.got_ip.ip_info.ip.addr);
        uint8_t * mask = (uint8_t *)&(event->event_info.got_ip.ip_info.netmask.addr);
        uint8_t * gw = (uint8_t *)&(event->event_info.got_ip.ip_info.gw.addr);
        log_d("ETH IP: %u.%u.%u.%u, MASK: %u.%u.%u.%u, GW: %u.%u.%u.%u",
            ip[0], ip[1], ip[2], ip[3],
            mask[0], mask[1], mask[2], mask[3],
            gw[0], gw[1], gw[2], gw[3]);
#endif
M
Me No Dev 已提交
1029 1030
        setStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP_BIT);

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    } else if(event->event_id == ARDUINO_EVENT_WIFI_STA_GOT_IP6) {
    	setStatusBits(STA_CONNECTED_BIT | STA_HAS_IP6_BIT);
    } else if(event->event_id == ARDUINO_EVENT_WIFI_AP_GOT_IP6) {
    	setStatusBits(AP_HAS_IP6_BIT);
    } else if(event->event_id == ARDUINO_EVENT_ETH_GOT_IP6) {
    	setStatusBits(ETH_CONNECTED_BIT | ETH_HAS_IP6_BIT);
    } else if(event->event_id == ARDUINO_EVENT_SC_GOT_SSID_PSWD) {
    	WiFi.begin(
			(const char *)event->event_info.sc_got_ssid_pswd.ssid,
			(const char *)event->event_info.sc_got_ssid_pswd.password,
			0,
			((event->event_info.sc_got_ssid_pswd.bssid_set == true)?event->event_info.sc_got_ssid_pswd.bssid:NULL)
		);
    } else if(event->event_id == ARDUINO_EVENT_SC_SEND_ACK_DONE) {
    	esp_smartconfig_stop();
    	WiFiSTAClass::_smartConfigDone = true;
1047
    }
1048

1049 1050 1051
    for(uint32_t i = 0; i < cbEventList.size(); i++) {
        WiFiEventCbList_t entry = cbEventList[i];
        if(entry.cb || entry.fcb || entry.scb) {
1052
            if(entry.event == (arduino_event_id_t) event->event_id || entry.event == ARDUINO_EVENT_MAX) {
1053
                if(entry.cb) {
1054
                    entry.cb((arduino_event_id_t) event->event_id);
1055
                } else if(entry.fcb) {
1056
                    entry.fcb((arduino_event_id_t) event->event_id, (arduino_event_info_t) event->event_info);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
                } else {
                    entry.scb(event);
                }
            }
        }
    }
    return ESP_OK;
}

/**
 * Return the current channel associated with the network
 * @return channel (1-13)
 */
int32_t WiFiGenericClass::channel(void)
{
M
Me No Dev 已提交
1072 1073 1074 1075 1076
    uint8_t primaryChan = 0;
    wifi_second_chan_t secondChan = WIFI_SECOND_CHAN_NONE;
    if(!lowLevelInitDone){
        return primaryChan;
    }
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    esp_wifi_get_channel(&primaryChan, &secondChan);
    return primaryChan;
}


/**
 * store WiFi config in SDK flash area
 * @param persistent
 */
void WiFiGenericClass::persistent(bool persistent)
{
    _persistent = persistent;
}


1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
/**
 * enable WiFi long range mode
 * @param enable
 */
void WiFiGenericClass::enableLongRange(bool enable)
{
    _long_range = enable;
}


1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
/**
 * set new mode
 * @param m WiFiMode_t
 */
bool WiFiGenericClass::mode(wifi_mode_t m)
{
    wifi_mode_t cm = getMode();
    if(cm == m) {
        return true;
    }
M
Me No Dev 已提交
1112
    if(!cm && m){
1113
        if(!wifiLowLevelInit(_persistent)){
M
Me No Dev 已提交
1114 1115 1116
            return false;
        }
    } else if(cm && !m){
1117 1118
        return espWiFiStop();
    }
1119

1120
    esp_err_t err;
1121 1122 1123 1124 1125 1126 1127
    if(m & WIFI_MODE_STA){
    	err = set_esp_interface_hostname(ESP_IF_WIFI_STA, get_esp_netif_hostname());
        if(err){
            log_e("Could not set hostname! %d", err);
            return false;
        }
    }
1128 1129
    err = esp_wifi_set_mode(m);
    if(err){
zhaoyanbai's avatar
zhaoyanbai 已提交
1130
        log_e("Could not set mode! %d", err);
1131 1132
        return false;
    }
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    if(_long_range){
        if(m & WIFI_MODE_STA){
            err = esp_wifi_set_protocol(WIFI_IF_STA, WIFI_PROTOCOL_LR);
            if(err != ESP_OK){
                log_e("Could not enable long range on STA! %d", err);
                return false;
            }
        }
        if(m & WIFI_MODE_AP){
            err = esp_wifi_set_protocol(WIFI_IF_AP, WIFI_PROTOCOL_LR);
            if(err != ESP_OK){
                log_e("Could not enable long range on AP! %d", err);
                return false;
            }
        }
    }
    if(!espWiFiStart()){
        return false;
    }
1152 1153 1154 1155 1156 1157 1158 1159

    #ifdef BOARD_HAS_DUAL_ANTENNA
        if(!setDualAntennaConfig(ANT1, ANT2, WIFI_RX_ANT_AUTO, WIFI_TX_ANT_AUTO)){
            log_e("Dual Antenna Config failed!");
            return false;
        }
    #endif

M
Me No Dev 已提交
1160
    return true;
1161 1162 1163 1164 1165 1166 1167 1168
}

/**
 * get WiFi mode
 * @return WiFiMode
 */
wifi_mode_t WiFiGenericClass::getMode()
{
1169
    if(!lowLevelInitDone || !_esp_wifi_started){
M
Me No Dev 已提交
1170
        return WIFI_MODE_NULL;
1171
    }
M
Me No Dev 已提交
1172
    wifi_mode_t mode;
1173
    if(esp_wifi_get_mode(&mode) != ESP_OK){
M
Me No Dev 已提交
1174 1175 1176 1177
        log_w("WiFi not started");
        return WIFI_MODE_NULL;
    }
    return mode;
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
}

/**
 * control STA mode
 * @param enable bool
 * @return ok
 */
bool WiFiGenericClass::enableSTA(bool enable)
{

    wifi_mode_t currentMode = getMode();
    bool isEnabled = ((currentMode & WIFI_MODE_STA) != 0);

    if(isEnabled != enable) {
        if(enable) {
            return mode((wifi_mode_t)(currentMode | WIFI_MODE_STA));
        }
M
Me No Dev 已提交
1195
        return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_STA)));
1196
    }
M
Me No Dev 已提交
1197
    return true;
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
}

/**
 * control AP mode
 * @param enable bool
 * @return ok
 */
bool WiFiGenericClass::enableAP(bool enable)
{

    wifi_mode_t currentMode = getMode();
    bool isEnabled = ((currentMode & WIFI_MODE_AP) != 0);

    if(isEnabled != enable) {
        if(enable) {
            return mode((wifi_mode_t)(currentMode | WIFI_MODE_AP));
        }
M
Me No Dev 已提交
1215
        return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_AP)));
1216
    }
M
Me No Dev 已提交
1217
    return true;
1218 1219
}

M
Me No Dev 已提交
1220 1221 1222 1223 1224
/**
 * control modem sleep when only in STA mode
 * @param enable bool
 * @return ok
 */
1225 1226
bool WiFiGenericClass::setSleep(bool enabled){
    return setSleep(enabled?WIFI_PS_MIN_MODEM:WIFI_PS_NONE);
M
Me No Dev 已提交
1227 1228
}

1229 1230 1231 1232 1233
/**
 * control modem sleep when only in STA mode
 * @param mode wifi_ps_type_t
 * @return ok
 */
1234
bool WiFiGenericClass::setSleep(wifi_ps_type_t sleepType)
1235
{
1236 1237 1238 1239 1240 1241 1242 1243 1244
    if(sleepType != _sleepEnabled){
        _sleepEnabled = sleepType;
        if((getMode() & WIFI_MODE_STA) != 0){
            if(esp_wifi_set_ps(_sleepEnabled) != ESP_OK){
                log_e("esp_wifi_set_ps failed!");
                return false;
            }
        }
        return true;
1245
    }
1246
    return false;
1247 1248
}

M
Me No Dev 已提交
1249 1250 1251 1252
/**
 * get modem sleep enabled
 * @return true if modem sleep is enabled
 */
1253
wifi_ps_type_t WiFiGenericClass::getSleep()
M
Me No Dev 已提交
1254
{
1255
    return _sleepEnabled;
M
Me No Dev 已提交
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281
}

/**
 * control wifi tx power
 * @param power enum maximum wifi tx power
 * @return ok
 */
bool WiFiGenericClass::setTxPower(wifi_power_t power){
    if((getStatusBits() & (STA_STARTED_BIT | AP_STARTED_BIT)) == 0){
        log_w("Neither AP or STA has been started");
        return false;
    }
    return esp_wifi_set_max_tx_power(power) == ESP_OK;
}

wifi_power_t WiFiGenericClass::getTxPower(){
    int8_t power;
    if((getStatusBits() & (STA_STARTED_BIT | AP_STARTED_BIT)) == 0){
        log_w("Neither AP or STA has been started");
        return WIFI_POWER_19_5dBm;
    }
    if(esp_wifi_get_max_tx_power(&power)){
        return WIFI_POWER_19_5dBm;
    }
    return (wifi_power_t)power;
}
1282

M
Me No Dev 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
/**
 * Initiate FTM Session.
 * @param frm_count Number of FTM frames requested in terms of 4 or 8 bursts (allowed values - 0(No pref), 16, 24, 32, 64)
 * @param burst_period Requested time period between consecutive FTM bursts in 100's of milliseconds (allowed values - 0(No pref), 2 - 255)
 * @param channel Primary channel of the FTM Responder
 * @param mac MAC address of the FTM Responder
 * @return true on success
 */
bool WiFiGenericClass::initiateFTM(uint8_t frm_count, uint16_t burst_period, uint8_t channel, const uint8_t * mac) {
  wifi_ftm_initiator_cfg_t ftmi_cfg = {
    .resp_mac = {0,0,0,0,0,0},
    .channel = channel,
    .frm_count = frm_count,
    .burst_period = burst_period,
  };
  if(mac != NULL){
    memcpy(ftmi_cfg.resp_mac, mac, 6);
  }
  // Request FTM session with the Responder
  if (ESP_OK != esp_wifi_ftm_initiate_session(&ftmi_cfg)) {
    log_e("Failed to initiate FTM session");
    return false;
  }
  return true;
}

1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
/**
 * Configure Dual antenna.
 * @param gpio_ant1 Configure the GPIO number for the antenna 1 connected to the RF switch (default GPIO2 on ESP32-WROOM-DA)
 * @param gpio_ant2 Configure the GPIO number for the antenna 2 connected to the RF switch (default GPIO25 on ESP32-WROOM-DA)
 * @param rx_mode Set the RX antenna mode. See wifi_rx_ant_t for the options.
 * @param tx_mode Set the TX antenna mode. See wifi_tx_ant_t for the options.
 * @return true on success
 */
bool WiFiGenericClass::setDualAntennaConfig(uint8_t gpio_ant1, uint8_t gpio_ant2, wifi_rx_ant_t rx_mode, wifi_tx_ant_t tx_mode) {

    wifi_ant_gpio_config_t wifi_ant_io;

    if (ESP_OK != esp_wifi_get_ant_gpio(&wifi_ant_io)) {
        log_e("Failed to get antenna configuration");
        return false;
    }

    wifi_ant_io.gpio_cfg[0].gpio_num = gpio_ant1;
    wifi_ant_io.gpio_cfg[0].gpio_select = 1;
    wifi_ant_io.gpio_cfg[1].gpio_num = gpio_ant2;
    wifi_ant_io.gpio_cfg[1].gpio_select = 1;

    if (ESP_OK != esp_wifi_set_ant_gpio(&wifi_ant_io)) {
        log_e("Failed to set antenna GPIO configuration");
        return false;
    }

    // Set antenna default configuration
    wifi_ant_config_t ant_config = {
        .rx_ant_mode = WIFI_ANT_MODE_AUTO,
1339
        .rx_ant_default = WIFI_ANT_MAX, // Ignored in AUTO mode
1340
        .tx_ant_mode = WIFI_ANT_MODE_AUTO,
1341 1342
        .enabled_ant0 = 1,
        .enabled_ant1 = 2,
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
    };

    switch (rx_mode)
    {
    case WIFI_RX_ANT0:
        ant_config.rx_ant_mode = WIFI_ANT_MODE_ANT0;
        break;
    case WIFI_RX_ANT1:
        ant_config.rx_ant_mode = WIFI_ANT_MODE_ANT1;
        break;
    case WIFI_RX_ANT_AUTO:
        log_i("TX Antenna will be automatically selected");
        ant_config.rx_ant_default = WIFI_ANT_ANT0;
        ant_config.rx_ant_mode = WIFI_ANT_MODE_AUTO;
        // Force TX for AUTO if RX is AUTO
        ant_config.tx_ant_mode = WIFI_ANT_MODE_AUTO;
        goto set_ant;
        break;
    default:
        log_e("Invalid default antenna! Falling back to AUTO");
        ant_config.rx_ant_mode = WIFI_ANT_MODE_AUTO;
        break;
    }

    switch (tx_mode)
    {
    case WIFI_TX_ANT0:
        ant_config.tx_ant_mode = WIFI_ANT_MODE_ANT0;
        break;
    case WIFI_TX_ANT1:
        ant_config.tx_ant_mode = WIFI_ANT_MODE_ANT1;
        break;
    case WIFI_TX_ANT_AUTO:
        log_i("RX Antenna will be automatically selected");
        ant_config.rx_ant_default = WIFI_ANT_ANT0;
        ant_config.tx_ant_mode = WIFI_ANT_MODE_AUTO;
        // Force RX for AUTO if RX is AUTO
        ant_config.rx_ant_mode = WIFI_ANT_MODE_AUTO;
        break;
    default:
        log_e("Invalid default antenna! Falling back to AUTO");
        ant_config.rx_ant_default = WIFI_ANT_ANT0;
        ant_config.tx_ant_mode = WIFI_ANT_MODE_AUTO;
        break;
    }

set_ant:
    if (ESP_OK != esp_wifi_set_ant(&ant_config)) {
        log_e("Failed to set antenna configuration");
        return false;
    }

    return true;
}

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------ Generic Network function ---------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------

/**
 * DNS callback
 * @param name
 * @param ipaddr
 * @param callback_arg
 */
static void wifi_dns_found_callback(const char *name, const ip_addr_t *ipaddr, void *callback_arg)
{
    if(ipaddr) {
        (*reinterpret_cast<IPAddress*>(callback_arg)) = ipaddr->u_addr.ip4.addr;
    }
1413
    xEventGroupSetBits(_arduino_event_group, WIFI_DNS_DONE_BIT);
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
}

/**
 * Resolve the given hostname to an IP address.
 * @param aHostname     Name to be resolved
 * @param aResult       IPAddress structure to store the returned IP address
 * @return 1 if aIPAddrString was successfully converted to an IP address,
 *          else error code
 */
int WiFiGenericClass::hostByName(const char* aHostname, IPAddress& aResult)
{
    ip_addr_t addr;
    aResult = static_cast<uint32_t>(0);
1427 1428
    waitStatusBits(WIFI_DNS_IDLE_BIT, 16000);
    clearStatusBits(WIFI_DNS_IDLE_BIT | WIFI_DNS_DONE_BIT);
1429 1430 1431 1432
    err_t err = dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult);
    if(err == ERR_OK && addr.u_addr.ip4.addr) {
        aResult = addr.u_addr.ip4.addr;
    } else if(err == ERR_INPROGRESS) {
1433
        waitStatusBits(WIFI_DNS_DONE_BIT, 15000);  //real internal timeout in lwip library is 14[s]
M
Me No Dev 已提交
1434 1435 1436 1437 1438
        clearStatusBits(WIFI_DNS_DONE_BIT);
    }
    setStatusBits(WIFI_DNS_IDLE_BIT);
    if((uint32_t)aResult == 0){
        log_e("DNS Failed for %s", aHostname);
1439
    }
M
Me No Dev 已提交
1440
    return (uint32_t)aResult != 0;
1441 1442
}

1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
IPAddress WiFiGenericClass::calculateNetworkID(IPAddress ip, IPAddress subnet) {
	IPAddress networkID;

	for (size_t i = 0; i < 4; i++)
		networkID[i] = subnet[i] & ip[i];

	return networkID;
}

IPAddress WiFiGenericClass::calculateBroadcast(IPAddress ip, IPAddress subnet) {
    IPAddress broadcastIp;
    
    for (int i = 0; i < 4; i++)
        broadcastIp[i] = ~subnet[i] | ip[i];

    return broadcastIp;
}

uint8_t WiFiGenericClass::calculateSubnetCIDR(IPAddress subnetMask) {
	uint8_t CIDR = 0;

	for (uint8_t i = 0; i < 4; i++) {
		if (subnetMask[i] == 0x80)  // 128
			CIDR += 1;
		else if (subnetMask[i] == 0xC0)  // 192
			CIDR += 2;
		else if (subnetMask[i] == 0xE0)  // 224
			CIDR += 3;
		else if (subnetMask[i] == 0xF0)  // 242
			CIDR += 4;
		else if (subnetMask[i] == 0xF8)  // 248
			CIDR += 5;
		else if (subnetMask[i] == 0xFC)  // 252
			CIDR += 6;
		else if (subnetMask[i] == 0xFE)  // 254
			CIDR += 7;
		else if (subnetMask[i] == 0xFF)  // 255
			CIDR += 8;
	}

	return CIDR;
}