Esp8266 + Mqtt

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
User avatar
andrequeiroz
Posts: 9
Joined: Tue Dec 04, 2018 11:07 pm
Location: Foz do Iguacu - Brasil
Contact:

Esp8266 + Mqtt

Post by andrequeiroz » Tue Dec 11, 2018 10:01 pm

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

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Esp8266 + Mqtt

Post by pythoncoder » Wed Dec 12, 2018 7:14 am

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.

Post Reply