The WiFi subsystem is maintained by background tasks that must run periodically. Any function or task that takes longer than 15ms (milliseconds) may cause the WiFi subsystem to crash. To avoid these potential crashes, it is advised that the WiFi subsystem be suspended with [wifi.suspend()](#wifisuspend) prior to the execution of any tasks or functions that exceed this 15ms guideline.
Courtesy: content for this chapter is borrowed/inspired by the [Arduino ESP8266 WiFi documentation](https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html).
Devices that connect to WiFi network are called stations (STA). Connection to Wi-Fi is provided by an access point (AP), that acts as a hub for one or more stations. The access point on the other end is connected to a wired network. An access point is usually integrated with a router to provide access from Wi-Fi network to the internet. Each access point is recognized by a SSID (**S**ervice **S**et **ID**entifier), that essentially is the name of network you select when connecting a device (station) to the WiFi.
Each ESP8266 module can operate as a station, so we can connect it to the WiFi network. It can also operate as a soft access point (soft-AP), to establish its own WiFi network. Therefore, we can connect other stations to such modules. Third, ESP8266 is also able to operate both in station and soft access point mode *at the same time*. This offers the possibility of building e.g. [mesh networks](https://en.wikipedia.org/wiki/Mesh_networking).
#### Station
Station (STA) mode is used to get the ESP8266 connected to a WiFi network established by an access point.
![ESP8266 operating in station mode](../../img/WiFi-station-mode.png)
#### Soft Access Point
An access point (AP) is a device that provides access to Wi-Fi network to other devices (stations) and connects them further to a wired network. ESP8266 can provide similar functionality except it does not have interface to a wired network. Such mode of operation is called soft access point (soft-AP). The maximum number of stations connected to the soft-AP is five.
![ESP8266 operating in Soft Access Point mode](../../img/WiFi-softap-mode.png)
The soft-AP mode is often used and an intermediate step before connecting ESP to a WiFi in a station mode. This is when SSID and password to such network is not known upfront. The module first boots in soft-AP mode, so we can connect to it using a laptop or a mobile phone. Then we are able to provide credentials to the target network. Once done ESP is switched to the station mode and can connect to the target WiFi.
Such functionality is provided by the [NodeMCU enduser setup module](../modules/enduser-setup.md).
#### Station + Soft Access Point
Another handy application of soft-AP mode is to set up [mesh networks](https://en.wikipedia.org/wiki/Mesh_networking). ESP can operate in both soft-AP and Station mode so it can act as a node of a mesh network.
![ESP8266 operating in station AP mode](../../img/WiFi-stationap-mode.png)
Configures whether or not WiFi automatically goes to sleep in NULL_MODE. Enabled by default.
!!! note
This function **does not** store it's setting in flash, if auto sleep in NULL_MODE is not desired, `wifi.nullmodesleep(false)` must be called after power-up, restart, or wake from deep sleep.
#### Syntax
`wifi.nullmodesleep([enable])`
#### Parameters
-`enable`
-`true` Enable WiFi auto sleep in NULL_MODE. (Default setting)
Wifi resume occurs asynchronously, this means that the resume request will only be processed when control of the processor is passed back to the SDK (after MyResumeFunction() has completed). The resume callback also executes asynchronously and will only execute after wifi has resumed normal operation.
-`wifi.STATION` for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
-`wifi.SOFTAP` for when the device is acting *only* as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
-`wifi.STATIONAP` is the combination of `wifi.STATION` and `wifi.SOFTAP`. It allows you to create a local WiFi connection *and* connect to another WiFi router.
-`wifi.NULLMODE` changing WiFi mode to NULL_MODE will put wifi into a low power state similar to MODEM_SLEEP, provided `wifi.nullmodesleep(false)` has not been called.
Sets WiFi maximum TX power. This setting is not persisted across power cycles, and the Espressif SDK documentation does not specify if the setting persists after deep sleep. The default value used is read from byte 34 of the ESP8266 init data, and its value is hence defined by the manufacturer.
The default value, 82, corresponds to maximum TX power. Lowering this setting could reduce power consumption on battery backed devices.
SmartConfig is disabled by default and can be enabled by setting `WIFI_SMART_ENABLE` in [`user_config.h`](https://github.com/nodemcu/nodemcu-firmware/blob/dev/app/include/user_config.h#L96) before you build the firmware.
Wifi suspension occurs asynchronously, this means that the suspend request will only be processed when control of the processor is passed back to the SDK (after MySuspendFunction() has completed). The suspend callback also executes asynchronously and will only execute after wifi has been successfully been suspended.
-`duration` Suspend duration in microseconds(μs). If a suspend duration of `0` is specified, suspension will be indefinite (Range: 0 or 50000 - 268435454 μs (0:4:28.000454))
-`suspend_cb` Callback to execute when WiFi is suspended. (Optional)
-`resume_cb` Callback to execute when WiFi wakes from suspension. (Optional)
-`preserve_mode` preserve current WiFi mode through node sleep. (Optional, Default: true)
- If true, Station and StationAP modes will automatically reconnect to previously configured Access Point when NodeMCU resumes.
- If false, discard WiFi mode and leave NodeMCU in [`wifi.NULL_MODE`](#wifigetmode). WiFi mode will be restored to original mode on restart.
#### Returns
-`suspend_state` if no parameters are provided, current WiFi suspension state will be returned
- States:
-`0` WiFi is awake.
-`1` WiFi suspension is pending. (Waiting for idle task)
-`2` WiFi is suspended.
#### Example
```lua
--get current wifi suspension state
print(wifi.suspend())
--Suspend WiFi for 10 seconds with suspend/resume callbacks
cfg={}
cfg.duration=10*1000*1000
cfg.resume_cb=function() print("WiFi resume") end
cfg.suspend_cb=function() print("WiFi suspended") end
wifi.suspend(cfg)
--Suspend WiFi for 10 seconds with suspend/resume callbacks and discard WiFi mode
cfg={}
cfg.duration=10*1000*1000
cfg.resume_cb=function() print("WiFi resume") end
cfg.suspend_cb=function() print("WiFfi suspended") end
It is not advised to assume that the WiFi is connected at any time during initialization start-up. WiFi connection status should be validated either by using a WiFi event callback or by polling the status on a timer.
-`pwd` string which is 0-64. Empty string indicates an open WiFi access point. _Note: WPA requires a minimum of 8-characters, but the ESP8266 can also connect to a WEP access point (a 40-bit WEP key can be provided as its corresponding 5-character ASCII string)._
-`bssid` string that contains the MAC address of the access point (optional)
- You can set BSSID if you have multiple access points with the same SSID.
- If you set BSSID for a specific SSID and would like to configure station to connect to the same SSID only without the BSSID requirement, you MUST first configure to station to a different SSID first, then connect to the desired SSID
- Event callbacks will only be available if `WIFI_SDK_EVENT_MONITOR_ENABLE` is uncommented in `user_config.h`
- Please note: To ensure all station events are handled at boot time, all relevant callbacks must be registered as early as possible in `init.lua` with either `wifi.sta.config()` or `wifi.eventmon.register()`.
-`connected_cb`: Callback to execute when station is connected to an access point. (Optional)
- Items returned in table :
-`SSID`: SSID of access point. (format: string)
-`BSSID`: BSSID of access point. (format: string)
-`channel`: The channel the access point is on. (format: number)
-`disconnected_cb`: Callback to execute when station is disconnected from an access point. (Optional)
- Items returned in table :
-`SSID`: SSID of access point. (format: string)
-`BSSID`: BSSID of access point. (format: string)
-`REASON`: See [wifi.eventmon.reason](#wifieventmonreason) below. (format: number)
-`authmode_change_cb`: Callback to execute when the access point has changed authorization mode. (Optional)
- Items returned in table :
-`old_auth_mode`: Old wifi authorization mode. (format: number)
-`new_auth_mode`: New wifi authorization mode. (format: number)
-`got_ip_cb`: Callback to execute when the station received an IP address from the access point. (Optional)
- Items returned in table :
-`IP`: The IP address assigned to the station. (format: string)
-`netmask`: Subnet mask. (format: string)
-`gateway`: The IP address of the access point the station is connected to. (format: string)
-`dhcp_timeout_cb`: Station DHCP request has timed out. (Optional)
Please note that disconnecting from Access Point does not reduce power consumption. If power saving is your goal, please refer to the description for `wifi.NULLMODE` in the function [`wifi.setmode()`](#wifisetmode) for more details.
-`channel` channel == 0, scan all channels, otherwise scan set channel (default is 0)
-`show_hidden` show_hidden == 1, get info for router with hidden SSID (default is 0)
-`format` select output table format, defaults to 0
- 0: old format (SSID : Authmode, RSSI, BSSID, Channel), any duplicate SSIDs will be discarded
- 1: new format (BSSID : SSID, RSSI, auth mode, Channel)
-`callback(table)` a callback function to receive the AP table when the scan is done. This function receives a table, the key is the BSSID, the value is other info in format: SSID, RSSID, auth mode, channel.
#### Returns
`nil`
#### Example
```lua
-- print AP list in old format (format not defined)
function listap(t)
for k,v in pairs(t) do
print(k.." : "..v)
end
end
wifi.sta.getap(listap)
-- Print AP list that is easier to read
function listap(t) -- (SSID : Authmode, RSSI, BSSID, Channel)
Get index of current Access Point stored in AP cache.
#### Syntax
`wifi.sta.getapindex()`
#### Parameters
none
#### Returns
`current_index` index of currently selected Access Point. (Range:1-5)
#### Example
```lua
print("the index of the currently selected AP is: "..wifi.sta.getapindex())
```
#### See also
- [`wifi.sta.getapindex()`](#wifistagetapindex)
- [`wifi.sta.apinfo()`](#wifistaapinfo)
- [`wifi.sta.apchange()`](#wifistaapchange)
## wifi.sta.getapinfo()
Get information of APs cached by ESP8266 station.
!!! Note
Any Access Points configured with save disabled `wifi.sta.config({save=false})` will populate this list (appearing to overwrite APs stored in flash) until restart.
-`1-5` index of AP. (the index corresponds to index used by [`wifi.sta.changeap()`](#wifistachangeap) and [`wifi.sta.getapindex()`](#wifistagetapindex))
-`ssid` ssid of Access Point
-`pwd` password for Access Point, `nil` if no password was configured
print(string.format(" %s%-6d %-32s %-64s %-18s",(i==y and ">" or " "), i, x[i].ssid, x[i].pwd and x[i].pwd or type(nil), x[i].bssid and x[i].bssid or type(nil)))
-`bssid_set` will return `true` if the station was configured specifically to connect to the AP with the matching `bssid`.
-`bssid` If a connection has been made to the configured AP this field will contain the AP's MAC address. Otherwise "ff:ff:ff:ff:ff:ff" will be returned.
print(string.format("\tCurrent station config\n\tssid:\"%s\"\tpassword:\"%s\"\n\tbssid:\"%s\"\tbssid_set:%s", sta_config.ssid, sta_config.pwd, sta_config.bssid, (sta_config.bssid_set and "true" or "false")))
-`bssid_set` will return `true` if the station was configured specifically to connect to the AP with the matching `bssid`.
-`bssid` If a connection has been made to the configured AP this field will contain the AP's MAC address. Otherwise "ff:ff:ff:ff:ff:ff" will be returned.
local def_sta_config=wifi.sta.getdefaultconfig(true)
print(string.format("\tDefault station config\n\tssid:\"%s\"\tpassword:\"%s\"\n\tbssid:\"%s\"\tbssid_set:%s", def_sta_config.ssid, def_sta_config.pwd, def_sta_config.bssid, (def_sta_config.bssid_set and "true" or "false")))
If 5 Access Points are stored and AP limit is set to 4, the AP at index 5 will remain until [`node.restore()`](node.md#noderestore) is called or AP limit is set to 5 and AP is overwritten.
Sets SSID and password in AP mode. Be sure to make the password at least 8 characters long! If you don't it will default to *no* password and not set the SSID! It will still work as an access point but use a default SSID like e.g. NODE_9997C3.
- Event callbacks will only be available if `WIFI_SDK_EVENT_MONITOR_ENABLE` is uncommented in `user_config.h`
- Please note: To ensure all SoftAP events are handled at boot time, all relevant callbacks must be registered as early as possible in `init.lua` with either `wifi.ap.config()` or `wifi.eventmon.register()`.
-`staconnected_cb`: Callback executed when a new client has connected to the access point. (Optional)
- Items returned in table :
-`MAC`: MAC address of client that has connected.
-`AID`: SDK provides no details concerning this return value.
-`stadisconnected_cb`: Callback executed when a client has disconnected from the access point. (Optional)
- Items returned in table :
-`MAC`: MAC address of client that has disconnected.
-`AID`: SDK provides no details concerning this return value.
-`probereq_cb`: Callback executed when a probe request was received. (Optional)
- Items returned in table :
-`MAC`: MAC address of the client that is probing the access point.
-`RSSI`: Received Signal Strength Indicator of client.
Deauths (forcibly removes) a client from the ESP access point by sending a corresponding IEEE802.11 management packet (first) and removing the client from it's data structures (afterwards).
-`pwd` Password, `nil` if no password was configured - `auth` Authentication Method (`wifi.OPEN`, `wifi.WPA_PSK`, `wifi.WPA2_PSK` or `wifi.WPA_WPA2_PSK`)
-`pwd` Password, `nil` if no password was configured - `auth` Authentication Method (`wifi.OPEN`, `wifi.WPA_PSK`, `wifi.WPA2_PSK` or `wifi.WPA_WPA2_PSK`)
- After a callback is registered, this function may be called to update a callback's function at any time
!!! note
To ensure all WiFi events are caught, the Wifi event monitor callbacks should be registered as early as possible in `init.lua`. Any events that occur before callbacks are registered will be discarded!