question

katia-khennoune avatar image
katia-khennoune asked

How I can run mosquitto_sub command from python script ?

Hi!

I want to run mosquitto sub command in a python script instead of typing it in raspberry pi terminal but I don't know how to do it. I need your help please

Venus GX - VGXRaspberry PiMQTT
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
Ole Saether avatar image
Ole Saether answered ·

Below is a python script that prints the battery voltage and exits. You need to change the mqtt_broker for your installation. See at the bottom of this page on how to find the correct one:
https://github.com/victronenergy/dbus-mqtt

  1. from time import sleep
  2. import ssl
  3. import json
  4. import os
  5. from paho.mqtt.client import Client
  6. username = "your VRM email"
  7. password = "your VRM pasword"
  8. portal_id = "your VRM portal ID"
  9. mqtt_broker = "mqtt67.victronenergy.com"
  10. def on_message(client, userdata, message):
  11. val = json.loads(message.payload)
  12. print(val["value"])
  13. client.loop_stop()
  14. client.disconnect()
  15. os._exit(0)
  16. def on_connect(client, userdata, rc, *args):
  17. client.subscribe("N/%s/system/0/Dc/Battery/Voltage" % portal_id)
  18. client = Client("P1")
  19. client.tls_set(cert_reqs=ssl.CERT_NONE)
  20. client.tls_insecure_set(True)
  21. client.username_pw_set(username, password=password)
  22. client.connect(mqtt_broker, port=8883)
  23. client.on_connect = on_connect
  24. client.on_message = on_message
  25. client.loop_start()
  26. while True:
  27. sleep(1)


3 comments
2 |3000

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

homestorage-77 avatar image homestorage-77 commented ·

When I run this with my credentials, nothing happens - the terminal window just has a square in.

Can anyone confirm if this works as intended?



0 Likes 0 ·
woogieboogie avatar image woogieboogie homestorage-77 commented ·

I had to run the Remote VRM console at the same time to get data back to this script. I think this is because of required keep-alive function that I've seen mentioned somewhere. In this case, running the remote VRM console in another window or device "wakes" up the MQTT broker.

0 Likes 0 ·
paulm avatar image paulm woogieboogie commented ·

Here's a python script that creates the 'keepalive' message without using VRM...

https://community.victronenergy.com/questions/141467/venus-mqtt-keepalive-how-to-do-this-in-python-scri.html

0 Likes 0 ·