class-based version
# wifi_connect.py
import network
import time
class WiFiConnector:
def __init__(self, ssid, password, timeout=20, max_retries=3):
"""
Initialize the WiFiConnector with credentials and settings.
Parameters:
ssid (str): Wi-Fi network SSID
password (str): Wi-Fi password
timeout (int): Timeout in seconds per connection attempt
max_retries (int): Number of reconnection retries
"""
self.ssid = ssid
self.password = password
self.timeout = timeout
self.max_retries = max_retries
self.wlan = network.WLAN(network.STA_IF)
def connect(self):
"""Attempts to connect to Wi-Fi once. Returns True if successful."""
try:
self.wlan.active(True)
if not self.wlan.isconnected():
print(f'Connecting to {self.ssid}...')
self.wlan.connect(self.ssid, self.password)
for _ in range(self.timeout):
if self.wlan.isconnected():
break
time.sleep(1)
if self.wlan.isconnected():
print('Connected successfully!')
print('IP address:', self.wlan.ifconfig()[0])
return True
else:
print('Connection failed: timeout.')
return False
except Exception as e:
print('Error during Wi-Fi connection:', str(e))
return False
def reconnect(self):
"""
Tries to reconnect to Wi-Fi, retrying up to max_retries times.
Returns:
bool: True if reconnection succeeded, False otherwise.
"""
print(f'Reconnecting (max {self.max_retries} retries)...')
for attempt in range(1, self.max_retries + 1):
print(f'Attempt {attempt}...')
if self.connect():
return True
time.sleep(2) # wait before retrying
print('Reconnection failed.')
return False
def disconnect(self):
"""Disconnects from the Wi-Fi network."""
if self.wlan.isconnected():
self.wlan.disconnect()
print('Disconnected from Wi-Fi.')
def is_connected(self):
"""Returns True if connected to Wi-Fi."""
return self.wlan.isconnected()
def ip_address(self):
"""Returns the current IP address, or None if not connected."""
if self.wlan.isconnected():
return self.wlan.ifconfig()[0]
return None
main
from wifi_connect import WiFiConnector
# Enter your Wi-Fi SSID and password here
SSID: str = "Raspberrypi_PICO_W"
PASSWORD: str = "qwertyuiop1234"
wifi = WiFiConnector(SSID, PASSWORD)
if not wifi.connect():
wifi.reconnect()
if wifi.is_connected():
print('Wi-Fi connection established.')
print('IP:', wifi.ip_address())
else:
print('Unable to connect after retries.')
コメント