from umqtt.simple import MQTTClient
import time
import machine
from machine import Pin, PWM, ADC
import network
import tm1637
from tm1637 import TM1637
#red WiFi, Clave y Topicos
ssid = 'Wokwi-GUEST'
wifipassword = ''
mqtt_server = 'io.adafruit.com'
port = 1883
user = 'Fabriconde'
password = 'aio_wCun95DCyhX44GxApSns5xztGad0'
client_id = 'Switchfabriconde'
topic_switch = 'Fabriconde/f/Switch'
topic_LED = 'Fabriconde/f/LED'
topic_humedad = 'Fabriconde/f/HUMEDAD'
topic_hum_max = 'Fabriconde/f/HMax'
topic_hum_min = 'Fabriconde/f/HMin'
#DECLARACION DE VARIABLES
LEDestado= Pin(23,Pin.OUT) #Pin verde indica si el sistema esta ON
LEDestado_enviar = "OFF" #para devolver el estado del led a adafruit
potenciometro = ADC(35) #Por ser ADC conectado al Pin 35 (compatible)
display = TM1637(clk=Pin(12),dio=Pin(13)) #Display para ver la humedad "Fisicamente"
pwmServo = PWM(Pin(2,Pin.OUT)) #Servomotor que funciona como regador (activaria el sistema)
pwmServo.freq(50)
humedad_min = 0 #declaramos variables y asignamos valores iniciales
humedad_max = 100
humedad = potenciometro.read()
bandarranque = int(0) #bandera para poder inicializar todo en OFF o en 0 una sola vez y que los valores
#puedan ser cambiados dentro del ciclo
riego = int(0)
tiempo = int(0)
displayhora = TM1637(clk=Pin(18),dio=Pin(5))
#conectarse a AP remoto
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
#Conectamos al WiFi
sta_if.connect(ssid, wifipassword)
print("Conectando")
while not sta_if.isconnected():
print(".", end="")
time.sleep(1)
print("Conectado a Wifi!")
#Vemos las IP
print(sta_if.ifconfig())
#FUNCIONES
def callback(topic, msg):
global LEDestado, LEDestado_enviar, humedad_max, humedad_min
dato = msg.decode('utf-8')
topicrec = topic.decode('utf-8')
print("Mensaje en topico "+topicrec+":"+dato)
if topicrec == topic_switch and "ON" in dato: #dependiendo el valor del switch se prende o se apaga el LED
LEDestado.value(1)
LEDestado_enviar = "ON"
if topicrec == topic_switch and "OFF" in dato:
LEDestado.value(0)
LEDestado_enviar= "OFF"
if topicrec == topic_hum_max:
humedad_max = dato
if topicrec == topic_hum_min:
humedad_min = dato
def Lecturadisplay():
global humedad
humedad = potenciometro.read()
humedad = humedad / 40.95
display.number(int(humedad))
def horario(hora):
if ((hora > 6 and hora < 12) or (hora > 17 and hora < 21)) :
return 1
else :
return 0
def MovServo():
global pwmServo, humedad
pwmServo.duty(45)
time.sleep_ms(200)
Lecturadisplay()
pwmServo.duty(25)
time.sleep_ms(200)
Lecturadisplay()
pwmServo.duty(45)
time.sleep_ms(200)
Lecturadisplay()
pwmServo.duty(75)
time.sleep_ms(200)
Lecturadisplay()
pwmServo.duty(100)
time.sleep_ms(200)
Lecturadisplay()
pwmServo.duty(125)
time.sleep_ms(200)
Lecturadisplay()
pwmServo.duty(100)
time.sleep_ms(200)
Lecturadisplay()
pwmServo.duty(75)
time.sleep_ms(200)
Lecturadisplay()
try: #recibimos mensajes de hum_max, hum_min y switch
conexionMQTT = MQTTClient(client_id, mqtt_server,user=user,password=password,port=int(port))
conexionMQTT.set_callback(callback) #Funcion Callback para recibir mensajes del broker
conexionMQTT.connect() #Hacemos la conexión
conexionMQTT.subscribe(topic_switch) #Nos suscribimos a los topicos
conexionMQTT.subscribe(topic_hum_max)
conexionMQTT.subscribe(topic_hum_min)
print("Conectado con Broker MQTT")
except OSError as e:
print("Fallo la conexion al Broker, reiniciando...")
time.sleep(5)
machine.reset()
while True:
global ledAnterior, humAnterior
try:
if bandarranque == 0:
ledAnterior = "OFF"
humAnterior = int(0)
bandarranque = 1
minutos = int(0)
hora = int(0)
bandTiempo = int(0)
conexionMQTT.check_msg() #chequeamos nuevos mensajes en el broker
if (ledAnterior != LEDestado_enviar): #Solo se publicaria el estado del LED en caso de cambiar
ledAnterior = LEDestado_enviar #de esta manera no se satura ADAFRUIT
conexionMQTT.publish(topic_LED,str(LEDestado_enviar))
if (humAnterior != humedad):
time.sleep(2) #Time.sleep para que no se envie cada valor x el q pasa el sensor(slider)
humAnterior = humedad
conexionMQTT.publish(topic_humedad,str(humedad))
humedad = potenciometro.read()
humedad = humedad / 40.95
display.number(int(humedad))
tiempo = (hora * 100) + minutos
displayhora.number(int(tiempo))
if LEDestado_enviar == "ON" :
if (int(humedad) < int(humedad_min)) :
while(int(humedad) < int(humedad_max) and LEDestado_enviar == "ON"):
if horario(hora) == 1:
MovServo()
tiempo = (hora * 100) + minutos
displayhora.number(int(tiempo))
minutos += 10
if minutos >= 60 :
minutos = 0
hora +=1
if hora == 24 :
riego = horario(hora)
hora = 0
conexionMQTT.check_msg() #Por si el usuario cambia el valor de humedad max
bandTiempo = 1
if horario(hora) == 0:
tiempo = (hora * 100) + minutos
displayhora.number(int(tiempo))
minutos += 1
if minutos == 60 :
minutos = 0
hora +=1
if hora == 24 :
riego = horario(hora)
hora = 0
#print("Hora: "+str(hora)+":"+str(minutos))
humedad = potenciometro.read()
humedad = humedad / 40.95
display.number(int(humedad))
if (humAnterior != humedad):
time.sleep_ms(500) #Time.sleep para que no se envie cada valor x el q pasa el sensor(slider)
humAnterior = humedad
conexionMQTT.publish(topic_humedad,str(humedad))
if (int(humedad) > int(humedad_max)) :
pwmServo.duty(0)
if bandTiempo == 0 :
minutos += 1
if minutos == 60 :
minutos = 0
hora +=1
if hora == 24 :
riego = horario(hora)
hora = 0
#print("Hora: "+str(hora)+":"+str(minutos))
tiempo = (hora * 100) + minutos
displayhora.number(int(tiempo))
except OSError as e:
print("Error ",e)
time.sleep(5)
machine.reset()