from time import sleep_ms, ticks_ms
from machine import Pin, I2C
import network
import urequests
import time
import json
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
ssid = "Grey pg 5G"
password = "SANDHU87"
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16)
button = Pin(4, Pin.IN, Pin.PULL_UP)
api_url = "http://192.168.1.16:5000/api/dashboard"
candidates = []
current_index = 0
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
lcd.clear()
lcd.putstr("Connecting WiFi...")
while not wlan.isconnected():
time.sleep(1)
lcd.clear()
lcd.putstr("WiFi Connected")
print("Connected to WiFi:", wlan.ifconfig())
time.sleep(2)
lcd.clear()
def fetch_candidates():
global candidates
try:
response = urequests.get(api_url)
if response.status_code == 200:
candidates = [entry['name'] for entry in response.json()]
response.close()
else:
lcd.clear()
lcd.putstr("API Error!")
time.sleep(2)
lcd.clear()
except Exception as e:
print("Error:", e)
lcd.clear()
lcd.putstr("Request Failed")
time.sleep(2)
lcd.clear()
def show_candidate(index):
lcd.clear()
name = candidates[index][:16]
lcd.putstr("Candidate:\n" + name)
connect_wifi()
fetch_candidates()
if candidates:
show_candidate(current_index)
last_button = button.value()
while True:
current_button = button.value()
if last_button == 1 and current_button == 0:
current_index += 1
if current_index >= len(candidates):
current_index = 0
show_candidate(current_index)
time.sleep(0.3)
last_button = current_button
time.sleep(0.05)