Mqtt

我似乎無法在 MQTT 中配置持久性

  • January 16, 2019

我正在執行 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/#publishingmanfor mosquitto 上的文件。

當您將消息發送到代理時設置持久性,預設情況下消息不是持久性的。

向 中添加第四個參數client.publish(),即true,它設置retain消息的質量,轉換為持久性。

引用自:https://unix.stackexchange.com/questions/494706