try:
  import usocket as socket
except:
  import socket

import network, time, urequests
from machine import Pin, PWM
from mqtt import MQTTClient
import dht
import gc
gc.collect()

sensor = dht.DHT22(Pin(19))

led = Pin(2,Pin.OUT)
sensorDHT = dht.DHT22(Pin(19))
push_button = Pin(13, Pin.IN)

ultima_peticion = 0
intervalo_peticiones = 30

# Funcion de Leer sensor DHT11
def leer_sensor():
    global temp, hum
    temp = hum = 0
    sensorDHT.measure()
    temp=sensorDHT.temperature()
    hum=sensorDHT.humidity()
    return()

# **************************************#
# Funcion de Reconectar conexion
def reconectar():
    print('Fallo de conexión. Reconectando...')
    time.sleep(10)
    machine.reset()

# **************************************#
# Funcion de mostrar Pagina Web
def pagina_web():
    html = """<!DOCTYPE HTML><html>
<head>
  <meta http-equiv=\"refresh\" content=\"10\">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
  <style>
    html {
     font-family: Arial;
     display: inline-block;
     margin: 0px auto;
     text-align: center;
    }
    h2 { font-size: 3.0rem; }
    p { font-size: 3.0rem; }
    .units { font-size: 1.2rem; }
    .dht-labels{
      font-size: 1.5rem;
      vertical-align:middle;
      padding-bottom: 15px;
    }
  </style>
</head>
<body>
  <h2>Datos de sensor</h2>
  <p>
    <i class="fas fa-thermometer-half" style="color:#059e8a;"></i> 
    <span class="dht-labels">Temperatura</span> 
    <span>"""+str(temp)+"""</span>
    <sup class="units">&deg;C</sup>
  </p>
  <p>
    <i class="fas fa-tint" style="color:#00add6;"></i> 
    <span class="dht-labels">Humedad</span>
    <span>"""+str(hum)+"""</span>
    <sup class="units">%</sup>
  </p>
  <p>
    <i class="fas fa-lightbulb" style="color:#FFD300;></i>
    <span class="dht-labels">LED</span>
    <a href="/led-on" class="btn btn-success">ON</a>
    <a href="/led-off" class="btn btn-success">OFF</a>
  </p>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</body>
</html>"""
    return html

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

# **************************************#
# Configure the ESP32 wifi a la red.
ssid = 'INTERCOM MENDIETA'  #Nombre de la Red
password = '0704566355' #Contraseña de la red
url = "https://api.thingspeak.com/update?api_key=GIMG5FMZLP69GV8I"
wlan = network.WLAN(network.STA_IF)
if not wlan.isconnected():
  print('connecting to network...')
  wlan.active(True)
  #wlan.connect('wifi ssid', 'wifi password')
  wlan.connect(ssid, password)
  while not wlan.isconnected():
    pass
print('network config:', wlan.ifconfig())

ultima_peticion = 0
intervalo_peticiones = 30

while True:
    conexion, direccion = s.accept()
    request = conexion.recv(1024)
    leer_sensor()
    respuesta = pagina_web()
    conexion.send('HTTP/1.1 200 OK\n')
    conexion.send('Content-Type: text/html\n')
    conexion.send('Connection: close\n\n')
    conexion.sendall(respuesta)
    conexion.close()