-
Notifications
You must be signed in to change notification settings - Fork 344
network
This module provides access to various network related functions and classes.
Operating in APSTA mode (AP and STA running simultaneously) is supported.
Create a WLAN instance object in STA (Station) or AP (access point) mode.
For mode
argument use constants network.STA_IF
or network.AP_IF
.
If mode
argument is not given, it defaults to network.STA_IF
.
WiFi interface is not started.
It is necessary to execute wlan.active(True)
to start it.
Check the WiFi interface status if no argument is given.
Returns True
if WiFi interface is started, False
if WiFi is not started.
If False
argument is given, stop the WiFi interface (it it was started).
Returns the new WiFi instance status.
If no other WiFi interface is active, stop and deinitialize the WiFi and free all used resources.
If True
argument is given, start the WiFi interface (if no other WiFi interface was started, start and initialize the WiFi).
Returns the new WiFi instance status.
If another WiFi interface was started, change mode to APSTA
(AP & STA interfaces running simultaneously).
If WiFi instance operates in STA mode:
Returns True
if WiFi interface is connected to AP and has walid IP address, otherwise returns False
.
If WiFi operates in AP mode:
Returns True
if WiFi interface is started and there is at least one station connected, otherwise returns False
.
If WiFi operates in STA mode:
Returns True
if WiFi is started on any interface (AP or STA including APSTA mode).
Only available for STA mode instances
Connects to access point using the given arguments.
For the first connect, at least ap_ssid
should be given.
Only available for STA mode instances
Disconnects from the access point.
Returns the status for the WiFi characteristic specified by arg
.
For now only one arg
can be used: 'stations'
for which a list of connected stations information is returned.
Each station information is represented by 3-item tuple containing station's MAC address, IP address and rssi.
Only available if WiFi operates in AP or APSTA mode.
Only available for STA mode instances
Scan WiFi network and return the list of available access points.
If the optional argument hidden
is set to True
the hidden access points (not broadsasting SSID) will also be scanned.
Each list entry is a tuple with the following items:
(ssid, bssid, primary_chan, rssi, auth_mode, auth_mode_string, hidden)
Get or set TCP/IP adapter configuration.
With no argument returns the current configuration as tuple (ip_address, net_mask, gateway_ip, DNS_ip)
.
If the config
argument is given (as tuple (ip_address, net_mask, gateway_ip, DNS_ip)
), sets the static IP configuration.
Retruns None
.
Configure various WiFi parameters or get their values.
The following parameters can be set/get:
Argument | Description |
---|---|
mac |
WiFi MAC address (BSSID), exactlly 6 bytes |
essid |
Acces point SSID, only in AP mode |
hidden |
Do not broadcast SSID if set to true , only in AP mode
|
authmode |
Authentication mode, only in AP mode, use the following constants:network.AUTH_OPEN , network.AUTH_WEP , network.AUTH_WPA_PSK ,network.AUTH_WPA2_PSK , network.AUTH_WPA_WPA2_PSK
|
wifimode |
Get WiFi mode, STA or AP; Get only |
password |
Set password; Set only, only in AP mode |
channel |
WiFi channel used, only in AP mode |
dhcp_hostname |
This device DHCP host name |
all |
Get only; Get all parameters as dictionary |
To set the parameter(s) use wlan.config(arg=value [,arg1=value1 [, .... ]])
format, multiple arguments can be entered.
To get the parameter(s) use wlan.config('arg')
format. Only one argument is allowed.
If args
argument is set to "all"
returns all parameters for the interface as dictionary.
It is possible to define the callback function which is executed on various WiFi events.
After the WLAN instance is created, the callback function can be set:
Without argument, returns True
if the callback function is set or False
if not.
If cb_func
argument is given, it must be the function object; returns None
.
If None
is given as the argument, no callbacks will be executed; returns None
.
Callback function
The callback function receives the 3-items tuple argument containing the information about the event:
(event_ID, event_description, event_info)
event_ID
is integer, ESP32 network event number
event_description
is string describing the event, or None
if not available
event_info
is dictionary providing the events parameters or None
if not available
Example:
This script tests various network functions:
import network, utime
start_time = utime.ticks_ms()
# ----------------------------------------------------------
# Define callback function used for monitoring wifi activity
# ----------------------------------------------------------
def wifi_cb(info):
if (info[2]):
msg = ", info: {}".format(info[2])
else:
msg = ""
print("{} [WiFi] event: {} ({}){}".format(utime.ticks_diff(utime.ticks_ms(), start_time), info[0], info[1], msg))
# Enable callbacks
network.WLANcallback(wifi_cb)
# --------------------------------------------------------------------
# Create two WLAN objects
# one will be used in STA (Station) mode, one in AP (acces point mode)
# --------------------------------------------------------------------
print("\n=== Create WLAN instance objects ===\n")
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
# Start STA WiFi interface
print("\n=== Activate STA ===================\n")
sta_if.active(True)
# Connect to access point
print("\n=== Connect to access point ========\n")
sta_if.connect("LoBoInternet", "my_password")
# Wait until connected and show IF config
tmo = 50
while not sta_if.isconnected():
utime.sleep_ms(100)
tmo -= 1
if tmo == 0:
break
print("\n=== STA Connected ==================\n")
sta_if.ifconfig()
# Start ftp server
print("\n=== Start Ftp server ===============\n")
network.ftp.start()
# Wait until started
tmo = 50
while network.ftp.status()[0] != 2:
utime.sleep_ms(100)
tmo -= 1
if tmo == 0:
break
# Get FTP server status
# FTP listens on Station IP
utime.sleep_ms(100)
network.ftp.status()
# Get STA WiFi interface configuration
print("\n=== STA configuration ==============\n")
sta_if.config('all')
# Start AP WiFi interface
print("\n=== Activate AP ====================\n")
ap_if.active(True)
# Wait until started and show IF config
# We don't need to check for connected clients
# so we give the False argument
tmo = 50
while not ap_if.isconnected(False):
utime.sleep_ms(100)
tmo -= 1
if tmo == 0:
break
print("\n=== AP started =====================\n")
ap_if.ifconfig()
# Wait until STA reconnected
tmo = 50
while not sta_if.isconnected():
utime.sleep_ms(100)
tmo -= 1
if tmo == 0:
break
print("\n=== STA ReConnected ================\n")
sta_if.ifconfig()
# Get AP WiFi interface configuration
print("\n=== AP configuration ===============\n")
ap_if.config('all')
# Get FTP server status
# FTP now listens on Station IP and AP IP
# Wait until activated after WiFi mode change
print("\n=== Ftp server status ==============\n")
tmo = 50
while network.ftp.status()[0] != 2:
utime.sleep_ms(100)
tmo -= 1
if tmo == 0:
break
utime.sleep_ms(100)
network.ftp.status()
utime.sleep(2)
# Change some AP parameters
# AP will stop than started with new parameters
print("\n=== Change AP parameters ===========\n")
ap_if.config(essid='ESP32_LoBo', authmode=network.AUTH_WPA_WPA2_PSK, password='12345678')
utime.sleep_ms(200)
# Wait until started and show IF config
# We don't need to check for connected clients
# so we give the False argument
tmo = 50
while not ap_if.isconnected(False):
utime.sleep_ms(100)
tmo -= 1
if tmo == 0:
break
print("\n=== AP ReStarted ===================\n")
ap_if.config('all')
utime.sleep(5)
# Stop STA interface
print("\n=== Stop STA interface =============\n")
sta_if.active(False)
utime.sleep(1)
# Get FTP server status
# FTP now listens only on AP IP
print("\n=== Ftp server status ==============\n")
network.ftp.status()
# Stop AP interface
# WiFi will be stopped
print("\n=== Stop AP interface ==============\n")
ap_if.active(False)
utime.sleep(1)
# Get FTP server status
# FTP is now disabled, as no WiFi interface is active
print("\n=== Ftp server status ==============\n")
network.ftp.status()
# Check WiFi status
print("WiFi active: {}".format(network.WLAN().wifiactive()))
The output produced when running the script:
D (22100) [modnetwork]: Initializing TCP/IP
D (22101) [modnetwork]: Initializing Event Loop
D (22101) [modnetwork]: Event loop initialized
=== Create WLAN instance objects ===
=== Activate STA ===================
I (22110) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
I (22119) system_api: Base MAC address is not set, read default base MAC address from BLK0 of EFUSE
D (22138) [modnetwork]: WiFi Initialized
I (22196) phy: phy_version: 383.0, 79a622c, Jan 30 2018, 15:38:06, 0, 0
D (22197) [modnetwork]: WiFi Started, mode 1
True
=== Connect to access point ========
108 [WiFi] event: 2 (Station start)
1117 [WiFi] event: 4 (Station connected to AP), info: {'ssid': 'LoBoInternet', 'channel': 1}
3528 [WiFi] event: 7 (Station got IP from connected AP), info: {'ip': '192.168.0.15', 'changed': True}
=== STA Connected ==================
('192.168.0.15', '255.255.255.0', '192.168.0.1', '83.139.103.3')
=== Start Ftp server ===============
True
(2, 0, 'Ready', 'Data: Disconnected', ('192.168.0.15',))
=== STA configuration ==============
{'wifimode': (1, 'STA'), 'dhcp_hostname': 'espressif', 'mac': b'0\xae\xa4#\x13\xd4', 'mode': (0, 'STA_IF')}
=== Activate AP ====================
D (25882) [modnetwork]: WiFi Stopped
D (25891) [modnetwork]: WiFi Started, mode 3
True
3899 [WiFi] event: 2 (Station start)
3904 [WiFi] event: 13 (Soft-AP start)
=== AP started =====================
('192.168.4.1', '255.255.255.0', '192.168.4.1', '0.0.0.0')
4019 [WiFi] event: 4 (Station connected to AP), info: {'ssid': 'LoBoInternet', 'channel': 1}
6031 [WiFi] event: 7 (Station got IP from connected AP), info: {'ip': '192.168.0.15', 'changed': False}
=== STA ReConnected ================
('192.168.0.15', '255.255.255.0', '192.168.0.1', '83.139.103.3')
=== AP configuration ===============
{'wifimode': (3, 'APSTA'), 'authmode': (0, 'OPEN'), 'mac': b'0\xae\xa4#\x13\xd5', 'dhcp_hostname': 'espressif', 'essid': 'ESP_2313D5', 'channel': 1, 'mode': (1, 'AP_IF')}
=== Ftp server status ==============
(2, 0, 'Ready', 'Data: Disconnected', ('192.168.0.15', '192.168.4.1'))
=== Change AP parameters ===========
9136 [WiFi] event: 14 (Soft-AP stop)
9142 [WiFi] event: 13 (Soft-AP start)
=== AP ReStarted ===================
{'wifimode': (3, 'APSTA'), 'authmode': (4, 'WPA_WPA2_PSK'), 'mac': b'0\xae\xa4#\x13\xd5', 'dhcp_hostname': 'espressif', 'essid': 'ESP32_LoBo', 'channel': 1, 'mode': (1, 'AP_IF')}
=== Stop STA interface =============
D (36267) [modnetwork]: WiFi Stopped
D (36276) [modnetwork]: WiFi Started, mode 2
False
=== Ftp server status ==============
(2, 0, 'Ready', 'Data: Disconnected', ('192.168.4.1',))
=== Stop AP interface ==============
I (37293) [modnetwork]: WiFi Stopped
False
=== Ftp server status ==============
(0, 0, 'Disabled', 'Data: Disconnected', None)
WiFi active: False
Telnet server
FTP server
Mqtt server
mDNS server
GSM-PPPoS support