|
| 1 | +# Automatically connect to the WiFi, based on the saved networks |
| 2 | + |
| 3 | +import network |
| 4 | +import ujson |
| 5 | +import os |
| 6 | +import time |
| 7 | + |
| 8 | + |
| 9 | +access_points={} |
| 10 | + |
| 11 | + |
| 12 | +def load_config(): |
| 13 | + print("load_config: Checking for /data directory") |
| 14 | + try: |
| 15 | + os.stat('/data') |
| 16 | + print("load_config: /data exists") |
| 17 | + except OSError: |
| 18 | + print("load_config: Creating /data directory") |
| 19 | + os.mkdir('/data') |
| 20 | + print("load_config: Checking for /data/com.example.wificonf directory") |
| 21 | + try: |
| 22 | + os.stat('/data/com.example.wificonf') |
| 23 | + print("load_config: /data/com.example.wificonf exists") |
| 24 | + except OSError: |
| 25 | + print("load_config: Creating /data/com.example.wificonf directory") |
| 26 | + os.mkdir('/data/com.example.wificonf') |
| 27 | + print("load_config: Loading config from conf.json") |
| 28 | + try: |
| 29 | + with open('/data/com.example.wificonf/conf.json','r') as f: |
| 30 | + global access_points |
| 31 | + access_points=ujson.load(f) |
| 32 | + print(f"load_config: Loaded access_points: {access_points}") |
| 33 | + except OSError: |
| 34 | + access_points={} |
| 35 | + print("load_config: No config file found, using empty access_points") |
| 36 | + |
| 37 | + |
| 38 | +def auto_connect(): |
| 39 | + # TODO: scan for wifi networks first, and only try to connect to the ones that are found |
| 40 | + print("auto_connect: Attempting to connect to known networks") |
| 41 | + for ssid,password in access_points.items(): |
| 42 | + print(f"auto_connect: Trying SSID: {ssid}") |
| 43 | + if attempt_connecting(ssid,password): |
| 44 | + print(f"auto_connect: Connected to {ssid}") |
| 45 | + return True |
| 46 | + print("auto_connect: No known networks connected") |
| 47 | + return False |
| 48 | + |
| 49 | + |
| 50 | +def attempt_connecting(ssid,password): |
| 51 | + print(f"attempt_connecting: Attempting to connect to SSID: {ssid}") |
| 52 | + try: |
| 53 | + wlan.connect(ssid,password) |
| 54 | + for i in range(10): |
| 55 | + if wlan.isconnected(): |
| 56 | + print(f"attempt_connecting: Connected to {ssid} after {i+1} seconds") |
| 57 | + return True |
| 58 | + print(f"attempt_connecting: Waiting for connection, attempt {i+1}/10") |
| 59 | + time.sleep(1) |
| 60 | + print(f"attempt_connecting: Failed to connect to {ssid}") |
| 61 | + return False |
| 62 | + except Exception as e: |
| 63 | + print(f"attempt_connecting: Connection error: {e}") |
| 64 | + return False |
| 65 | + |
| 66 | +print("auto_connect.py running...") |
| 67 | +load_config() |
| 68 | + |
| 69 | +wlan=network.WLAN(network.STA_IF) |
| 70 | +wlan.active(True) |
| 71 | + |
| 72 | +if auto_connect(): |
| 73 | + print("WiFi auto-connect managed to connect.") |
| 74 | +else: |
| 75 | + print("WiFi auto connect did not manage to connect.") |
0 commit comments