[WiFi] First part of moving code around to restructure WiFi code

This commit is contained in:
TD-er
2024-11-02 13:59:21 +01:00
parent 07a6c55354
commit e5100b180d
35 changed files with 1777 additions and 823 deletions
+8 -2
View File
@@ -43,7 +43,9 @@
#include "../Commands/Timer.h"
#include "../Commands/UPD.h"
#include "../Commands/wd.h"
#if FEATURE_WIFI
#include "../Commands/WiFi.h"
#endif
#include "../DataStructs/TimingStats.h"
@@ -302,14 +304,18 @@ bool InternalCommands::executeInternalCommand()
case ESPEasy_cmd_e::ethdisconnect: COMMAND_CASE_A(Command_ETH_Disconnect, 0); // Network Command
case ESPEasy_cmd_e::ethwifimode: COMMAND_CASE_R(Command_ETH_Wifi_Mode, 1); // Network Command
#endif // FEATURE_ETHERNET
#if FEATURE_WIFI
case ESPEasy_cmd_e::erasesdkwifi: COMMAND_CASE_R(Command_WiFi_Erase, 0); // WiFi.h
#endif
case ESPEasy_cmd_e::event: COMMAND_CASE_A(Command_Rules_Events, -1); // Rule.h
case ESPEasy_cmd_e::executerules: COMMAND_CASE_A(Command_Rules_Execute, -1); // Rule.h
case ESPEasy_cmd_e::factoryreset: COMMAND_CASE_R(Command_Settings_FactoryReset, 0); // Settings.h
case ESPEasy_cmd_e::gateway: COMMAND_CASE_R(Command_Gateway, 1); // Network Command
case ESPEasy_cmd_e::gpio: COMMAND_CASE_A(Command_GPIO, 2); // Gpio.h
case ESPEasy_cmd_e::gpiotoggle: COMMAND_CASE_A(Command_GPIO_Toggle, 1); // Gpio.h
#if FEATURE_WIFI
case ESPEasy_cmd_e::hiddenssid: COMMAND_CASE_R(Command_Wifi_HiddenSSID, 1); // wifi.h
#endif
case ESPEasy_cmd_e::i2cscanner: COMMAND_CASE_R(Command_i2c_Scanner, -1); // i2c.h
case ESPEasy_cmd_e::inc: COMMAND_CASE_A(Command_Rules_Inc, -1); // Rules.h
case ESPEasy_cmd_e::ip: COMMAND_CASE_R(Command_IP, 1); // Network Command
@@ -461,7 +467,7 @@ bool InternalCommands::executeInternalCommand()
case ESPEasy_cmd_e::wdconfig: COMMAND_CASE_R(Command_WD_Config, 3); // WD.h
case ESPEasy_cmd_e::wdread: COMMAND_CASE_R(Command_WD_Read, 2); // WD.h
#endif // ifndef LIMIT_BUILD_SIZE
#if FEATURE_WIFI
case ESPEasy_cmd_e::wifiallowap: COMMAND_CASE_R(Command_Wifi_AllowAP, 0); // WiFi.h
case ESPEasy_cmd_e::wifiapmode: COMMAND_CASE_R(Command_Wifi_APMode, 0); // WiFi.h
case ESPEasy_cmd_e::wificonnect: COMMAND_CASE_A(Command_Wifi_Connect, 0); // WiFi.h
@@ -473,7 +479,7 @@ bool InternalCommands::executeInternalCommand()
case ESPEasy_cmd_e::wifissid: COMMAND_CASE_R(Command_Wifi_SSID, 1); // WiFi.h
case ESPEasy_cmd_e::wifissid2: COMMAND_CASE_R(Command_Wifi_SSID2, 1); // WiFi.h
case ESPEasy_cmd_e::wifistamode: COMMAND_CASE_R(Command_Wifi_STAMode, 0); // WiFi.h
#endif
case ESPEasy_cmd_e::NotMatched:
return false;
@@ -57,9 +57,15 @@ const char Internal_commands_d[] PROGMEM =
"dst|"
;
#if FEATURE_WIFI
#define Int_cmd_e_offset ESPEasy_cmd_e::erasesdkwifi
#else
#define Int_cmd_e_offset ESPEasy_cmd_e::event
#endif
const char Internal_commands_e[] PROGMEM =
#if FEATURE_WIFI
"erasesdkwifi|"
#endif
"event|"
"executerules|"
#if FEATURE_ETHERNET
@@ -84,7 +90,9 @@ const char Internal_commands_fghij[] PROGMEM =
"gateway|"
"gpio|"
"gpiotoggle|"
#if FEATURE_WIFI
"hiddenssid|"
#endif
"i2cscanner|"
"inc|"
"ip|"
@@ -259,8 +267,14 @@ const char Internal_commands_u[] PROGMEM =
"usentp|"
;
#if FEATURE_WIFI || !defined(LIMIT_BUILD_SIZE)
#if FEATURE_WIFI
#define Int_cmd_w_offset ESPEasy_cmd_e::wifiallowap
#else
#define Int_cmd_w_offset ESPEasy_cmd_e::wdconfig
#endif
const char Internal_commands_w[] PROGMEM =
#if FEATURE_WIFI
"wifiallowap|"
"wifiapmode|"
"wificonnect|"
@@ -272,11 +286,13 @@ const char Internal_commands_w[] PROGMEM =
"wifissid|"
"wifissid2|"
"wifistamode|"
#endif
#ifndef LIMIT_BUILD_SIZE
"wdconfig|"
"wdread|"
#endif // ifndef LIMIT_BUILD_SIZE
;
#endif
const char* getInternalCommand_Haystack_Offset(const char firstLetter, int& offset)
{
@@ -345,10 +361,12 @@ const char* getInternalCommand_Haystack_Offset(const char firstLetter, int& offs
offset = static_cast<int>(Int_cmd_u_offset);
haystack = Internal_commands_u;
break;
#if FEATURE_WIFI || !defined(LIMIT_BUILD_SIZE)
case 'w':
offset = static_cast<int>(Int_cmd_w_offset);
haystack = Internal_commands_w;
break;
#endif
default:
return nullptr;
+6 -1
View File
@@ -40,8 +40,9 @@ enum class ESPEasy_cmd_e : uint8_t {
#endif // #if FEATURE_PLUGIN_PRIORITY
dns,
dst,
#if FEATURE_WIFI
erasesdkwifi,
#endif
event,
executerules,
#if FEATURE_ETHERNET
@@ -64,7 +65,9 @@ enum class ESPEasy_cmd_e : uint8_t {
gateway,
gpio,
gpiotoggle,
#if FEATURE_WIFI
hiddenssid,
#endif
i2cscanner,
inc,
@@ -216,6 +219,7 @@ enum class ESPEasy_cmd_e : uint8_t {
unmonitorrange,
usentp,
#if FEATURE_WIFI
wifiallowap,
wifiapmode,
wificonnect,
@@ -227,6 +231,7 @@ enum class ESPEasy_cmd_e : uint8_t {
wifissid,
wifissid2,
wifistamode,
#endif
#ifndef LIMIT_BUILD_SIZE
wdconfig,
wdread,
+11 -6
View File
@@ -2,11 +2,14 @@
#include "../../ESPEasy_common.h"
#if FEATURE_WIFI
#include "../Commands/Common.h"
#include "../DataStructs/ESPEasy_EventStruct.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../ESPEasyCore/Serial.h"
#include "../Globals/ESPEasyWiFiEvent.h"
@@ -96,13 +99,13 @@ const __FlashStringHelper* Command_Wifi_Disconnect(struct EventStruct *event, co
const __FlashStringHelper* Command_Wifi_APMode(struct EventStruct *event, const char *Line)
{
setAP(true);
ESPEasy::net::wifi::setAP(true);
return return_command_success_flashstr();
}
const __FlashStringHelper* Command_Wifi_STAMode(struct EventStruct *event, const char *Line)
{
setSTA(true);
ESPEasy::net::wifi::setSTA(true);
return return_command_success_flashstr();
}
@@ -125,12 +128,12 @@ String Command_Wifi_Mode(struct EventStruct *event, const char *Line)
}
if ((mode >= WIFI_OFF) && (mode < WIFI_MODE_MAX)) {
setWifiMode(mode);
ESPEasy::net::wifi::setWifiMode(mode);
} else {
return return_result(event, F("Wifi Mode: invalid arguments"));
}
} else {
return return_result(event, concat(F("WiFi Mode:"), getWifiModeString(WiFi.getMode())));
return return_result(event, concat(F("WiFi Mode:"), ESPEasy::net::wifi::getWifiModeString(WiFi.getMode())));
}
return return_command_success();
}
@@ -147,7 +150,7 @@ const __FlashStringHelper* Command_WiFi_Erase(struct EventStruct *event, const c
{
#ifdef ESP8266
WifiDisconnect();
setWifiMode(WIFI_OFF);
ESPEasy::net::wifi::setWifiMode(WIFI_OFF);
if (!ESP.eraseConfig())
return return_command_failed_flashstr();
addLog(LOG_LEVEL_INFO, F("WiFi : Erased WiFi calibration data"));
@@ -155,7 +158,7 @@ const __FlashStringHelper* Command_WiFi_Erase(struct EventStruct *event, const c
#ifdef ESP32
WifiDisconnect();
setWifiMode(WIFI_OFF);
ESPEasy::net::wifi::setWifiMode(WIFI_OFF);
delay(100);
esp_phy_erase_cal_data_in_nvs();
addLog(LOG_LEVEL_INFO, F("WiFi : Erased WiFi calibration data"));
@@ -166,3 +169,5 @@ const __FlashStringHelper* Command_WiFi_Erase(struct EventStruct *event, const c
#endif
return return_command_success_flashstr();
}
#endif
+4
View File
@@ -1,6 +1,9 @@
#ifndef COMMAND_WIFI_H
#define COMMAND_WIFI_H
#include "../../ESPEasy_common.h"
#if FEATURE_WIFI
#include <WString.h>
String Command_Wifi_SSID(struct EventStruct *event,
@@ -33,4 +36,5 @@ const __FlashStringHelper* Command_Wifi_AllowAP(struct EventStruct *event,
const __FlashStringHelper* Command_WiFi_Erase(struct EventStruct *event,
const char *Line);
#endif
#endif // COMMAND_WIFI_H
+10
View File
@@ -3121,6 +3121,16 @@ To create/register a plugin, you have to :
#define FEATURE_ETHERNET 0
#endif
#ifndef FEATURE_WIFI
#ifdef ESP8266
#define FEATURE_WIFI 1
#elif SOC_WIFI_SUPPORTED || CONFIG_ESP_WIFI_REMOTE_ENABLED
#define FEATURE_WIFI 1
#else
#define FEATURE_WIFI 0
#endif
#endif
#ifndef FEATURE_EXT_RTC
#define FEATURE_EXT_RTC 0
#endif
+19 -20
View File
@@ -59,27 +59,25 @@ struct WiFiEventData_t {
return bitRead(wifiStatus, ESPEASY_WIFI_SERVICES_INITIALIZED);
}
void setWiFiDisconnected();
void setWiFiGotIP();
void setWiFiConnected();
void setWiFiServicesInitialized();
void setWiFiDisconnected();
void setWiFiGotIP();
void setWiFiConnected();
void setWiFiServicesInitialized();
void markGotIP();
void markGotIP();
#if FEATURE_USE_IPV6
void markGotIPv6(const IPAddress& ip6);
void markGotIPv6(const IPAddress& ip6);
#endif
void markLostIP();
void markDisconnect(WiFiDisconnectReason reason);
void markConnected(const String& ssid,
const uint8_t bssid[6],
uint8_t channel);
void markConnectedAPmode(const uint8_t mac[6]);
void markDisconnectedAPmode(const uint8_t mac[6]);
void markLostIP();
void markDisconnect(WiFiDisconnectReason reason);
void markConnected(const String& ssid,
const uint8_t bssid[6],
uint8_t channel);
void markConnectedAPmode(const uint8_t mac[6]);
void markDisconnectedAPmode(const uint8_t mac[6]);
void setAuthMode(uint8_t newMode) {
auth_mode = newMode;
}
void setAuthMode(uint8_t newMode) { auth_mode = newMode; }
String ESPeasyWifiStatusToString() const;
@@ -135,11 +133,11 @@ struct WiFiEventData_t {
// Semaphore like bools for processing data gathered from WiFi events.
bool processedConnect = true;
bool processedDisconnect = true;
bool processedGotIP = true;
bool processedConnect = true;
bool processedDisconnect = true;
bool processedGotIP = true;
#if FEATURE_USE_IPV6
bool processedGotIP6 = true;
bool processedGotIP6 = true;
#endif
bool processedDHCPTimeout = true;
bool processedConnectAPmode = true;
@@ -158,6 +156,7 @@ struct WiFiEventData_t {
#ifdef ESP32
WiFiEventId_t wm_event_id = 0;
#endif // ifdef ESP32
};
#endif // ifndef DATASTRUCTS_WIFIEVENTDATA_H
+18 -16
View File
@@ -4,26 +4,28 @@
#include "../../ESPEasy_common.h"
enum class WiFiConnectionProtocol {
Unknown,
WiFi_Protocol_11b,
WiFi_Protocol_11g,
Unknown,
WiFi_Protocol_11b,
WiFi_Protocol_11g,
#ifdef ESP8266
WiFi_Protocol_11n
WiFi_Protocol_11n
#endif
#ifdef ESP32
WiFi_Protocol_HT20,
WiFi_Protocol_HT40,
WiFi_Protocol_HE20, // WiFi 6
#if ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 2, 0)
WiFi_Protocol_11a, // traditional (old) 5 GHz
WiFi_Protocol_VHT20, // 5 GHz WiFi 5, 802.11ac
#endif
WiFi_Protocol_LR
#endif
WiFi_Protocol_HT20,
WiFi_Protocol_HT40,
WiFi_Protocol_HE20, // WiFi 6
# if ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, \
2, \
0)
WiFi_Protocol_11a, // traditional (old) 5 GHz
WiFi_Protocol_VHT20, // 5 GHz WiFi 5, 802.11ac
# endif // if ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 2, 0)
WiFi_Protocol_LR
#endif // ifdef ESP32
};
const __FlashStringHelper * toString(WiFiConnectionProtocol proto);
const __FlashStringHelper* toString(WiFiConnectionProtocol proto);
#endif
#endif // ifndef DATATYPES_WIFICONNECTIONPROTOCOL_H
@@ -0,0 +1,26 @@
#pragma once
#include "../../ESPEasy_common.h"
#if FEATURE_WIFI
namespace ESPEasy {
namespace net {
namespace wifi {
enum class STA_connected_state {
Idle,
Connecting,
Connected,
Error_Not_Found,
Error_Connect_Failed
};
} // namespace wifi
} // namespace net
} // namespace ESPEasy
#endif // if FEATURE_WIFI
+92
View File
@@ -0,0 +1,92 @@
#pragma once
#include "../../ESPEasy_common.h"
#if FEATURE_WIFI
namespace ESPEasy {
namespace net {
namespace wifi {
/*
State machine:
Start at boot: Disabled
Disabled:
When AP or STA is needed -> OFF
OFF:
When STA is needed -> IdleWaiting
IdleWaiting:
After waiting period:
If candidate present -> start STA_Connecting
Else if AP enabled (and client connected to AP) -> Start STA_AP_Scanning
Else -> start STA_Scanning
STA_Scanning:
When finished:
If known candidate present -> IdleWaiting
else if no known candidate present -> start AP_only -> IdleWaiting
STA_Connecting:
When failed -> STA_Reconnecting
Else -> STA_Connected
STA_Reconnecting:
When failed -> IdleWaiting
Else -> STA_Connected
STA_Connected:
If disconnected -> OFF
If connected for X minutes -> mark as stable
*/
enum class WiFiState_e
{
// WiFi radio is off and no new attempt should be made (e.g. low power mode or Ethernet active)
Disabled,
// WiFi radio off, to continue, everything needs to be (re)initialized
OFF,
// Only running in AP mode
AP_only,
// WiFi was in some kind of error state or needs waiting period
IdleWaiting,
// STA mode + scanning
STA_Scanning,
// STA+AP mode + scanning,
// needs some careful handling to prevent disconnecting the connected stations
STA_AP_Scanning,
// Connecting to an AP
STA_Connecting,
// Reconnecting to an AP
// May need to handle some specific disconnect reasons differently from connecting for the first time.
STA_Reconnecting,
// Connected to an AP
STA_Connected
};
} // namespace wifi
} // namespace net
} // namespace ESPEasy
#endif // if FEATURE_WIFI
+2 -1
View File
@@ -3,6 +3,7 @@
#include "../ESPEasyCore/ESPEasy_Log.h"
#include "../ESPEasyCore/ESPEasyEth.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../Globals/ESPEasy_time.h"
#include "../Globals/ESPEasyWiFiEvent.h"
#include "../Globals/NetworkState.h"
@@ -175,7 +176,7 @@ esp_netif_t * getActiveNetworkMediumInterface() {
} else
#endif
{
if (WifiIsSTA(WiFi.getMode())) {
if ( ESPEasy::net::wifi::WifiIsSTA(WiFi.getMode())) {
iface = ESP_IF_WIFI_STA;
}
}
+21 -22
View File
@@ -27,9 +27,7 @@
# include "../Globals/ESPEasyEthEvent.h"
# endif // if FEATURE_ETHERNET
void setUseStaticIP(bool enabled) {
}
void setUseStaticIP(bool enabled) {}
// ********************************************************************************
// Functions called on events.
@@ -40,37 +38,38 @@ void setUseStaticIP(bool enabled) {
static bool ignoreDisconnectEvent = false;
void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info) {
switch (event) {
switch (event)
{
case ARDUINO_EVENT_WIFI_READY:
// ESP32 WiFi ready
break;
case ARDUINO_EVENT_WIFI_STA_START:
# ifndef BUILD_NO_DEBUG
# ifndef BUILD_NO_DEBUG
// addLog(LOG_LEVEL_INFO, F("WiFi : Event STA Started"));
# endif // ifndef BUILD_NO_DEBUG
# endif // ifndef BUILD_NO_DEBUG
break;
case ARDUINO_EVENT_WIFI_STA_STOP:
# ifndef BUILD_NO_DEBUG
# ifndef BUILD_NO_DEBUG
// addLog(LOG_LEVEL_INFO, F("WiFi : Event STA Stopped"));
# endif // ifndef BUILD_NO_DEBUG
# endif // ifndef BUILD_NO_DEBUG
break;
case ARDUINO_EVENT_WIFI_AP_START:
# ifndef BUILD_NO_DEBUG
# ifndef BUILD_NO_DEBUG
// addLog(LOG_LEVEL_INFO, F("WiFi : Event AP Started"));
# endif // ifndef BUILD_NO_DEBUG
# endif // ifndef BUILD_NO_DEBUG
break;
case ARDUINO_EVENT_WIFI_AP_STOP:
# ifndef BUILD_NO_DEBUG
# ifndef BUILD_NO_DEBUG
// addLog(LOG_LEVEL_INFO, F("WiFi : Event AP Stopped"));
# endif // ifndef BUILD_NO_DEBUG
# endif // ifndef BUILD_NO_DEBUG
break;
case ARDUINO_EVENT_WIFI_STA_LOST_IP:
// ESP32 station lost IP and the IP is reset to 0
# if FEATURE_ETHERNET
# if FEATURE_ETHERNET
if (active_network_medium == NetworkMedium_t::Ethernet) {
// DNS records are shared among WiFi and Ethernet (very bad design!)
@@ -78,9 +77,9 @@ void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info) {
// As soon as WiFi is turned off, the DNS entry for Ethernet is cleared.
EthEventData.markLostIP();
}
# endif // if FEATURE_ETHERNET
# endif // if FEATURE_ETHERNET
WiFiEventData.markLostIP();
# ifndef BUILD_NO_DEBUG
# ifndef BUILD_NO_DEBUG
// addLog(LOG_LEVEL_INFO,
@@ -90,16 +89,16 @@ void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info) {
*/
// F("WiFi : Event Lost IP"));
# endif // ifndef BUILD_NO_DEBUG
# endif // ifndef BUILD_NO_DEBUG
break;
case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED:
// Receive probe request packet in soft-AP interface
// TODO TD-er: Must implement like onProbeRequestAPmode for ESP8266
# ifndef BUILD_NO_DEBUG
# ifndef BUILD_NO_DEBUG
// addLog(LOG_LEVEL_INFO, F("WiFi : Event AP got probed"));
# endif // ifndef BUILD_NO_DEBUG
# endif // ifndef BUILD_NO_DEBUG
break;
case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE:
@@ -136,7 +135,7 @@ void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info) {
ignoreDisconnectEvent = false;
WiFiEventData.markGotIP();
break;
# if FEATURE_USE_IPV6
# if FEATURE_USE_IPV6
case ARDUINO_EVENT_WIFI_STA_GOT_IP6:
{
ip_event_got_ip6_t *event = static_cast<ip_event_got_ip6_t *>(&info.got_ip6);
@@ -147,7 +146,7 @@ void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info) {
case ARDUINO_EVENT_WIFI_AP_GOT_IP6:
addLog(LOG_LEVEL_INFO, F("WIFI : AP got IP6"));
break;
# endif // if FEATURE_USE_IPV6
# endif // if FEATURE_USE_IPV6
case ARDUINO_EVENT_WIFI_AP_STACONNECTED:
WiFiEventData.markConnectedAPmode(info.wifi_ap_staconnected.mac);
break;
@@ -157,7 +156,7 @@ void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info) {
case ARDUINO_EVENT_WIFI_SCAN_DONE:
WiFiEventData.processedScanDone = false;
break;
# if FEATURE_ETHERNET
# if FEATURE_ETHERNET
case ARDUINO_EVENT_ETH_START:
case ARDUINO_EVENT_ETH_CONNECTED:
case ARDUINO_EVENT_ETH_GOT_IP:
@@ -167,7 +166,7 @@ void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info) {
// Handled in EthEvent
break;
# endif // FEATURE_ETHERNET
# endif // FEATURE_ETHERNET
default:
{
// addLogMove(LOG_LEVEL_ERROR, concat(F("UNKNOWN WIFI/ETH EVENT: "), event));
+12 -10
View File
@@ -3,22 +3,23 @@
#ifdef ESP32
#include "../../ESPEasy_common.h"
# include "../../ESPEasy_common.h"
#include <IPAddress.h>
# include <IPAddress.h>
// ********************************************************************************
// Work-around for setting _useStaticIP
// See reported issue: https://github.com/esp8266/Arduino/issues/4114
// ********************************************************************************
#include <IPAddress.h>
#include <WiFiSTA.h>
#include <WiFi.h>
#include <WiFiType.h>
# include <IPAddress.h>
# include <WiFiSTA.h>
# include <WiFi.h>
# include <WiFiType.h>
class WiFi_Access_Static_IP : public WiFiSTAClass {
class WiFi_Access_Static_IP : public WiFiSTAClass
{
public:
void set_use_static_ip(bool enabled);
@@ -31,8 +32,9 @@ void setUseStaticIP(bool enabled);
// Functions called on events.
// Make sure not to call anything in these functions that result in delay() or yield()
// ********************************************************************************
void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info);
void WiFiEvent(WiFiEvent_t event,
arduino_event_info_t info);
#endif
#endif // ifdef ESP32
#endif
#endif // ifndef ESPEASY_WIFI_EVENT_ESP32_H
@@ -1,48 +1,42 @@
#include "../ESPEasyCore/ESPEasyWiFiEvent_ESP8266.h"
#ifdef ESP8266
#if FEATURE_WIFI
# ifdef ESP8266
#include "../DataStructs/RTCStruct.h"
# include "../DataStructs/RTCStruct.h"
#include "../DataTypes/ESPEasyTimeSource.h"
# include "../DataTypes/ESPEasyTimeSource.h"
#include "../ESPEasyCore/ESPEasyEth.h"
#include "../ESPEasyCore/ESPEasy_Log.h"
#include "../ESPEasyCore/ESPEasyNetwork.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_ProcessEvent.h"
# include "../ESPEasyCore/ESPEasyEth.h"
# include "../ESPEasyCore/ESPEasy_Log.h"
# include "../ESPEasyCore/ESPEasyNetwork.h"
# include "../ESPEasyCore/ESPEasyWifi.h"
# include "../ESPEasyCore/ESPEasyWifi_ProcessEvent.h"
#include "../Globals/ESPEasyWiFiEvent.h"
#include "../Globals/NetworkState.h"
#include "../Globals/RTC.h"
#include "../Globals/WiFi_AP_Candidates.h"
# include "../Globals/ESPEasyWiFiEvent.h"
# include "../Globals/NetworkState.h"
# include "../Globals/RTC.h"
# include "../Globals/WiFi_AP_Candidates.h"
#include "../Helpers/ESPEasy_time_calc.h"
# include "../Helpers/ESPEasy_time_calc.h"
void WiFi_Access_Static_IP::set_use_static_ip(bool enabled) { _useStaticIp = enabled; }
void WiFi_Access_Static_IP::set_use_static_ip(bool enabled) {
_useStaticIp = enabled;
}
void setUseStaticIP(bool enabled) {
WiFi_Access_Static_IP tmp_wifi;
tmp_wifi.set_use_static_ip(enabled);
}
// ********************************************************************************
// Functions called on events.
// Make sure not to call anything in these functions that result in delay() or yield()
// ********************************************************************************
void onConnected(const WiFiEventStationModeConnected& event) {
WiFiEventData.markConnected(event.ssid, event.bssid, event.channel);
}
void onConnected(const WiFiEventStationModeConnected& event) { WiFiEventData.markConnected(event.ssid, event.bssid, event.channel); }
void onDisconnect(const WiFiEventStationModeDisconnected& event) {
WiFiEventData.markDisconnect(event.reason);
if (WiFi.status() == WL_CONNECTED) {
// See https://github.com/esp8266/Arduino/issues/5912
WiFi.persistent(false);
@@ -51,65 +45,62 @@ void onDisconnect(const WiFiEventStationModeDisconnected& event) {
}
}
void onGotIP(const WiFiEventStationModeGotIP& event) {
WiFiEventData.markGotIP();
}
void onGotIP(const WiFiEventStationModeGotIP& event) { WiFiEventData.markGotIP(); }
void onDHCPTimeout() {
WiFiEventData.processedDHCPTimeout = false;
}
void onDHCPTimeout() { WiFiEventData.processedDHCPTimeout = false; }
void onConnectedAPmode(const WiFiEventSoftAPModeStationConnected& event) {
WiFiEventData.markConnectedAPmode(event.mac);
}
void onConnectedAPmode(const WiFiEventSoftAPModeStationConnected& event) { WiFiEventData.markConnectedAPmode(event.mac); }
void onDisconnectedAPmode(const WiFiEventSoftAPModeStationDisconnected& event) {
WiFiEventData.markDisconnectedAPmode(event.mac);
}
void onDisconnectedAPmode(const WiFiEventSoftAPModeStationDisconnected& event) { WiFiEventData.markDisconnectedAPmode(event.mac); }
void onStationModeAuthModeChanged(const WiFiEventStationModeAuthModeChanged& event) {
WiFiEventData.setAuthMode(event.newMode);
}
void onStationModeAuthModeChanged(const WiFiEventStationModeAuthModeChanged& event) { WiFiEventData.setAuthMode(event.newMode); }
# if FEATURE_ESP8266_DIRECT_WIFI_SCAN
#if FEATURE_ESP8266_DIRECT_WIFI_SCAN
void onWiFiScanDone(void *arg, STATUS status) {
if (status == OK) {
auto *head = reinterpret_cast<bss_info *>(arg);
int scanCount = 0;
auto *head = reinterpret_cast<bss_info *>(arg);
int scanCount = 0;
for (bss_info *it = head; it != nullptr; it = STAILQ_NEXT(it, next)) {
WiFi_AP_Candidates.process_WiFiscan(*it);
++scanCount;
}
WiFi_AP_Candidates.after_process_WiFiscan();
WiFiEventData.lastGetScanMoment.setNow();
// WiFiEventData.processedScanDone = true;
# ifndef BUILD_NO_DEBUG
/*
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
addLogMove(LOG_LEVEL_INFO, concat(F("WiFi : Scan finished (ESP8266), found: "), scanCount));
}
*/
#endif
// WiFiEventData.processedScanDone = true;
# ifndef BUILD_NO_DEBUG
/*
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
addLogMove(LOG_LEVEL_INFO, concat(F("WiFi : Scan finished (ESP8266), found: "), scanCount));
}
*/
# endif // ifndef BUILD_NO_DEBUG
WiFi_AP_Candidates.load_knownCredentials();
if (WiFi_AP_Candidates.addedKnownCandidate() || !NetworkConnected()) {
WiFiEventData.wifiConnectAttemptNeeded = true;
# ifndef BUILD_NO_DEBUG
# ifndef BUILD_NO_DEBUG
if (WiFi_AP_Candidates.addedKnownCandidate()) {
//addLog(LOG_LEVEL_INFO, F("WiFi : Added known candidate, try to connect"));
// addLog(LOG_LEVEL_INFO, F("WiFi : Added known candidate, try to connect"));
}
#endif
# endif // ifndef BUILD_NO_DEBUG
NetworkConnectRelaxed();
}
}
WiFiMode_t mode = WiFi.getMode();
setWifiMode(WIFI_OFF);
ESPEasy::net::wifi::setWifiMode(WIFI_OFF);
delay(1);
setWifiMode(mode);
ESPEasy::net::wifi::setWifiMode(mode);
delay(1);
}
#endif
# endif // if FEATURE_ESP8266_DIRECT_WIFI_SCAN
#endif
# endif // ifdef ESP8266
#endif // if FEATURE_WIFI
+16 -10
View File
@@ -4,9 +4,11 @@
#ifdef ESP8266
#include "../../ESPEasy_common.h"
# include "../../ESPEasy_common.h"
#include <IPAddress.h>
# if FEATURE_WIFI
# include <IPAddress.h>
// ********************************************************************************
@@ -14,9 +16,11 @@
// See reported issue: https://github.com/esp8266/Arduino/issues/4114
// ********************************************************************************
#include <ESP8266WiFi.h>
#include <ESP8266WiFiSTA.h>
class WiFi_Access_Static_IP : public ESP8266WiFiSTAClass {
# include <ESP8266WiFi.h>
# include <ESP8266WiFiSTA.h>
class WiFi_Access_Static_IP : public ESP8266WiFiSTAClass
{
public:
void set_use_static_ip(bool enabled);
@@ -43,10 +47,12 @@ void onDisconnectedAPmode(const WiFiEventSoftAPModeStationDisconnected& event);
void onStationModeAuthModeChanged(const WiFiEventStationModeAuthModeChanged& event);
#if FEATURE_ESP8266_DIRECT_WIFI_SCAN
void onWiFiScanDone(void *arg, STATUS status);
#endif
# if FEATURE_ESP8266_DIRECT_WIFI_SCAN
void onWiFiScanDone(void *arg,
STATUS status);
# endif // if FEATURE_ESP8266_DIRECT_WIFI_SCAN
#endif
# endif // if FEATURE_WIFI
#endif
#endif // ifdef ESP8266
#endif // ifndef ESPEASY_WIFI_EVENT_ESP8266_H
@@ -0,0 +1,288 @@
#include "../ESPEasyCore/ESPEasyWiFi_state_machine.h"
#if FEATURE_WIFI
# include "../ESPEasyCore/ESPEasyWifi.h"
# include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../ESPEasyCore/ESPEasyNetwork.h" // for setNetworkMedium, however this should not be part of the WiFi code
# include "../Globals/ESPEasyWiFiEvent.h"
# include "../Globals/RTC.h"
# include "../Globals/Settings.h"
# include "../Globals/WiFi_AP_Candidates.h"
# include "../Helpers/StringConverter.h"
namespace ESPEasy {
namespace net {
namespace wifi {
# define WIFI_STATE_MACHINE_STA_CONNECTING_TIMEOUT 20000
# define WIFI_STATE_MACHINE_STA_AP_SCANNING_TIMEOUT 20000
# define WIFI_STATE_MACHINE_STA_SCANNING_TIMEOUT 10000
void ESPEasyWiFi_t::setup() {
// TODO TD-er: Must maybe also call 'disable()' first?
// TODO TD-er: Load settings
// TODO TD-er: Check if settings have changed.
if (_disabledAtBoot) {
disable();
return;
}
WiFi_pre_setup();
begin();
}
void ESPEasyWiFi_t::enable() {}
void ESPEasyWiFi_t::disable() {}
void ESPEasyWiFi_t::begin() {}
void ESPEasyWiFi_t::loop()
{
if (_state != WiFiState_e::IdleWaiting) {
if (_callbackError || (_state_timeout.isSet() && _state_timeout.timeReached()))
{
// TODO TD-er: Must check what error was given???
_callbackError = false;
setState(WiFiState_e::OFF);
}
}
switch (_state)
{
case WiFiState_e::Disabled:
// Do nothing here, as the device is disabled.
break;
case WiFiState_e::OFF:
begin();
setState(WiFiState_e::IdleWaiting, 100);
break;
case WiFiState_e::AP_only:
break;
case WiFiState_e::IdleWaiting:
// Wait for timeout to expire
if (_state_timeout.timeReached()) {
// Do we have candidate to connect to ?
if (WiFi_AP_Candidates.hasCandidates()) {
setState(WiFiState_e::STA_Connecting, WIFI_STATE_MACHINE_STA_CONNECTING_TIMEOUT);
} else if (WifiIsAP(WiFi.getMode())) {
// TODO TD-er: Must check if any client is connected.
// If not, then we can disable AP mode and switch to WiFiState_e::STA_Scanning
setState(WiFiState_e::STA_AP_Scanning, WIFI_STATE_MACHINE_STA_AP_SCANNING_TIMEOUT);
} else {
setState(WiFiState_e::STA_Scanning, WIFI_STATE_MACHINE_STA_SCANNING_TIMEOUT);
}
}
break;
case WiFiState_e::STA_Scanning:
case WiFiState_e::STA_AP_Scanning:
// Check if scanning is finished
// When scanning per channel, call for scanning next channel
break;
case WiFiState_e::STA_Connecting:
case WiFiState_e::STA_Reconnecting:
// Check if (re)connecting has finished
if (getSTA_connected_state() != STA_connected_state::Connecting) {
if (getSTA_connected_state() == STA_connected_state::Connected) {
setState(WiFiState_e::STA_Connected);
} else {
if (_state == WiFiState_e::STA_Connecting) {
setState(WiFiState_e::STA_Reconnecting, WIFI_STATE_MACHINE_STA_CONNECTING_TIMEOUT);
} else {
setState(WiFiState_e::OFF);
}
}
}
break;
case WiFiState_e::STA_Connected:
// Check if still connected
if (getSTA_connected_state() != STA_connected_state::Connected) {
setState(WiFiState_e::OFF);
} else {
// Else mark last timestamp seen as connected
_last_seen_connected.setNow();
}
break;
}
{
// Check if we need to start AP
// Flag captive portal in webserver and/or whether we might be in setup mode
}
# ifdef USE_IMPROV
{
// Check for Improv mode.
}
# endif // ifdef USE_IMPROV
}
IPAddress ESPEasyWiFi_t::getIP() const
{
IPAddress res;
return res;
}
void ESPEasyWiFi_t::disconnect() {}
void ESPEasyWiFi_t::setState(WiFiState_e newState, uint32_t timeout) {
switch (newState)
{
case WiFiState_e::Disabled:
// Do nothing here, as the device is disabled.
break;
case WiFiState_e::OFF:
// TODO TD-er: Must cancel all and turn off WiFi.
break;
case WiFiState_e::AP_only:
break;
case WiFiState_e::IdleWaiting:
// Do nothing here as we're waiting till the timeout is over
break;
case WiFiState_e::STA_Scanning:
// Start scanning
break;
case WiFiState_e::STA_AP_Scanning:
// Start scanning per channel
break;
case WiFiState_e::STA_Connecting:
case WiFiState_e::STA_Reconnecting:
// Start connecting
connectSTA();
break;
case WiFiState_e::STA_Connected:
_last_seen_connected.setNow();
break;
}
if (timeout == 0)
{
_state_timeout.clear();
} else {
_state_timeout.setMillisFromNow(timeout);
}
_last_state_change.setNow();
_state = newState;
}
void ESPEasyWiFi_t::checkConnectProgress() {}
void ESPEasyWiFi_t::startScanning()
{
_state = WiFiState_e::STA_Scanning;
WifiScan(true);
_last_state_change.setNow();
}
bool ESPEasyWiFi_t::connectSTA()
{
if (!WiFi_AP_Candidates.hasCandidateCredentials())
{
if (!WiFiEventData.warnedNoValidWiFiSettings)
{
addLog(LOG_LEVEL_ERROR, F("WIFI : No valid wifi settings"));
WiFiEventData.warnedNoValidWiFiSettings = true;
}
WiFiEventData.last_wifi_connect_attempt_moment.clear();
WiFiEventData.wifi_connect_attempt = 1;
WiFiEventData.wifiConnectAttemptNeeded = false;
// No need to wait longer to start AP mode.
if (!Settings.DoNotStartAP())
{
setAP(true);
}
return false;
}
WiFiEventData.warnedNoValidWiFiSettings = false;
setSTA(true);
# if defined(ESP8266)
wifi_station_set_hostname(NetworkCreateRFCCompliantHostname().c_str());
# endif // if defined(ESP8266)
# if defined(ESP32)
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
# endif // if defined(ESP32)
setConnectionSpeed();
setupStaticIPconfig();
// Start the process of connecting or starting AP
if (!WiFi_AP_Candidates.getNext(true))
{
return false;
}
const WiFi_AP_Candidate candidate = WiFi_AP_Candidates.getCurrent();
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
addLogMove(LOG_LEVEL_INFO, strformat(
F("WIFI : Connecting %s attempt #%u"),
candidate.toString().c_str(),
_connect_attempt));
}
WiFiEventData.markWiFiBegin();
if (prepareWiFi()) {
setNetworkMedium(NetworkMedium_t::WIFI);
RTC.clearLastWiFi();
RTC.lastWiFiSettingsIndex = candidate.index;
float tx_pwr = 0; // Will be set higher based on RSSI when needed.
// FIXME TD-er: Must check WiFiEventData.wifi_connect_attempt to increase TX power
#if FEATURE_SET_WIFI_TX_PWR
if (Settings.UseMaxTXpowerForSending()) {
tx_pwr = Settings.getWiFi_TX_power();
}
SetWiFiTXpower(tx_pwr, candidate.rssi);
#endif
// Start connect attempt now, so no longer needed to attempt new connection.
WiFiEventData.wifiConnectAttemptNeeded = false;
WiFiEventData.wifiConnectInProgress = true;
const String key = WiFi_AP_CandidatesList::get_key(candidate.index);
#if FEATURE_USE_IPV6
if (Settings.EnableIPv6()) {
WiFi.enableIPv6(true);
}
#endif
#ifdef ESP32
if (Settings.IncludeHiddenSSID()) {
setWiFiCountryPolicyManual();
}
#endif
if ((Settings.HiddenSSID_SlowConnectPerBSSID() || !candidate.bits.isHidden)
&& candidate.allowQuickConnect()) {
WiFi.begin(candidate.ssid.c_str(), key.c_str(), candidate.channel, candidate.bssid.mac);
} else {
WiFi.begin(candidate.ssid.c_str(), key.c_str());
}
// Always wait for a second
WiFi.waitForConnectResult(1000); // https://github.com/arendst/Tasmota/issues/14985
}
return true;
}
} // namespace wifi
} // namespace net
} // namespace ESPEasy
#endif // if FEATURE_WIFI
@@ -0,0 +1,128 @@
#pragma once
#include "../../ESPEasy_common.h"
#if FEATURE_WIFI
# include "../DataStructs/WiFi_AP_Candidate.h"
# include "../Helpers/LongTermTimer.h"
# include "../DataTypes/WiFi_STA_connected_state.h"
# include "../DataTypes/WiFi_State.h"
# include <IPAddress.h>
namespace ESPEasy {
namespace net {
namespace wifi {
class ESPEasyWiFi_t
{
public:
// Called after settings have changed or at boot
void setup();
// Start the process of connecting or start AP, depending on the existing configuration.
void enable();
// Terminate WiFi activity
void disable();
private:
void begin();
public:
// Process the state machine for managing WiFi connection
void loop();
WiFiState_e getState() const
{
return _state;
}
// Get the IP-address in this order:
// - STA interface if connected,
// - AP interface if active
// - 0.0.0.0 if neither connected nor active.
IPAddress getIP() const;
void disconnect();
private:
void setState(WiFiState_e newState, uint32_t timeout = 0);
// Handle timeouts + start of AP mode
void checkConnectProgress();
// Check to see if we already have some AP to connect to.
void checkScanningProgress();
void startScanning();
bool connectSTA();
STA_connected_state getSTA_connected_state();
WiFi_AP_Candidate _active_sta;
WiFi_AP_Candidate _AP_conf;
String _last_ssid;
MAC_address _last_bssid;
uint8_t _last_channel = 0;
WiFiState_e _state = WiFiState_e::Disabled;
LongTermTimer _last_state_change;
LongTermTimer _state_timeout;
LongTermTimer _last_seen_connected;
LongTermTimer _AP_start_timestamp;
uint32_t _connect_attempt = 0;
uint32_t _nrReconnects = 0;
bool _callbackError = false;
// Special modes for initial setup or re-configuration of a node via serial port/IMPROV
bool _improvActive = false;
bool _setupActive = false;
// WiFi settings => Move to separate class/struct
bool _disabledAtBoot = false;
bool _passiveScan = false;
bool _includeHiddenSSID = false;
float _TX_power = -1;
// Manual IP settings
// IP
// Gateway
// Subnet
// DNS
// soft AP configuration => TODO TD-er: Implement
// bool _must_Start_AP; // "Do Not Start AP"
// bool _has_ap{false}; // Maybe just check for active mode?
// WiFiAP _ap_config;
// WPA AP mode key
// Don't force /setup in AP-Mode
}; // class ESPEasyWiFi_t
} // namespace wifi
} // namespace net
} // namespace ESPEasy
#endif // if FEATURE_WIFI
@@ -0,0 +1,61 @@
#include "../ESPEasyCore/ESPEasyWiFi_state_machine.h"
#ifdef ESP32
# if FEATURE_WIFI
# include <WiFiGeneric.h>
# include <esp_wifi.h> // Needed to call ESP-IDF functions like esp_wifi_....
# include <esp_phy_init.h>
# include <WiFi.h>
# include <WiFiType.h>
# include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
namespace ESPEasy {
namespace net {
namespace wifi {
STA_connected_state ESPEasyWiFi_t::getSTA_connected_state()
{
switch (WiFi.status())
{
case WL_CONNECTED:
return STA_connected_state::Connected;
case WL_NO_SSID_AVAIL:
return STA_connected_state::Error_Not_Found;
case WL_CONNECT_FAILED:
case WL_CONNECTION_LOST:
return STA_connected_state::Error_Connect_Failed;
case WL_IDLE_STATUS:
return STA_connected_state::Idle;
case WL_NO_SHIELD:
case WL_STOPPED:
case WL_SCAN_COMPLETED:
case WL_DISCONNECTED:
// TODO: what to do here? Do we need an extra connected state?
break;
}
// TODO: Keep track of whether connection is in progress
// The status() function does not return a reply stating "connecting"
/* if (_sta_connecting) {
return STA_connected_state::Connecting;
}
*/
return STA_connected_state::Idle;
}
} // namespace wifi
} // namespace net
} // namespace ESPEasy
# endif // if FEATURE_WIFI
#endif // ifdef ESP32
@@ -0,0 +1,42 @@
#include "../ESPEasyCore/ESPEasyWiFi_state_machine.h"
#ifdef ESP8266
# if FEATURE_WIFI
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
namespace ESPEasy {
namespace net {
namespace wifi {
STA_connected_state ESPEasyWiFi_t::getSTA_connected_state()
{
// Perform check on SDK function, see: https://github.com/esp8266/Arduino/issues/7432
station_status_t status = wifi_station_get_connect_status();
switch (status)
{
case STATION_GOT_IP:
return STA_connected_state::Connected;
case STATION_NO_AP_FOUND:
return STA_connected_state::Error_Not_Found;
case STATION_CONNECT_FAIL:
case STATION_WRONG_PASSWORD:
return STA_connected_state::Error_Connect_Failed;
case STATION_CONNECTING:
return STA_connected_state::Connecting;
case STATION_IDLE:
break;
default:
break;
}
return STA_connected_state::Idle;
}
} // namespace wifi
} // namespace net
} // namespace ESPEasy
# endif // if FEATURE_WIFI
#endif // ifdef ESP8266
+30 -332
View File
@@ -1,5 +1,7 @@
#include "../ESPEasyCore/ESPEasyWifi.h"
#if FEATURE_WIFI
#include "../../ESPEasy-Globals.h"
#include "../DataStructs/TimingStats.h"
#include "../ESPEasyCore/ESPEasyNetwork.h"
@@ -35,129 +37,6 @@
#include <esp_phy_init.h>
#endif
// FIXME TD-er: Cleanup of WiFi code
#ifdef ESPEASY_WIFI_CLEANUP_WORK_IN_PROGRESS
bool ESPEasyWiFi_t::begin() {
return true;
}
void ESPEasyWiFi_t::end() {
}
void ESPEasyWiFi_t::loop() {
switch (_state) {
case WiFiState_e::OFF:
break;
case WiFiState_e::AP_only:
break;
case WiFiState_e::ErrorRecovery:
// Wait for timeout to expire
// Start again from scratch
break;
case WiFiState_e::STA_Scanning:
case WiFiState_e::STA_AP_Scanning:
// Check if scanning is finished
// When scanning per channel, call for scanning next channel
break;
case WiFiState_e::STA_Connecting:
case WiFiState_e::STA_Reconnecting:
// Check if (re)connecting has finished
break;
case WiFiState_e::STA_Connected:
// Check if still connected
// Reconnect if not.
// Else mark last timestamp seen as connected
break;
}
{
// Check if we need to start AP
// Flag captive portal in webserver and/or whether we might be in setup mode
}
#ifdef USE_IMPROV
{
// Check for Improv mode.
}
#endif
}
IPAddress ESPEasyWiFi_t::getIP() const {
IPAddress res;
return res;
}
void ESPEasyWiFi_t::disconnect() {
}
void ESPEasyWiFi_t::checkConnectProgress() {
}
void ESPEasyWiFi_t::startScanning() {
_state = WiFiState_e::STA_Scanning;
WifiScan(true);
_last_state_change.setNow();
}
bool ESPEasyWiFi_t::connectSTA() {
if (!WiFi_AP_Candidates.hasCandidateCredentials()) {
if (!WiFiEventData.warnedNoValidWiFiSettings) {
addLog(LOG_LEVEL_ERROR, F("WIFI : No valid wifi settings"));
WiFiEventData.warnedNoValidWiFiSettings = true;
}
WiFiEventData.last_wifi_connect_attempt_moment.clear();
WiFiEventData.wifi_connect_attempt = 1;
WiFiEventData.wifiConnectAttemptNeeded = false;
// No need to wait longer to start AP mode.
if (!Settings.DoNotStartAP()) {
setAP(true);
}
return false;
}
WiFiEventData.warnedNoValidWiFiSettings = false;
setSTA(true);
#if defined(ESP8266)
wifi_station_set_hostname(NetworkCreateRFCCompliantHostname().c_str());
#endif // if defined(ESP8266)
#if defined(ESP32)
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
#endif // if defined(ESP32)
setConnectionSpeed();
setupStaticIPconfig();
// Start the process of connecting or starting AP
if (WiFi_AP_Candidates.getNext(true)) {
// Try to connect to AP
} else {
// No (known) AP, start scanning
startScanning();
}
return true;
}
#endif // ESPEASY_WIFI_CLEANUP_WORK_IN_PROGRESS
// ********************************************************************************
// WiFi state
@@ -239,7 +118,7 @@ bool WiFiConnected() {
}
#endif
if (!WifiIsSTA(WiFi.getMode())) {
if (! ESPEasy::net::wifi::WifiIsSTA(WiFi.getMode())) {
lastState = false;
return lastState;
}
@@ -265,7 +144,7 @@ bool WiFiConnected() {
if (WiFiEventData.unprocessedWifiEvents()) { return false; }
bool wifi_isconnected = ESPEasy_WiFi_abstraction::WiFiConnected();
bool wifi_isconnected = ESPEasy::net::wifi::WiFiConnected();
if (recursiveCall) return wifi_isconnected;
recursiveCall = true;
@@ -307,12 +186,12 @@ bool WiFiConnected() {
if (WiFiEventData.timerAPoff.isSet() && !WiFiEventData.timerAPoff.timeReached()) {
if (!Settings.DoNotStartAP()) {
// Timer reached, so enable AP mode.
if (!WifiIsAP(WiFi.getMode())) {
if (! ESPEasy::net::wifi::WifiIsAP(WiFi.getMode())) {
if (!WiFiEventData.wifiConnectAttemptNeeded) {
addLog(LOG_LEVEL_INFO, F("WiFi : WiFiConnected(), start AP"));
WifiScan(false);
setSTA(false); // Force reset WiFi + reduce power consumption
setAP(true);
ESPEasy::net::wifi::setSTA(false); // Force reset WiFi + reduce power consumption
ESPEasy::net::wifi::setAP(true);
}
}
}
@@ -324,7 +203,7 @@ bool WiFiConnected() {
// When made this far in the code, we apparently do not have valid WiFi connection.
if (!WiFiEventData.timerAPstart.isSet() && !WifiIsAP(WiFi.getMode())) {
if (!WiFiEventData.timerAPstart.isSet() && ! ESPEasy::net::wifi::WifiIsAP(WiFi.getMode())) {
// First run we do not have WiFi connection any more, set timer to start AP mode
// Only allow the automatic AP mode in the first N minutes after boot.
if (getUptimeMinutes() < WIFI_ALLOW_AP_AFTERBOOT_PERIOD) {
@@ -455,9 +334,9 @@ void AttemptWiFiConnect() {
if (WiFiEventData.unprocessedWifiEvents()) {
return;
}
setSTA(false);
ESPEasy::net::wifi::setSTA(false);
setSTA(true);
ESPEasy::net::wifi::setSTA(true);
if (WiFi_AP_Candidates.getNext(WiFiScanAllowed())) {
const WiFi_AP_Candidate candidate = WiFi_AP_Candidates.getCurrent();
@@ -549,7 +428,7 @@ void AttemptWiFiConnect() {
// Set Wifi config
// ********************************************************************************
bool prepareWiFi() {
ESPEasy_WiFi_abstraction::registerWiFiEventHandler();
ESPEasy::net::wifi::registerWiFiEventHandler();
if (!WiFi_AP_Candidates.hasCandidateCredentials()) {
if (!WiFiEventData.warnedNoValidWiFiSettings) {
@@ -563,12 +442,12 @@ bool prepareWiFi() {
// No need to wait longer to start AP mode.
if (!Settings.DoNotStartAP()) {
WifiScan(false);
// setAP(true);
// ESPEasy::net::wifi::setAP(true);
}
return false;
}
WiFiEventData.warnedNoValidWiFiSettings = false;
setSTA(true);
ESPEasy::net::wifi::setSTA(true);
#if defined(ESP8266)
wifi_station_set_hostname(NetworkCreateRFCCompliantHostname().c_str());
@@ -577,7 +456,7 @@ bool prepareWiFi() {
#if defined(ESP32)
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE);
#endif // if defined(ESP32)
setConnectionSpeed();
ESPEasy::net::wifi::setConnectionSpeed();
setupStaticIPconfig();
WiFiEventData.wifiConnectAttemptNeeded = true;
@@ -653,7 +532,7 @@ void resetWiFi() {
// Send this log only after WifiDisconnect() or else sending to syslog may cause issues
addLog(LOG_LEVEL_INFO, F("Reset WiFi."));
// setWifiMode(WIFI_OFF);
// ESPEasy::net::wifi::setWifiMode(WIFI_OFF);
initWiFi();
}
@@ -670,7 +549,7 @@ void initWiFi()
// WiFi = ESP8266WiFiClass();
#endif // ifdef ESP8266
#ifdef ESP32
ESPEasy_WiFi_abstraction::removeWiFiEventHandler();
ESPEasy::net::wifi::removeWiFiEventHandler();
#endif
@@ -680,12 +559,12 @@ void initWiFi()
WiFi.disconnect(false);
delay(1);
if (active_network_medium != NetworkMedium_t::NotSet) {
setSTA(true);
ESPEasy::net::wifi::setSTA(true);
WifiScan(false);
}
setWifiMode(WIFI_OFF);
ESPEasy::net::wifi::setWifiMode(WIFI_OFF);
ESPEasy_WiFi_abstraction::registerWiFiEventHandler();
ESPEasy::net::wifi::registerWiFiEventHandler();
delay(100);
}
@@ -741,7 +620,7 @@ void SetWiFiTXpower(float dBm, float rssi) {
dBm = minTXpwr;
}
ESPEasy_WiFi_abstraction::SetWiFiTXpower(dBm);
ESPEasy::net::wifi::SetWiFiTXpower(dBm);
if (WiFiEventData.wifi_TX_pwr < dBm) {
// Will increase the TX power, give power supply of the unit some rest
@@ -779,7 +658,7 @@ ESPEasy_WiFi_abstraction::SetWiFiTXpower(dBm);
float GetRSSIthreshold(float& maxTXpwr) {
maxTXpwr = Settings.getWiFi_TX_power();
return ESPEasy_WiFi_abstraction::GetRSSIthreshold(maxTXpwr);
return ESPEasy::net::wifi::GetRSSIthreshold(maxTXpwr);
}
int GetRSSI_quality() {
@@ -793,7 +672,7 @@ int GetRSSI_quality() {
}
WiFiConnectionProtocol getConnectionProtocol() {
return ESPEasy_WiFi_abstraction::getConnectionProtocol();
return ESPEasy::net::wifi::getConnectionProtocol();
}
#ifdef ESP32
@@ -824,7 +703,7 @@ void WifiDisconnect()
# ifndef BUILD_NO_DEBUG
addLog(LOG_LEVEL_INFO, F("WiFi : WifiDisconnect()"));
#endif
ESPEasy_WiFi_abstraction::WiFiDisconnect();
ESPEasy::net::wifi::WiFiDisconnect();
WiFiEventData.setWiFiDisconnected();
WiFiEventData.markDisconnect(WIFI_DISCONNECT_REASON_UNSPECIFIED);
/*
@@ -918,7 +797,7 @@ bool WiFiScanAllowed() {
void WifiScan(bool async, uint8_t channel) {
setSTA(true);
ESPEasy::net::wifi::setSTA(true);
if (!WiFiScanAllowed()) {
return;
}
@@ -1043,7 +922,7 @@ void WiFiScan_log_to_serial()
if (WiFi_AP_Candidates.scanComplete() <= 0) {
WiFiMode_t cur_wifimode = WiFi.getMode();
WifiScan(false);
setWifiMode(cur_wifimode);
ESPEasy::net::wifi::setWifiMode(cur_wifimode);
}
const int8_t scanCompleteStatus = WiFi_AP_Candidates.scanComplete();
@@ -1072,61 +951,10 @@ void WiFiScan_log_to_serial()
serialPrintln("");
}
// ********************************************************************************
// Manage Wifi Modes
// ********************************************************************************
void setSTA(bool enable) {
switch (WiFi.getMode()) {
case WIFI_OFF:
if (enable) { setWifiMode(WIFI_STA); }
break;
case WIFI_STA:
if (!enable) { setWifiMode(WIFI_OFF); }
break;
case WIFI_AP:
if (enable) { setWifiMode(WIFI_AP_STA); }
break;
case WIFI_AP_STA:
if (!enable) { setWifiMode(WIFI_AP); }
break;
default:
break;
}
}
void setAP(bool enable) {
WiFiMode_t wifimode = WiFi.getMode();
switch (wifimode) {
case WIFI_OFF:
if (enable) {
setWifiMode(WIFI_AP);
}
break;
case WIFI_STA:
if (enable) { setWifiMode(WIFI_AP_STA); }
break;
case WIFI_AP:
if (!enable) { setWifiMode(WIFI_OFF); }
break;
case WIFI_AP_STA:
if (!enable) { setWifiMode(WIFI_STA); }
break;
default:
break;
}
}
// Only internal scope
void setAPinternal(bool enable)
void setAPinternal(bool enable)
{
if (enable) {
// create and store unique AP SSID/PW to prevent ESP from starting AP mode with default SSID and No password!
@@ -1146,7 +974,7 @@ void setAPinternal(bool enable)
}
int channel = 1;
if (WifiIsSTA(WiFi.getMode()) && WiFiConnected()) {
if ( ESPEasy::net::wifi::WifiIsSTA(WiFi.getMode()) && WiFiConnected()) {
channel = WiFi.channel();
}
@@ -1188,136 +1016,8 @@ void setAPinternal(bool enable)
}
}
const __FlashStringHelper * getWifiModeString(WiFiMode_t wifimode)
{
switch (wifimode) {
case WIFI_OFF: return F("OFF");
case WIFI_STA: return F("STA");
case WIFI_AP: return F("AP");
case WIFI_AP_STA: return F("AP+STA");
default:
break;
}
return F("Unknown");
}
void setWifiMode(WiFiMode_t new_mode) {
const WiFiMode_t cur_mode = WiFi.getMode();
static WiFiMode_t processing_wifi_mode = cur_mode;
if (cur_mode == new_mode) {
return;
}
if (processing_wifi_mode == new_mode) {
// Prevent loops
return;
}
processing_wifi_mode = new_mode;
if (cur_mode == WIFI_OFF) {
#if defined(ESP32)
// Needs to be set while WiFi is off
WiFi.hostname(NetworkCreateRFCCompliantHostname());
#endif
WiFiEventData.markWiFiTurnOn();
}
if (new_mode != WIFI_OFF) {
#ifdef ESP8266
// See: https://github.com/esp8266/Arduino/issues/6172#issuecomment-500457407
WiFi.forceSleepWake(); // Make sure WiFi is really active.
#endif
delay(100);
} else {
WifiDisconnect();
// delay(100);
processDisconnect();
WiFiEventData.clear_processed_flags();
}
addLog(LOG_LEVEL_INFO, concat(F("WIFI : Set WiFi to "), getWifiModeString(new_mode)));
int retry = 2;
while (!WiFi.mode(new_mode) && retry > 0) {
addLog(LOG_LEVEL_INFO, F("WIFI : Cannot set mode!!!!!"));
delay(100);
--retry;
}
retry = 2;
while (WiFi.getMode() != new_mode && retry > 0) {
addLog(LOG_LEVEL_INFO, F("WIFI : mode not yet set"));
delay(100);
--retry;
}
if (new_mode == WIFI_OFF) {
// FIXME TD-er: Is this correct to mark Turn ON ????
WiFiEventData.markWiFiTurnOn();
#if defined(ESP32)
// Needs to be set while WiFi is off
WiFi.hostname(NetworkCreateRFCCompliantHostname());
#endif
delay(100);
#if defined(ESP32)
esp_wifi_set_ps(WIFI_PS_NONE);
// esp_wifi_set_ps(WIFI_PS_MAX_MODEM);
#endif
#ifdef ESP8266
WiFi.forceSleepBegin();
#endif // ifdef ESP8266
delay(1);
} else {
if (cur_mode == WIFI_OFF) {
ESPEasy_WiFi_abstraction::registerWiFiEventHandler();
}
// Only set power mode when AP is not enabled
// When AP is enabled, the sleep mode is already set to WIFI_NONE_SLEEP
if (!WifiIsAP(new_mode)) {
if (Settings.WifiNoneSleep()) {
ESPEasy_WiFi_abstraction::setWiFiNoneSleep();
} else if (Settings.EcoPowerMode()) {
ESPEasy_WiFi_abstraction::setWiFiEcoPowerMode();
} else {
// Default
ESPEasy_WiFi_abstraction::setWiFiDefaultPowerMode();
}
}
#if FEATURE_SET_WIFI_TX_PWR
SetWiFiTXpower();
#endif
if (WifiIsSTA(new_mode)) {
// WiFi.setAutoConnect(Settings.SDK_WiFi_autoreconnect());
WiFi.setAutoReconnect(Settings.SDK_WiFi_autoreconnect());
}
delay(100); // Must allow for some time to init.
}
const bool new_mode_AP_enabled = WifiIsAP(new_mode);
if (WifiIsAP(cur_mode) && !new_mode_AP_enabled) {
eventQueue.add(F("WiFi#APmodeDisabled"));
}
if (WifiIsAP(cur_mode) != new_mode_AP_enabled) {
// Mode has changed
setAPinternal(new_mode_AP_enabled);
}
#if FEATURE_MDNS
#ifdef ESP8266
// notifyAPChange() is not present in the ESP32 MDNSResponder
MDNS.notifyAPChange();
#endif
#endif
}
bool WifiIsAP(WiFiMode_t wifimode)
{
return ESPEasy_WiFi_abstraction::WifiIsAP(wifimode);
}
bool WifiIsSTA(WiFiMode_t wifimode)
{
return ESPEasy_WiFi_abstraction::WifiIsSTA(wifimode);
}
bool WiFiUseStaticIP() {
return Settings.IP[0] != 0 && Settings.IP[0] != 255;
@@ -1325,7 +1025,7 @@ bool WiFiUseStaticIP() {
bool wifiAPmodeActivelyUsed()
{
if (!WifiIsAP(WiFi.getMode()) || (!WiFiEventData.timerAPoff.isSet())) {
if (! ESPEasy::net::wifi::WifiIsAP(WiFi.getMode()) || (!WiFiEventData.timerAPoff.isSet())) {
// AP not active or soon to be disabled in processDisableAPmode()
return false;
}
@@ -1335,10 +1035,6 @@ bool wifiAPmodeActivelyUsed()
// reconnect?
}
void setConnectionSpeed() {
ESPEasy_WiFi_abstraction::setConnectionSpeed(Settings.ForceWiFi_bg_mode());
}
void setupStaticIPconfig() {
setUseStaticIP(WiFiUseStaticIP());
@@ -1443,3 +1139,5 @@ void logConnectionStatus() {
*/
#endif // ifndef BUILD_NO_DEBUG
}
#endif
+52 -118
View File
@@ -3,106 +3,36 @@
#include "../../ESPEasy_common.h"
#if defined(ESP8266)
# include <ESP8266WiFi.h>
#endif // if defined(ESP8266)
#if defined(ESP32)
# include <WiFi.h>
#endif // if defined(ESP32)
#if FEATURE_WIFI
#include "../DataTypes/WiFiConnectionProtocol.h"
#include "../DataStructs/WiFi_AP_Candidate.h"
# if defined(ESP8266)
# include <ESP8266WiFi.h>
# endif // if defined(ESP8266)
# if defined(ESP32)
# include <WiFi.h>
# endif // if defined(ESP32)
#include "../Helpers/LongTermTimer.h"
# include "../DataTypes/WiFiConnectionProtocol.h"
# include "../DataStructs/WiFi_AP_Candidate.h"
#define WIFI_RECONNECT_WAIT 30000 // in milliSeconds
#define WIFI_AP_OFF_TIMER_DURATION 300000 // in milliSeconds
#if FEATURE_CUSTOM_PROVISIONING
#define WIFI_CONNECTION_CONSIDERED_STABLE 60000 // in milliSeconds
#else
#define WIFI_CONNECTION_CONSIDERED_STABLE 60000 // in milliSeconds
#endif
#define WIFI_ALLOW_AP_AFTERBOOT_PERIOD 5 // in minutes
#define WIFI_SCAN_INTERVAL_AP_USED 125000 // in milliSeconds
#define WIFI_SCAN_INTERVAL_MINIMAL 60000 // in milliSeconds
# include "../Helpers/LongTermTimer.h"
# define WIFI_RECONNECT_WAIT 30000 // in milliSeconds
# define WIFI_AP_OFF_TIMER_DURATION 300000 // in milliSeconds
# if FEATURE_CUSTOM_PROVISIONING
# define WIFI_CONNECTION_CONSIDERED_STABLE 60000 // in milliSeconds
# else
# define WIFI_CONNECTION_CONSIDERED_STABLE 60000 // in milliSeconds
# endif // if FEATURE_CUSTOM_PROVISIONING
# define WIFI_ALLOW_AP_AFTERBOOT_PERIOD 5 // in minutes
# define WIFI_SCAN_INTERVAL_AP_USED 125000 // in milliSeconds
# define WIFI_SCAN_INTERVAL_MINIMAL 60000 // in milliSeconds
#ifdef ESPEASY_WIFI_CLEANUP_WORK_IN_PROGRESS
enum class WiFiState_e {
// WiFi radio off
OFF,
// Only running in AP mode
AP_only,
// WiFi was in some kind of error state, waiting period
ErrorRecovery,
// STA mode + scanning
STA_Scanning,
// STA+AP mode + scanning,
// needs some careful handling to prevent disconnecting the connected stations
STA_AP_Scanning,
// Connecting to an AP
STA_Connecting,
// Reconnecting to an AP
// May need to handle some specific disconnect reasons differently from connecting for the first time.
STA_Reconnecting,
// Connected to an AP
STA_Connected
};
# ifdef ESPEASY_WIFI_CLEANUP_WORK_IN_PROGRESS
class ESPEasyWiFi_t {
public:
// Start the process of connecting or start AP, depending on the existing configuration.
bool begin();
// Terminate WiFi activity
void end();
// Process the state machine for managing WiFi connection
void loop();
WiFiState_e getState() const { return _state; }
// Get the IP-address in this order:
// - STA interface if connected,
// - AP interface if active
// - 0.0.0.0 if neither connected nor active.
IPAddress getIP() const;
void disconnect();
private:
// Handle timeouts + start of AP mode
void checkConnectProgress();
// Check to see if we already have some AP to connect to.
void checkScanningProgress();
void startScanning();
bool connectSTA();
WiFi_AP_Candidate _active_sta;
WiFi_AP_Candidate _AP_conf;
String _last_ssid;
MAC_address _last_bssid;
uint8_t _last_channel = 0;
WiFiState_e _state = WiFiState_e::OFF;
LongTermTimer _last_state_change;
LongTermTimer _last_seen_connected;
};
#endif // ESPEASY_WIFI_CLEANUP_WORK_IN_PROGRESS
# endif // ESPEASY_WIFI_CLEANUP_WORK_IN_PROGRESS
bool WiFiConnected();
void WiFiConnectRelaxed();
@@ -113,41 +43,45 @@ void resetWiFi();
void initWiFi();
#if FEATURE_SET_WIFI_TX_PWR
void SetWiFiTXpower();
void SetWiFiTXpower(float dBm); // 0-20.5
void SetWiFiTXpower(float dBm, float rssi);
#endif
# if FEATURE_SET_WIFI_TX_PWR
void SetWiFiTXpower();
void SetWiFiTXpower(float dBm); // 0-20.5
void SetWiFiTXpower(float dBm,
float rssi);
# endif // if FEATURE_SET_WIFI_TX_PWR
float GetRSSIthreshold(float& maxTXpwr);
// Return some quality based on RSSI.
// <-97 => 0 , >-50 => 10
// -97 ... -50 => 1 ... 9
int GetRSSI_quality();
int GetRSSI_quality();
WiFiConnectionProtocol getConnectionProtocol();
#ifdef ESP32
# ifdef ESP32
// TSF time is 64-bit timer in usec, sent by the AP along with other packets.
// On tested access points, this seems to be the uptime in usec.
// Could be used among nodes connected to the same AP to increase time sync accuracy.
int64_t WiFi_get_TSF_time();
#endif
void WifiDisconnect();
bool WiFiScanAllowed();
void WifiScan(bool async, uint8_t channel = 0);
void WiFiScan_log_to_serial();
void setSTA(bool enable);
void setAP(bool enable);
const __FlashStringHelper * getWifiModeString(WiFiMode_t wifimode);
void setWifiMode(WiFiMode_t wifimode);
bool WifiIsAP(WiFiMode_t wifimode);
bool WifiIsSTA(WiFiMode_t wifimode);
bool WiFiUseStaticIP();
bool wifiAPmodeActivelyUsed();
void setConnectionSpeed();
void setupStaticIPconfig();
String formatScanResult(int i, const String& separator);
String formatScanResult(int i, const String& separator, int32_t& rssi);
# endif // ifdef ESP32
void WifiDisconnect();
bool WiFiScanAllowed();
void WifiScan(bool async,
uint8_t channel = 0);
void WiFiScan_log_to_serial();
void setAPinternal(bool enable); // FIXME TD-er: Move to ESPEasyWifi_abstracted...
bool WiFiUseStaticIP();
bool wifiAPmodeActivelyUsed();
void setupStaticIPconfig();
String formatScanResult(int i,
const String& separator);
String formatScanResult(int i,
const String& separator,
int32_t & rssi);
void logConnectionStatus();
#endif // if FEATURE_WIFI
#endif // ESPEASY_WIFI_H
#endif // ESPEASY_WIFI_H
+112 -76
View File
@@ -3,10 +3,11 @@
#include "../../ESPEasy-Globals.h"
#if FEATURE_ETHERNET
#include "../ESPEasyCore/ESPEasyEth_ProcessEvent.h"
# include "../ESPEasyCore/ESPEasyEth_ProcessEvent.h"
#endif
#include "../ESPEasyCore/ESPEasyNetwork.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../Globals/ESPEasyWiFiEvent.h"
#include "../Globals/ESPEasy_Scheduler.h"
@@ -39,7 +40,6 @@
#include "../WebServer/ESPEasy_WebServer.h"
// ********************************************************************************
// Called from the loop() to make sure events are processed as soon as possible.
// These functions are called from Setup() or Loop() and thus may call delay() or yield()
@@ -52,39 +52,45 @@ void handle_unprocessedNetworkEvents()
if (active_network_medium == NetworkMedium_t::WIFI) {
const bool should_be_initialized = (WiFiEventData.WiFiGotIP() && WiFiEventData.WiFiConnected()) || NetworkConnected();
if (WiFiEventData.WiFiServicesInitialized() != should_be_initialized)
{
if (!WiFiEventData.WiFiServicesInitialized()) {
WiFiEventData.processedDHCPTimeout = true; // FIXME TD-er: Find out when this happens (happens on ESP32 sometimes)
WiFiEventData.processedDHCPTimeout = true; // FIXME TD-er: Find out when this happens (happens on ESP32 sometimes)
if (WiFiConnected()) {
if (!WiFiEventData.WiFiGotIP()) {
# ifndef BUILD_NO_DEBUG
#ifndef BUILD_NO_DEBUG
addLog(LOG_LEVEL_DEBUG, F("WiFi : Missed gotIP event"));
#endif
WiFiEventData.processedGotIP = false;
processGotIP();
}
if (!WiFiEventData.WiFiConnected()) {
# ifndef BUILD_NO_DEBUG
#ifndef BUILD_NO_DEBUG
addLog(LOG_LEVEL_DEBUG, F("WiFi : Missed connected event"));
#endif
WiFiEventData.processedConnect = false;
processConnect();
}
// Apparently we are connected, so no need to process any late disconnect event
WiFiEventData.processedDisconnect = true;
}
}
WiFiEventData.setWiFiServicesInitialized();
//#ifdef ESP32
// #ifdef ESP32
setWebserverRunning(false);
delay(1);
setWebserverRunning(true);
delay(1);
/*
#else
CheckRunningServices();
#endif
*/
/*
#else
CheckRunningServices();
#endif
*/
}
}
}
@@ -104,7 +110,7 @@ void handle_unprocessedNetworkEvents()
// WiFi connection is not yet available, so introduce some extra delays to
// help the background tasks managing wifi connections
delay(0);
if (!WiFiEventData.processedConnect) {
#ifndef BUILD_NO_DEBUG
addLog(LOG_LEVEL_DEBUG, F("WIFI : Entering processConnect()"));
@@ -127,12 +133,13 @@ void handle_unprocessedNetworkEvents()
WifiDisconnect();
}
if (WiFi.status() == WL_DISCONNECTED && WiFiEventData.wifiConnectInProgress) {
if (WiFiEventData.last_wifi_connect_attempt_moment.isSet() &&
if ((WiFi.status() == WL_DISCONNECTED) && WiFiEventData.wifiConnectInProgress) {
if (WiFiEventData.last_wifi_connect_attempt_moment.isSet() &&
WiFiEventData.last_wifi_connect_attempt_moment.timeoutReached(DEFAULT_WIFI_CONNECTION_TIMEOUT)) {
logConnectionStatus();
resetWiFi();
}
if (!WiFiEventData.last_wifi_connect_attempt_moment.isSet()) {
WiFiEventData.wifiConnectInProgress = false;
}
@@ -152,9 +159,10 @@ void handle_unprocessedNetworkEvents()
if (loglevelActiveFor(LOG_LEVEL_DEBUG)) {
static LongTermTimer lastDisconnectMoment_log;
static uint8_t lastWiFiStatus_log = 0;
uint8_t cur_wifi_status = WiFi.status();
if (WiFiEventData.lastDisconnectMoment.get() != lastDisconnectMoment_log.get() ||
lastWiFiStatus_log != cur_wifi_status) {
uint8_t cur_wifi_status = WiFi.status();
if ((WiFiEventData.lastDisconnectMoment.get() != lastDisconnectMoment_log.get()) ||
(lastWiFiStatus_log != cur_wifi_status)) {
lastDisconnectMoment_log.set(WiFiEventData.lastDisconnectMoment.get());
lastWiFiStatus_log = cur_wifi_status;
String wifilog = F("WIFI : Disconnected: WiFi.status() = ");
@@ -162,13 +170,13 @@ void handle_unprocessedNetworkEvents()
wifilog += F(" RSSI: ");
wifilog += String(WiFi.RSSI());
wifilog += F(" status: ");
#ifdef ESP8266
# ifdef ESP8266
station_status_t status = wifi_station_get_connect_status();
wifilog += SDKwifiStatusToString(status);
#endif
#ifdef ESP32
# endif // ifdef ESP8266
# ifdef ESP32
wifilog += ArduinoWifiStatusToString(WiFi.status());
#endif
# endif
addLogMove(LOG_LEVEL_DEBUG, wifilog);
}
}
@@ -191,7 +199,7 @@ void handle_unprocessedNetworkEvents()
if (WiFiEventData.WiFiServicesInitialized()) {
if (WiFiEventData.lastConnectMoment.isSet() && WiFiEventData.lastConnectMoment.timeoutReached(WIFI_CONNECTION_CONSIDERED_STABLE)) {
// Connection considered stable
WiFiEventData.wifi_connect_attempt = 0;
WiFiEventData.wifi_connect_attempt = 0;
WiFiEventData.wifi_considered_stable = true;
WiFi_AP_Candidates.markCurrentConnectionStable();
@@ -226,12 +234,12 @@ void processDisconnect() {
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
String log = strformat(
F("WIFI : Disconnected! Reason: '%s'"),
F("WIFI : Disconnected! Reason: '%s'"),
getLastDisconnectReason().c_str());
if (WiFiEventData.lastConnectedDuration_us > 0) {
log += concat(
F(" Connected for "),
F(" Connected for "),
format_msec_duration(WiFiEventData.lastConnectedDuration_us / 1000ll));
}
addLogMove(LOG_LEVEL_INFO, log);
@@ -239,14 +247,14 @@ void processDisconnect() {
logConnectionStatus();
if (WiFiEventData.processingDisconnect.isSet()) {
if (WiFiEventData.processingDisconnect.millisPassedSince() > 5000 || WiFiEventData.processedDisconnect) {
if ((WiFiEventData.processingDisconnect.millisPassedSince() > 5000) || WiFiEventData.processedDisconnect) {
WiFiEventData.processedDisconnect = true;
WiFiEventData.processingDisconnect.clear();
}
}
if (WiFiEventData.processedDisconnect ||
if (WiFiEventData.processedDisconnect ||
WiFiEventData.processingDisconnect.isSet()) { return; }
WiFiEventData.processingDisconnect.setNow();
WiFiEventData.setWiFiDisconnected();
@@ -260,36 +268,42 @@ void processDisconnect() {
// FIXME TD-er: With AutoReconnect enabled, WiFi must be reset or else we completely loose track of the actual WiFi state
bool mustRestartWiFi = Settings.WiFiRestart_connection_lost() || WiFi.getAutoReconnect();
if (WiFiEventData.lastConnectedDuration_us > 0 && (WiFiEventData.lastConnectedDuration_us / 1000) < 5000) {
if (!WiFi_AP_Candidates.getBestCandidate().usable())
// addLog(LOG_LEVEL_INFO, F("WIFI : !getBestCandidate().usable() => mustRestartWiFi = true"));
if ((WiFiEventData.lastConnectedDuration_us > 0) && ((WiFiEventData.lastConnectedDuration_us / 1000) < 5000)) {
if (!WiFi_AP_Candidates.getBestCandidate().usable()) {
// addLog(LOG_LEVEL_INFO, F("WIFI : !getBestCandidate().usable() => mustRestartWiFi = true"));
mustRestartWiFi = true;
}
}
if (WiFi.status() == WL_IDLE_STATUS) {
// addLog(LOG_LEVEL_INFO, F("WIFI : WiFi.status() == WL_IDLE_STATUS => mustRestartWiFi = true"));
// addLog(LOG_LEVEL_INFO, F("WIFI : WiFi.status() == WL_IDLE_STATUS => mustRestartWiFi = true"));
mustRestartWiFi = true;
}
#ifdef USES_ESPEASY_NOW
if (use_EspEasy_now) {
// mustRestartWiFi = true;
// mustRestartWiFi = true;
}
#endif
//WifiDisconnect(); // Needed or else node may not reconnect reliably.
#endif // ifdef USES_ESPEASY_NOW
// WifiDisconnect(); // Needed or else node may not reconnect reliably.
if (mustRestartWiFi) {
WiFiEventData.processedDisconnect = true;
resetWiFi();
// WifiScan(false);
// delay(100);
// setWifiMode(WIFI_OFF);
// initWiFi();
// delay(100);
// WifiScan(false);
// delay(100);
// ESPEasy::net::wifi::setWifiMode(WIFI_OFF);
// initWiFi();
// delay(100);
}
// delay(500);
// delay(500);
logConnectionStatus();
WiFiEventData.processedDisconnect = true;
WiFiEventData.processingDisconnect.clear();
@@ -297,11 +311,13 @@ void processDisconnect() {
void processConnect() {
if (WiFiEventData.processedConnect) { return; }
//delay(100); // FIXME TD-er: See https://github.com/letscontrolit/ESPEasy/issues/1987#issuecomment-451644424
// delay(100); // FIXME TD-er: See https://github.com/letscontrolit/ESPEasy/issues/1987#issuecomment-451644424
if (checkAndResetWiFi()) {
return;
}
WiFiEventData.processedConnect = true;
if (WiFi.status() == WL_DISCONNECTED) {
// Apparently not really connected
return;
@@ -315,21 +331,24 @@ void processConnect() {
const bool mustResetCredentials = CUSTOM_EMERGENCY_FALLBACK_RESET_CREDENTIALS;
#else
const bool mustResetCredentials = false;
#endif
#endif // ifdef CUSTOM_EMERGENCY_FALLBACK_RESET_CREDENTIALS
#ifdef CUSTOM_EMERGENCY_FALLBACK_START_AP
const bool mustStartAP = CUSTOM_EMERGENCY_FALLBACK_START_AP;
#else
const bool mustStartAP = false;
#endif
#endif // ifdef CUSTOM_EMERGENCY_FALLBACK_START_AP
if (mustStartAP) {
int allowedUptimeMinutes = 10;
#ifdef CUSTOM_EMERGENCY_FALLBACK_ALLOW_MINUTES_UPTIME
allowedUptimeMinutes = CUSTOM_EMERGENCY_FALLBACK_ALLOW_MINUTES_UPTIME;
#endif
if (getUptimeMinutes() < allowedUptimeMinutes) {
WiFiEventData.timerAPstart.setNow();
}
}
if (mustResetCredentials && !WiFiEventData.performedClearWiFiCredentials) {
WiFiEventData.performedClearWiFiCredentials = true;
SecuritySettings.clearWiFiCredentials();
@@ -341,7 +360,7 @@ void processConnect() {
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
const LongTermTimer::Duration connect_duration = WiFiEventData.last_wifi_connect_attempt_moment.timeDiff(WiFiEventData.lastConnectMoment);
String log = strformat(
String log = strformat(
F("WIFI : Connected! AP: %s (%s) Ch: %d"),
WiFi.SSID().c_str(),
WiFi.BSSIDstr().c_str(),
@@ -356,7 +375,7 @@ void processConnect() {
addLogMove(LOG_LEVEL_INFO, log);
}
// WiFiEventData.last_wifi_connect_attempt_moment.clear();
// WiFiEventData.last_wifi_connect_attempt_moment.clear();
if (Settings.UseRules) {
if (WiFiEventData.bssid_changed) {
@@ -366,7 +385,7 @@ void processConnect() {
if (WiFiEventData.channel_changed) {
eventQueue.add(F("WiFi#ChangedWiFichannel"));
}
}
}
if (useStaticIP()) {
WiFiEventData.markGotIP(); // in static IP config the got IP event is never fired.
@@ -380,6 +399,7 @@ void processGotIP() {
if (WiFiEventData.processedGotIP) {
return;
}
if (checkAndResetWiFi()) {
return;
}
@@ -388,15 +408,17 @@ void processGotIP() {
if (!useStaticIP()) {
#ifdef ESP8266
if (!ip.isSet()) {
#else
if (ip[0] == 0 && ip[1] == 0 && ip[2] == 0 && ip[3] == 0) {
#endif
#else // ifdef ESP8266
if ((ip[0] == 0) && (ip[1] == 0) && (ip[2] == 0) && (ip[3] == 0)) {
#endif // ifdef ESP8266
return;
}
}
const IPAddress gw = WiFi.gatewayIP();
const IPAddress subnet = WiFi.subnetMask();
const IPAddress gw = WiFi.gatewayIP();
const IPAddress subnet = WiFi.subnetMask();
const LongTermTimer::Duration dhcp_duration = WiFiEventData.lastConnectMoment.timeDiff(WiFiEventData.lastGetIPmoment);
WiFiEventData.dns0_cache = WiFi.dnsIP(0);
WiFiEventData.dns1_cache = WiFi.dnsIP(1);
@@ -462,17 +484,22 @@ void processGotIP() {
}
#if FEATURE_USE_IPV6
void processGotIPv6() {
if (!WiFiEventData.processedGotIP6) {
WiFiEventData.processedGotIP6 = true;
if (loglevelActiveFor(LOG_LEVEL_INFO))
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
addLog(LOG_LEVEL_INFO, String(F("WIFI : STA got IP6 ")) + WiFiEventData.unprocessed_IP6.toString(true));
#if FEATURE_ESPEASY_P2P
// updateUDPport(true);
#endif
}
# if FEATURE_ESPEASY_P2P
// updateUDPport(true);
# endif // if FEATURE_ESPEASY_P2P
}
}
#endif
#endif // if FEATURE_USE_IPV6
// A client disconnected from the AP on this node.
void processDisconnectAPmode() {
@@ -480,6 +507,7 @@ void processDisconnectAPmode() {
WiFiEventData.processedDisconnectAPmode = true;
#ifndef BUILD_NO_DEBUG
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
const int nrStationsConnected = WiFi.softAPgetStationNum();
String log = F("AP Mode: Client disconnected: ");
@@ -488,16 +516,18 @@ void processDisconnectAPmode() {
log += nrStationsConnected;
addLogMove(LOG_LEVEL_INFO, log);
}
#endif
#endif // ifndef BUILD_NO_DEBUG
}
// Client connects to AP on this node
void processConnectAPmode() {
if (WiFiEventData.processedConnectAPmode) { return; }
WiFiEventData.processedConnectAPmode = true;
// Extend timer to switch off AP.
WiFiEventData.timerAPoff.setMillisFromNow(WIFI_AP_OFF_TIMER_DURATION);
#ifndef BUILD_NO_DEBUG
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
String log = F("AP Mode: Client connected: ");
log += WiFiEventData.lastMacConnectedAPmode.toString();
@@ -505,9 +535,10 @@ void processConnectAPmode() {
log += WiFi.softAPgetStationNum();
addLogMove(LOG_LEVEL_INFO, log);
}
#endif
#endif // ifndef BUILD_NO_DEBUG
#if FEATURE_DNS_SERVER
// Start DNS, only used if the ESP has no valid WiFi config
// It will reply with it's own address on all DNS requests
// (captive portal concept)
@@ -522,16 +553,18 @@ void processConnectAPmode() {
void processDisableAPmode() {
if (!WiFiEventData.timerAPoff.isSet()) { return; }
if (!WifiIsAP(WiFi.getMode())) {
if (!ESPEasy::net::wifi::WifiIsAP(WiFi.getMode())) {
return;
}
// disable AP after timeout and no clients connected.
if (WiFiEventData.timerAPoff.timeReached() && (WiFi.softAPgetStationNum() == 0)) {
setAP(false);
ESPEasy::net::wifi::setAP(false);
}
if (!WifiIsAP(WiFi.getMode())) {
if (!ESPEasy::net::wifi::WifiIsAP(WiFi.getMode())) {
WiFiEventData.timerAPoff.clear();
if (WiFiEventData.wifiConnectAttemptNeeded) {
// Force a reconnect cycle
WifiDisconnect();
@@ -541,24 +574,28 @@ void processDisableAPmode() {
void processScanDone() {
WiFi_AP_Candidates.load_knownCredentials();
if (WiFiEventData.processedScanDone) { return; }
if (WiFiEventData.processedScanDone) { return; }
// Better act on the scan done event, as it may get triggered for normal wifi begin calls.
int8_t scanCompleteStatus = WiFi.scanComplete();
switch (scanCompleteStatus) {
switch (scanCompleteStatus)
{
case 0: // Nothing (yet) found
if (WiFiEventData.lastGetScanMoment.timeoutReached(5000)) {
WiFi.scanDelete();
WiFiEventData.processedScanDone = true;
}
return;
case -1: // WIFI_SCAN_RUNNING
// FIXME TD-er: Set timeout...
if (WiFiEventData.lastGetScanMoment.timeoutReached(5000)) {
# ifndef BUILD_NO_DEBUG
addLog(LOG_LEVEL_ERROR, F("WiFi : Scan Running Timeout"));
#ifndef BUILD_NO_DEBUG
addLog(LOG_LEVEL_ERROR, F("WiFi : Scan Running Timeout"));
#endif
WiFi.scanDelete();
WiFiEventData.processedScanDone = true;
@@ -573,11 +610,12 @@ void processScanDone() {
WiFiEventData.lastGetScanMoment.setNow();
WiFiEventData.processedScanDone = true;
# ifndef BUILD_NO_DEBUG
#ifndef BUILD_NO_DEBUG
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
addLogMove(LOG_LEVEL_INFO, concat(F("WiFi : Scan finished, found: "), scanCompleteStatus));
}
#endif
#endif // ifndef BUILD_NO_DEBUG
#if !FEATURE_ESP8266_DIRECT_WIFI_SCAN
WiFi_AP_Candidates.process_WiFiscan(scanCompleteStatus);
@@ -587,14 +625,16 @@ void processScanDone() {
if (WiFi_AP_Candidates.addedKnownCandidate() && !NetworkConnected()) {
if (!WiFiEventData.wifiConnectInProgress) {
WiFiEventData.wifiConnectAttemptNeeded = true;
# ifndef BUILD_NO_DEBUG
#ifndef BUILD_NO_DEBUG
if (WiFi_AP_Candidates.addedKnownCandidate()) {
addLog(LOG_LEVEL_INFO, F("WiFi : Added known candidate, try to connect"));
}
#endif
#endif // ifndef BUILD_NO_DEBUG
#ifdef ESP32
// setSTA(false);
#endif
// ESPEasy::net::wifi::setSTA(false);
#endif // ifdef ESP32
NetworkConnectRelaxed();
#ifdef USES_ESPEASY_NOW
temp_disable_EspEasy_now_timer = millis() + 20000;
@@ -605,7 +645,3 @@ void processScanDone() {
}
}
@@ -0,0 +1,151 @@
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#if FEATURE_WIFI
# include "../Globals/EventQueue.h"
# include "../Globals/Settings.h"
# include "../Globals/ESPEasyWiFiEvent.h"
# include "../Helpers/StringConverter.h"
namespace ESPEasy {
namespace net {
namespace wifi {
const __FlashStringHelper* getWifiModeString(WiFiMode_t wifimode)
{
switch (wifimode)
{
case WIFI_OFF: return F("OFF");
case WIFI_STA: return F("STA");
case WIFI_AP: return F("AP");
case WIFI_AP_STA: return F("AP+STA");
default:
break;
}
return F("Unknown");
}
bool setSTA(bool enable) { return setSTA_AP(enable, WifiIsAP(WiFi.getMode())); }
bool setAP(bool enable) { return setSTA_AP(WifiIsSTA(WiFi.getMode()), enable); }
bool setSTA_AP(bool sta_enable, bool ap_enable)
{
if (ap_enable) {
return setWifiMode(sta_enable ? WIFI_AP_STA : WIFI_AP);
}
return setWifiMode(sta_enable ? WIFI_STA : WIFI_OFF);
}
// ********************************************************************************
// Configure WiFi TX power
// ********************************************************************************
# if FEATURE_SET_WIFI_TX_PWR
void SetWiFiTXpower() {
SetWiFiTXpower(0); // Just some minimal value, will be adjusted in SetWiFiTXpower
}
void SetWiFiTXpower(float dBm) { SetWiFiTXpower(dBm, WiFi.RSSI()); }
void SetWiFiTXpower(float dBm, float rssi) {
const WiFiMode_t cur_mode = WiFi.getMode();
if (cur_mode == WIFI_OFF) {
return;
}
if (Settings.UseMaxTXpowerForSending()) {
dBm = 30; // Just some max, will be limited later
}
// Range ESP32 : -1dBm - 20dBm
// Range ESP8266: 0dBm - 20.5dBm
float maxTXpwr;
float threshold = GetRSSIthreshold(maxTXpwr);
# ifdef ESP8266
float minTXpwr{};
# endif
# ifdef ESP32
float minTXpwr = -1.0f;
# endif
threshold += Settings.WiFi_sensitivity_margin; // Margin in dBm on top of threshold
// Assume AP sends with max set by ETSI standard.
// 2.4 GHz: 100 mWatt (20 dBm)
// US and some other countries allow 1000 mW (30 dBm)
// We cannot send with over 20 dBm, thus it makes no sense to force higher TX power all the time.
const float newrssi = rssi - 20;
if (newrssi < threshold) {
minTXpwr = threshold - newrssi;
}
if (minTXpwr > maxTXpwr) {
minTXpwr = maxTXpwr;
}
if (dBm > maxTXpwr) {
dBm = maxTXpwr;
} else if (dBm < minTXpwr) {
dBm = minTXpwr;
}
doSetWiFiTXpower(dBm);
if (WiFiEventData.wifi_TX_pwr < dBm) {
// Will increase the TX power, give power supply of the unit some rest
delay(1);
}
WiFiEventData.wifi_TX_pwr = dBm;
delay(0);
# ifndef BUILD_NO_DEBUG
if (loglevelActiveFor(LOG_LEVEL_DEBUG)) {
const int TX_pwr_int = WiFiEventData.wifi_TX_pwr * 4;
const int maxTXpwr_int = maxTXpwr * 4;
if (TX_pwr_int != maxTXpwr_int) {
static int last_log = -1;
if (TX_pwr_int != last_log) {
last_log = TX_pwr_int;
String log = strformat(
F("WiFi : Set TX power to %ddBm sensitivity: %ddBm"),
static_cast<int>(dBm),
static_cast<int>(threshold));
if (rssi < 0) {
log += strformat(F(" RSSI: %ddBm"), static_cast<int>(rssi));
}
addLogMove(LOG_LEVEL_DEBUG, log);
}
}
}
# endif // ifndef BUILD_NO_DEBUG
}
# endif // if FEATURE_SET_WIFI_TX_PWR
int GetRSSI_quality() {
long rssi = WiFi.RSSI();
if (-50 < rssi) { return 10; }
if (rssi <= -98) { return 0; }
rssi = rssi + 97; // Range 0..47 => 1..9
return (rssi / 5) + 1;
}
void setConnectionSpeed() { setConnectionSpeed(Settings.ForceWiFi_bg_mode()); }
} // namespace wifi
} // namespace net
} // namespace ESPEasy
#endif // if FEATURE_WIFI
+69 -18
View File
@@ -3,27 +3,60 @@
#include "../../ESPEasy_common.h"
#if FEATURE_WIFI
#include "../DataTypes/WiFiConnectionProtocol.h"
# include "../DataTypes/WiFiConnectionProtocol.h"
# include "../DataTypes/WiFi_STA_connected_state.h"
# include "../DataTypes/WiFi_State.h"
#if defined(ESP8266)
#include "../ESPEasyCore/ESPEasyWiFiEvent_ESP8266.h"
# include <ESP8266WiFi.h>
#endif // if defined(ESP8266)
#if defined(ESP32)
#include "../ESPEasyCore/ESPEasyWiFiEvent_ESP32.h"
# include <WiFi.h>
#endif // if defined(ESP32)
# if defined(ESP8266)
# include "../ESPEasyCore/ESPEasyWiFiEvent_ESP8266.h"
# include <ESP8266WiFi.h>
# endif // if defined(ESP8266)
# if defined(ESP32)
# include "../ESPEasyCore/ESPEasyWiFiEvent_ESP32.h"
# include <WiFi.h>
# include <WiFiType.h>
# endif // if defined(ESP32)
namespace ESPEasy_WiFi_abstraction {
bool WiFiConnected();
namespace ESPEasy {
namespace net {
namespace wifi {
void WiFiDisconnect();
bool WifiIsAP(WiFiMode_t wifimode);
bool WifiIsSTA(WiFiMode_t wifimode);
// Call before starting WiFi
bool WiFi_pre_setup();
// Call before setting WiFi into STA mode
bool WiFi_pre_STA_setup();
STA_connected_state getSTA_connected_state();
bool WiFiConnected();
void WiFiDisconnect();
// ********************************************************************************
// Manage Wifi Modes
// ********************************************************************************
bool WifiIsAP(WiFiMode_t wifimode);
bool WifiIsSTA(WiFiMode_t wifimode);
const __FlashStringHelper* getWifiModeString(WiFiMode_t wifimode);
bool setSTA(bool enable);
bool setAP(bool enable);
bool setSTA_AP(bool sta_enable,
bool ap_enable);
bool setWifiMode(WiFiMode_t new_mode);
// ********************************************************************************
// Event handlers
// ********************************************************************************
void removeWiFiEventHandler();
void registerWiFiEventHandler();
@@ -31,18 +64,36 @@ void registerWiFiEventHandler();
WiFiConnectionProtocol getConnectionProtocol();
float GetRSSIthreshold(float& maxTXpwr);
#if FEATURE_SET_WIFI_TX_PWR
void SetWiFiTXpower(float& dBm);
#endif // if FEATURE_SET_WIFI_TX_PWR
// ********************************************************************************
// Configure WiFi TX power
// ********************************************************************************
# if FEATURE_SET_WIFI_TX_PWR
void SetWiFiTXpower();
void SetWiFiTXpower(float dBm);
void SetWiFiTXpower(float dBm,
float rssi);
// Actually set the TX power using platform specific calls.
void doSetWiFiTXpower(float& dBm);
# endif // if FEATURE_SET_WIFI_TX_PWR
int GetRSSI_quality();
void setConnectionSpeed();
void setConnectionSpeed(bool ForceWiFi_bg_mode);
void setWiFiNoneSleep();
void setWiFiEcoPowerMode();
void setWiFiDefaultPowerMode();
void setWiFiCountryPolicyManual();
}
} // namespace wifi
} // namespace net
} // namespace ESPEasy
#endif // if FEATURE_WIFI
#endif // ifndef ESPEASYCORE_ESPEASYWIFI_ABSTRACTED_H
@@ -1,23 +1,86 @@
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#ifdef ESP32
#if FEATURE_WIFI
# ifdef ESP32
# include "../Globals/ESPEasyWiFiEvent.h"
# include "../Globals/WiFi_AP_Candidates.h"
# include "../ESPEasyCore/ESPEasyWiFiEvent_ESP32.h"
# include "../Globals/ESPEasyWiFiEvent.h"
# include "../Globals/EventQueue.h"
# include "../Globals/Settings.h"
# include "../Globals/WiFi_AP_Candidates.h"
# include "../ESPEasyCore/ESPEasyWiFiEvent_ESP32.h"
# include "../Helpers/StringConverter.h"
# include <WiFiGeneric.h>
# include <esp_wifi.h> // Needed to call ESP-IDF functions like esp_wifi_....
# include "../ESPEasyCore/ESPEasyNetwork.h" // Needed for NetworkCreateRFCCompliantHostname, WiFi code should not include network code
# include "../ESPEasyCore/ESPEasyWifi.h" // Needed for WifiDisconnect. Maybe this should be moved to these 'abstract' files?
# include <esp_phy_init.h>
# include "../ESPEasyCore/ESPEasyWifi_ProcessEvent.h"
namespace ESPEasy_WiFi_abstraction {
bool WiFiConnected() {
return WiFi.isConnected();
# include <WiFiGeneric.h>
# include <esp_wifi.h> // Needed to call ESP-IDF functions like esp_wifi_....
# include <esp_phy_init.h>
namespace ESPEasy {
namespace net {
namespace wifi {
bool WiFi_pre_setup() {
registerWiFiEventHandler();
WiFi.persistent(false);
return setSTA_AP(false, false);
}
bool WiFi_pre_STA_setup()
{
if (!setSTA(true)) { return false; }
WiFi.setAutoReconnect(false);
delay(10);
return true;
}
STA_connected_state getSTA_connected_state()
{
switch (WiFi.status())
{
case WL_CONNECTED:
return STA_connected_state::Connected;
case WL_NO_SSID_AVAIL:
return STA_connected_state::Error_Not_Found;
case WL_CONNECT_FAILED:
case WL_CONNECTION_LOST:
return STA_connected_state::Error_Connect_Failed;
case WL_NO_SHIELD:
case WL_STOPPED:
case WL_IDLE_STATUS:
case WL_SCAN_COMPLETED:
case WL_DISCONNECTED:
// ToDo TD-er: What to do here? Should we add some disconnected state?
break;
}
// TODO: Keep track of whether connection is in progress
// The status() function does not return a reply stating "connecting"
/* if (_sta_connecting) {
return STA_connected_state::Connecting;
}
*/
return STA_connected_state::Idle;
}
bool WiFiConnected() { return WiFi.isConnected(); }
void WiFiDisconnect() {
removeWiFiEventHandler();
WiFi.disconnect();
@@ -31,14 +94,138 @@ void WiFiDisconnect() {
}
}
bool WifiIsAP(WiFiMode_t wifimode)
{
return (wifimode == WIFI_MODE_AP) || (wifimode == WIFI_MODE_APSTA);
}
bool WifiIsAP(WiFiMode_t wifimode) { return (wifimode == WIFI_MODE_AP) || (wifimode == WIFI_MODE_APSTA); }
bool WifiIsSTA(WiFiMode_t wifimode)
bool WifiIsSTA(WiFiMode_t wifimode) { return (wifimode & WIFI_MODE_STA) != 0; }
bool setWifiMode(WiFiMode_t new_mode)
{
return (wifimode & WIFI_MODE_STA) != 0;
const WiFiMode_t cur_mode = WiFi.getMode();
// Made this static flag an int as ESP8266 and ESP32 differ in the "not set" values
static int8_t processing_wifi_mode = -1;
if (cur_mode == new_mode) {
return true;
}
if (processing_wifi_mode == static_cast<int8_t>(new_mode)) {
// Prevent loops
return true;
}
processing_wifi_mode = static_cast<int8_t>(new_mode);
if (cur_mode == WIFI_OFF) {
# if defined(ESP32)
// Needs to be set while WiFi is off
WiFi.hostname(NetworkCreateRFCCompliantHostname());
# endif // if defined(ESP32)
WiFiEventData.markWiFiTurnOn();
}
if (new_mode != WIFI_OFF) {
# ifdef ESP8266
// See: https://github.com/esp8266/Arduino/issues/6172#issuecomment-500457407
WiFi.forceSleepWake(); // Make sure WiFi is really active.
# endif // ifdef ESP8266
delay(100);
} else {
WifiDisconnect();
// delay(100);
processDisconnect();
WiFiEventData.clear_processed_flags();
}
addLog(LOG_LEVEL_INFO, concat(F("WIFI : Set WiFi to "), getWifiModeString(new_mode)));
int retry = 2;
while (!WiFi.mode(new_mode) && retry > 0) {
delay(100);
--retry;
}
retry = 2;
while (WiFi.getMode() != new_mode && retry > 0) {
addLog(LOG_LEVEL_INFO, F("WIFI : mode not yet set"));
delay(100);
--retry;
}
if (WiFi.getMode() != new_mode) {
addLog(LOG_LEVEL_ERROR, F("WIFI : Cannot set mode!!!!!"));
return false;
}
if (new_mode == WIFI_OFF) {
// FIXME TD-er: Is this correct to mark Turn ON ????
WiFiEventData.markWiFiTurnOn();
# if defined(ESP32)
// Needs to be set while WiFi is off
WiFi.hostname(NetworkCreateRFCCompliantHostname());
# endif // if defined(ESP32)
delay(100);
# if defined(ESP32)
esp_wifi_set_ps(WIFI_PS_NONE);
// esp_wifi_set_ps(WIFI_PS_MAX_MODEM);
# endif // if defined(ESP32)
# ifdef ESP8266
WiFi.forceSleepBegin();
# endif // ifdef ESP8266
delay(1);
} else {
if (cur_mode == WIFI_OFF) {
registerWiFiEventHandler();
}
// Only set power mode when AP is not enabled
// When AP is enabled, the sleep mode is already set to WIFI_NONE_SLEEP
if (!WifiIsAP(new_mode)) {
if (Settings.WifiNoneSleep()) {
setWiFiNoneSleep();
} else if (Settings.EcoPowerMode()) {
setWiFiEcoPowerMode();
} else {
// Default
setWiFiDefaultPowerMode();
}
}
# if FEATURE_SET_WIFI_TX_PWR
SetWiFiTXpower();
# endif
if (WifiIsSTA(new_mode)) {
// WiFi.setAutoConnect(Settings.SDK_WiFi_autoreconnect());
WiFi.setAutoReconnect(Settings.SDK_WiFi_autoreconnect());
}
delay(100); // Must allow for some time to init.
}
const bool new_mode_AP_enabled = WifiIsAP(new_mode);
if (WifiIsAP(cur_mode) && !new_mode_AP_enabled) {
eventQueue.add(F("WiFi#APmodeDisabled"));
}
if (WifiIsAP(cur_mode) != new_mode_AP_enabled) {
// Mode has changed
setAPinternal(new_mode_AP_enabled);
}
# if FEATURE_MDNS
# ifdef ESP8266
// notifyAPChange() is not present in the ESP32 MDNSResponder
MDNS.notifyAPChange();
# endif // ifdef ESP8266
# endif // if FEATURE_MDNS
return true;
}
void removeWiFiEventHandler()
@@ -56,9 +243,12 @@ void registerWiFiEventHandler()
}
float GetRSSIthreshold(float& maxTXpwr) {
maxTXpwr = Settings.getWiFi_TX_power();
float threshold = WIFI_SENSITIVITY_n;
switch (getConnectionProtocol()) {
switch (getConnectionProtocol())
{
case WiFiConnectionProtocol::WiFi_Protocol_11b:
threshold = WIFI_SENSITIVITY_11b;
@@ -77,11 +267,11 @@ float GetRSSIthreshold(float& maxTXpwr) {
if (maxTXpwr > MAX_TX_PWR_DBM_n) { maxTXpwr = MAX_TX_PWR_DBM_n; }
break;
# if ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 2, 0)
# if ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 2, 0)
case WiFiConnectionProtocol::WiFi_Protocol_11a:
case WiFiConnectionProtocol::WiFi_Protocol_VHT20:
// FIXME TD-er: Must determine max. TX power for these 5 GHz modi
# endif // if ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 2, 0)
# endif // if ESP_IDF_VERSION > ESP_IDF_VERSION_VAL(5, 2, 0)
case WiFiConnectionProtocol::WiFi_Protocol_LR:
case WiFiConnectionProtocol::Unknown:
break;
@@ -95,26 +285,28 @@ WiFiConnectionProtocol getConnectionProtocol()
wifi_phy_mode_t phymode;
esp_wifi_sta_get_negotiated_phymode(&phymode);
switch (phymode) {
switch (phymode)
{
case WIFI_PHY_MODE_11B: return WiFiConnectionProtocol::WiFi_Protocol_11b;
case WIFI_PHY_MODE_11G: return WiFiConnectionProtocol::WiFi_Protocol_11g;
case WIFI_PHY_MODE_HT20: return WiFiConnectionProtocol::WiFi_Protocol_HT20;
case WIFI_PHY_MODE_HT40: return WiFiConnectionProtocol::WiFi_Protocol_HT40;
case WIFI_PHY_MODE_HE20: return WiFiConnectionProtocol::WiFi_Protocol_HE20;
case WIFI_PHY_MODE_LR: return WiFiConnectionProtocol::WiFi_Protocol_LR;
# if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
# if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
// 5 GHz
case WIFI_PHY_MODE_11A: return WiFiConnectionProtocol::WiFi_Protocol_11a;
case WIFI_PHY_MODE_VHT20: return WiFiConnectionProtocol::WiFi_Protocol_VHT20;
# endif // if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
# endif // if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 3, 0)
}
}
return WiFiConnectionProtocol::Unknown;
}
# if FEATURE_SET_WIFI_TX_PWR
void SetWiFiTXpower(float& dBm)
# if FEATURE_SET_WIFI_TX_PWR
void doSetWiFiTXpower(float& dBm)
{
int8_t power = dBm * 4;
@@ -125,7 +317,7 @@ void SetWiFiTXpower(float& dBm)
}
}
# endif // if FEATURE_SET_WIFI_TX_PWR
# endif // if FEATURE_SET_WIFI_TX_PWR
void setConnectionSpeed(bool ForceWiFi_bg_mode) {
// Does not (yet) work, so commented out.
@@ -143,12 +335,13 @@ void setConnectionSpeed(bool ForceWiFi_bg_mode) {
if (!ForceWiFi_bg_mode || (WiFiEventData.connectionFailures > 10)) {
// Set to use BGN
protocol |= WIFI_PROTOCOL_11N;
#ifdef ESP32C6
# ifdef ESP32C6
protocol |= WIFI_PROTOCOL_11AX;
#endif
# endif
}
const WiFi_AP_Candidate candidate = WiFi_AP_Candidates.getCurrent();
if (candidate.phy_known()) {
// Check to see if the access point is set to "N-only"
if ((protocol & WIFI_PROTOCOL_11N) == 0) {
@@ -158,48 +351,46 @@ void setConnectionSpeed(bool ForceWiFi_bg_mode) {
protocol |= WIFI_PROTOCOL_11N;
addLog(LOG_LEVEL_INFO, F("WIFI : AP is set to 802.11n only"));
}
#ifdef ESP32C6
# ifdef ESP32C6
if (candidate.bits.phy_11ax) {
// Set to use WiFi6
protocol |= WIFI_PROTOCOL_11AX;
addLog(LOG_LEVEL_INFO, F("WIFI : AP is set to 802.11ax"));
}
#endif
# endif // ifdef ESP32C6
}
}
}
if (ESPEasy_WiFi_abstraction::WifiIsSTA(WiFi.getMode())) {
if (WifiIsSTA(WiFi.getMode())) {
// Set to use "Long GI" making it more resilliant to reflections
// See: https://www.tp-link.com/us/configuration-guides/q_a_basic_wireless_concepts/?configurationId=2958#_idTextAnchor038
esp_wifi_config_80211_tx_rate(WIFI_IF_STA, WIFI_PHY_RATE_MCS3_LGI);
esp_wifi_set_protocol(WIFI_IF_STA, protocol);
}
if (ESPEasy_WiFi_abstraction::WifiIsAP(WiFi.getMode())) {
if (WifiIsAP(WiFi.getMode())) {
esp_wifi_set_protocol(WIFI_IF_AP, protocol);
}
}
void setWiFiNoneSleep()
{
WiFi.setSleep(WIFI_PS_NONE);
}
void setWiFiNoneSleep() { WiFi.setSleep(WIFI_PS_NONE); }
void setWiFiEcoPowerMode()
{
// Allow light sleep during idle times
# ifdef ESP8266
# ifdef ESP8266
WiFi.setSleepMode(WIFI_LIGHT_SLEEP);
# endif // ifdef ESP8266
# ifdef ESP32
# endif // ifdef ESP8266
# ifdef ESP32
// Maximum modem power saving.
// In this mode, interval to receive beacons is determined by the listen_interval parameter in wifi_sta_config_t
// FIXME TD-er: Must test if this is desired behavior in ESP32.
WiFi.setSleep(WIFI_PS_MAX_MODEM);
# endif // ifdef ESP32
# endif // ifdef ESP32
}
void setWiFiDefaultPowerMode()
@@ -209,11 +400,21 @@ void setWiFiDefaultPowerMode()
WiFi.setSleep(WIFI_PS_MIN_MODEM);
}
void setWiFiCountryPolicyManual()
{
wifi_country_t config = {
.cc = "01",
.schan = 1,
.nchan = 14,
.policy = WIFI_COUNTRY_POLICY_MANUAL,
};
esp_wifi_set_country(&config);
}
} // namespace wifi
} // namespace net
} // namespace ESPEasy
} // namespace ESPEasy_WiFi_abstraction
#endif // ifdef ESP32
# endif // ifdef ESP32
#endif // if FEATURE_WIFI
@@ -1,43 +1,72 @@
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#ifdef ESP8266
#if FEATURE_WIFI
# ifdef ESP8266
# include "../Globals/ESPEasyWiFiEvent.h"
# include "../Globals/WiFi_AP_Candidates.h"
# include "../Helpers/StringConverter.h"
# include "../ESPEasyCore/ESPEasyWiFiEvent_ESP8266.h"
# include "../Globals/ESPEasyWiFiEvent.h"
# include "../Globals/Settings.h"
# include "../Globals/WiFi_AP_Candidates.h"
namespace ESPEasy_WiFi_abstraction {
bool WiFiConnected()
# include "../ESPEasyCore/ESPEasyWiFiEvent_ESP8266.h"
namespace ESPEasy {
namespace net {
namespace wifi {
bool WiFi_pre_setup() {
registerWiFiEventHandler();
setSTA_AP(false, false);
delay(100);
return true;
}
bool WiFi_pre_STA_setup() {
if (! setSTA(true)) { return false; }
// Assign to 2 separate bools to make sure both are executed.
const bool autoConnect = WiFi.setAutoConnect(false);
const bool autoReconnect = WiFi.setAutoReconnect(false);
if (!autoConnect || !autoReconnect) {
addLog(LOG_LEVEL_ERROR, F("WiFi : Disabling auto (re)connect failed"));
}
delay(100);
return true;
}
STA_connected_state getSTA_connected_state()
{
bool wifi_isconnected = WiFi.isConnected();
// Perform check on SDK function, see: https://github.com/esp8266/Arduino/issues/7432
station_status_t status = wifi_station_get_connect_status();
switch (status) {
switch (status)
{
case STATION_GOT_IP:
wifi_isconnected = true;
break;
return STA_connected_state::Connected;
case STATION_NO_AP_FOUND:
return STA_connected_state::Error_Not_Found;
case STATION_CONNECT_FAIL:
case STATION_WRONG_PASSWORD:
wifi_isconnected = false;
break;
case STATION_IDLE:
return STA_connected_state::Error_Connect_Failed;
case STATION_CONNECTING:
return STA_connected_state::Connecting;
case STATION_IDLE:
break;
default:
wifi_isconnected = false;
break;
}
return wifi_isconnected;
return STA_connected_state::Idle;
}
bool WiFiConnected() { return getSTA_connected_state() == STA_connected_state::Connected; }
void WiFiDisconnect() {
// Only call disconnect when STA is active
if (ESPEasy_WiFi_abstraction::WifiIsSTA(WiFi.getMode())) {
if ( WifiIsSTA(WiFi.getMode())) {
wifi_station_disconnect();
}
station_config conf{};
@@ -47,14 +76,170 @@ void WiFiDisconnect() {
ETS_UART_INTR_ENABLE();
}
bool WifiIsAP(WiFiMode_t wifimode)
{
return (wifimode == WIFI_AP) || (wifimode == WIFI_AP_STA);
}
bool WifiIsAP(WiFiMode_t wifimode) { return (wifimode == WIFI_AP) || (wifimode == WIFI_AP_STA); }
bool WifiIsSTA(WiFiMode_t wifimode)
bool WifiIsSTA(WiFiMode_t wifimode) { return (wifimode & WIFI_STA) != 0; }
bool setWifiMode(WiFiMode_t new_mode)
{
return (wifimode & WIFI_STA) != 0;
const WiFiMode_t cur_mode = WiFi.getMode();
// Made this static flag an int as ESP8266 and ESP32 differ in the "not set" values
static int8_t processing_wifi_mode = -1;
if (cur_mode == new_mode) {
return true;
}
if (processing_wifi_mode == static_cast<int8_t>(new_mode)) {
// Prevent loops
return true;
}
processing_wifi_mode = static_cast<int8_t>(new_mode);
if (! WifiIsSTA(new_mode)) {
// calls lwIP's dhcp_stop(),
// safe to call even if not started
// See: https://github.com/esp8266/Arduino/pull/5703/files
wifi_station_dhcpc_stop();
}
if (new_mode != WIFI_OFF) {
// See: https://github.com/esp8266/Arduino/issues/6172#issuecomment-500457407
WiFi.forceSleepWake(); // Make sure WiFi is really active.
delay(100);
}
addLog(LOG_LEVEL_INFO, concat(F("WIFI : Set WiFi to "), getWifiModeString(new_mode)));
int retry = 2;
while (!WiFi.mode(new_mode) && retry > 0) {
delay(100);
--retry;
}
retry = 2;
while (WiFi.getMode() != new_mode && retry > 0) {
addLog(LOG_LEVEL_INFO, F("WIFI : mode not yet set"));
delay(100);
--retry;
}
if (WiFi.getMode() != new_mode) {
addLog(LOG_LEVEL_ERROR, F("WIFI : Cannot set mode!!!!!"));
return false;
}
if (new_mode == WIFI_OFF) {
WiFi.forceSleepBegin();
delay(1);
}
/*
if (cur_mode == WIFI_OFF) {
#if defined(ESP32)
// Needs to be set while WiFi is off
WiFi.hostname(NetworkCreateRFCCompliantHostname());
#endif
WiFiEventData.markWiFiTurnOn();
}
if (new_mode != WIFI_OFF) {
#ifdef ESP8266
// See: https://github.com/esp8266/Arduino/issues/6172#issuecomment-500457407
WiFi.forceSleepWake(); // Make sure WiFi is really active.
#endif
delay(100);
} else {
WifiDisconnect();
// delay(100);
processDisconnect();
WiFiEventData.clear_processed_flags();
}
addLog(LOG_LEVEL_INFO, concat(F("WIFI : Set WiFi to "), getWifiModeString(new_mode)));
int retry = 2;
while (!WiFi.mode(new_mode) && retry > 0) {
delay(100);
--retry;
}
retry = 2;
while (WiFi.getMode() != new_mode && retry > 0) {
addLog(LOG_LEVEL_INFO, F("WIFI : mode not yet set"));
delay(100);
--retry;
}
if (WiFi.getMode() != new_mode) {
addLog(LOG_LEVEL_ERROR, F("WIFI : Cannot set mode!!!!!"));
return false;
}
if (new_mode == WIFI_OFF) {
// FIXME TD-er: Is this correct to mark Turn ON ????
WiFiEventData.markWiFiTurnOn();
#if defined(ESP32)
// Needs to be set while WiFi is off
WiFi.hostname(NetworkCreateRFCCompliantHostname());
#endif
delay(100);
#if defined(ESP32)
esp_wifi_set_ps(WIFI_PS_NONE);
// esp_wifi_set_ps(WIFI_PS_MAX_MODEM);
#endif
#ifdef ESP8266
WiFi.forceSleepBegin();
#endif // ifdef ESP8266
delay(1);
} else {
if (cur_mode == WIFI_OFF) {
registerWiFiEventHandler();
}
// Only set power mode when AP is not enabled
// When AP is enabled, the sleep mode is already set to WIFI_NONE_SLEEP
if (! WifiIsAP(new_mode)) {
if (Settings.WifiNoneSleep()) {
setWiFiNoneSleep();
} else if (Settings.EcoPowerMode()) {
setWiFiEcoPowerMode();
} else {
// Default
setWiFiDefaultPowerMode();
}
}
#if FEATURE_SET_WIFI_TX_PWR
SetWiFiTXpower();
#endif
if ( WifiIsSTA(new_mode)) {
// WiFi.setAutoConnect(Settings.SDK_WiFi_autoreconnect());
WiFi.setAutoReconnect(Settings.SDK_WiFi_autoreconnect());
}
delay(100); // Must allow for some time to init.
}
const bool new_mode_AP_enabled = WifiIsAP(new_mode);
if ( WifiIsAP(cur_mode) && !new_mode_AP_enabled) {
eventQueue.add(F("WiFi#APmodeDisabled"));
}
if ( WifiIsAP(cur_mode) != new_mode_AP_enabled) {
// Mode has changed
setAPinternal(new_mode_AP_enabled);
}
*/
# if FEATURE_MDNS
# ifdef ESP8266
// notifyAPChange() is not present in the ESP32 MDNSResponder
MDNS.notifyAPChange();
# endif // ifdef ESP8266
# endif // if FEATURE_MDNS
return true;
}
void removeWiFiEventHandler() {
@@ -79,9 +264,12 @@ void registerWiFiEventHandler()
}
float GetRSSIthreshold(float& maxTXpwr) {
maxTXpwr = Settings.getWiFi_TX_power();
float threshold = WIFI_SENSITIVITY_n;
switch (getConnectionProtocol()) {
switch (getConnectionProtocol())
{
case WiFiConnectionProtocol::WiFi_Protocol_11b:
threshold = WIFI_SENSITIVITY_11b;
@@ -106,7 +294,8 @@ float GetRSSIthreshold(float& maxTXpwr) {
WiFiConnectionProtocol getConnectionProtocol()
{
if (WiFi.RSSI() < 0) {
switch (wifi_get_phy_mode()) {
switch (wifi_get_phy_mode())
{
case PHY_MODE_11B:
return WiFiConnectionProtocol::WiFi_Protocol_11b;
case PHY_MODE_11G:
@@ -118,20 +307,20 @@ WiFiConnectionProtocol getConnectionProtocol()
return WiFiConnectionProtocol::Unknown;
}
# if FEATURE_SET_WIFI_TX_PWR
void SetWiFiTXpower(float& dBm)
{
WiFi.setOutputPower(dBm);
}
# if FEATURE_SET_WIFI_TX_PWR
# endif // if FEATURE_SET_WIFI_TX_PWR
void doSetWiFiTXpower(float& dBm) { WiFi.setOutputPower(dBm); }
# endif // if FEATURE_SET_WIFI_TX_PWR
void setConnectionSpeed(bool ForceWiFi_bg_mode) {
// ESP8266 only supports 802.11g mode when running in STA+AP
const bool forcedByAPmode = ESPEasy_WiFi_abstraction::WifiIsAP(WiFi.getMode());
WiFiPhyMode_t phyMode = (ForceWiFi_bg_mode || forcedByAPmode) ? WIFI_PHY_MODE_11G : WIFI_PHY_MODE_11N;
const bool forcedByAPmode = WifiIsAP(WiFi.getMode());
WiFiPhyMode_t phyMode = (ForceWiFi_bg_mode || forcedByAPmode) ? WIFI_PHY_MODE_11G : WIFI_PHY_MODE_11N;
if (!forcedByAPmode) {
const WiFi_AP_Candidate candidate = WiFi_AP_Candidates.getCurrent();
if (candidate.phy_known() && (candidate.bits.phy_11g != candidate.bits.phy_11n)) {
if ((WIFI_PHY_MODE_11G == phyMode) && !candidate.bits.phy_11g) {
phyMode = WIFI_PHY_MODE_11N;
@@ -139,9 +328,10 @@ void setConnectionSpeed(bool ForceWiFi_bg_mode) {
} else if ((WIFI_PHY_MODE_11N == phyMode) && !candidate.bits.phy_11n) {
phyMode = WIFI_PHY_MODE_11G;
addLog(LOG_LEVEL_INFO, F("WIFI : AP is set to 802.11g only"));
}
}
} else {
bool useAlternate = WiFiEventData.connectionFailures > 10;
if (useAlternate) {
phyMode = (WIFI_PHY_MODE_11G == phyMode) ? WIFI_PHY_MODE_11N : WIFI_PHY_MODE_11G;
}
@@ -154,25 +344,25 @@ void setConnectionSpeed(bool ForceWiFi_bg_mode) {
if (WiFi.getPhyMode() == phyMode) {
return;
}
#ifndef BUILD_NO_DEBUG
# ifndef BUILD_NO_DEBUG
if (loglevelActiveFor(LOG_LEVEL_INFO)) {
String log = concat(F("WIFI : Set to 802.11"), (WIFI_PHY_MODE_11G == phyMode) ? 'g' : 'n');
if (forcedByAPmode) {
log += (F(" (AP+STA mode)"));
}
if (Settings.ForceWiFi_bg_mode()) {
log += F(" Force B/G mode");
}
addLogMove(LOG_LEVEL_INFO, log);
}
#endif
# endif // ifndef BUILD_NO_DEBUG
WiFi.setPhyMode(phyMode);
}
void setWiFiNoneSleep()
{
WiFi.setSleepMode(WIFI_NONE_SLEEP);
}
void setWiFiNoneSleep() { WiFi.setSleepMode(WIFI_NONE_SLEEP); }
void setWiFiEcoPowerMode()
{
@@ -180,17 +370,15 @@ void setWiFiEcoPowerMode()
WiFi.setSleepMode(WIFI_LIGHT_SLEEP);
}
void setWiFiDefaultPowerMode()
{
WiFi.setSleepMode(WIFI_MODEM_SLEEP);
void setWiFiDefaultPowerMode() { WiFi.setSleepMode(WIFI_MODEM_SLEEP); }
void setWiFiCountryPolicyManual() {
// Not yet implemented/required for ESP8266
}
} // namespace wifi
} // namespace net
} // namespace ESPEasy
} // namespace ESPEasy_WiFi_abstraction
#endif // ifdef ESP8266
# endif // ifdef ESP8266
#endif // if FEATURE_WIFI
+4 -3
View File
@@ -10,6 +10,7 @@
#include "../ESPEasyCore/ESPEasyNetwork.h"
#include "../ESPEasyCore/ESPEasyRules.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../ESPEasyCore/ESPEasyWifi_ProcessEvent.h"
#include "../ESPEasyCore/Serial.h"
#include "../Globals/Cache.h"
@@ -393,7 +394,7 @@ void ESPEasy_setup()
if (initWiFi) {
WiFi_AP_Candidates.clearCache();
WiFi_AP_Candidates.load_knownCredentials();
setSTA(true);
ESPEasy::net::wifi::setSTA(true);
if (!WiFi_AP_Candidates.hasCandidates()) {
WiFiEventData.wifiSetup = true;
RTC.clearLastWiFi(); // Must scan all channels
@@ -416,14 +417,14 @@ void ESPEasy_setup()
addLog(LOG_LEVEL_INFO, F("Setup: Scan all channels"));
WifiScan(false);
}
// setWifiMode(WIFI_OFF);
// ESPEasy::net::wifi::setWifiMode(WIFI_OFF);
}
#ifndef BUILD_NO_RAM_TRACKER
logMemUsageAfter(F("WifiScan()"));
#endif
// setWifiMode(WIFI_STA);
// ESPEasy::net::wifi::setWifiMode(WIFI_STA);
checkRuleSets();
#ifndef BUILD_NO_RAM_TRACKER
logMemUsageAfter(F("checkRuleSets()"));
+2 -1
View File
@@ -3,6 +3,7 @@
#include "../../ESPEasy_common.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../ESPEasyCore/ESPEasyNetwork.h"
#include "../Globals/Settings.h"
@@ -52,7 +53,7 @@ void statusLED(bool traffic)
}
// AP mode is active
else if (WifiIsAP(WiFi.getMode()))
else if ( ESPEasy::net::wifi::WifiIsAP(WiFi.getMode()))
{
nStatusValue = ((millis() >> 1) & PWMRANGE_FULL) - (PWMRANGE_FULL >> 2); // ramp up for 2 sec, 3/4 luminosity
}
+2 -1
View File
@@ -12,6 +12,7 @@
#include "../ESPEasyCore/ESPEasy_Log.h"
#include "../ESPEasyCore/ESPEasyNetwork.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../ESPEasyCore/ESPEasyRules.h"
#include "../ESPEasyCore/Serial.h"
#include "../Globals/ESPEasyWiFiEvent.h"
@@ -490,7 +491,7 @@ void prepareShutdown(IntendedRebootReason_e reason)
process_serialWriteBuffer();
flushAndDisconnectAllClients();
saveUserVarToRTC();
setWifiMode(WIFI_OFF);
ESPEasy::net::wifi::setWifiMode(WIFI_OFF);
ESPEASY_FS.end();
process_serialWriteBuffer();
delay(100); // give the node time to flush all before reboot or sleep
+4 -1
View File
@@ -144,12 +144,15 @@ bool WiFi_AP_CandidatesList::getNext(bool scanAllowed) {
load_knownCredentials();
if (candidates.empty()) {
if (scanAllowed) {
return false;
/* if (scanAllowed) {
return false;
}
loadCandidatesFromScanned();
attemptsLeft = 1;
if (candidates.empty()) { return false; }
*/
}
currentCandidate = candidates.front();
+3 -2
View File
@@ -3,6 +3,7 @@
#include "../ESPEasyCore/ESPEasy_Log.h"
#include "../ESPEasyCore/ESPEasyNetwork.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../Globals/SecuritySettings.h"
#include "../Globals/Services.h"
@@ -57,7 +58,7 @@ bool getIPallowedRange(IPAddress& low, IPAddress& high)
switch (SecuritySettings.IPblockLevel) {
case LOCAL_SUBNET_ALLOWED:
if (WifiIsAP(WiFi.getMode())) {
if ( ESPEasy::net::wifi::WifiIsAP(WiFi.getMode())) {
// WiFi is active as accesspoint, do not check.
return false;
}
@@ -114,7 +115,7 @@ boolean clientIPallowed()
return true;
}
if (WifiIsAP(WiFi.getMode())) {
if ( ESPEasy::net::wifi::WifiIsAP(WiFi.getMode())) {
// @TD-er Fixme: Should match subnet of SoftAP.
return true;
}
+2 -1
View File
@@ -53,6 +53,7 @@
#include "../ESPEasyCore/ESPEasyNetwork.h"
#include "../ESPEasyCore/ESPEasyRules.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../Globals/CPlugins.h"
#include "../Globals/Device.h"
@@ -127,7 +128,7 @@ void sendHeadandTail_stdtemplate(bool Tail, bool rebooting) {
sendHeadandTail(F("TmplStd"), Tail, rebooting);
if (!Tail) {
if (!clientIPinSubnet() && WifiIsAP(WiFi.getMode()) && (WiFi.softAPgetStationNum() > 0)) {
if (!clientIPinSubnet() && ESPEasy::net::wifi::WifiIsAP(WiFi.getMode()) && (WiFi.softAPgetStationNum() > 0)) {
addHtmlError(F("Warning: Connected via AP"));
}
+2 -1
View File
@@ -13,6 +13,7 @@
# include "../ESPEasyCore/ESPEasyNetwork.h"
# include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
# include "../Globals/ESPEasyWiFiEvent.h"
# include "../Globals/NetworkState.h"
@@ -250,7 +251,7 @@ void handle_setup_scan_and_show(const String& ssid, const String& other, const S
WiFiMode_t cur_wifimode = WiFi.getMode();
WifiScan(false);
scanCompleteStatus = WiFi_AP_Candidates.scanComplete();
setWifiMode(cur_wifimode);
ESPEasy::net::wifi::setWifiMode(cur_wifimode);
}
+3 -2
View File
@@ -5,6 +5,7 @@
#include "../WebServer/HTML_wrappers.h"
#include "../ESPEasyCore/ESPEasyWifi.h"
#include "../ESPEasyCore/ESPEasyWifi_abstracted.h"
#include "../Globals/WiFi_AP_Candidates.h"
#include "../Helpers/StringGenerator_WiFi.h"
@@ -31,7 +32,7 @@ void handle_wifiscanner_json() {
if (WiFi_AP_Candidates.scanComplete() <= 0) {
WiFiMode_t cur_wifimode = WiFi.getMode();
WifiScan(false);
setWifiMode(cur_wifimode);
ESPEasy::net::wifi::setWifiMode(cur_wifimode);
}
for (auto it = WiFi_AP_Candidates.scanned_begin(); it != WiFi_AP_Candidates.scanned_end(); ++it)
@@ -68,7 +69,7 @@ void handle_wifiscanner() {
WiFiMode_t cur_wifimode = WiFi.getMode();
WifiScan(false);
int8_t scanCompleteStatus = WiFi_AP_Candidates.scanComplete();
setWifiMode(cur_wifimode);
ESPEasy::net::wifi::setWifiMode(cur_wifimode);
navMenuIndex = MENU_INDEX_TOOLS;
TXBuffer.startStream();
+28 -28
View File
@@ -950,7 +950,7 @@ indent_namespace = false # true/false
# Whether to indent only the first namespace, and not any nested namespaces.
# Requires indent_namespace=true.
indent_namespace_single_indent = false # true/false
indent_namespace_single_indent = true # true/false
# The number of spaces to indent a namespace block.
# If set to zero, use the value indent_columns
@@ -1242,7 +1242,7 @@ indent_ignore_asm_block = false # true/false
nl_collapse_empty_body = true # true/false
# Don't split one-line braced assignments, as in 'foo_t f = { 1, 2 };'.
nl_assign_leave_one_liners = false # true/false
nl_assign_leave_one_liners = true # true/false
# Don't split one-line braced statements inside a 'class xx { }' body.
nl_class_leave_one_liners = false # true/false
@@ -1251,19 +1251,19 @@ nl_class_leave_one_liners = false # true/false
nl_enum_leave_one_liners = false # true/false
# Don't split one-line get or set functions.
nl_getset_leave_one_liners = false # true/false
nl_getset_leave_one_liners = true # true/false
# (C#) Don't split one-line property get or set functions.
nl_cs_property_leave_one_liners = false # true/false
# Don't split one-line function definitions, as in 'int foo() { return 0; }'.
nl_func_leave_one_liners = false # true/false
nl_func_leave_one_liners = true # true/false
# Don't split one-line C++11 lambdas, as in '[]() { return 0; }'.
nl_cpp_lambda_leave_one_liners = false # true/false
# Don't split one-line if/else statements, as in 'if(...) b++;'.
nl_if_leave_one_liners = false # true/false
nl_if_leave_one_liners = true # true/false
# Don't split one-line while statements, as in 'while(...) b++;'.
nl_while_leave_one_liners = false # true/false
@@ -1410,16 +1410,16 @@ nl_using_brace = ignore # ignore/add/remove/force
# Add or remove newline between two open or close braces. Due to general
# newline/brace handling, REMOVE may not work.
nl_brace_brace = ignore # ignore/add/remove/force
nl_brace_brace = add # ignore/add/remove/force
# Add or remove newline between 'do' and '{'.
nl_do_brace = ignore # ignore/add/remove/force
nl_do_brace = add # ignore/add/remove/force
# Add or remove newline between '}' and 'while' of 'do' statement.
nl_brace_while = ignore # ignore/add/remove/force
# Add or remove newline between 'switch' and '{'.
nl_switch_brace = ignore # ignore/add/remove/force
nl_switch_brace = add # ignore/add/remove/force
# Add or remove newline between 'synchronized' and '{'.
nl_synchronized_brace = ignore # ignore/add/remove/force
@@ -1429,7 +1429,7 @@ nl_synchronized_brace = ignore # ignore/add/remove/force
#
# Overrides nl_for_brace, nl_if_brace, nl_switch_brace, nl_while_switch and
# nl_catch_brace.
nl_multi_line_cond = false # true/false
nl_multi_line_cond = true # true/false
# Force a newline in a define after the macro name for multi-line defines.
nl_multi_line_define = false # true/false
@@ -1444,7 +1444,7 @@ nl_after_case = false # true/false
# Add or remove newline between a case ':' and '{'.
#
# Overrides nl_after_case.
nl_case_colon_brace = ignore # ignore/add/remove/force
nl_case_colon_brace = add # ignore/add/remove/force
# Add or remove newline between ')' and 'throw'.
nl_before_throw = ignore # ignore/add/remove/force
@@ -1456,7 +1456,7 @@ nl_namespace_brace = remove # ignore/add/remove/force
nl_template_class = ignore # ignore/add/remove/force
# Add or remove newline between 'class' and '{'.
nl_class_brace = remove # ignore/add/remove/force
nl_class_brace = add # ignore/add/remove/force
# Add or remove newline before or after (depending on pos_class_comma,
# may not be IGNORE) each',' in the base class list.
@@ -1465,11 +1465,11 @@ nl_class_init_args = add # ignore/add/remove/force
# Add or remove newline after each ',' in the constructor member
# initialization. Related to nl_constr_colon, pos_constr_colon and
# pos_constr_comma.
nl_constr_init_args = ignore # ignore/add/remove/force
nl_constr_init_args = add # ignore/add/remove/force
# Add or remove newline before first element, after comma, and after last
# element, in 'enum'.
nl_enum_own_lines = ignore # ignore/add/remove/force
nl_enum_own_lines = add # ignore/add/remove/force
# Add or remove newline between return type and function name in a function
# definition.
@@ -1610,7 +1610,7 @@ nl_cpp_ldef_brace = ignore # ignore/add/remove/force
nl_return_expr = ignore # ignore/add/remove/force
# Whether to add a newline after semicolons, except in 'for' statements.
nl_after_semicolon = false # true/false
nl_after_semicolon = true # true/false
# (Java) Add or remove newline between the ')' and '{{' of the double brace
# initializer.
@@ -1752,7 +1752,7 @@ nl_create_while_one_liner = true # true/false
# Whether to collapse a function definition whose body (not counting braces)
# is only one line so that the entire definition (prototype, braces, body) is
# a single line.
nl_create_func_def_one_liner = false # true/false
nl_create_func_def_one_liner = true # true/false
# Whether to split one-line simple unbraced if statements into two lines by
# adding a newline, as in 'if(b) <here> i++;'.
@@ -1780,7 +1780,7 @@ nl_max_blank_in_func = 0 # unsigned number
nl_before_func_body_proto = 0 # unsigned number
# The number of newlines before a multi-line function definition.
nl_before_func_body_def = 0 # unsigned number
nl_before_func_body_def = 2 # unsigned number
# The number of newlines before a class constructor/destructor prototype.
nl_before_func_class_proto = 0 # unsigned number
@@ -1789,7 +1789,7 @@ nl_before_func_class_proto = 0 # unsigned number
nl_before_func_class_def = 0 # unsigned number
# The number of newlines after a function prototype.
nl_after_func_proto = 0 # unsigned number
nl_after_func_proto = 1 # unsigned number
# The number of newlines after a function prototype, if not followed by
# another function prototype.
@@ -1816,7 +1816,7 @@ nl_after_func_body = 2 # unsigned number
# declaration. Also affects class constructors/destructors.
#
# Overrides nl_after_func_body.
nl_after_func_body_class = 0 # unsigned number
nl_after_func_body_class = 2 # unsigned number
# The number of newlines after '}' of a single line function body. Also
# affects class constructors/destructors.
@@ -1884,13 +1884,13 @@ nl_after_multiline_comment = true # true/false
nl_after_label_colon = false # true/false
# The number of newlines after '}' or ';' of a struct/enum/union definition.
nl_after_struct = 0 # unsigned number
nl_after_struct = 2 # unsigned number
# The number of newlines before a class definition.
nl_before_class = 0 # unsigned number
nl_before_class = 2 # unsigned number
# The number of newlines after '}' or ';' of a class definition.
nl_after_class = 0 # unsigned number
nl_after_class = 2 # unsigned number
# The number of newlines before an access specifier label. This also includes
# the Qt-specific 'signals:' and 'slots:'. Will not change the newline count
@@ -1944,10 +1944,10 @@ nl_property_brace = ignore # ignore/add/remove/force
nl_inside_namespace = 0 # unsigned number
# Whether to remove blank lines after '{'.
eat_blanks_after_open_brace = true # true/false
eat_blanks_after_open_brace = false # true/false
# Whether to remove blank lines before '}'.
eat_blanks_before_close_brace = true # true/false
eat_blanks_before_close_brace = false # true/false
# How aggressively to remove extra newlines not in preprocessor.
#
@@ -2531,11 +2531,11 @@ mod_add_long_function_closebrace_comment = 0 # unsigned number
# If a namespace body exceeds the specified number of newlines and doesn't
# have a comment after the close brace, a comment will be added.
mod_add_long_namespace_closebrace_comment = 0 # unsigned number
mod_add_long_namespace_closebrace_comment = 10 # unsigned number
# If a class body exceeds the specified number of newlines and doesn't have a
# comment after the close brace, a comment will be added.
mod_add_long_class_closebrace_comment = 0 # unsigned number
mod_add_long_class_closebrace_comment = 10 # unsigned number
# If a switch body exceeds the specified number of newlines and doesn't have a
# comment after the close brace, a comment will be added.
@@ -2543,14 +2543,14 @@ mod_add_long_switch_closebrace_comment = 0 # unsigned number
# If an #ifdef body exceeds the specified number of newlines and doesn't have
# a comment after the #endif, a comment will be added.
mod_add_long_ifdef_endif_comment = 1 # unsigned number
mod_add_long_ifdef_endif_comment = 2 # unsigned number
# If an #ifdef or #else body exceeds the specified number of newlines and
# doesn't have a comment after the #else, a comment will be added.
mod_add_long_ifdef_else_comment = 1 # unsigned number
mod_add_long_ifdef_else_comment = 2 # unsigned number
# Whether to sort consecutive single-line 'import' statements.
mod_sort_import = false # true/false
mod_sort_import = true # true/false
# (C#) Whether to sort consecutive single-line 'using' statements.
mod_sort_using = false # true/false