Bladeren bron

support multiple wifi networks

Thomas Buck 1 jaar geleden
bovenliggende
commit
1fccd7486c
3 gewijzigde bestanden met toevoegingen van 22 en 8 verwijderingen
  1. 1
    1
      CatToy.py
  2. 4
    3
      config.py
  3. 17
    4
      wifi.py

+ 1
- 1
CatToy.py Bestand weergeven

@@ -397,7 +397,7 @@ buttonTimerCallback(None)
397 397
 ledTimerCallback(None)
398 398
 
399 399
 print("Initializing WiFi...")
400
-w = Wifi(Config.ssid, Config.password)
400
+w = Wifi(Config.networks)
401 401
 w.add_handler("/", rootCallback)
402 402
 w.add_handler("/servos", servoCallback)
403 403
 w.add_handler("/laser", laserCallback)

+ 4
- 3
config.py Bestand weergeven

@@ -1,4 +1,5 @@
1 1
 class Config:
2
-# Set your wifi ssid and password here
3
-    ssid = const('')
4
-    password = const('')
2
+    networks = [
3
+        ("SSID_1", "PASS_1"),
4
+        ("SSID_2", "PASS_2"),
5
+    ]

+ 17
- 4
wifi.py Bestand weergeven

@@ -17,17 +17,30 @@ class Wifi:
17 17
     </html>
18 18
     """
19 19
 
20
-    def __init__(self, ssid, password, port = 80):
20
+    def __init__(self, networks, port = 80):
21 21
         # Check if wifi details have been set
22
-        if len(ssid) == 0 or len(password) == 0:
23
-            raise RuntimeError('Please set wifi ssid and password in config.py')
22
+        if len(networks) == 0:
24 23
             self.led.value(1)
24
+            raise RuntimeError('Please set wifi ssid and password in config.py')
25 25
 
26 26
         self.led = Pin("LED", Pin.OUT)
27 27
 
28 28
         # Start connection
29 29
         self.wlan = network.WLAN(network.STA_IF)
30 30
         self.wlan.active(True)
31
+        visible = self.wlan.scan()
32
+        ssid = None
33
+        password = None
34
+        for name, a, b, c, d, e in visible:
35
+            for t_ssid, t_password in networks:
36
+                if name.decode("utf-8") == t_ssid:
37
+                    ssid = t_ssid
38
+                    password = t_password
39
+                    break
40
+        if (ssid == None) or (password == None):
41
+            self.led.value(1)
42
+            raise RuntimeError("No known network found")
43
+
31 44
         self.wlan.connect(ssid, password)
32 45
 
33 46
         # Wait for connect success or failure
@@ -49,8 +62,8 @@ class Wifi:
49 62
 
50 63
         # Handle connection error
51 64
         if self.wlan.status() != 3:
52
-            raise RuntimeError('wifi connection failed %d' % self.wlan.status())
53 65
             self.led.value(1)
66
+            raise RuntimeError('wifi connection failed %d' % self.wlan.status())
54 67
 
55 68
         print('connected')
56 69
         status = self.wlan.ifconfig()

Laden…
Annuleren
Opslaan