import network
import time
from machine import Pin
import BlynkLib
led1 = Pin(3, Pin.OUT)
print("Connecting to WiFi", end="")
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect("NOWIFI5G","sheiksh@123")
# Wait for network connection
wait = 10
while wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
wait -= 1
print('waiting for connection...')
time.sleep(1)
# Handle connection error
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
ip = wlan.ifconfig()[0]
print('IP: ', ip)
# Connect to Blynk
BLYNK_AUTH = 'I67WAieQKB0J7kEtXmjLv5_8wn-EgH1s'
blynk = BlynkLib.Blynk(BLYNK_AUTH)
# Track connection state
is_connected = True
last_ping_time = time.time()
@blynk.on("V1")
def v1_write_handler(value):
print("Value received from V1:", value)
print("Received value from V1:", value)
try:
if int(value[0]) == 1:
led1.value(1)
print("Relay ON")
else:
led1.value(0)
print("Relay OFF")
except Exception as e:
print("Error processing value:", e)
def check_connection():
"""Ping the Blynk server to verify connectivity."""
global is_connected, last_ping_time
current_time = time.time()
if current_time - last_ping_time > 1: # Ping every 10 seconds
try:
blynk.virtual_write(255, "Ping") # Send a test write
print("Connection OK")
is_connected = True
except Exception as e:
print("Connection Error:", e)
is_connected = False
finally:
last_ping_time = current_time
while True:
try:
blynk.run()
check_connection()
except Exception as e:
print("Error in Blynk loop:", e)
is_connected = False
time.sleep(1) # Pause briefly before retrying