umqtt.simple set_last_will() isn't working

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
gregsvo
Posts: 10
Joined: Fri Oct 21, 2016 6:12 pm

umqtt.simple set_last_will() isn't working

Post by gregsvo » Sun Jul 16, 2017 5:03 am

umqtt.simple is working great in every way except set_last_will(). I can't seem to get it to work. Below is a portion of my code.
My two questions are:
  • 1) How do I get set_last_will() to actually set a last-will on my MQTT broker (mosquitto).
    2) How would I test this? Just unplug the esp8266 and watch for a last message to post?

Code: Select all

import machine
import time
import network
import ubinascii
from umqtt.simple import MQTTClient

CONFIG = {
	# WIFI Configuration
	"SSID": "mywifiname",
	"WIFI_PASSWORD": "mywifipassword",
	# MQTT Configuration
	"MQTT_BROKER": "10.0.0.14",
	"USER": "username",
	"PASSWORD": "password",
	"PORT": 1883,
	"TOPIC": b"button/color",
	"LAST_WILL_MESSAGE": b"OFFLINE",
	"LAST_WILL_TOPIC": b"button/status",
	# unique identifier of the chip
	"CLIENT_ID": b"esp8266_" + ubinascii.hexlify(machine.unique_id())
}

def mqtt_connect():
	print('connecting to mqtt broker...')
	# Create client object
	client = MQTTClient(CONFIG.get('CLIENT_ID'), CONFIG.get('MQTT_BROKER'), user=CONFIG.get('USER'), 	
	password=CONFIG.get('PASSWORD'), port=CONFIG.get('PORT'))
	# Set last will and it's topic - setting last_will before client.connect() is called, as per documentation.
	client.set_last_will(topic=CONFIG.get('LAST_WILL_TOPIC'),msg=CONFIG.get('LAST_WILL_MESSAGE'),retain=False, qos=0)
	# Connect to the broker
	client.connect()
	print("Connected to %s, waiting for button presses" % CONFIG.get('MQTT_BROKER'))
	

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

Re: umqtt.simple set_last_will() isn't working

Post by pythoncoder » Sun Jul 16, 2017 7:58 am

In my own testing the last will feature does work.

To test it I set the keepalive period to (say) 120 seconds. You can either power down the ESP8266 or simply stop your application. As I understand it the broker periodically sends MQTT PING packets to the client. If it hasn't received PINGRESP in 1.5 times the keepalive period it assumes the client has died and publishes the will.

In the absence of an explicit keepalive time the behaviour of the broker is somewhat indeterminate (see MQTT spec section 3.1.2.10). I think this is the reason your code is not producing the expected outcome.
Peter Hinch
Index to my micropython libraries.

ajiji
Posts: 1
Joined: Thu Aug 26, 2021 2:40 pm

Re: umqtt.simple set_last_will() isn't working

Post by ajiji » Thu Aug 26, 2021 2:43 pm

Thank you @pythoncoder, you saved my day!

Post Reply