from machine import Pin, I2C
from utime import sleep, sleep_ms
import network, time
import ujson
from neopixel import NeoPixel 
from umqtt.simple import MQTTClient
from ssd1306 import SSD1306_I2C

ancho = 128
alto =  64

i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(ancho, alto, i2c)

MQTT_CLIENT_ID = "cli66787665Rhugo"
MQTT_BROKER    = "broker.hivemq.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC_SUB = "control/bombillo"

np = NeoPixel(Pin(16), 1)


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()
  
    
    

    def sub_cb(topic, msg):
        global info
        dato = msg.decode()
        info=dato
        print(f'Recibido:{dato}')
        oled.fill(0)
        oled.pixel(64,34,1)
        oled.hline(0,0,128,1)
        oled.hline(0,30,128,1)
        oled.vline(0,0,30,1)
        oled.vline(127,0,30,1)
        oled.text("Hugo", 50, 10, 1)
        oled.text("Dato: ", 0, 50, 1)
        oled.text(str(info), 50, 50, 1)
        oled.show()

        if dato == "Rojo":
            np[0]=(255,0,0)
            np.write()

        elif dato == "Verde":
            np[0]=(0,255,0)
            np.write()

        elif dato== "Off":
            np[0]=(255,255,255)
            np.write()
     


    while True:
        
        client.set_callback(sub_cb)
        client.subscribe(MQTT_TOPIC_SUB)
        print ("esperando")
        client.wait_msg()
        time.sleep(3)