# Importe tout les modules requis
from machine import Pin, I2C
import uSGP30
import uBME280
from i2c_lcd import lcd
import time
import network
import socket

# Défini l'interface du protocole I2C
i2c = I2C(0, scl = Pin(9), sda = Pin(8), freq = 400000)

# Défini l'adresse I2C requis pour les capteurs
BME_addr = 0x76;
SGP30_addr = 0x58;

# Déclare les paramètres dans des variables
bme280 = uBME280.BME280(uBME280.BME280_OSAMPLE_1, BME_addr, i2c)
sgp30 = uSGP30.SGP30(i2c, SGP30_addr);
display = lcd(i2c)

t = str(bme280.read_temperature()/100)
p = str(bme280.read_pressure()/1000)
h = str(bme280.read_humidity()/1000)
t_CO2, t_COV = sgp30.measure_iaq()
co2 = str(t_CO2)

def Update():
    # Récupère toutes les données du capteur BME280
    t = str(bme280.read_temperature()/100)
    p = str(bme280.read_pressure()/1000)
    h = str(bme280.read_humidity()/1000)
    t_CO2, t_COV = sgp30.measure_iaq()
    co2 = str(t_CO2)

    
    # Affiche la première image (Température + Humidité)
    display.home()
    display.write("Temp = ")
    display.write(t)
    display.write(" °C")
    display.setCursor(0,1)
    display.write("THum = ")
    display.write(h)
    display.write(" %")
    time.sleep(1.5)
    # Affiche la deuxième image (Pression + CO2)
    display.clear()
    display.home()
    display.write("P = ")
    display.write(p)
    display.write(" Pa")
    display.setCursor(0,1)
    display.write("TCO2 = ")
    display.write(co2)
    display.write(" ppm")
    time.sleep(1.5)
    display.clear()

def web_page():
  html = """<html>
                <head>
                    <meta name="viewport" content="width=device-width, initial-scale=1">
                    <script type="text/javascript">
                    <!-- Begin
                    function reFresh() {
                      location.reload(true)
                    }
                    /* Definir le temp de refraichir le nombre en  in milliseconds, 1 minute = 60000 milliseconds. */
                    window.setInterval("reFresh()",500);
                    // End -->
                    </script>
                </head>
                <body>
                    <h1>Weather Station</h1>
                    <p>Temperature : {t}</p>
                    <p>Pression Atmoshérique : {p}</p>
                    <p>Humiditée : {h}</p>
                    <p>Taux de CO2 : {co2}</p>
                </body>
            </html>
         """
  return html

# if you do not see the network you may have to power cycle
# unplug your pico w for 10 seconds and plug it in again
def ap_mode(ssid, password):
    """
        Description: This is a function to activate AP mode
        
        Parameters:
        
        ssid[str]: The name of your internet connection
        password[str]: Password for your internet connection
        
        Returns: Nada
    """
    # Just making our internet connection
    ap = network.WLAN(network.AP_IF)
    ap.config(essid=ssid, password=password)
    ap.active(True)
    
    while ap.active() == False:
        pass
    print('AP Mode Is Active, You can Now Connect')
    print('IP Address To Connect to:: ' + ap.ifconfig()[0])
    
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   #creating socket object
    s.bind(('', 80))
    s.listen(5)

    while True:
      conn, addr = s.accept()
      print('Got a connection from %s' % str(addr))
      request = conn.recv(1024)
      print('Content = %s' % str(request))
      Update()
      response = web_page()
      conn.send(response)
      conn.close()
      
ap_mode('Weather Station',
        'Miam1234')
