How do i write if/else code for subscribing or not subscribing to a message?

80 views
Skip to first unread message

Spencer Du

unread,
Aug 8, 2019, 9:00:39 AM8/8/19
to MQTT
Hi I have some code I need help with. How do I write if else code meaning that if I have subscribed to a topic then I execute some commands and if I don't subscribe to a topic then I output an error message on the else block. 

import logging
from datetime import timedelta
import time
from thespian.actors import *
from transitions import Machine
import paho.mqtt.client as mqtt
class devices(mqtt.Client):
    def on_connect(self, mqttc, obj, flags, rc):
     if rc==0:
      client.connected_flag=True #set flag
      print("Connecting to broker")
     else:
         print("Bad connection Returned code=",rc)
    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 on_log(self, mqttc, userdata, level, buf):
    #     print("log: ",buf)
    def run(self):
        self.connect("broker.hivemq.com", 1883, 60)
client = devices("Laser")
client.run()
client.loop_start() #start the loop
time.sleep(2)
print("creating new instance laser")
print("Publishing message to topic","microscope/light_sheet_microscope/UI")
client.publish("microscope/light_sheet_microscope/UI","Hello World Im a laser!")
time.sleep(2) # wai
client.loop_stop() #stop the loop
# print("creating new instance motorized mirror galvo")
# client = devices("Motorized mirror galvo")
# client.run()
# client.loop_start() #start the loop
# time.sleep(2)
# print("Publishing message to topic","microscope/light_sheet_microscope/UI")
# client.publish("microscope/light_sheet_microscope/UI","Hello World Im a motorized mirror galvo!")
# time.sleep(2) # wait
# client.loop_stop() #stop the loop
# print("creating new instance cameras")
# client = devices("Cameras")
# client.run()
# client.loop_start() #start the loop
# time.sleep(2)
# print("Publishing message to topic","microscope/light_sheet_microscope/UI")
# client.publish("microscope/light_sheet_microscope/UI","Hello World Im a camera!")
# time.sleep(2) # wait
# client.loop_stop() #stop the loop

# print("creating new instance filter wheel")
# client = devices("Filter wheel")
# client.run()
# client.loop_start() #start the loop
# time.sleep(2)
# print("Publishing message to topic","microscope/light_sheet_microscope/UI")
# client.publish("microscope/light_sheet_microscope/UI","Hello World Im a Filter Wheel!")
# time.sleep(2) # wait
# client.loop_stop() #stop the loop
class Generic_device(mqtt.Client, Actor):
 def on_connect(self, mqttc, obj, flags, rc):
  # print("rc: "+str(rc))
  a = 9
  b = 20
  print("Subscribing to topic","microscope/light_sheet_microscope/UI/")
        # print("Subscribing to topic","microscope/light_sheet_microscope/UI/motorized_mirror_galvo")
        # print("Subscribing to topic","microscope/light_sheet_microscope/UI/stages")
        # print("Subscribing to topic","microscope/light_sheet_microscope/UI/cameras")
        # print("Subscribing to topic","microscope/light_sheet_microscope/UI/filter_wheel")       
  mqttc.subscribe("microscope/light_sheet_microscope/UI" + device)
 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)
 # def receiveMessage(self, message, sender):
 #  if message == "'Subscribing to topic','microscope/light_sheet_microscope/UI/laser'":
 #   laser = self.createActor(Laser)
 #   lasermsg = (sender, 'Laser')
 #   self.send(laser, lasermsg)
     # if message == "'Subscribing to topic','microscope/light_sheet_microscope/UI/motorized_mirror_galvo'":
     #     galvo = self.createActor(Galvo)
     #     galvomsg = (sender, 'Galvo')
     #     self.send(galvo, galvomsg)
     # if message == "'Subscribing to topic','microscope/light_sheet_microscope/UI/stages'":
     #  stages = self.createActor(Stages)   
     #  stagesmsg = (sender, 'Stages')
     #  self.send(stages, stagesmsg)
     # if message == "'Subscribing to topic','microscope/light_sheet_microscope/UI/cameras'":
     #     cameras = self.createActor(Cameras)
     #     camerasmsg = (sender, 'Cameras')
     #     self.send(cameras, camerasmsg)
     # if message == "'Subscribing to topic','microscope/light_sheet_microscope/UI/filter_wheel'":
     #     filter_wheel = self.createActor(Filter_wheel)
     #     filter_wheelmsg = (sender, 'Filter wheel')
     #     self.send(filter_wheel, filter_wheelmsg)
client = Generic_device("Generic devices")
client.run()
client.loop_start() #start the loop
time.sleep(2) # wait
client.loop_stop() #stop the loop

class State(object):
    """
    We define a state object which provides some utility functions for the
    individual states within the state machine.
   
    """
    def __init__(self):
     print("Current state: ", str(self))
    def on_event(self, event):
        """
        Handle events that are delegated to this State.
       
        """
        pass
   
    def __repr__(self):
        """
        Leverages the __str__ method to describe the State.
        """
        return self.__str__()
    def __str__(self):
        """
        Returns the name of the State.
        """
        return self.__class__.__name__
# Start of our states
class UninitialisedState(State):
    """
    The uninitialised state.       
   
    """
    def on_event(self, event):
        if event == 'Initialised':
            return InitialisedState()
        return self
class InitialisedState(State):
    """
    The initialised state.
    """
    def on_event(self, event):
        if event == "Configured":
            return ConfiguredState()
        return self
class ConfiguredState(State):
    """
    The configured state.
    """
    def on_event(self, event):
        if event == "Running":
            return RunningState()
        return self
