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
中添加以下内容:
评论
/home/pi/bin/py.conf的内容是什么?您可以将其编辑到您的帖子中吗?我不确定,我得到的代码是:palebluedot.nl/jml/computer-stuff/raspberry-pi / ...