question

paulm avatar image
paulm asked

Venus MQTT keepalive - how to do this in python script with topic list payload ??

I have a python script to send the 'keepalive' message to the Venus MQTT broker running on a raspberry pi 3 :

import paho.mqtt.client as mqtt     # MQTT support
import time
import json

mqttBroker ="victronpi"                 # define MQTT broker address
client = mqtt.Client("KeepAlive") # identify client
client.connect(mqttBroker)              # connect to broker
print("VictronPi MQTT broker connected...")

while True:
  # send 'keepalive' message
  errcode = client.publish("R/b123abc7d123/keepalive") # publish all topics
#  topics = json.dumps("solarcharger/+/Dc/0/Voltage")
#  errcode = client.publish("R/b123abc7d123/keepalive",topics) # publish selected topics
  print("VictronPi KeepAlive sent : ",errcode)
  time.sleep(10)

I'd like to just keep alive the topics I'm interested in. I gather you can do this by including a payload in the 'keepalive' message but I'm struggling with the python syntax to do this, see commented out lines above, which just create a new read topic. Can anyone enlighten me what the correct python syntax to do this is please ?

PaulM


Venus OSRaspberry PiMQTTpython
2 |3000

Up to 8 attachments (including images) can be used with a maximum of 190.8 MiB each and 286.6 MiB total.

1 Answer
paulm avatar image
paulm answered ·

Solved, the 'topics = json.dumps(....)' parameter(s) should be a list, not a string, corrected and expanded python script :

#!/usr/bin/python3

# Send 'keepalive' to Victron Venus MQTT broker
#   with payload = list of topics to publish

import paho.mqtt.client as mqtt         # MQTT support
import time
import json

mqttBroker ="victronpi"                 # define MQTT broker address
client = mqtt.Client("KeepAlive")       # identify client
client.connect(mqttBroker)              # connect to broker
print("VictronPi MQTT broker connected...")

while True:

  # publish 'keepalive' message for all topics

  #errcode = client.publish("R/b123abc7d123/keepalive")

  # publish 'keepalive' message for selected topics

  topics = []                               # create list..
  topics.append("inverter/+/Dc/0/Voltage")  # ..and append MQTT topics
  topics.append("inverter/+/Ac/Out/L1/V")
  topics.append("inverter/+/Ac/Out/L1/I")
  topics.append("solarcharger/+/Pv/V")
  topics.append("solarcharger/+/Yield/Dc/0/Voltage")
  topics.append("solarcharger/+/Yield/Dc/0/Current")
  payload = json.dumps(topics)              # publish 'json' payload..
  errcode = client.publish("R/b123abc7d123/keepalive",payload)
  print("VictronPi KeepAlive sent : ",errcode)
  time.sleep(10)                            # repeat every 10 seconds

PaulM


2 |3000

Up to 8 attachments (including images) can be used with a maximum of 190.8 MiB each and 286.6 MiB total.