2 Commits

Author SHA1 Message Date
Daniel Svitan
7d2ad1cd49 🐛 Fixes memory overflow and removes server health check
All checks were successful
Gitea Build Action / build (push) Successful in 22s
2025-06-02 20:46:55 +02:00
Daniel Svitan
307b467ac1 🚧 Adds checking and reconnecting when wlan is down
All checks were successful
Gitea Build Action / build (push) Successful in 24s
2025-06-01 21:19:13 +02:00

View File

@@ -1,3 +1,4 @@
import gc
import utime
import ujson
import network
@@ -17,6 +18,7 @@ class App:
opened: bool = False
previously_opened: bool = False
wlan: network.WLAN
led = Pin(15, Pin.OUT)
trigger = Pin(2, Pin.OUT)
@@ -55,18 +57,18 @@ class App:
def connect(self):
print("Connecting to Wi-Fi...")
wlan = network.WLAN(network.STA_IF)
self.wlan = network.WLAN(network.STA_IF)
wlan.active(False)
self.wlan.active(False)
utime.sleep_ms(250)
wlan.active(True)
self.wlan.active(True)
utime.sleep_ms(250)
wlan.connect(self.ssid, self.password)
self.wlan.connect(self.ssid, self.password)
utime.sleep_ms(100)
retry_count = 0
while not wlan.isconnected():
while not self.wlan.isconnected():
if retry_count >= MAX_CONNECTION_RETRIES:
print("Max connection retries reached")
exit(1)
@@ -80,22 +82,14 @@ class App:
if retry_count % 10 == 0:
print("Attempting to restart connection...")
wlan.connect(self.ssid, self.password)
self.wlan.connect(self.ssid, self.password)
for _ in range(10):
self.led.toggle()
utime.sleep_ms(50)
print(f"Connected with IP {wlan.ifconfig()[0]}")
print(f"Connected with IP {self.wlan.ifconfig()[0]}")
self.update_server()
def health_check_server(self):
print("Health checking server...", end="\r")
try:
r = urequests.get(f"{self.server}/")
print(f"Server healthy [{r.status_code}]{" " * 8}")
except Exception as e:
print(f"Error occurred: {e}")
def update_server(self):
print("Updating state...", end="\r")
data = {"opened": self.opened}
@@ -128,7 +122,7 @@ class App:
delta_time = received_time - sent_time
distance = delta_time / 1_000_000 * SOUND_SPEED / 2
print(f"Distance: {distance} cm")
print(f"Distance: {distance:0<5} cm; mem_free = {gc.mem_free()}")
return distance
@@ -139,6 +133,9 @@ class App:
i = 0
while True:
try:
if not self.wlan.isconnected():
self.connect()
distance = self.measure_distance()
self.opened = distance >= THRESHOLD_DISTANCE
@@ -157,13 +154,14 @@ class App:
self.previously_opened = True
if i >= 20:
print("Blinking...")
self.led.toggle()
utime.sleep_ms(100)
self.led.toggle()
utime.sleep_ms(400)
i = 0
self.health_check_server()
gc.collect()
else:
utime.sleep_ms(500)