-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwifi.py
More file actions
80 lines (70 loc) · 2.28 KB
/
Copy pathwifi.py
File metadata and controls
80 lines (70 loc) · 2.28 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
import socket, json
import network
import time
class PicoWiFi():
"""
A class for Wifi connectivity on the Pico.
"""
def __init__(self, ssid: str, password: str):
self.ssid = ssid
self.password = password
self.wlan = network.WLAN(network.STA_IF)
self.wlan.active(True)
self.networks = None
def is_connected(self):
status = self.wlan.status()
if status == 3:
print('Connected')
print('Network config:', self.wlan.ifconfig())
return True
else:
self._handle_connection_failure(status)
return False
def _handle_connection_failure(self, status):
if status == -1:
print('Wi-Fi connection failed: Connection failed')
elif status == -2:
print('Wi-Fi connection failed: No AP found')
elif status == -3:
print('Wi-Fi connection failed: Wrong password')
else:
print(f'Wi-Fi connection failed with status code: {status}')
return
def connect(self):
print(f"Connecting to {self.ssid}...")
self.wlan.connect(self.ssid, self.password)
max_tries = 1
while max_tries < 11:
status = self.wlan.status()
if status < 0 or status >= 3:
break
max_tries += 1
print(f'Waiting for connection, status: {status}')
time.sleep(1)
return self.is_connected()
def disconnect(self):
self.wlan.disconnect()
print("Disconnected from Wi-Fi.")
return
def check_SSID(self, ssid=None, networks=None):
"""
Check to see if the SSID is available,
"""
found = False
for net in networks:
if net[0].decode('utf-8') == ssid:
found = True
return found
def scan_networks(self, debug=False):
"""
Scan for networks
"""
self.networks = self.wlan.scan()
if debug:
if len(self.networks) > 0:
for net in self.networks:
ssid = net[0].decode('utf-8')
print(f"SSID: {ssid}, Signal Strength: {net[3]}")
return self.networks
def get_ip(self):
return self.wlan.ifconfig()[0]