One help please. I'm initiating my studies with micropython, I'm using a lang esp8266 board with Mqtt. Everything works fine but if you pass a time interval of 1 min without the esp8266 receiving some message it stops responding to mqtt commands.
--------------------------------------------------Code------------------------------------------------------------------------------------
from umqtt.simple import MQTTClient
from machine import Pin
import machine
import ubinascii
import micropython
# Setup a GPIO Pin for output
led = Pin(12, Pin.OUT)
pin = machine.Pin(2, machine.Pin.OUT)
# Modify below section as required
CONFIG = {
# Configuration details of the MQTT broker
"MQTT_BROKER": "iot.eclipse.org",
"USER": "",
"PASSWORD": "",
"PORT": 1883,
"TOPIC": b"micro/python",
# unique identifier of the chip
"CLIENT_ID": b"esp8266_" + ubinascii.hexlify(machine.unique_id())
}
# Method to act based on message received
def onMessage(topic, msg):
print("Topic: %s, Message: %s" % (topic, msg))
if msg == b"on":
pin.off()
led.on()
elif msg == b"off":
pin.on()
led.off()
def listen():
#Create an instance of MQTTClient
client = MQTTClient(CONFIG['CLIENT_ID'], CONFIG['MQTT_BROKER'], user=CONFIG['USER'], password=CONFIG['PASSWORD'], port=CONFIG['PORT'])
# Attach call back handler to be called on receiving messages
client.set_callback(onMessage)
client.connect()
#client.publish("test", "ESP8266 is Connected")
client.subscribe(CONFIG['TOPIC'])
print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC']))
try:
while True:
client.wait_msg()
#msg = (client.check_msg())
finally:
#client.disconnect()
client.publish("test", "ESP8266 is Connected")
listen()
Esp8266 + Mqtt
- andrequeiroz
- Posts: 9
- Joined: Tue Dec 04, 2018 11:07 pm
- Location: Foz do Iguacu - Brasil
- Contact:
- pythoncoder
- Posts: 5956
- Joined: Fri Jul 18, 2014 8:01 am
- Location: UK
- Contact:
Re: Esp8266 + Mqtt
My guess is that the broker has a keep alive time of one minute. Try adapting your code to publish every 30 seconds. I general it's worth using a local broker to learn MQTT before moving to a real web service.
Peter Hinch
Index to my micropython libraries.
Index to my micropython libraries.