-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_wifi.py
More file actions
84 lines (68 loc) · 2.68 KB
/
Copy path_wifi.py
File metadata and controls
84 lines (68 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# This file is part of espzero, automatically synced from
# https://github.com/roboticsware/espzero at revision 24cae2bc1c028458052675181e95f2a08fdf7481.
# Do not edit this file directly — run update_user_libs.py espzero instead.
"""
espzero/_wifi.py
WiFi class for ESP32 — wraps the network module in a picozero-style API.
"""
from . import _hal
class WiFi:
"""
Wraps ESP32 WiFi (station mode) in a simple, picozero-style interface.
Usage::
from espzero import WiFi
wifi = WiFi()
ip = wifi.connect("MySSID", "password")
print("Connected:", ip)
"""
def __init__(self):
import network
self._sta = network.WLAN(network.STA_IF)
def connect(self, ssid, password, timeout=10):
"""
Connect to the given access point.
Blocks until connected (up to *timeout* seconds) then returns the
assigned IP address string. Raises ``OSError`` on timeout.
Also sets the HAL ``_wifi_active`` flag so that any subsequent call to
``make_adc()`` with an ADC2 pin will print a warning.
:param str ssid: Network name (SSID).
:param str password: Network password.
:param int timeout: Maximum seconds to wait for connection. Default 10.
:returns: IP address string.
:raises OSError: If the connection times out.
"""
import time
self._sta.active(True)
self._sta.connect(ssid, password)
start = time.time()
while not self._sta.isconnected():
if time.time() - start > timeout:
raise OSError("[espzero] WiFi connection timed out.")
time.sleep(0.1)
_hal._wifi_active = True
print("[espzero] WiFi connected. IP:", self._sta.ifconfig()[0])
print("[espzero] NOTE: ADC2 pins are unavailable while WiFi is active.")
return self._sta.ifconfig()[0]
def disconnect(self):
"""Disconnect from the current access point."""
self._sta.disconnect()
_hal._wifi_active = False
def scan(self):
"""
Scan for nearby access points.
:returns: List of tuples ``(ssid, bssid, channel, rssi, authmode, hidden)``.
"""
self._sta.active(True)
return self._sta.scan()
@property
def is_connected(self):
"""``True`` if currently connected to an access point."""
return self._sta.isconnected()
@property
def ip(self):
"""Current IP address, or ``None`` if not connected."""
return self._sta.ifconfig()[0] if self.is_connected else None
@property
def ifconfig(self):
"""Full interface config tuple ``(ip, mask, gateway, dns)``."""
return self._sta.ifconfig()