-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuwifi.py
103 lines (90 loc) · 3.23 KB
/
uwifi.py
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
"""
Module to allow the connection of a Oi Pico to a Wifi network
- pre-requisite: a SSIDs list of pair (ssid, passwd) in a ssids module
Example of ssids.py:
from micropython import const
SSIDs = const((
("home ssid", 'password1'),
("eric's phone", 'password2')
))
"""
from time import sleep
import network
from ubinascii import hexlify
from ssids import SSIDs
class uWifi:
_wlan = None
def __init__(self, display=None):
"""
Connect to a Wifi network looking through the possible ssids list
"""
self._wlan = network.WLAN(network.STA_IF)
self._wlan.active(True)
nets = self._wlan.scan()
foundSSIDs = [n[0].decode('utf-8') for n in nets]
# print(nets)
for SSID, PASSWORD in SSIDs:
if SSID in foundSSIDs:
print("Trying SSID", SSID)
self._wlan.connect(SSID, PASSWORD)
# Wait for connect or fail
for max_wait in range(10):
print('Waiting for connection...', max_wait, "Status", self._wlan.status())
if display:
display.multiLines(f"Connecting to\n{SSID}\n\n{1 + max_wait}/10")
sleep(1)
if self._wlan.isconnected():
print("Connected with self.ip:", self.ip)
if display:
display.multiLines(f"Connected to\n{SSID}\nIP {self.ip}")
return
# def __init__(self, display=None):
# """
# Connects to a Wifi network looking through the possible ssids list
# """
# self._wlan = network.WLAN(network.STA_IF)
# self._wlan.active(True)
# # go through the list of possibilities ; returns at the first connection
# for SSID, PASSWORD in SSIDs:
# print("SSID", SSID)
# self._wlan.connect(SSID, PASSWORD)
# # Wait for connect or fail
# for max_wait in range(10):
# print('waiting for connection...', max_wait, "Status", self._wlan.status())
# if display:
# display.multiLines(f"Connecting to\n{SSID}\n\n{1 + max_wait}/10")
# if self._wlan.status() < 0 or self._wlan.status() >= 3:
# # sleep(1)
# break
# sleep(1)
# if self._wlan.isconnected():
# print("Connected with self.ip:", self.ip)
# if display:
# display.multiLines(f"Connected to\n{SSID}\nIP {self.ip}")
# return
def __bool__(self):
return self._wlan.isconnected()
def ifconfig(self):
return self._wlan.ifconfig()
@property
def ssid(self):
return self._wlan.config("ssid")
@property
def mac(self):
try:
mac = hexlify(self._wlan.config('mac'), ':').decode()
except:
mac = ""
return mac
@property
def ip(self):
try:
res = self.ifconfig()[0]
except IndexError:
res = "?.?.?.?"
return res
if __name__ == "__main__":
wlan = uWifi()
if wlan:
print(f"Connected as {wlan.ip}")
print(f"MAC as {wlan.mac}")