#Connects to Wi-Fi, synchronises its clock using NTP (Network Time Protocol)
#Retrieves the weather from the Open-Meteo API every 15 minutes
#Display the current time on a 4-digit TM1637 7-segment display
#Shows outdoor temperature using 4 LED arrays, which update automatically from the internet

#TP Goff August 2025

import network
import urequests
import time
import ntptime
from machine import Pin, RTC
from tm1637 import TM1637

# --- Wi-Fi settings ---
WIFI_SSID = "Your SSID"
WIFI_PASS = "YOUR PASSWORD"

# --- LED pins ---
led_blue = Pin(12, Pin.OUT)
led_green = Pin(13, Pin.OUT)
led_amber = Pin(14, Pin.OUT)
led_red = Pin(15, Pin.OUT)

# --- TM1637 pins ---
tm = TM1637(clk=Pin(2), dio=Pin(3))  # Adjust pins as needed

# --- Connect to Wi-Fi ---
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASS)

print("Connecting to Wi-Fi...", end="")
while not wlan.isconnected():
    print(".", end="")
    time.sleep(0.5)
print("\nConnected! IP:", wlan.ifconfig()[0])

# --- Sync time via NTP ---
try:
    print("Syncing time with NTP...")
    ntptime.settime()  # Sets Pico's RTC (UTC)
    print("Time synced!")
except:
    print("NTP sync failed")

# Adjust for your timezone (e.g., UK = UTC+1 in summer)
TIME_OFFSET = 3600  # seconds

# --- Weather fetch function ---
def fetch_weather():
    try:
        url = "https://api.open-meteo.com/v1/forecast?latitude=52.63&longitude=1.30&current_weather=true"
        response = urequests.get(url)
        data = response.json()
        response.close()

        temperature = data["current_weather"]["temperature"]
        print(f"Temp: {temperature}°C")
        return temperature
    except Exception as e:
        print("Weather fetch error:", e)
        return None

# --- LED update based on temperature ---
def update_leds(temp):
    led_blue.off()
    led_green.off()
    led_amber.off()
    led_red.off()

    if temp is None:
        return
    if temp < 5:
        led_blue.on()
    elif 5 <= temp <= 16:
        led_green.on()
    elif 16 <= temp <= 25:
        led_amber.on()
    else:
        led_red.on()

# --- Main loop ---
last_weather = 0
temperature = fetch_weather()
update_leds(temperature)

while True:
    now = time.time() + TIME_OFFSET
    local_time = time.localtime(now)
    hour = local_time[3]
    minute = local_time[4]

    # Update weather every 15 minutes
    if time.time() - last_weather > 900:
        temperature = fetch_weather()
        update_leds(temperature)
        last_weather = time.time()

    # Display HH:MM
    try:
        tm.numbers(hour, minute)
    except TypeError:
        tm.show(f"{hour:02d}{minute:02d}")

    time.sleep(1)