micropython / micropython/micropython-lib

umqtt: keepalive feature doesn’t function correctly

Open
#909 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
2.9k
Forks
1.1k
Avg merge
7d 6h
Merged PRs (30d)
3

Description

Hi!

Here’s some example code to reproduce the issue:

import ssl
import machine
import network
from umqtt.simple import MQTTClient

client_id = machine.unique_id().hex()
mqtt_server = 'XXX.s1.eu.hivemq.cloud'
mqtt_user = 'XXX'
mqtt_password = 'XXX'
mqtt_topic_sub = b'test/topic'

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('XXX','XXX')

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)

def mqtt_connect():
    client = MQTTClient(client_id, mqtt_server, 8883, mqtt_user, mqtt_password, 15, ssl_context)
    client.connect()
    print('Connected to %s MQTT Broker'%(mqtt_server))
    return client

def reconnect():
    print('Failed to connect to the MQTT Broker. Reconnecting...')
    machine.reset()
    
def callback(topic, msg):
    print(topic, msg)

try:
    client = mqtt_connect()
    client.set_callback(callback)
    client.subscribe(mqtt_topic_sub)
except OSError as e:
    reconnect()
while True:
    client.wait_msg()

The library allows setting the keepalive to any value (default is 0, which disables it). However, when you set a keepalive value, the library does not automatically send pings to the server as expected. This causes the server to disconnect the client after 1.5 times the specified keepalive duration.

Are there any possible solutions to this?

I tested this with Mosquitto and HiveMQ serverless.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the umqtt.simple MQTTClient implementation used by the example and trace how the keepalive argument is handled while wait_msg() blocks. Reproduce against Mosquitto or HiveMQ with keepalive=15; done means the client sends the required pings and remains connected beyond the broker timeout, with regression coverage for the behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
networking
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.