snipplets.dev/code/MicroPython/network_sta.py

39 lines
1017 B
Python

import time
import network
def connect(ssid: str, password: str) -> bool:
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.config(reconnects=2)
if not wlan.isconnected():
print('Scanning networks...')
wlan.scan()
print('Connecting to {0}...'.format(ssid))
# try:
wlan.connect(ssid, password)
while not wlan.isconnected():
status = wlan.status()
if status in (network.STAT_IDLE, network.STAT_WRONG_PASSWORD, network.STAT_NO_AP_FOUND):
print('\nConnection to "{0}" failed!'.format(ssid))
wlan.active(False)
return False
print('.', end='')
time.sleep(0.1)
print('\nConnection success!')
ifconfig = wlan.ifconfig()
print('IP: {0}'.format(ifconfig[0]))
return True
else:
print('Already connected!')
ifconfig = wlan.ifconfig()
print('IP: {0}'.format(ifconfig[0]))
return True