class RunningState(State):
    """
    The running state.
    """
    def on_event(self, event):
        if event == "Stop":
            return UninitialisedState()
        return self
class SimpleDevice(object):
    """
    A simple state machine that mimics the functionality of a device from a
    high level.
    """
    def __init__(self):
        """ Initialise the components. """
        # Start with a default state.
        self.state = UninitialisedState()
    def on_event(self, event):
        """
        This is the bread and butter of the state machine. Incoming events are
        delegated to the given states which then handle the event. The result is
        then assigned as the new state.
       
        """
        # The next state will be the result of the on_event function.
        self.state = self.state.on_event(event)
device = SimpleDevice()
""" Shelf class """
class Shelf(dict):
    def __setitem__(self, key, item):
        self.__dict__[key] = item
    def __getitem__(self, key):
        return self.__dict__[key]
    def __repr__(self):
        return repr(self.__dict__)
    def __len__(self):
        return len(self.__dict__)
    def __delitem__(self, key):
        del self.__dict__[key]
    def clear(self):
        return self.__dict__.clear()
    def copy(self):
        return self.__dict__.copy()
    def has_key(self, k):
        return k in self.__dict__
    def update(self, *args, **kwargs):
        return self.__dict__.update(*args, **kwargs)
    def keys(self):
        return self.__dict__.keys()
    def values(self):
        return self.__dict__.values()
    def items(self):
        return self.__dict__.items()
    def pop(self, *args):
        return self.__dict__.pop(*args)
    def __cmp__(self, dict_):
        return self.__cmp__(self.__dict__, dict_)
    def __contains__(self, item):
        return item in self.__dict__
    def __iter__(self):
        return iter(self.__dict__)
    def __unicode__(self):
        return unicode(repr(self.__dict__))
s = Shelf()
s.shelf = "GFP"
print(s)
# class Laser(Actor):
#     def receiveMessage(self, message, sender):
#      if isinstance(message, tuple):
#             orig_sender, pre_laser = message
#             self.send(orig_sender, pre_laser + ' actor created')
# class Galvo(Actor):
#     def receiveMessage(self, message, sender):
#         if isinstance(message, tuple):
#             orig_sender, pre_galvo = message
#             self.send(orig_sender, pre_galvo + ' actor created')
# class Stages(Actor):
#     def receiveMessage(self, message, sender):
#         if isinstance(message, tuple):
#             orig_sender, pre_galvo = message
#             self.send(orig_sender, pre_galvo + ' actor created')
# class Cameras(Actor):
#     def receiveMessage(self, message, sender):
#         if isinstance(message, tuple):
#             orig_sender, pre_cameras = message
#             self.send(orig_sender, pre_cameras + ' actor created')
# class Filter_wheel(Actor):
#     def receiveMessage(self, message, sender):
#         if isinstance(message, tuple):
#             orig_sender, pre_filter_wheel = message
#             self.send(orig_sender, pre_filter_wheel + ' actor created')
# def run_example(systembase=None):
#     generic_device = ActorSystem().createActor(Generic_device)
#     laser = ActorSystem().ask(generic_device, "'Subscribing to topic','microscope/light_sheet_microscope/UI/laser'", 1.5)
#     print(laser)
#     # galvo = ActorSystem().ask(generic_device, "'Subscribing to topic','microscope/light_sheet_microscope/UI/motorized_mirror_galvo'", 1.5)
#     # print(galvo)
#     # stages = ActorSystem().ask(generic_device, "'Subscribing to topic','microscope/light_sheet_microscope/UI/stages'", 1.5)
#     # print(stages)
#     # cameras = ActorSystem().ask(generic_device, "'Subscribing to topic','microscope/light_sheet_microscope/UI/cameras'", 1.5)
#     # print(cameras)
#     # filter_wheel = ActorSystem().ask(generic_device, "'Subscribing to topic','microscope/light_sheet_microscope/UI/filter_wheel'", 1.5)
#     # print(filter_wheel)
#     ActorSystem().shutdown()
# if __name__ == "__main__":
#     import sys
#     run_example(sys.argv[1] if len(sys.argv) > 1 else None)

Thanks
Spencer

wally kulecz

unread,
Aug 8, 2019, 9:44:12 AM8/8/19
to mq...@googlegroups.com
This makes absolutely no sense.  If you subscribe to a topic or not you know it when you do or don't do it, so whats the need for if/else?  When you connect and subscribe you know if it succeeds or not.  Look into using the on_subscribe callback.

--
To learn more about MQTT please visit http://mqtt.org
---
You received this message because you are subscribed to the Google Groups "MQTT" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mqtt+uns...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mqtt/e764ca65-9328-430d-a919-c9f920405cad%40googlegroups.com.

Spencer Du

unread,
Aug 8, 2019, 9:53:45 AM8/8/19
to MQTT
Sorry what I meant was if a message is subscribed to then I can execute some commands.
To unsubscribe from this group and stop receiving emails from it, send an email to mq...@googlegroups.com.

wally kulecz

unread,
Aug 8, 2019, 10:38:18 AM8/8/19
to mq...@googlegroups.com
That is what the on_subscribe callback is for.
See:


To unsubscribe from this group and stop receiving emails from it, send an email to mqtt+uns...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/mqtt/ffd26190-ae6c-4957-a8c4-808b05fcdbc8%40googlegroups.com.

Spencer Du

unread,
Aug 8, 2019, 4:37:16 PM8/8/19
to MQTT
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
Reply all
Reply to author
Forward
0 new messages