katia-khennoune avatar image
katia-khennoune asked

How I can run mosquitto_sub command from python script ?


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:

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 = ""
def on_message(client, userdata, message):
    val = json.loads(message.payload)
def on_connect(client, userdata, rc, *args): 
    client.subscribe("N/%s/system/0/Dc/Battery/Voltage" % portal_id)
client = Client("P1")
client.username_pw_set(username, password=password)
client.connect(mqtt_broker, port=8883)
client.on_connect = on_connect
client.on_message = on_message
while True:

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...

0 Likes 0 ·