我正在运行 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
蚊子。
答案1
持久性是在您将消息发送到代理时设置的,默认情况下消息不是持久性的。
添加第四个参数client.publish()
,即true
,它设置retain
消息的质量,即持久性。