import network, time, urequests
from machine import Pin, ADC
from utime import sleep, sleep_ms, ticks_us
import ujson
from umqtt.simple import MQTTClient

pot_oxigeno= ADC(Pin(33))
pot_ph = ADC(Pin(35))


# MQTT Server Parameters
MQTT_CLIENT_ID = "pepitoxx23467900"#cambiar siempre
MQTT_BROKER    = "broker.hivemq.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "tilapia/piscina2/s2/medidas"


def map_value(value, in_min, in_max, out_min, out_max):
    return (value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min


def conectaWifi (red, password):
      global miRed
      miRed = network.WLAN(network.STA_IF)     
      if not miRed.isconnected():              #Si no está conectado…
          miRed.active(True)                   #activa la interface
          miRed.connect(red, password)         #Intenta conectar con la red
          print('Conectando a la red', red +"…")
          timeout = time.time ()
          while not miRed.isconnected():           #Mientras no se conecte..
              if (time.ticks_diff (time.time (), timeout) > 10):
                  return False
      return True


if conectaWifi ("Wokwi-GUEST", ""):

    print ("Conexión exitosa!")
    print('Datos de la red (IP/netmask/gw/DNS):', miRed.ifconfig())
     
    print("Conectando a  MQTT server... ",MQTT_BROKER,"...", end="")
    client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
    client.connect()
    
    print("Conectado al Broker!")

    while True:

        lectura_oxigeno = pot_oxigeno.read_u16()
        lectura_ph = pot_ph.read_u16()

        spo2 = map_value(lectura_oxigeno, 0, 65535, 0, 100)
        ph = map_value(lectura_ph, 0, 65535, 0, 100)
      
        


        print("Spo2: {:.1f}%, ph: {:.1f}% ".format(spo2, ph))

        print("Revisando Condiciones ...... ")
        message = ujson.dumps({
        "oxigeno": spo2,
        "ph": ph,
         })
        sleep(2)
        print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
        client.publish(MQTT_TOPIC, message)


    

else:
       print ("Imposible conectar")
       miRed.active (False)