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

from time import sleep
import ssl
import json
import os
from paho.mqtt.client import Client 
 
username = "your VRM email"
password = "your VRM pasword"
portal_id = "your VRM portal ID"
mqtt_broker = "mqtt67.victronenergy.com"
 
def on_message(client, userdata, message):
    val = json.loads(message.payload)
    print(val["value"])
    client.loop_stop()
    client.disconnect()
    os._exit(0)
 
 
def on_connect(client, userdata, rc, *args): 
    client.subscribe("N/%s/system/0/Dc/Battery/Voltage" % portal_id)
 
client = Client("P1")
client.tls_set(cert_reqs=ssl.CERT_NONE)
client.tls_insecure_set(True)
client.username_pw_set(username, password=password)
client.connect(mqtt_broker, port=8883)
client.on_connect = on_connect
client.on_message = on_message
 
client.loop_start()
 
while True:
    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 ·
Show more comments