import urequests
import network
import time
from machine import Pin


print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
  print(".", end="")
  time.sleep(0.1)
print(" Connected!")

# URL de la función de Google Apps Script
AppScriptId = "AKfycbwoiqyS61vVBzou3Qx9iVnaeJa3BJwHw-J53wKiSEvsGKxWKZHk5DPiWuw5nf7vqSH8"
AppScriptBase = "https://script.google.com/macros/s/"

def urlencode(params):
    # Codifica los parámetros en URL
    return '&'.join('{}={}'.format(key, str(value).replace(' ', '%20')) for key, value in params.items())

# Obtener el tiempo actual
current_time = time.time()

data = {
    "p1": current_time/10,
    "p2": "ESP 32"
}

parameters = urlencode(data)
url_with_params  = f"{AppScriptBase}{AppScriptId}/exec?{parameters}"
response = urequests.get(url_with_params)
print(url_with_params)

# Verificar si la solicitud fue exitosa
if response.status_code == 200:
    print("Datos enviados correctamente")
    print("Response:", response.text)
else:
    print("Error al enviar los datos")

# Cerrar la respuesta para liberar recursos
response.close()


#DTL a Google Sheets
#https://www.youtube.com/watch?v=cYLll3gkzkY&list=LL&index=59&ab_channel=Makerlab
#Formato de url:
#https://docs.google.com/forms/d/[ID del formulario]/formResponse?entry.[ID del campo]={{payload}}

#Vinculo prellenado:
#https://docs.google.com/forms/d/e/1FAIpQLSeT8VerJi3BMhYerYsZeA6WglJ7pYnfIEqCRfDRGVDTJdbsdg/viewform?usp=pp_url&entry.703680858=33.3

import dht
sensor = dht.DHT22(Pin(15))
sensor.measure()

idFormulario = "10mbMYQrWEezcwAxxoNztu7IqtwLhYlYJ0RTT2_q3peo"
idCampo = "703680858"
payload = sensor.temperature()

url_dtl = f"https://docs.google.com/forms/d/{idFormulario}/formResponse?entry.{idCampo}={payload}"
response = urequests.get(url_dtl)
# Verificar si la solicitud fue exitosa
if response.status_code == 200:
    print("Datos enviados correctamente")
    #print("Response:", response.text)
else:
    print("Error al enviar los datos")