osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How do i execute some code when I have subscribed to a topic with a message payload for mqtt in python?


Ok so here is some code below. How do I write an if code block to execute some commands when I subscribe to the topic: microscope/light_sheet_microscope/UI and which has a message which is a device type published to it. I want to execute some code to check if the device has a python file in the currently directory because each device also relates to a python file. If the file exists then import the file into the python program else print an error message. If I need to use on_subscribe callback then tell and show me how the code is to be written and if another method then also tell me and show me how to write the code. I really appreciate all the help you can give me because this is really important for me and I am currently really struggling with MQTT because I need help with writing MQTT code because I am working on MQTT at work.

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt

class device(mqtt.Client):
    def on_connect(self, mqttc, obj, flags, rc):
     if rc == 0:
      print("Connected to broker") 
     else:
      print("Connection failed")
     mqttc.subscribe("microscope/light_sheet_microscope/UI")
    def on_message(self, mqttc, userdata, message):
        print("message received " ,str(message.payload.decode("utf-8")))
        print("message topic=",message.topic)
        print("message qos=",message.qos)
        print("message retain flag=",message.retain)
    def on_publish(self, mqttc, obj, mid):
        print("mid: "+str(mid))
    def on_subscribe(self, mqttc, obj, mid, granted_qos):
        print("Subscribed: "+str(mid)+" "+str(granted_qos))
    def run(self):
        self.connect("broker.hivemq.com", 1883, 60)
print("creating new instance laser")
client = device("Device")
client.run()
client.loop_start() #start the loop
device = "laser"
time.sleep(2)
print("Publishing message to topic","microscope/light_sheet_microscope/UI")
client.publish("microscope/light_sheet_microscope/UI",device)
time.sleep(2) # wait
print("subscribing ")
client.subscribe("microscope/light_sheet_microscope/UI")
client.loop_stop() #stop the loop

Thanks
Spencer