background-test3.jpg
Search

MQTT Last Will and Testament Example

Medium One's MQTT broker supports the MQTT last will and testament feature. This is a useful feature where the MQTT broker will send an event on behalf of your device when there is a network interruption. This will trigger when the connection is lost unexpectedly, not when there's an MQTT.disconnect().


This is an example of a python MQTT client that connects and then goes into an infinite loop. Run this client and observe the {"connected":True} event on your dashboard. Wait a few seconds or however long you'd like and then kill the python program via ctrl-c (on your keyboard) to force an unexpected disconnect. At this time you should notice a {"connected":False} event on your dashboard.


The following example in running python 2 on Linux.


Create a file called main.py with the following code and replace with your MQTT device credentials


import time
import paho.mqtt.client as mqtt
import json
import uuid


user_password = '##############'
api_key = '############################'
project_mqtt_id = '########'
MQTT_PORT = 61618
MQTT_URL = 'mqtt.mediumone.com'
device_id = "########"
device_mqtt_id = "#########"

def on_connect(client, userdata, flags, rc):
    connect_event = {
        "event_data": {
            "connected": True
        }
    }
    client.publish(
        '0/{}/{}{}'.format(project_mqtt_id, device_mqtt_id, '/{}'.format(device_id) if device_id else ''),
        json.dumps(connect_event, separators=(',', ':')), qos=0)

lwt_event = {
    'event_data': {
        "connected": False
    }
}
mqtt_client = mqtt.Client(client_id=uuid.uuid4().get_hex())
mqtt_client.tls_set()
mqtt_client.username_pw_set('{}/{}'.format(project_mqtt_id, device_mqtt_id), '{}/{}'.format(api_key, user_password))
mqtt_client.on_connect = on_connect
mqtt_client.will_set('0/{}/{}{}'.format(project_mqtt_id, device_mqtt_id, '/{}'.format(device_id) if device_id else ''),
                     json.dumps(lwt_event, separators=(',', ':')), qos=0)
mqtt_client.connect(MQTT_URL, port=MQTT_PORT)

mqtt_client.loop_start()

# keep connection alive
while True:
    time.sleep(1)


# will never goes here if you control-c
print('Disconnecting from M1...')
mqtt_client.disconnect()
mqtt_client.loop_stop()


On Linux command line (note this example is python2)


> pip install paho.mqtt
> python main.py 
(observe the {connected:True} event)
(kill via ctrl-c and observe the {connected:False} event)

Example of Dashboard




Recent Posts

See All

Company

Support

Access

Medium One, Inc

4633 Old Ironsides Drive, Suite 280

Santa Clara, California 95054

info@mediumone.com

650-257-0442

All Rights Reserved © 2021 Medium One, Inc.