Skip to content

Commit 4adaaf2

Browse files
committed
wifi_client: simplify nic object
trying to fix a bug whereby I cannot get STAT_WRONG_PASSWORD failed in fixing, but resulting code is better
1 parent ef45a68 commit 4adaaf2

File tree

1 file changed

+57
-30
lines changed

1 file changed

+57
-30
lines changed

bridge/lib/wifi_client.py

Lines changed: 57 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from sys import platform
1313

1414
RP2 = platform == "rp2"
15-
15+
'''
1616
# cyw43_wifi_link_status
1717
error_codes_to_messages = {
1818
0: "CYW43_LINK_DOWN",
@@ -22,6 +22,16 @@
2222
-1: "CYW43_LINK_FAIL",
2323
-2: "CYW43_LINK_NONET",
2424
-3: "CYW43_LINK_BADAUTH",
25+
}'''
26+
# cyw43_wifi_link_status
27+
error_codes_to_messages = {
28+
0: "STAT_IDLE",
29+
1: "STAT_CONNECTING",
30+
2: "STAT_GOT_IP",
31+
3: "CYW43_LINK_UP",
32+
-1: "STAT_CONNECT_FAIL",
33+
-2: "STAT_NO_AP_FOUND",
34+
-3: "STAT_WRONG_PASSWORD",
2535
}
2636

2737
logger = logging.getLogger(__name__)
@@ -33,7 +43,7 @@ def __init__(self, config):
3343
# self._ping_interval = 20000
3444
# self._in_connect = False
3545
# self._has_connected = False # Define 'Clean Session' value to use.
36-
self._sta_if = network.WLAN(network.STA_IF)
46+
self.nic = network.WLAN(network.STA_IF)
3747
self._ssid = config.ssid
3848
self._wifi_pw = config.password
3949
try:
@@ -46,59 +56,76 @@ def __init__(self, config):
4656

4757
async def wifi_connect(self, onboard_led, quick=False):
4858
await onboard_led.set_status(onboard_led.WIFI_CONNECTING)
49-
nic = self._sta_if
50-
nic.active(True)
51-
if RP2: # Disable auto-sleep.
59+
#nic = self._sta_if
60+
#nic.disconnect()
61+
#nic.active(False)
62+
'''if RP2: # Disable auto-sleep.
5263
# https://datasheets.raspberrypi.com/picow/connecting-to-the-internet-with-pico-w.pdf
5364
# para 3.6.3
5465
nic.config(pm=0xA11140)
5566
import rp2
5667
5768
if self._country:
58-
rp2.country(self._country)
69+
rp2.country(self._country)'''
70+
self.nic.deinit()
71+
self.nic = network.WLAN(network.STA_IF)
72+
network.hostname("tilt_micro_bridge")
73+
self.nic.config(pm = network.WLAN.PM_PERFORMANCE)
74+
if self._country:
75+
network.country(self._country)
5976
logger.info("Attempting to connect to wifi")
60-
nic.connect(self._ssid, self._wifi_pw)
61-
for _ in range(60): # Break out on fail or success. Check once per sec.
62-
await asyncio.sleep(1)
77+
self.nic.active(True)
78+
self.nic.connect(self._ssid, self._wifi_pw)
79+
catch = 0
80+
for _ in range(30): # Break out on fail or success. Check once per sec.
81+
catch = self.nic.status() # can be a fleeting status, so capture it
82+
# print(catch)
6383
# Loop while connecting or no IP
64-
if nic.isconnected():
84+
if self.nic.isconnected():
6585
logger.info("wifi connected")
6686
await onboard_led.set_status(onboard_led.WIFI_CONNECTED)
6787
break
68-
if RP2: # 1 is joining. 2 is No IP, ie in process of connecting
69-
if not 1 <= nic.status() <= 3:
70-
logger.warning(f"wifi reports {error_codes_to_messages[nic.status()]}")
71-
break
88+
#if RP2: # 1 is joining. 2 is No IP, ie in process of connecting
89+
# if not 1 <= nic.status() <= 3:
90+
if catch < 1:
91+
logger.warning(f"wifi reports {error_codes_to_messages[catch]}")
92+
break
93+
await asyncio.sleep(1)
7294
else: # Timeout: still in connecting state
73-
nic.disconnect()
74-
nic.active(False)
7595
await onboard_led.set_status(onboard_led.WIFI_DISCONNECTED)
7696
await asyncio.sleep(1)
7797
#if not nic.isconnected(): # Timed out
78-
logger.warning(f"wifi connect timed out {error_codes_to_messages[nic.status()]}")
98+
logger.warning(f"wifi connect timed out {error_codes_to_messages[catch]}")
7999
#raise OSError("Wi-Fi connect timed out")
80100
#else:
81-
if nic.isconnected():
101+
if self.nic.isconnected():
82102
if not quick: # Skip on first connection only if power saving
83103
# Ensure connection stays up for a few secs.
84104
logger.info("Checking wifi integrity")
85105
for _ in range(5):
86-
if not nic.isconnected():
106+
if not self.nic.isconnected():
87107
logger.warning("Connection Unstable")
88108
#raise OSError("Connection Unstable") # in 1st 5 secs
89109
await asyncio.sleep(1)
90110
logger.info("Got reliable connection")
91-
return nic.status()
111+
else: # reset nic
112+
self.nic.disconnect()
113+
self.nic.active(False)
114+
self.nic.deinit()
115+
return catch #nic.status()
92116

