import time
import network
import urequests
import machine
import ujson
import dht
from onewire import OneWire
from ds18x20 import DS18X20
import neopixel
import bme280  # Import BME280 library
#import analogio  # Import analogio for UV sensor


# ThingSpeak settings
THINGSPEAK_API_KEY = "K21EF6QEW4SURWT1"
THINGSPEAK_URL = "http://api.thingspeak.com/update"


# Wi-Fi settings
WIFI_SSID = "iPhone Little"
WIFI_PASSWORD = "87654321"


# Setup DHT22 (AM2302) sensor on GPIO 4
dht_sensor = dht.DHT22(machine.Pin(4))


# Setup DS18B20 on GPIO 5
ow = OneWire(machine.Pin(5))
ds_sensor = DS18X20(ow)
ds_roms = ds_sensor.scan()


# Setup NeoPixel on GPIO 2 with 16 LEDs (adjust the number if needed)
np = neopixel.NeoPixel(machine.Pin(2), 16)


# Setup BME280 on I2C (assuming default I2C pins)
i2c = machine.I2C(0, scl=machine.Pin(14), sda=machine.Pin(15))  # Adjust pins as needed
bme = bme280.BME280(i2c=i2c)


# Setup UV Sensor on GPIO 26 (Analog input)
#uv_sensor = analogio.AnalogIn(machine.Pin(26))


# Function to set NeoPixel color based on light intensity
def set_neopixel_color(light_intensity):
    if light_intensity > 75:
        color = (255, 0, 0)  # Red for high intensity
    elif light_intensity > 25:
        color = (255, 255, 0)  # Yellow for medium intensity
    else:
        color = (0, 255, 0)  # Green for low intensity
    for i in range(16):
        np[i] = color
    np.write()


# Function to read room temperature and humidity from DHT22
def read_room_temperature_humidity():
    dht_sensor.measure()
    temperature = dht_sensor.temperature()
    humidity = dht_sensor.humidity()
    return temperature, humidity


# Function to read soil temperature from DS18B20
def read_soil_temperature():
    ds_sensor.convert_temp()
    time.sleep(1)  # Wait for the temperature conversion
    if ds_roms:
        soil_temp = ds_sensor.read_temp(ds_roms[0])
        return soil_temp
    else:
        return None


# Function to read pressure from BME280
def read_pressure():
    pressure = bme.pressure  # Read pressure in hPa
    return pressure


# Function to read UV level from UV Sensor
def read_uv_level():
    uv_value = uv_sensor.read_u16()  # Read the analog value
    # You may want to convert this value to a meaningful scale
    return (uv_value / 65535) * 100  # Convert to percentage


# Function to send data to ThingSpeak
def send_data_to_thingspeak(temperature, humidity, soil_temp, pressure, uv_level):
    data = {
        "api_key": THINGSPEAK_API_KEY,
        "field1": temperature,
        "field2": humidity,
        "field3": soil_temp,
        "field4": pressure,
        "field5": uv_level,
    }
    response = urequests.post(THINGSPEAK_URL, data=ujson.dumps(data), headers={"Content-Type": "application/json"})
    response.close()


# Initialize the Wi-Fi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)


# Wait for the Wi-Fi connection to establish
while not wifi.isconnected():
    time.sleep(1)


print("Connected to Wi-Fi")


if __name__ == "__main__":
    try:
        while True:
            # Read data from DHT22
            temperature, humidity = read_room_temperature_humidity()


            # Read data from DS18B20
            soil_temp = read_soil_temperature()
            if soil_temp is None:
                print("No DS18B20 devices found")


            # Read pressure from BME280
            pressure = read_pressure()


            # Read UV level
            uv_level = read_uv_level()


            # Set NeoPixel color based on UV level
            set_neopixel_color(uv_level)


            # Send data to ThingSpeak
            send_data_to_thingspeak(temperature, humidity, soil_temp, pressure, uv_level)
            little = 0;
            print("Data sent to ThingSpeak", little+1)
            little + 1
            
            
            # Delay for 15 seconds (ThingSpeak rate limit)
            time.sleep(15)
    except KeyboardInterrupt:
        pass