import time
import machine
import dht
import network
import urequests
from machine import SoftI2C, Pin
from i2c_lcd import I2cLcd

# ThingSpeak settings
THINGSPEAK_API_KEY = '7URRNK5I2YH3HIYQ'
THINGSPEAK_URL = 'http://api.thingspeak.com/update'

# Initialize the DHT22 sensor (check library documentation for potential arguments)
dht_sensor = dht.DHT22(Pin(12))  # Might require additional arguments depending on the library

# Initialize I2C LCD
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=100000)
lcd = I2cLcd(i2c, 0x27, 2, 16)

# Connect to Wi-Fi
wifi_ssid = 'Wokwi-GUEST'
wifi_password = ''

def connect_wifi(ssid, password):
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid, password)
    while not wlan.isconnected():
        time.sleep(1)
    print('Connected to WiFi')
    return wlan

# Send data to ThingSpeak
def send_to_thingspeak(temp, hum):
    url = f"{THINGSPEAK_URL}?api_key={THINGSPEAK_API_KEY}&field1={temp}&field2={hum}"
    response = urequests.get(url)
    response.close()
    print('Data sent to ThingSpeak')

# Main loop
def main():
    wlan = connect_wifi(wifi_ssid, wifi_password)

    while True:
        try:
            dht_sensor.measure()  # Might need additional arguments
            temp = dht_sensor.temperature()
            hum = dht_sensor.humidity()

            # Display on LCD
            lcd.clear()
            lcd.putstr(f'Temp: {temp} C')
            lcd.putstr(f'\nHum: {hum} %')

            # Send to ThingSpeak
            send_to_thingspeak(temp, hum)

            # Wait before next reading
            time.sleep(60)  # Increased delay for sensor communication

        except OSError as e:  # Handle specific sensor communication errors
            print('Failed to read sensor:', e)
            time.sleep(5)

if __name__ == '__main__':
    main()