WiFiGeneric.cpp 11.1 KB
Newer Older
M
me-no-dev 已提交
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
/*
 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>
M
me-no-dev 已提交
35

M
me-no-dev 已提交
36 37 38
#include <esp_err.h>
#include <esp_wifi.h>
#include <esp_event_loop.h>
M
me-no-dev 已提交
39
#include "lwip/ip_addr.h"
M
me-no-dev 已提交
40 41 42
#include "lwip/opt.h"
#include "lwip/err.h"
#include "lwip/dns.h"
43
#include "esp_ipc.h"
M
me-no-dev 已提交
44 45


46 47
} //extern "C"

M
me-no-dev 已提交
48 49
#include "esp32-hal-log.h"

M
me-no-dev 已提交
50 51 52 53
#undef min
#undef max
#include <vector>

M
me-no-dev 已提交
54 55 56 57 58 59 60 61 62
void tcpipInit(){
    static bool initialized = false;
    if(!initialized){
        initialized = true;
        tcpip_adapter_init();
        esp_event_loop_init(&WiFiGenericClass::_eventCallback, NULL);
    }
}

M
me-no-dev 已提交
63 64 65
static bool wifiLowLevelInit(){
    static bool lowLevelInitDone = false;
    if(!lowLevelInitDone){
M
me-no-dev 已提交
66
        tcpipInit();
M
me-no-dev 已提交
67 68 69 70
        wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
        esp_err_t err = esp_wifi_init(&cfg);
        if(err){
            log_e("esp_wifi_init %d", err);
71 72
            return false;
        }
M
me-no-dev 已提交
73 74 75
        esp_wifi_set_storage(WIFI_STORAGE_FLASH);
        esp_wifi_set_mode(WIFI_MODE_NULL);
        lowLevelInitDone = true;
76
    }
M
me-no-dev 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89
    return true;
}

static bool wifiLowLevelDeinit(){
    //deinit not working yet!
    //esp_wifi_deinit();
    return true;
}

static bool _esp_wifi_started = false;

static bool espWiFiStart(){
    if(_esp_wifi_started){
90 91
        return true;
    }
M
me-no-dev 已提交
92
    if(!wifiLowLevelInit()){
93 94
        return false;
    }
M
me-no-dev 已提交
95
    esp_err_t err = esp_wifi_start();
96
    if (err != ESP_OK) {
M
me-no-dev 已提交
97 98
        log_e("esp_wifi_start %d", err);
        wifiLowLevelDeinit();
99 100
        return false;
    }
M
me-no-dev 已提交
101 102 103
    _esp_wifi_started = true;
    return true;
}
104

M
me-no-dev 已提交
105 106 107 108
static bool espWiFiStop(){
    esp_err_t err;
    if(!_esp_wifi_started){
        return true;
109
    }
M
me-no-dev 已提交
110 111 112 113 114 115 116
    err = esp_wifi_stop();
    if(err){
        log_e("Could not stop WiFi! %u", err);
        return false;
    }
    _esp_wifi_started = false;
    return wifiLowLevelDeinit();
117 118
}

M
me-no-dev 已提交
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
// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------- Generic WiFi function -----------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------

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

bool WiFiGenericClass::_persistent = true;
wifi_mode_t WiFiGenericClass::_forceSleepLastMode = WIFI_MODE_NULL;

WiFiGenericClass::WiFiGenericClass()
{

}

/**
 * set callback function
 * @param cbEvent WiFiEventCb
 * @param event optional filter (WIFI_EVENT_MAX is all events)
 */
void WiFiGenericClass::onEvent(WiFiEventCb cbEvent, system_event_id_t event)
{
    if(!cbEvent) {
        return;
    }
    WiFiEventCbList_t newEventHandler;
    newEventHandler.cb = cbEvent;
    newEventHandler.event = event;
    cbEventList.push_back(newEventHandler);
}

/**
 * removes a callback form event handler
 * @param cbEvent WiFiEventCb
 * @param event optional filter (WIFI_EVENT_MAX is all events)
 */
void WiFiGenericClass::removeEvent(WiFiEventCb cbEvent, system_event_id_t event)
{
    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);
        }
    }
}

/**
 * callback for WiFi events
 * @param arg
 */
