Skip to content

Commit 6a9bf4e

Browse files
Rework WifiService to lock while scanning
1 parent 41c1ce1 commit 6a9bf4e

File tree

6 files changed

+133
-27
lines changed

6 files changed

+133
-27
lines changed

internal_filesystem/builtin/apps/com.micropythonos.wifi/assets/wifi.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
import mpos.config
1010
import mpos.ui.anim
11+
import mpos.wifi
1112

1213
have_network = True
1314
try:
@@ -46,8 +47,8 @@ def onCreate(self):
4647
self.aplist.align(lv.ALIGN.TOP_MID,0,0)
4748
print("create_ui: Creating error label")
4849
self.error_label=lv.label(main_screen)
49-
self.error_label.set_text("")
50-
self.error_label.align(lv.ALIGN.BOTTOM_MID,0,-40)
50+
self.error_label.set_text("THIS IS ERROR TEXT THAT WILL BE SET LATER")
51+
self.error_label.align_to(self.aplist, lv.ALIGN.OUT_BOTTOM_MID,0,0)
5152
self.error_label.add_flag(lv.obj.FLAG.HIDDEN)
5253
print("create_ui: Creating Scan button")
5354
self.scan_button=lv.button(main_screen)
@@ -63,8 +64,12 @@ def onResume(self, screen):
6364
global access_points
6465
access_points = mpos.config.SharedPreferences("com.micropythonos.system.wifiservice").get_dict("access_points")
6566
self.keep_running = True
66-
if len(self.ssids) == 0:
67-
self.start_scan_networks()
67+
if mpos.wifi.WifiService.wifi_busy == False:
68+
mpos.wifi.WifiService.wifi_busy = True
69+
if len(self.ssids) == 0:
70+
self.start_scan_networks()
71+
else:
72+
self.show_error("Wifi is busy, please try again later.")
6873

6974
def onStop(self, screen):
7075
self.keep_running = False
@@ -75,7 +80,7 @@ def show_error(self, message):
7580
print(f"show_error: Displaying error: {message}")
7681
lv.async_call(lambda l: self.error_label.set_text(message), None)
7782
lv.async_call(lambda l: self.error_label.remove_flag(lv.obj.FLAG.HIDDEN), None)
78-
timer=lv.timer_create(lambda t: self.error_label.add_flag(lv.obj.FLAG.HIDDEN),3000,None)
83+
timer=lv.timer_create(lambda t: self.error_label.add_flag(lv.obj.FLAG.HIDDEN),5000,None)
7984
timer.set_repeat_count(1)
8085

8186
def scan_networks_thread(self):
@@ -99,6 +104,7 @@ def scan_networks_thread(self):
99104
self.show_error("Wi-Fi scan failed")
100105
# scan done:
101106
self.busy_scanning = False
107+
mpos.wifi.WifiService.wifi_busy = False
102108
if self.keep_running:
103109
# Schedule UI updates because different thread
104110
lv.async_call(lambda l: self.scan_button_label.set_text(self.scan_button_scan_text), None)
@@ -147,7 +153,7 @@ def refresh_list(self):
147153
def scan_cb(self, event):
148154
print("scan_cb: Scan button clicked, refreshing list")
149155
self.start_scan_networks()
150-
156+
151157
def select_ssid_cb(self,ssid):
152158
print(f"select_ssid_cb: SSID selected: {ssid}")
153159
intent = Intent(activity_class=PasswordPage)

internal_filesystem/builtin/system/WifiService.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@
1010
import mpos.config
1111
import mpos.time
1212

13+
# crude lock on wifi:
14+
wifi_busy = False
15+
1316
def auto_connect():
1417
networks = wlan.scan()
1518
for n in networks:
@@ -48,7 +51,6 @@ def attempt_connecting(ssid,password):
4851
print(f"auto_connect.py attempt_connecting: Connection error: {e}")
4952
return False
5053

51-
5254
print("WifiService.py running")
5355

5456
have_network=True
@@ -65,12 +67,15 @@ def attempt_connecting(ssid,password):
6567
print("WifiService.py: no network module found, exiting...")
6668
elif len(access_points):
6769
wlan=network.WLAN(network.STA_IF)
68-
wlan.active(False) # restart WiFi hardware in case it's in a bad state
69-
wlan.active(True)
70-
if auto_connect():
71-
print("WifiService.py managed to connect.")
72-
else:
73-
print("WifiService.py did not manage to connect.")
74-
wlan.active(False) # disable to conserve power
70+
if not wifi_busy:
71+
wifi_busy = True
72+
wlan.active(False) # restart WiFi hardware in case it's in a bad state
73+
wlan.active(True)
74+
if auto_connect():
75+
print("WifiService.py managed to connect.")
76+
else:
77+
print("WifiService.py did not manage to connect.")
78+
wlan.active(False) # disable to conserve power
79+
wifi_busy = False
7580
else:
7681
print("WifiService.py: not access points configured, exiting...")

internal_filesystem/lib/mpos/apps.py

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -219,17 +219,6 @@ def parse_manifest(manifest_path):
219219
except OSError:
220220
print(f"parse_manifest: error loading manifest_path: {manifest_path}")
221221
return default_app
222-
223-
224-
225-
def auto_connect():
226-
builtin_auto_connect = "builtin/system/WifiService.py"
227-
try:
228-
print(f"Starting {builtin_auto_connect}...")
229-
stat = uos.stat(builtin_auto_connect)
230-
execute_script_new_thread(builtin_auto_connect, True)
231-
except Exception as e:
232-
print("Couldn't execute {builtin_auto_connect} because exception {e}, continuing...")
233222

