from machine import Pin, Timer
import network
import urequests # para peticiones a API http
import time
import sys
from dht import DHT22 #para crear objetos de tipo DHT

import random

dht22 = DHT22(Pin(12))


def leer_Dht():
    dht22.measure()
    return dht22.temperature(), dht22.humidity()

print (leer_Dht())


#nos conectamos con WiFi

import network
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""

# función para conectarse al wifi local de WokWi

def conectarse_a_wifi():
    wifi = network.WLAN(network.STA_IF)
    wifi.active(True)
    wifi.disconnect()
    wifi.connect(WIFI_SSID, WIFI_PASSWORD)
    if not wifi.isconnected():
        print('Conectando..')
        timeout = 0
        while (not wifi.isconnected() and timeout < 10):
            print(10 - timeout)
            timeout = timeout + 1
            time.sleep(1) 
    if(wifi.isconnected()):
        print('Conectado')
    else:
        print('No conectado')
        sys.exit()
    print('Configuración de red:', wifi.ifconfig())
        
conectarse_a_wifi() # se conecta a la red wifi local


HTTP_HEADERS = {'Content-Type': 'application/json'} 
THINGSPEAK_WRITE_API_KEY = 'QXDTKXWVFM9NB5X3' # API key (write key) del canal de Thingspeak 


while True:
    time.sleep(1) 
    
    dht22 = DHT22(Pin(12)) #se crea un objeto de tipo DHT22 en el pin 12
    dht22.measure()
    print("Temperatura: {}".format(dht22.temperature()))
    print("Humedad: {}".format(dht22.humidity()))
    
    Temperatura  = dht22.temperature() # 
    Humedad = dht22.humidity() #
    Presion = random.uniform(10.5, 75.5)
    Altitud = random.uniform(12.5, 85.5)

    dht_readings = {'field1':Temperatura, 'field2':Humedad, 'field3': Presion, 'field4': Altitud} 
    peticion = urequests.post( 'http://api.thingspeak.com/update?api_key=' + THINGSPEAK_WRITE_API_KEY, json = dht_readings, headers = HTTP_HEADERS )  
    peticion.close() 
    print(dht_readings)
    print('Altitud:', Altitud)
    print(" Datos enviados a ThingSpeak!")
    print(" ............................")