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

pir= Pin(12, Pin.IN)
magnetico = Pin(2, Pin.IN)

# MQTT Server Parameters
MQTT_CLIENT_ID = "vanessa54545454ifhfbfh"#cambiar siempre
MQTT_BROKER    = "broker.hivemq.com"
MQTT_USER      = ""
MQTT_PASSWORD  = ""
MQTT_TOPIC     = "datos/hogar/"


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())
    
    ntptime.host = "ntp.ign.gob.ar"

    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:

        
        ntptime.settime () 
        print ("Hora sincronizada: ", time.localtime())
        sleep(1)
        tiempo=time.localtime ()
        fecha = tiempo[0:3]
        hora = tiempo[3:6]
        #print(hora)

         

        datoPir= pir.value()
        datoMag= magnetico.value()
        print(datoMag, datoPir)
        print("Revisando Condiciones ...... ")

        if datoPir == 1: 
            message = ujson.dumps({
            "Alerta":1,
            "Fecha":fecha,
            "Hora": hora,
            })
            
            print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
            client.publish(MQTT_TOPIC, message)

        elif datoMag ==1:
            message = ujson.dumps({
            "Intruso":1,
            "Fecha":fecha,
            "Hora": hora,
            })
            
            print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
            client.publish(MQTT_TOPIC, message)


        else:
            message = ujson.dumps({
            "Alerta":0,
            "Intruso":0,
             })
            
            print("Reportando a  MQTT topic {}: {}".format(MQTT_TOPIC, message))
            client.publish(MQTT_TOPIC, message)

        sleep(3)   

    

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