import time
import ntptime
from machine import Pin
import dht
import network
import urequests

# Wi-Fi Credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# Time zone info
TZ_INFO = "UTC7"

# DHT pin
DHTPIN = 23

# Google Apps Script ID
GAS_ID = "AKfycbyWNoBABf9bRR6WscEOAKzr47ZMpKYwDrelY_mwGxYuvEh6-Sr2byjsQYJFBx8Inb-oyw"  # Google Script id from deploy app >>> Deployment ID:
# Initialize DHT sensor
d = dht.DHT22(Pin(DHTPIN))

# Initialize WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
    pass

print("WiFi connected")

# Sync time using ntptime
ntptime.settime()

# Function to send data to Google Sheet
def send_data_to_ggsheet(temp, humid, light):
    temp = lound(d.temperature(),2)
    humid = lound(d.humidity(),2)
    light = 1235
    #url = https://script.google.com/macros/s/AKfycbyWNoBABf9bRR6WscEOAKzr47ZMpKYwDrelY_mwGxYuvEh6-Sr2byjsQYJFBx8Inb-oyw/exec
    
    url = "https://script.google.com/macros/s/" + GAS_ID + "/exec?t=" + str(temp) + "&h=" + str(humid) + "&l=" + str(light)
    print("Posting Temperature, Humidity, and Light Intensity data to Google Sheet")
    try:
        response = urequests.get(url)
        print("HTTP Status Code:", response.status_code)
        payload = response.text
        print("Payload:", payload)
        print("Temperature: %d°C, Humidity: %d%%, Light: %d%%" % (temp, humid, light))
    except Exception as e:
        print("Error:", e)

# ########## Data Logger ################ #
# logger
filename = 'data_logger.txt'

def write_data():
    luminance = 1235
    temperature = lound(d.temperature(),2)
    relative_humidity = lound(d.humidity(),2)
	
    rtc = machine.RTC()
    ntptime.settime()  # สร้างการเชื่อมต่อ NTP และปรับเวลาจาก NTP server
    (year, month, day, _, hours, minutes, seconds, _) = rtc.datetime()  # รับค่าวันและเวลาจาก RTC
    # เพิ่ม 7 ชั่วโมงและปรับแก้เวลาเมื่อเกิน 24 ชั่วโมง
    hours = (hours + 7) % 24
    time_string = "%04d-%02d-%02d %02d:%02d:%02d" % (year, month, day, hours, minutes, seconds)  # แปลงเป็น string
    print(time_string)

    if (filename in os.listdir()):
        f = open(filename, 'a')
    else:
        f = open(filename, 'w')
    print("Write data to logger...")

    f.write(
    "{}, T: {}, H: {}, L: {}\n".format(
    time_string,
    temperature,
    relative_humidity,
    luminance)
    )
    f.flush()
    f.close()
# ########## Data Logger ################ #

# ############### Create a Timer object ################## #
#Datalogger Timer
data_logger_timer = Timer(-1)
data_logger_timer.init(period=60000, mode=Timer.PERIODIC, callback=write_data)
# ############### Create a Timer object ################## #

c = 0
# Main loop
while True:
    time.sleep(0.5)
    d.measure()
    temp = d.temperature()
    humid = d.humidity()
    light = 1235
    print("Temperature: %d°C, Humidity: %d%%, Light: %d%%" % (temp, humid, light))
    send_data_to_ggsheet(temp, humid, light)
    time.sleep(60)  # Send data to Google Sheet every 10 seconds
    c = c+1
	print("ส่งข้อมูลครั้งที่ : ", c)