93117
async def connect(
94118
self, onboard_led, display=False, quick=False
95119
): # Quick initial connect option for battery apps
96-
nic = self._sta_if
120+
#nic = self._sta_if
97121
attempt = 0
98-
while not nic.isconnected():
122+
while not self.nic.isconnected():
123+
if attempt > 0 and display:
124+
display.show_msg("trying connection again")
125+
del display.startup_msg[-1]
99126
attempt += 1
100127
result = await self.wifi_connect(onboard_led, quick)
101-
if result < 0:
128+
if result < 2:
102129
# wifi not connected
103130
if display:
104131
display.show_msg(f"{error_codes_to_messages[result]} ({attempt})", append = (False if attempt>1 else True))
@@ -111,10 +138,10 @@ async def connect(
111138
logger.debug("sleep 120 secs and try wifi again")
112139
if display:
113140
display.show_msg("trying again in 2 minutes.")
114-
del display.startup_msg[-1] #remove that last message from list - it's a hack
141+
del display.startup_msg[-1] #remove that last message from list - it's hacky
115142
await asyncio.sleep(120)
116143

117-
if nic.isconnected():
144+
if self.nic.isconnected():
118145
if self.check_interval > 0:
119146
asyncio.create_task(self._keep_connected())
120147
# Runs forever unless user issues .disconnect()
@@ -124,10 +151,10 @@ async def connect(
124151
# Scheduled on 1st successful connection. Runs forever maintaining wifi and
125152
# broker connection. Must handle conditions at edge of wifi range.
126153
async def _keep_connected(self):
127-
nic = self._sta_if
154+
#nic = self._sta_if
128155
while True: # nic.active():
129156
logger.debug("running in _keep_connected")
130-
if nic.isconnected(): # Pause for 1 second
157+
if self.nic.isconnected(): # Pause for 1 second
131158
# await asyncio.sleep(1) # debug
132159
await asyncio.sleep(
133160
randrange(
@@ -137,7 +164,7 @@ async def _keep_connected(self):
137164
gc.collect()
138165
else: # Link is down
139166
try:
140-
nic.disconnect()
167+
self.nic.disconnect()
141168
except OSError:
142169
logger.error("Wi-Fi not started, unable to disconnect interface")
143170
await asyncio.sleep(1)
@@ -152,7 +179,7 @@ async def _keep_connected(self):
152179
except OSError as e:
153180
logger.error(f"Error in reconnect. {e}")
154181
# Can get ECONNABORTED or -1. The latter signifies no or bad CONNACK received.
155-
nic.disconnect()
182+
self.nic.disconnect()
156183
logger.warning("Disconnected, exited _keep_connected")
157184

158185

@@ -181,4 +208,4 @@ async def wan_ok(
181208
return False
182209

183210

184-
__version__ = "1.0.1"
211+
__version__ = "1.0.2"

0 commit comments

Comments
 (0)