7

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?

Bence Kaulics
  • 7,783
  • 8
  • 41
  • 90
pivk95
  • 115
  • 5
  • What's the contents of /home/pi/bin/py.conf? Could you [edit] that into your post? – Aurora0001 Jun 27 '18 at 13:39
  • I'm not sure, I got the code on: http://www.palebluedot.nl/jml/computer-stuff/raspberry-pi/51-request-response-message-exchange-with-mqtt-and-python – pivk95 Jun 27 '18 at 13:52

1 Answers1

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)

Aurora0001
  • 18,490
  • 13
  • 53
  • 168