import machine
import network
import time
import urequests
import ujson

WIFI_SSID = "lkl"
WIFI_PASSWORD = "123456"

THINGSPEAK_API_KEY = "6LPCRS83DO40UFIL"
THINGSPEAK_URL = "https://api.thingspeak.com/update?api_key=6LPCRS83DO40UFIL"

LDR_SENSOR_PIN = machine.ADC(1)

def connect_to_wifi():
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.connect(WIFI_SSID, WIFI_PASSWORD)

    while not wifi.isconnected():
        time.sleep(1)

    print("Connected to Wi-Fi")

def read_ldr():
    ldr_value = LDR_SENSOR_PIN.read_u16()
    return ldr_value

def convert_to_lux(ldr_value):
    GAMMA = 0.7
    RL10 = 50

    voltage = ldr_value / 65535 * 5
    resistance = 2000 * voltage / (1 - voltage / 5)

    print(f"Voltage: {voltage}, Resistance: {resistance}")

    lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA))
    return lux

def send_data_to_thingspeak(Lux_Values, ADC_Values):
    data = {
        "api_key": THINGSPEAK_API_KEY,
        "field1": Lux_Values,
        "field2": ADC_Values,
    }
    response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
    response.close()

if __name__ == "__main__":
    try:
        connect_to_wifi()

        while True:
            ldr = read_ldr()
            lux = convert_to_lux(ldr)
            print("Sensor Reading:")
            print(f"  LDR Value (ADC): {ldr}")
            print(f"  Lux Value: {lux}")
            send_data_to_thingspeak(lux, ldr)
            print("Data sent to ThingSpeak")
            time.sleep(15)

    except KeyboardInterrupt:
        print("Program terminated.")