adafruit / adafruit/Adafruit_IO_Python

Can't detect MQTT client login errors on the main thread

Open
#109 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Python
Stars
230
Forks
96
PR merge metrics
No merged PRs in 30d

Description

Hi all,

There does not seem to be a good way to detect a client error on the python main thread when connecting to a feed. I believe this is because the paho.mqtt.client module goes into 'async' mode when there are callbacks set (from the paho docs [here](https://www.eclipse.org/paho/files/mqttdoc/MQTTClient/html/async.html)).

If the user credentials are incorrect there isn't a way to detect this in a single thread application, such as something that connects and just posts a message to a feed then disconnects.

I have a bit of a hacky work-around

```
import logging
import json

import Adafruit_IO

logging.basicConfig(level=logging.DEBUG)

AGENT_MESSAGE_VERSION = .1
ADAFRUIT_IO_USERNAME = "my ada fruit username"
ADAFRUIT_IO_KEY = "WRONG KEY"
FEED_ID = "test_feed_example_derp"

adafruit_io_mqtt_client = Adafruit_IO.MQTTClient(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

adafruit_io_mqtt_client.connect()

feed_message = {"message" : "message would go here"}

adafruit_io_mqtt_client.loop()

# Do some work here

adafruit_io_mqtt_client.publish(FEED_ID, json.dumps(feed_message))

if adafruit_io_mqtt_client.is_connected():
adafruit_io_mqtt_client.disconnect()
else:
logging.error("Message not sent!")

```

The `is_connected()` call will only return true if the networking thread is connected to the feed, but in this case the paho.mqtt.client doesn't try to connect to the IO servers until the 'publish()' call is made.

Ideally the call `adafruit_io_mqtt_client.connect()` or `adafruit_io_mqtt_client.publish()` would raise an exception.

Thanks

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by tracing the MQTTClient connect(), publish(), loop(), and is_connected() behavior described in the issue, including how paho.mqtt.client handles callbacks and connection errors. The work is done when a single-threaded application can detect invalid credentials during connect or publish rather than relying on the networking thread or a later connection check.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
api, networking
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.