234223

235224
class Activity:

internal_filesystem/lib/mpos/ui/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import lvgl as lv
44
import mpos.apps
5+
import mpos.wifi
56
from mpos.ui.anim import WidgetAnimator
67

78
th = None
@@ -197,7 +198,7 @@ def update_time(timer):
197198
print("Warning: could not check WLAN status:", str(e))
198199

199200
def update_wifi_icon(timer):
200-
if not can_check_network or network.WLAN(network.STA_IF).isconnected():
201+
if mpos.wifi.WifiService.is_connected():
201202
wifi_icon.remove_flag(lv.obj.FLAG.HIDDEN)
202203
else:
203204
wifi_icon.add_flag(lv.obj.FLAG.HIDDEN)
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
# Automatically connect to the WiFi, based on the saved networks
2+
# Manage concurrent accesses to the wifi (scan while connect, connect while scan etc)
3+
# Manage saved networks
4+
# This gets started in a new thread, does an autoconnect, and exits.
5+
6+
import ujson
7+
import os
8+
import time
9+
10+
import mpos.config
11+
import mpos.time
12+
13+
have_network = False
14+
try:
15+
import network
16+
have_network = True
17+
except Exception as e:
18+
print("Could not import network, have_network=False")
19+
20+
class WifiService():
21+
22+
wifi_busy = False # crude lock on wifi
23+
24+
@staticmethod
25+
def connect():
26+
networks = wlan.scan()
27+
for n in networks:
28+
ssid = n[0].decode()
29+
print(f"auto_connect: checking ssid '{ssid}'")
30+
if ssid in access_points:
31+
password = access_points.get(ssid).get("password")
32+
print(f"auto_connect: attempting to connect to saved network {ssid} with password {password}")
33+
if attempt_connecting(ssid,password):
34+
print(f"auto_connect: Connected to {ssid}")
35+
return True
36+
else:
37+
print(f"auto_connect: failed to connect to {ssid}")
38+
else:
39+
print(f"auto_connect: not trying {ssid} because it hasn't been configured")
40+
print("auto_connect: no known networks connected")
41+
return False
42+
43+
@staticmethod
44+
def attempt_connecting(ssid,password):
45+
print(f"auto_connect.py attempt_connecting: Attempting to connect to SSID: {ssid}")
46+
try:
47+
wlan.connect(ssid,password)
48+
for i in range(10):
49+
if wlan.isconnected():
50+
print(f"auto_connect.py attempt_connecting: Connected to {ssid} after {i+1} seconds")
51+
mpos.time.sync_time()
52+
return True
53+
elif not wlan.active(): # wificonf app or others might stop the wifi, no point in continuing then
54+
print("auto_connect.py attempt_connecting: Someone disabled wifi, bailing out...")
55+
return False
56+
print(f"auto_connect.py attempt_connecting: Waiting for connection, attempt {i+1}/10")
57+
time.sleep(1)
58+
print(f"auto_connect.py attempt_connecting: Failed to connect to {ssid}")
59+
return False
60+
except Exception as e:
61+
print(f"auto_connect.py attempt_connecting: Connection error: {e}")
62+
return False
63+
64+
@staticmethod
65+
def auto_connect():
66+
print("auto_connect thread running")
67+
68+
# load config:
69+
access_points = mpos.config.SharedPreferences("com.micropythonos.system.wifiservice").get_dict("access_points")
70+
if not len(access_points):
71+
print("WifiService.py: not access points configured, exiting...")
72+
return
73+
74+
if not WifiService.wifi_busy:
75+
WifiService.wifi_busy = True
76+
if not have_network:
77+
print("auto_connect: no network module found, waiting to simulate connection...")
78+
time.sleep(10)
79+
print("auto_connect: wifi connect simulation done")
80+
else:
81+
wlan=network.WLAN(network.STA_IF)
82+
wlan.active(False) # restart WiFi hardware in case it's in a bad state
83+
wlan.active(True)
84+
if connect():
85+
print("WifiService.py managed to connect.")
86+
else:
87+
print("WifiService.py did not manage to connect.")
88+
wlan.active(False) # disable to conserve power
89+
WifiService.wifi_busy = False
90+
91+
@staticmethod
92+
def is_connected():
93+
if WifiService.wifi_busy:
94+
return False
95+
elif not have_network:
96+
return True
97+
else:
98+
return network.WLAN(network.STA_IF).isconnected()

internal_filesystem/main.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import task_handler
2+
import _thread
23

34
# Allow LVGL M:/path/to/file or M:relative/path/to/file to work for image set_src etc
45
import fs_driver
@@ -35,7 +36,13 @@
3536

3637
apps.execute_script("builtin/system/button.py", True) # Install button handler through IRQ
3738

38-
apps.auto_connect()
39+
try:
40+
import mpos.wifi
41+
import mpos.apps
42+
_thread.stack_size(mpos.apps.good_stack_size())
43+
_thread.start_new_thread(mpos.wifi.WifiService.auto_connect, ())
44+
except Exception as e:
45+
print(f"Couldn't start mpos.wifi.WifiService.auto_connect thread because: {e}")
3946

4047
apps.restart_launcher()
4148

0 commit comments

Comments
 (0)