6

This is my code and on the bottom is the error I keep getting.

import configparser
from time import localtime, strftime
import json
import paho.mqtt.client as mqtt


config = configparser.ConfigParser()
config.read('/home/pi/bin/py.conf')     # Broker connection config.

requestTopic  = 'services/timeservice/request/+'        # Request comes in 
here. Note wildcard.
responseTopic = 'services/timeservice/response/'        # Response goes 
here. Request ID will be appended later

def onConnect(client, userdata, flags, rc):
   print("Connected with result code " + str(rc))

def onMessage(client, userdata, message):
   requestTopic = message.topic
   requestID = requestTopic.split('/')[3]       # obtain requestID as last 
field from the topic

   print("Received a time request on topic " + requestTopic + ".")

   lTime = strftime('%H:%M:%S', localtime())
   
   client.publish((responseTopic + requestID), payload=lTime, qos=0, 
retain=False)

def onDisconnect(client, userdata, message):
    print("Disconnected from the broker.")


# Create MQTT client instance
mqttc = mqtt.Client(client_id='raspberrypi', clean_session=True)

mqttc.on_connect = onConnect
mqttc.on_message = onMessage
mqttc.on_disconnect = onDisconnect

And after I try to connect to a broker:

mqttc.username_pw_set(config['MQTT']['userMQTT'], password=config['MQTT']['passwdMQTT'])
mqttc.connect(config['MQTT']['hostMQTT'], port=int(config['MQTT']['portMQTT']), keepalive=60, bind_address="")

I get the fallowing error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.5/configparser.py", line 956, in __getitem__
    raise KeyError(key)
KeyError: 'MQTT'

Does anybody know how to fix this error while trying to connect to a broker?

2

1 Answer 1

5

If you haven't created /home/pi/bin/py.conf... that's your problem.

config = configparser.ConfigParser()
config.read('/home/pi/bin/py.conf')

That code tries to open the file /home/pi/bin/py.conf and read it using an INI-like format. It turns that into a Python dict. Working back from the code, you need to add the following to /home/pi/bin/py.conf:

[MQTT]
userMQTT = username
passwdMQTT = password
hostMQTT = broker address
portMQTT = broker port

(filling in the details, of course)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.