I'm trying to make automation for the greenhouse using umqtt.simple. I have a 4 channel LC Technology relay with ESP-01(2MB) on board.
I have written some code using examples from this forum (thanks for pythoncoder ) and other sites. This relay can be controlled using special 4byte commands sent by UART.
This is my main.py file. I made boot.py empty.
This program is working and I can switch 1 of 4 relays sending ON or OFF command over MQTT.
My problem is that after about 2 minutes of working relay doesn't respond correctly to my commands. For example, I send ON command and relay opens and after several seconds it closes automatically(I can't understand WHY). Another example is that after some minutes of correct work It doesn't respond to my MQTT messages at all( I saw fast blue led blink but relay didn't change the state.)
I hope for your help and sorry for my poor English.
Code: Select all
import time from umqtt.simple import MQTTClient import ubinascii import machine import micropython import network import esp esp.osdebug(None) import gc gc.collect() ssid = 'example' password = '12345678' mqtt_server = '192.168.0.91' client_id = ubinascii.hexlify(machine.unique_id()) topic_sub = b'esp/relay' topic_pub = b'esp/relay/answer' state = b'OFF' uart = machine.UART(0, 115200) station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while station.isconnected() == False: pass print('Connection successful') print(station.ifconfig()) def sub_cb(topic, msg): global state print((topic, msg)) if msg == b'ON': uart.write(bytes([0xA0, 0x01, 0x01, 0xA2])) state = b'ON' client.publish(topic_pub, state) elif msg == b'OFF': uart.write(bytes([0xA0, 0x01, 0x00, 0xA1])) state = b'OFF' client.publish(topic_pub, state) def connect_and_subscribe(): global client_id, mqtt_server, topic_sub client = MQTTClient(client_id, mqtt_server) client.set_callback(sub_cb) client.connect() client.subscribe(topic_sub) print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub)) return client def restart_and_reconnect(): print('Failed to connect to MQTT broker. Reconnecting...') time.sleep(10) machine.reset() try: client = connect_and_subscribe() except OSError as e: restart_and_reconnect() while True: try: client.check_msg() time.sleep(0.2) except OSError as e: restart_and_reconnect()
P.S. I mentioned that after several minutes of work, the ESP-01 is hot, maybe this is a problem?