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