我正在运行 Raspbian 的 Raspberry Pi 上尝试 MQTT。基本设置有效,但我似乎无法配置持久性。
关注https://tutorials-raspberrypi.com/raspberry-pi-mqtt-broker-client-wireless-communication/
我安装了mosquitto mosquitto-clients
我在后台进程中安装paho-mqtt
并运行以下脚本,以从连接的传感器发布温度和湿度读数。
#!/usr/bin/python3
import os
import time
import sys
import Adafruit_DHT as dht
import paho.mqtt.client as mqtt
import json
import datetime
#
# Sensor should be set to Adafruit_DHT.DHT11, Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = dht.DHT11
pin = 4
BROKER = 'localhost'
# Data capture and upload interval in seconds.
INTERVAL=15
sensor_data = {'date': 0, 'temperature': 0, 'humidity': 0}
next_reading = time.time()
client = mqtt.Client()
# Connect to BROKER using default MQTT port and 60 seconds keepalive interval
client.connect(BROKER, 1883, 60)
client.loop_start()
try:
while True:
humidity,temperature = dht.read_retry(sensor, pin)
humidity = round(humidity, 2)
temperature = round(temperature, 2)
print(u"Temperature: {:g}\u00b0C, Humidity: {:g}%".format(temperature, humidity))
sensor_data['temperature'] = temperature
sensor_data['humidity'] = humidity
sensor_data['date'] = datetime.datetime.now().replace(microsecond=0).isoformat()
# client.publish('test_channel', json.dumps(sensor_data), 1)
client.publish('test_channel', json.dumps(sensor_data), 2)
next_reading += INTERVAL
sleep_time = next_reading-time.time()
if sleep_time > 0:
time.sleep(sleep_time)
except KeyboardInterrupt:
pass
client.loop_stop()
client.disconnect()
这有效,我可以在另一个 Pi 上看到消息,mosquitto_sub -h IPaddress -v -t test_channel
但这仅在进程运行时有效。我希望代理保存消息,直到订阅者连接。
我在文件中添加了“persistence true”,/etc/mosquitto/conf.d/Milliways.conf
日志文件显示如下消息
1547597521: Saving in-memory database to /var/lib/mosquitto/mosquitto.db.
该数据库似乎不包含任何相关数据。
我已阅读https://pypi.org/project/paho-mqtt/#publishing和man
for mosquitto 上的文档。
当您将消息发送到代理时设置持久性,默认情况下消息不是持久性的。
向 中添加第四个参数
client.publish()
,即true
,它设置retain
消息的质量,转换为持久性。