Think I finally nailed this problem.
Running this test.py:
Code: Select all
import network
from wifi_functions import connect
from wifi_functions import disconnect
import utime
sta_if = network.WLAN(network.STA_IF) # create station interface
while True:
connect()
utime.sleep(5)
disconnect()
print ('disconnected')
utime.sleep(5)
and my wifi_functions.py
Code: Select all
import network
import utime
import machine
import config
sta_if = network.WLAN(network.STA_IF) # create station interface
ap_if = network.WLAN(network.AP_IF) # create access-point interface
def connect():
count = 0
# disconnects AP if it is up
ap_if.active(False) # de-activate the AP interface
utime.sleep(1)
if not sta_if.isconnected():
print('connecting to hotspot...')
sta_if.active(True)
sta_if.ifconfig((config.WiFi_device, '255.255.255.0', config.gateway, '8.8.8.8'))
sta_if.connect(config.hotspot, config.password)
while (count < 5):
count += 1
if (sta_if.isconnected()):
count = 0
print (' network config:', sta_if.ifconfig())
break
print ('.', end = '')
utime.sleep(1)
if (count == 5):
try:
with open('errors.txt', 'a') as outfile:
outfile.write('failed to connect' + '\n')
except OSError:
pass
# disconnect or you get errors
disconnect()
count = 0 # reset count
utime.sleep(1)
def disconnect():
# disconnects STA, even if it is not connected
sta_if.disconnect() # This is line 59
sta_if.active(False)
utime.sleep(1)
I would get this error:
Code: Select all
MPY: soft reboot
connecting to hotspot...
.....Traceback (most recent call last):
File "main.py", line 2, in <module>
File "test.py", line 12, in <module>
File "wifi_functions.py", line 59, in disconnect
OSError: Wifi Not Started
MicroPython v1.18 on 2022-01-17; ESP32 module with ESP32
Type "help()" for more information.
I guess it is not a surprise that trying to disconnect when you are NOT connected
might be an issue. Re-reading Shards response I thought I would put line 59
in a try ... except block.
Code: Select all
def disconnect():
try:
# disconnects STA, even if it is not connected
sta_if.disconnect()
except:
pass
sta_if.active(False)
utime.sleep(1)
Voila!! No more ... OSError: Wifi Not Started
When running test.py if you do a Ctrl C during the connection attempt, then another
CtrlD I get:
Code: Select all
MPY: soft reboot
connecting to hotspot...
E (63083) wifi:sta is connecting, return error
Traceback (most recent call last):
File "main.py", line 2, in <module>
File "test.py", line 10, in <module>
File "wifi_functions.py", line 24, in connect
OSError: Wifi Internal Error
MicroPython v1.18 on 2022-01-17; ESP32 module with ESP32
Type "help()" for more information
.
This suggests that:
Code: Select all
sta_if.connect(config.hotspot, config.password)
should be a try ... except block. But that was what Shards recommended in the first place!!
I hope this is another step towards getting reliable WiFi access.
Thanks to both of you for your suggestions.