连接到 MQTT 代理时出现 KeyError

物联网 MQTT
2021-06-10 05:01:31

这是我的代码,底部是我不断收到的错误。

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

在我尝试连接到代理之后:

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="")

我得到了以下错误:

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'

有人知道如何在尝试连接到代理时修复此错误吗?

1个回答

如果你还没有创建/home/pi/bin/py.conf......那是你的问题。

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

该代码尝试打开文件/home/pi/bin/py.conf并使用类似 INI 的格式读取它它把它变成了一个 Python dict从代码开始,您需要将以下内容添加到/home/pi/bin/py.conf

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

(当然是填写详细信息)