173
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_DEBUG
174
const char * system_event_names[] = { "WIFI_READY", "SCAN_DONE", "STA_START", "STA_STOP", "STA_CONNECTED", "STA_DISCONNECTED", "STA_AUTHMODE_CHANGE", "STA_GOT_IP", "STA_WPS_ER_SUCCESS", "STA_WPS_ER_FAILED", "STA_WPS_ER_TIMEOUT", "STA_WPS_ER_PIN", "AP_START", "AP_STOP", "AP_STACONNECTED", "AP_STADISCONNECTED", "AP_PROBEREQRECVED", "AP_STA_GOT_IP6", "ETH_START", "ETH_STOP", "ETH_CONNECTED", "ETH_DISCONNECTED", "ETH_GOT_IP", "MAX"};
175 176
#endif
#if ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_WARN
177
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", "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" };
M
me-no-dev 已提交
178
#define reason2str(r) ((r>176)?system_event_reasons[r-176]:system_event_reasons[r-1])
179
#endif
M
me-no-dev 已提交
180 181
esp_err_t WiFiGenericClass::_eventCallback(void *arg, system_event_t *event)
{
182
    log_d("Event: %d - %s", event->event_id, system_event_names[event->event_id]);
M
me-no-dev 已提交
183 184 185 186
    if(event->event_id == SYSTEM_EVENT_SCAN_DONE) {
        WiFiScanClass::_scanDone();
    } else if(event->event_id == SYSTEM_EVENT_STA_DISCONNECTED) {
        uint8_t reason = event->event_info.disconnected.reason;
187
        log_w("Reason: %u - %s", reason, reason2str(reason));
M
me-no-dev 已提交
188 189 190 191 192 193
        if(reason == WIFI_REASON_NO_AP_FOUND) {
            WiFiSTAClass::_setStatus(WL_NO_SSID_AVAIL);
        } else if(reason == WIFI_REASON_AUTH_FAIL || reason == WIFI_REASON_ASSOC_FAIL) {
            WiFiSTAClass::_setStatus(WL_CONNECT_FAILED);
        } else if(reason == WIFI_REASON_BEACON_TIMEOUT || reason == WIFI_REASON_HANDSHAKE_TIMEOUT) {
            WiFiSTAClass::_setStatus(WL_CONNECTION_LOST);
M
me-no-dev 已提交
194 195
        } else if(reason == WIFI_REASON_AUTH_EXPIRE) {
            WiFi.begin();
M
me-no-dev 已提交
196 197 198 199 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 242 243 244 245 246
        } else {
            WiFiSTAClass::_setStatus(WL_DISCONNECTED);
        }
    } else if(event->event_id == SYSTEM_EVENT_STA_START) {
        WiFiSTAClass::_setStatus(WL_DISCONNECTED);
    } else if(event->event_id == SYSTEM_EVENT_STA_STOP) {
        WiFiSTAClass::_setStatus(WL_NO_SHIELD);
    } else if(event->event_id == SYSTEM_EVENT_STA_GOT_IP) {
        WiFiSTAClass::_setStatus(WL_CONNECTED);
    }

    for(uint32_t i = 0; i < cbEventList.size(); i++) {
        WiFiEventCbList_t entry = cbEventList[i];
        if(entry.cb) {
            if(entry.event == (system_event_id_t) event->event_id || entry.event == SYSTEM_EVENT_MAX) {
                entry.cb((system_event_id_t) event->event_id);
            }
        }
    }
    return ESP_OK;
}

/**
 * Return the current channel associated with the network
 * @return channel (1-13)
 */
int32_t WiFiGenericClass::channel(void)
{
    uint8_t primaryChan;
    wifi_second_chan_t secondChan;
    esp_wifi_get_channel(&primaryChan, &secondChan);
    return primaryChan;
}


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


/**
 * set new mode
 * @param m WiFiMode_t
 */
bool WiFiGenericClass::mode(wifi_mode_t m)
{
247 248 249 250 251
    wifi_mode_t cm = getMode();
    if(cm == WIFI_MODE_MAX){
        return false;
    }
    if(cm == m) {
M
me-no-dev 已提交
252 253
        return true;
    }
M
me-no-dev 已提交
254 255 256 257 258 259 260 261 262 263
    esp_err_t err;
    err = esp_wifi_set_mode(m);
    if(err){
        log_e("Could not set mode! %u", err);
        return false;
    }
    if(m){
        return espWiFiStart();
    }
    return espWiFiStop();
M
me-no-dev 已提交
264 265 266 267 268 269 270 271
}

/**
 * get WiFi mode
 * @return WiFiMode
 */
wifi_mode_t WiFiGenericClass::getMode()
{
M
me-no-dev 已提交
272
    if(!wifiLowLevelInit()){
273 274
        return WIFI_MODE_MAX;
    }
M
me-no-dev 已提交
275
    uint8_t mode;
M
me-no-dev 已提交
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    esp_wifi_get_mode((wifi_mode_t*)&mode);
    return (wifi_mode_t)mode;
}

/**
 * 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));
        } else {
            return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_STA)));
        }
    } else {
        return true;
    }
}

/**
 * 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));
        } else {
            return mode((wifi_mode_t)(currentMode & (~WIFI_MODE_AP)));
        }
    } else {
        return true;
    }
}


// -----------------------------------------------------------------------------------------------------------------------
// ------------------------------------------------ Generic Network function ---------------------------------------------
// -----------------------------------------------------------------------------------------------------------------------

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
static bool _dns_busy = false;

/**
 * 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;
    }
    _dns_busy = false;
}
M
me-no-dev 已提交
344 345 346 347 348 349 350 351 352 353 354 355

/**
 * 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);
356 357

    _dns_busy = true;
M
me-no-dev 已提交
358
    err_t err = dns_gethostbyname(aHostname, &addr, &wifi_dns_found_callback, &aResult);
359
    if(err == ERR_OK && addr.u_addr.ip4.addr) {
M
me-no-dev 已提交
360
        aResult = addr.u_addr.ip4.addr;
361 362 363 364 365
        _dns_busy = false;
    } else if(err == ERR_INPROGRESS) {
        while(_dns_busy){
            delay(1);
        }
M
me-no-dev 已提交
366
    } else {
367
        _dns_busy = false;
M
me-no-dev 已提交
368 369 370 371 372
        return 0;
    }
    return 1;
}