-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
56 lines (49 loc) · 1.73 KB
/
main.py
File metadata and controls
56 lines (49 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import network
import credentials
import time
from simple import MQTTClient
from machine import Pin, SPI
import utime
import screen
import wifi
# Constants for WiFi and MQTT reconnection attempts
WIFI_RECONNECT_INTERVAL = 10 # seconds
MQTT_RECONNECT_INTERVAL = 10 # seconds
# Initialize last attempt timers
last_wifi_attempt = 0
last_mqtt_attempt = 0
def maintain_wifi_connection():
global last_wifi_attempt
if not network.WLAN(network.STA_IF).isconnected():
# Only attempt to reconnect if WIFI_RECONNECT_INTERVAL has passed
if time.time() - last_wifi_attempt > WIFI_RECONNECT_INTERVAL:
screen.display_centered_text("Reconnecting WiFi...")
wifi.connect_wifi() # Your function to connect to WiFi
last_wifi_attempt = time.time()
screen.show_network_status()
else:
wifi_connected = 1
def maintain_mqtt_connection():
global last_mqtt_attempt
# Check if an MQTT client object exists and is connected
if wifi.mqtt_connected:
# Only attempt to reconnect if MQTT_RECONNECT_INTERVAL has passed
if time.time() - last_mqtt_attempt > MQTT_RECONNECT_INTERVAL:
screen.display_centered_text("Reconnecting MQTT...")
wifi.connect_mqtt() # Your function to connect to MQTT
last_mqtt_attempt = time.time()
#screen.display_centered_text("Init")
# Connec to Wifi
wifi.connect_wifi()
#screen.display_centered_text("MQTT")
wifi.connect_mqtt()
# Show "Waiting" message initially
#screen.display_centered_text("Waiting")
screen.show_network_status()
# Main loop
while True:
maintain_wifi_connection()
maintain_mqtt_connection()
# Your main code logic would be here
# Sleep for a bit to avoid a busy loop
time.sleep(1)