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.
from datetime import timedelta
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
def on_connect(self, mqttc, obj, flags, rc):
if rc == 0:
print("Connected to broker")
def on_message(self, mqttc, userdata, message):
print("message received " ,str(message.payload.decode("utf-8")))
print("message retain flag=",message.retain)
def on_publish(self, mqttc, obj, mid):
def on_subscribe(self, mqttc, obj, mid, granted_qos):
print("Subscribed: "+str(mid)+" "+str(granted_qos))
self.connect("broker.hivemq.com", 1883, 60)
print("creating new instance laser")
client = device("Device")
client.loop_start() #start the loop
device = "laser"
print("Publishing message to topic","microscope/light_sheet_microscope/UI")
time.sleep(2) # wait
client.loop_stop() #stop the loop