Search code examples
pythonmqttpaho

Connect to MQTT Broker with .env variables


I wrote a python code to connect to a MQTT Broker, which worked completely fine until I tried working with environment variables. The library used is paho-mqtt.

At first, the broker, port, topic, password and username were declared in the code, and the code worked well. Then, I created a .env file which stores those variables, and now it cannot connect to the broker anymore.

Here's how the python code "loads" the environment variables :

from dotenv import load_dotenv
...
if private_lorawan == True:
    load_dotenv('mqtt-private.env') # loads file
    broker = os.getenv('BROKER')
    port = int(os.getenv('PORT')) # convert in integer
    topic = os.getenv('TOPIC')
    username = os.getenv('USERNAME')
    password = os.getenv('PASSWORD')

Here's the mqtt-private.env file :

BROKER='xxx.xx.xx.xxx' # IP address
PORT=1883
TOPIC="v3/<topic>/devices/<device-eui>/up"
USERNAME="<username>"
PASSWORD="<password>"

And here's the output when running the code :

Connect_mqtt
my-client-0
Loop started
Failed to connect, return code 5

When searching what the return code means :

5 : Connection Refused. The client is not authorized to connect.

I tried :

  • username and password in double quotes

  • username and password without double quotes

But none of these options seem to work.


Solution

  • As per the docs:

    By default, load_dotenv doesn't override existing environment variables.

    USERNAME is set to the login name in many operating systems, so the result you are seeing is to be expected. Solutions include using a different variable name, loading the data into a dict (dotenv_values), and specifying override - load_dotenv(dotenv_path='mqtt-private.env', override=True).