import machine
from machine import Pin, PWM # Se importa la librería pwm
from time import sleep_ms
from lcd import LCD
import random
from math import log
import time
import json




BETA = 3950 # es el coeficiente del beta del termistor
KELVIN_CONSTANT = 273.15

#Funciones
def adc_to_celsius(x):
    return (1 / (log(1/(4096/x - 1))/BETA + 1/298.15) - KELVIN_CONSTANT)

                             

import socket
import rgb


rgbObj = rgb.rgb(32, 33, 25, True)
rgbObj.off()

r_state = False
g_state = False
b_state = False

r_value = "OFF"
g_value = "OFF"
b_value = "OFF"
Temperatura   = "25°C"

#**********************************************************************


def actualizar_temperatura(timer):
  global Temperatura  
  temperatura = adc34.read() * (3.3 / 4095)
  lectura = adc34.read() 
  Temperatura = str(round(adc_to_celsius(lectura), 1)) + "°C" 
  
#**********************************************************************

def get_string_value(input: bool):
    if input:
        return "ON"
    return "OFF"

def web_page():
    
    r_value = get_string_value(r_state)
    g_value = get_string_value(g_state)
    b_value = get_string_value(b_state)
    html = """
      <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Servidor Web ESP32bits</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f0f0f0;
            margin: 0;
            padding: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
        }

        h1 {
            color: #0F3376;
        }

        p {
            font-size: 1.5rem;
        }

        table {
            border-collapse: collapse;
            margin-top: 20px;
        }

        td {
            padding: 10px;
            text-align: center;
        }

        .Button {
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1.2rem;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            margin: 4px 2px;
            transition-duration: 0.4s;
        }

        .ButtonR {
            background-color: #ec4949;
            color: white;
            border: 2px solid #991f1f;
        }

        .ButtonR:hover {
            background-color: #f51616;
        }

        .ButtonG {
            background-color: #49ec56;
            color: white;
            border: 2px solid #23991f;
        }

        .ButtonG:hover {
            background-color: #29f516;
        }

        .ButtonB {
            background-color: #4974ec;
            color: white;
            border: 2px solid #1f3599;
        }

        .ButtonB:hover {
            background-color: #165df5;
        }

        #user-text {
            padding: 10px;
            font-size: 1.2rem;
            border: 2px solid #ccc;
            border-radius: 4px;
        }

        #submit-button {
            background-color: #0F3376;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 10px 20px;
            cursor: pointer;
            font-size: 1.2rem;
        }
        .numero {
        font-size: 20px;
        font-family: sans-serif;
        color: #000;
        border-radius: 50%;
        background-color: #fff;
        padding: 10px;
        }

        /* Estilo para la etiqueta temperatura */
        .temperatura {
        font-size: 15px;
        font-family: sans-serif;
        color: #000;
        position: absolute;
        top: 0;
        left: 20px; /* Ajusta el valor de left según tus necesidades */
        }
    </style>
    
</head>
<body>
    <h1>Servidor Web ESP32bits</h1>
    <p>Control de Cargas </p>

    <table>
        <tbody>
            <tr>
                <td>
                    <a href="/?led-r"><button class="Button ButtonR">Carga 1</button></a>
                </td>
                <td>
                    <strong> """+ r_value +"""</strong> 
                </td>
            </tr>
            <tr>
                <td>
                    <a href="/?led-g"><button class="Button ButtonG">Carga 2</button></a>
                </td>
                <td>
                    <strong> """+ g_value +"""</strong> 
                </td>
            </tr>
            <tr>
                <td>
                    <a href="/?led-b"><button class="Button ButtonB">Carga 3</button></a>
                </td>
                <td>
                    <strong> """+ b_value +""" </strong> 
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <form action="/submit-text" method="GET">
                        <label for="user-text">Entre el Texto:</label>
                        <input type="text" id="Texto_1" name="text">
                        <input type="submit" id="submit-button" value="Enviar">
                    </form>                    
                </td>
            </tr>
            <tr>
                <td>
                    <div class="numero"> """+ Temperatura +"""</div>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

        """
    return html

# Configurar el temporizador 1 para que se active cada segundo (1000 ms)


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

timer = machine.Timer(1)
timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=actualizar_temperatura)
sleep_ms(1200)

while True:
    try:
        conn, addr = s.accept()
        print('Got a connection from %s' % str(addr))
        request = conn.recv(1024)
        request = str(request)
        #print(request) 
        
        led_r = request.find('/?led-r')
        led_g = request.find('/?led-g')
        led_b = request.find('/?led-b')
        B_Texto = request.find('/submit-text')   
        
        if B_Texto == 6:
            B_Texto = request.find('text=')
            B_Texto2 = request.find('HTTP')
            Longitud = B_Texto2 - (B_Texto+5)
            Mensaje_R = request[B_Texto+5:B_Texto+5+Longitud]
            Mensaje = ""

            for char in Mensaje_R:
                if char == "+":
                    Mensaje += " "
                else:
                    Mensaje += char

            print("El mensaje wifi recibido fue : " + Mensaje) 
            lcd.clear()
            lcd.move_to(0,0)
            lcd.putstr(Mensaje)
            Motor.duty(1023)
        
             
        if led_r == 6:
            print('LED R ')
            Motor.duty(280) 
            r_state = not r_state
            g_state = False
            b_state = False
            if r_state == True:
                rgbObj.red()
            else:
                rgbObj.off()
            
        elif led_g == 6:
            print('LED G ') 
            Motor.duty(560)
            r_state = False
            g_state = not g_state
            b_state = False
            if g_state == True:
                rgbObj.green()  
            else:
                rgbObj.off()    
        
        elif led_b == 6:
            print('LED B ')
            Motor.duty(800)  
            r_state = False
            g_state = False
            b_state = not b_state
            if b_state == True:
                rgbObj.blue()  
            else:
                rgbObj.off()   
            
        response = web_page()
        conn.send('HTTP/1.1 200 OK\n')
        conn.send('Content-Type: text/html\n')
        conn.send('Connection: close\n\n')
        conn.sendall(response)
        conn.close()
    except Exception as e:
        print(e)