Ejemplo n.º 1
0
class BikeRack:
    def __init__(self, name, mqtt_broker, mqtt_port):
        """
        Start the component.
        ## Start of MQTT
        We subscribe to the topic(s) the component listens to.
        The client is available as variable `self.client` so that subscriptions
        may also be changed over time if necessary.
        The MQTT client reconnects in case of failures.
        ## State Machine driver
        We create a single state machine driver for STMPY. This should fit
        for most components. The driver is available from the variable
        `self.driver`. You can use it to send signals into specific state
        machines, for instance.
        """

        # TODO Make the mqtt topics into bike/$name/command (input) and bike/$name (output).
        # Something wrong happened trying to do so.
        self.MQTT_TOPIC_INPUT = 'bike/'  #, name, '/command'
        self.MQTT_TOPIC_OUTPUT = 'bike/'  #, name

        # Get the logger object for the component
        self._logger = logging.getLogger(__name__)
        print('Logging under name {}.'.format(__name__))

        # ::: DEBUGGING :::
        # logging.DEBUG: Most fine-grained logging, printing everything
        # logging.INFO:  Only the most important informational log items
        # logging.WARN:  Show only warnings and errors.
        # logging.ERROR: Show only error messages.
        debug_level = logging.DEBUG
        logger = logging.getLogger(__name__)
        logger.setLevel(debug_level)
        ch = logging.StreamHandler()
        ch.setLevel(debug_level)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)-12s - %(levelname)-8s - %(message)s')
        ch.setFormatter(formatter)
        logger.addHandler(ch)
        # END DEBUGGING

        self._logger.info('Starting Component')

        # Create a new MQTT client
        self._logger.debug('Connecting to MQTT broker {} at port {}'.format(
            mqtt_broker, mqtt_port))
        self.mqtt_client = mqtt.Client()

        # Callback methods
        self.mqtt_client.on_connect = self.on_connect
        self.mqtt_client.on_message = self.on_message

        # Connect to the broker
        self.mqtt_client.connect(mqtt_broker, mqtt_port)

        # Subscribe to proper topic(s) of your choice
        self.mqtt_client.subscribe(self.MQTT_TOPIC_INPUT)

        # Start the internal loop to process MQTT messages
        self.mqtt_client.loop_start()

        # We start the stmpy driver, without any state machines for now
        self.driver = Driver()
        self.driver.start(keep_active=True)

        self._logger.debug('Component initialization finished')

        # Active machines
        self.active_machines = {}
        self.name = name

        # Add test_lock
        lock_name = "en"
        self._logger.debug(f'Create machine with name: {lock_name}')
        lock_stm = BikeLock(self.driver, self, lock_name)

        self.driver.add_machine(lock_stm.stm)
        self.active_machines[lock_name] = lock_name

        self._logger.debug("Start driver")
        self.driver.start()
        # TEST END

    def stop(self):
        """
        Stop the component.
        """
        # Stop the MQTT client
        self.mqtt_client.loop_stop()
        # Stop the state machine Driver
        self.driver.stop()

    def on_connect(self, client, userdata, flags, rc):
        # We just log that we are connected
        self._logger.debug('MQTT connected to {}'.format(client))

    def check_available(self):
        for name in self.active_machines:
            if self.driver._stms_by_id[name].state == "available":
                return True

    def on_message(self, client, userdata, msg):
        """
        Processes incoming MQTT messages.
        We assume the payload of all received MQTT messages is an UTF-8 encoded
        string, which is formatted as a JSON object. The JSON object contains
        a field called `command` which identifies what the message should achieve.
        As a reaction to a received message, we can for example do the following:
        * create a new state machine instance to handle the incoming messages,
        * route the message to an existing state machine session,
        * handle the message right here,
        * throw the message away.
        """
        self._logger.debug('Incoming message to topic {}'.format(msg.topic))

        payload = json.loads(msg.payload)
        command = payload.get('command')
        self._logger.debug(f"Have detected this command: {command}")

        if command == "check_driver":
            self._logger.debug(f"State Machine: {self.driver.print_status()}")
            if self.check_available():
                self.mqtt_client.publish(self.MQTT_TOPIC_OUTPUT,
                                         self.driver.print_status())

        # Assumes payload with ``lock_name`` and ``nfc_tag``
        elif command == "reserve":
            for name in self.active_machines:
                if self.driver._stms_by_id[name].state == "available":
                    self._logger.debug(f"Reserving lock with id: {name}")
                    kwargs = {"nfc_tag": payload.get("value")}
                    self.driver.send(message_id='reserve',
                                     stm_id=name,
                                     kwargs=kwargs)
                    self.mqtt_client.publish(
                        self.MQTT_TOPIC_OUTPUT,
                        f'Reserved lock with name {name}')
                    self.mqtt_client.publish(
                        self.get_stm_by_name(name)._obj.get_nfc_tag())
                    self._logger.debug(
                        self.get_stm_by_name(name)._obj.get_nfc_tag())
                    return
            self._logger.debug("No locks available in this rack")
            self.mqtt_client.publish(self.MQTT_TOPIC_OUTPUT,
                                     f'No locks available')

        elif command == "add_lock":
            lock_name = payload.get("lock_name")
            self._logger.debug(f"Add lock with name: {lock_name}")
            lock_stm = BikeLock(self.driver, self, lock_name)
            self.driver.add_machine(lock_stm.stm)
            self.active_machines[lock_name] = lock_name

        # Assumes payload with``nfc_tag`` and ``lock_name``
        elif command == "nfc_det":
            self._logger.debug("running nfc_det")
            self.nfc_det(nfc_tag=payload.get("value"),
                         lock_name=payload.get("lock_name"))

        elif command == "check_state":
            name = payload.get("name")
            self._logger.debug(
                f"Machine: {name}, is in state: {self.get_stm_by_name(name).state}"
            )
            self.mqtt_client.publish(
                self.MQTT_TOPIC_OUTPUT,
                f"Machine: {name}, is in state: {self.get_stm_by_name(name).state}"
            )

        # Catch message without handler
        else:
            self._logger.debug(f"Command: {command} does not have a handler")

    def res_expired(self, nfc_tag):
        self.mqtt_client.publish(self.MQTT_TOPIC_OUTPUT,
                                 f'Reservetion timed out for {nfc_tag}')

    def nfc_det(self, nfc_tag, lock_name):
        self._logger.debug(
            f"Detected NFC-tag with value: {nfc_tag} presented to lock: {lock_name}"
        )
        self._logger.debug(self.get_stm_by_name(lock_name).state)
        kwargs = {"nfc_tag": nfc_tag}
        self.driver.send(message_id='nfc_det', stm_id=lock_name, kwargs=kwargs)

    # Getter for stm_by name
    def get_stm_by_name(self, stm_name):
        if self.driver._stms_by_id[stm_name]:
            self._logger.debug(f"Getting stm with name: {stm_name}")
            return self.driver._stms_by_id[stm_name]
        # Did not find machine with ``stm_name``
        self._logger.error(f"Error: did not find stm with name: {stm_name}")
        return None
Ejemplo n.º 2
0
class WalkieTalkie:
    def __init__(self, transitions, states, debug):
        self.payload = {}
        self._logger = logging.getLogger(__name__)
        self._logger.info('logging under name {}.'.format(__name__))
        self._logger.info('Starting Component')
        self.debug = debug
        self.app = None
        self.lock = Lock()
        self.recorder = Recorder(self)
        self.text_to_speech = Speaker()
        self.overwrote_last = False

        self.uuid = uuid4().hex
        if self.debug:
            self.uuid = "122ec9e8edda48f8a6dd290747acfa8c"
        self.channel = "{server}{uuid}".format(server=MQTT_TOPIC_BASE,uuid=self.uuid)

        self.name = "jonas"
        stm_walkie_talkie_name = "{}_walkie_talkie".format(self.name)
        walkie_talkie_machine = Machine(transitions=transitions, states=states, obj=self, name=stm_walkie_talkie_name)
        self.stm = walkie_talkie_machine

        recognizer_stm = get_state_machine('stm_recognizer', [stm_walkie_talkie_name])

        self.stm_driver = Driver()
        self.stm_driver.add_machine(walkie_talkie_machine)
        self.stm_driver.add_machine(recognizer_stm)
        self.stm_driver.start()
        self._logger.debug('Component initialization finished')

    def create_gui(self):
        self.app = gui("Walkie Talkie", "320x568", bg='yellow')
        self.app.setStretch("both")
        self.app.setSticky("")
        self.app.setBgImage("images/bg.gif")

        if self.debug == True:
            self.app.setInPadding([30,40])
            self.app.setPadding([0,50])
        self.app.addLabel("status", "State: STATUS", 0, 0)
        self.app.setLabelBg("status", "#3e3e3e")
        self.app.setLabelFg("status", "white")

        def on_button_pressed_start(label):
            label = label.lower()
            command = label
            if 'stop' in label:
                self.stop_recording()
                command = "stop"
            elif 'send <' in label:
                self.stm.send("send", kwargs={'action': 'send', 'argument': 'bob ross'})
                command = "send"
            elif 'replay <' in label:
                self.stm.send("replay", kwargs={'action': 'replay', 'argument': 'bob ross'})
                command = "replay"
            elif 'replay' in label:
                self.stm.send("replay")
                command = "replay"
            elif 'next' in label:
                self.stm.send("next") 
                command = "next"
            elif 'play' in label:
                self.stm.send("play")
                command = "play"
            print("[ACTION]:", command)
            print("[STATE]:", self.stm.state)
        
        if self.debug == True:
            self.app.setPadding([0,0])
            self.app.setInPadding([60,40])
            self.app.startLabelFrame("Debug panel",1,0)
            self.app.setStretch("both")
            self.app.setSticky("news")
            self.app.addButton('Send <name>', on_button_pressed_start)
            self.app.addButton('Stop recording', on_button_pressed_start)
            self.app.addButton('Play', on_button_pressed_start)
            self.app.addButton('Replay', on_button_pressed_start)
            self.app.addButton('Next', on_button_pressed_start)
            self.app.addButton('Replay <name>', on_button_pressed_start)
            self.app.stopLabelFrame()
        else:
            self.app.addLabel("padding", "", 1, 0)
        self.update_led(False)
        self.update_status('LISTENING')
        self.app.go()

    def on_init(self):
        # Create and start MQTT client on init
        client = MQTT_Client(self)
        self.mqtt_client = client.client # for publishing/subscribing to broker
        client.stm = self.stm
        client.start(MQTT_BROKER, MQTT_PORT)

        self.mqtt_client.subscribe(self.channel)
        print("{uuid}: listening on channel {channel}".format(uuid=self.uuid, channel=self.channel))

        # Create GUI in a new thread
        th = Thread(target=self.create_gui)
        th.start()
    
    # Text-to-speech
    def tts(self, text):
        th = Thread(target=self.text_to_speech.speak, args=[str(text)])
        th.start()
        self._logger.debug(text)

    def force_stop(self):
        if self.recorder.playing:
            self.recorder.force_stop()
            while not self.recorder.terminated:
                pass

    def register(self):
        msg = {
            "command":"register",
            "uuid":self.uuid,
            "name":self.name
        }
        json_msg = json.dumps(msg)
        self.mqtt_client.publish(MQTT_TOPIC_OUTPUT, json_msg)
        print(self.uuid)

    def query_server(self, **kwargs): # check if recipient/sender is registered
        if kwargs.get("argument") and kwargs.get("action"):
            msg = {
                "command":"query",
                "device_id_from":self.uuid,
                "recipient_name": kwargs.get("argument")
            }
            json_msg = json.dumps(msg)
            self.mqtt_client.publish(MQTT_TOPIC_OUTPUT, json_msg)
        else:
            self.stm.send("time_out")

        '''
        request:
        {"device_id_from": uuid, "recipient_name": name, "command" : "query" }
 
        response:
        {"device_id_from": sender, "recipient_name": name, "exists": true/false}
        '''

    def start_recording(self):
        self.update_status("RECORDING")
        self.recorder.record()

    def stop_recording(self):
        self.update_status("STOP RECORDING")
        self.recorder.stop()
    
    # Parses server responses
    def parse_message(self, payload):
        if payload.get('command') == "message":
            self.stm.send("save_message", args=[payload])
        elif payload.get('exists') == True: # if recipient exists
            self.recipient = payload.get("recipient_name")
            self.stm.send("query_ok")
        elif payload.get('exists') == False: # if recipient does not exists
            self.stm.send("query_not_found")
        elif payload.get('data'):
            self.stm.send('replay_save_message', args=[payload])
    
    def threaded_save(self, lock, payload):
        lock.acquire()
        try:
            sender_name = payload.get('device_owner_name_from')
            self.tts(f"Received message from {sender_name}")
            # Retreive message from payload
            wf = payload.get('data')
            data = base64.b64decode(wf)
            # Get queue length and saves message in the FIFO order
            queue_number = len(os.listdir("message_queue"))
            with open(f'message_queue/{queue_number}.wav', 'wb') as fil:
                fil.write(data)
                self._logger.debug(f'Message saved to /message_queue/{queue_number}.wav')
        except:
            self._logger.error(f'Payload could not be read!')
        lock.release()
        self.iterate_queue(False)

    def save_message(self, payload):
        th = Thread(target=self.threaded_save, args=[self.lock,payload])
        th.start()
        th.join()

    def play_replay_message(self, payload):
        try:
            # Retreive message from payload
            wf = payload.get('data')
            data = base64.b64decode(wf)
            with open(f'replay_message.wav', 'wb') as fil:
                fil.write(data)
                self._logger.debug(f'Message saved to replay_message.wav')
            self.recorder.play("replay_message.wav")
            self.stm.send("replay_finished")
        except: # Should never happen, but added as insurance so the program doesn't throw an error and stops
            self._logger.error(f'Payload could not be read!')
            self.stm.send("replay_finished")

    def print_timer(self):
        print(self.stm.get_timer('time_out'))

    def play_message(self):
        self.update_status("PLAYING")
        self.overwrote_last = False

        # Check queue length
        queue_folder = "message_queue"
        queue_length = len(os.listdir(queue_folder))
        if self.check_message_queue(1):
            self._logger.info(f'Playing message 1/{queue_length}!')
            self.recorder.play(f"{queue_folder}/1.wav")
            if not self.overwrote_last:
                self.stm.send('message_played')
                self.update_led(False, 1)
        else:
            self.stm.send("queue_empty")
    
    def load_next_message_in_queue(self):
        # Iterates queue in FIFO order deleting the first file and shifting the filenames to the left
        if self.check_message_queue(2):  # if there are more than 2, it is safe to iterate
            self.iterate_queue(True, True)
        else:
            self.iterate_queue(True, True)
            self.stm.send("queue_empty")

    def check_message_queue(self, i): # returns true if there are more than i messages left in queue
        if len(os.listdir("message_queue")) > i:
            return True
        return False
    
    def threaded_iterate(self, lock, remove):
        lock.acquire()
        queue_folder = "message_queue"
        num = 1
        listdir = os.listdir(queue_folder)
        listdir.sort()
        for filename in listdir:
            if filename.split(".")[0] == "1" and num == 1 and remove:
                os.remove(f"{queue_folder}/{filename}")
            else:
                if filename != ".gitkeep":
                    os.rename(f"{queue_folder}/{filename}", f"{queue_folder}/{num}.wav")
                    num += 1
        self.update_led(False)
        lock.release()

    def iterate_queue(self, remove, force=False):
        if force:
            self.overwrite_current_playing()
        th = Thread(target=self.threaded_iterate, args=[self.lock, remove])
        th.start()
        th.join()

    # Request replay message from the server
    def get_latest_user_message(self):
        self.update_status("REPLAYING")
        name = self.recipient
        uuid = self.uuid
        msg = {
            "device_id_from": uuid,
            "device_owner_name_to": name,
            "command":"replay",
        }
        json_msg = json.dumps(msg)
        self.mqtt_client.publish(MQTT_TOPIC_OUTPUT, json_msg)

    def send_data(self):
        filename = self.recorder.filename
        byte_data = open(filename, 'rb')
        data = base64.b64encode(byte_data.read())
        msg = {
            "device_id_from":self.uuid,
            "device_owner_name_to": self.recipient,
            "command": "message",
            "data": data.decode()
        }
        json_msg = json.dumps(msg)
        self.mqtt_client.publish(MQTT_TOPIC_OUTPUT,json_msg)
     
    def update_status(self, text):
        if self.app != None:
            label = "State:"+text
            self.app.setLabel("status", label)

    def update_led(self, is_error, queue_pad=0):
        if self.app != None:
            if is_error:
                self.app.setBgImage("images/bg_red.gif")
            else:
                if self.check_message_queue(1+queue_pad): # check if there are more than 1 messages in queue
                    self.app.setBgImage("images/bg_green.gif")
                else:
                    self.app.setBgImage("images/bg.gif")

    def vibrate(self):
        self.recorder.play("vibrate.wav")
        self._logger.debug("Walkie goes brrrrrr...")

    def stop(self):
        # stop the MQTT client
        self.mqtt_client.loop_stop()
        # stop the state machine Driver
        self.stm_driver.stop()

    def overwrite_current_playing(self):
        self.overwrote_last = True
        self.force_stop()
class WalkieTalkie:
    """
    The component to send and receive voice messages.
    """

    def __init__(self):
        # setting the standard channel as 0 and ID as default
        self.channel = 0
        self.ID = "default"

        # the output dir is where received recordings are stored
        self.output_dir = "../player/"
        self.record_dir = "../recordings/"
        self.channel_dir = self.output_dir + str(self.channel)
        self.fileNameList = []
        self.messageList = []

        # cleaing the player list
        self.create_channel_folder(self.output_dir, self.record_dir)

        #Burde vi ha create_player_folder for konsistent??
        self.clear_player_folder(self.output_dir)

        # get the logger object for the component
        self._logger = logging.getLogger(__name__)
        print('logging under name {}.'.format(__name__))
        self._logger.info('Starting Component')


        # create a new MQTT client
        self._logger.debug('Connecting to MQTT broker {} at port {}'.format(MQTT_BROKER, MQTT_PORT))
        self.mqtt_client = mqtt.Client()
        # callback methods
        self.mqtt_client.on_connect = self.on_connect
        self.mqtt_client.on_message = self.on_message
        self.mqtt_client.on_disconnect = self.on_disconnect


        # Connect to the broker
        try:
            self.mqtt_client.connect(MQTT_BROKER, MQTT_PORT)

        except:
            print("Connection fails")
            sys.exit(1)


        self.mqtt_client.loop_start()

        '''
        #Testing the on_disconnect function
        time.sleep(10)
        self.mqtt_client.disconnect() # disconnect gracefully
        self.mqtt_client.loop_stop() # stops network loop
        time.sleep(5)
        self.mqtt_client.connect()
        '''


        # recorder
        recorder = Recorder.create_machine('stm_recorder', self)
        self.recorder = recorder
        stm_recorder = recorder.stm

        # player
        player = Player.create_machine('stm_player', self)
        self.player = player
        stm_player = player.stm

        # creating driver, attaching machines
        self.driver = Driver()
        self.driver.add_machine(stm_recorder)
        self.driver.add_machine(stm_player)

        # starting driver
        self.driver.start(keep_active = True)
        self.create_gui()
        print("Bye!")


    def create_channel_folder(self, output_dir, record_dir):
        if not os.path.exists(output_dir): os.mkdir(output_dir)
        if not os.path.exists(record_dir): os.mkdir(record_dir)
        for i in range(MAX_CHANNELS):
            path = output_dir + str(i)
            if not os.path.exists(path):
                os.mkdir(path)

    def clear_player_folder(self, output_dir):
        for i in range(MAX_CHANNELS):
            for f in os.listdir(output_dir + str(i)):
                if f.endswith(".wav"):
                    os.remove(os.path.join(output_dir+str(i), f))

    def set_channel_path(self):
        self.channel_dir=self.output_dir +str(self.channel)


    def on_connect(self, client, userdata, flags, rc):
        print(mqtt.connack_string(rc))
        if(rc == 0):
            self.mqtt_client.subscribe(MQTT_TOPIC_INPUT + str(self.channel))
            self.mqtt_client.subscribe(MQTT_TOPIC_INPUT+ str(self.channel)+"/ACK")
            self._logger.debug('MQTT connected to {}'.format(client))
            self.client_id = client
        else:
            print(mqtt.connack_string(rc))

    def on_disconnect(self, client, userdata, rc):
        if(rc == 0):
            print("Disconnected gracefully.")
        else:
            print("Unexpected disconnection.")
            self.app.setLabel("delivered", text = "Connection lost: Waiting to reconnect \n and resend latest message")


    # Runs when WalkieTalkie receives a message
    def on_message(self, client, userdata, msg):
        print("A message is received")
        self._logger.debug('Incoming message to topic {}'.format(msg.topic))


        #message_payload_received = json.load(io.BytesIO(msg.payload))
        if(msg.payload):
            message_payload_received = json.loads(msg.payload)
            # Check correct channel
            if(str(msg.topic) == MQTT_TOPIC_OUTPUT + str(self.channel) and message_payload_received):
                dataToByteArray = base64.b64decode(bytearray(bytes(message_payload_received['data'], "utf-8")))

                print("client_id: " + message_payload_received['ID'])

                # Check that message is not sent to self
                if (message_payload_received['ID'] != self.ID):
                    temp_file = message_payload_received['ID'] + str(strftime(" %Y-%m-%d %H-%M-%S", gmtime())) + ".wav"
                    self.temp_file = temp_file
                    f = open(os.path.join(self.channel_dir, self.temp_file), 'wb')
                    f.write(dataToByteArray)
                    print("Data written to file")
                    f.close()
                    self.driver.send('start', 'stm_player', args=[os.path.join(self.channel_dir, self.temp_file)])
                    time.sleep(1)
                    self.messageList  = [ Message(path) for path in os.listdir(self.channel_dir) if path.endswith(".wav") ]
                    self.fileNameList = [ m.path for m in self.messageList]
                    print(self.fileNameList)
                    self.app.changeOptionBox("Choose message", self.fileNameList)

                    # Sending ack
                    package_ack = {'message_id': message_payload_received['Msg_ID'], 'sender': message_payload_received['ID']}
                    payload_ack = json.dumps(package_ack)
                    self.mqtt_client.publish(str(msg.topic)+"/ACK", payload_ack, qos=2)


            # Checks for ACK
            if (str(msg.topic) == MQTT_TOPIC_INPUT+ str(self.channel)+"/ACK"):
                if(message_payload_received['message_id'] == self.recorder.get_latest_file()):
                    if(message_payload_received['sender'] == self.ID):
                        print("Message delivered with ID: "+ message_payload_received['message_id'] + " and sender: " + message_payload_received['sender'])
                        self.app.setLabel("delivered","Message delivered")
                        self.app.setLabelFg("delivered","green")




    def send_message(self):
        print("Sending a new message")
        #self.mqtt_client.connect(MQTT_BROKER, MQTT_PORT)
        path = self.recorder.get_latest_file()
        f = open(path, "rb")
        imagestring = f.read()
        f.close()
        imageByteArray = bytearray(imagestring)
        imageByteArrayString = str(base64.b64encode(imageByteArray), "utf-8")
        package = {'ID': self.ID, 'data': imageByteArrayString, 'Msg_ID': path}
        payload = json.dumps(package)
        mqtt_msg = self.mqtt_client.publish(MQTT_TOPIC_OUTPUT + str(self.channel), payload, qos = 2)
        timestamp = time.time()
        print("Sending the message took: {} ".format(time.time()-timestamp))

        self.app.setLabel("delivered",text = "Sending")
        self.app.setLabelFg("delivered","orange")
        time.sleep(1)
        # catching the exception thrown by mqtt when no acc is given.
        ## TODO: Her kan vi kanskje ha Message failed rød tekst? Hvis Catch error.


    # Creates the appJar GUI
    def create_gui(self):
        BUTTON_WIDTH = 30
        self.app = gui("Walkie-Talkie", "300x500")


        #set username
        def on_button_name(title):
            self.ID = self.app.getEntry("NameEntry")
            self.app.setLabel("NameLabel", "User: "******"User ID changed")

        #channel up
        def on_button_pressed_increase(title):
            self.mqtt_client.unsubscribe(MQTT_TOPIC_INPUT + str(self.channel))
            self.mqtt_client.unsubscribe(MQTT_TOPIC_INPUT+ str(self.channel)+"/ACK")
            self.channel = (self.channel + 1)% MAX_CHANNELS
            self.set_channel_path()
            self.mqtt_client.subscribe(MQTT_TOPIC_INPUT + str(self.channel))
            self.mqtt_client.subscribe(MQTT_TOPIC_INPUT+ str(self.channel)+"/ACK")
            self.app.setLabel("Channel",text="Connected to channel: {}".format(self.channel))

        #channel up
        def on_button_pressed_decrease(title):
            self.mqtt_client.unsubscribe(MQTT_TOPIC_INPUT + str(self.channel))
            self.mqtt_client.unsubscribe(MQTT_TOPIC_INPUT+ str(self.channel)+"/ACK")
            self.channel = (self.channel - 1) % MAX_CHANNELS
            self.set_channel_path()
            self.mqtt_client.subscribe(MQTT_TOPIC_INPUT + str(self.channel))
            self.mqtt_client.subscribe(MQTT_TOPIC_INPUT+ str(self.channel)+"/ACK")
            self.app.setLabel("Channel",text="Connected to channel: {}".format(self.channel))


        #start recording
        def on_button_pressed_start(title):
            self.driver.send('start', 'stm_recorder')
            print("Start recording")

        #Stop recording and send message
        def on_button_pressed_stop(title):
            self.driver.send('stop', 'stm_recorder')
            time.sleep(1)
            self.send_message()
            print("Stop recording")

        #resend latest message
        def on_button_pressed_resend(title):
            if os.listdir(self.record_dir) != []:
                self.send_message()
            else:
                print("You have no messages. ")

        #Replay chosen message
        def on_button_pressed_replay(title):
            play_list = self.fileNameList
            if play_list:
                tmp = self.app.getOptionBox('Choose message')
                self.driver.send('replay', 'stm_player', args=[os.path.join(self.channel_dir, tmp)])
            else:
                print("You have no messages. ")


        def voiceToText(title):
            play_list = self.fileNameList
            if play_list:
                tmp = self.app.getOptionBox('Choose message')
                r = sr.Recognizer()

                lyd=sr.AudioFile(os.path.join(self.channel_dir, tmp))
                with lyd as source:
                    audio = r.record(source)
                try:
                    s = r.recognize_google(audio)
                    self.app.setLabel("message","Message: " + s)
                except Exception as e:
                    print("Exception: "+str(e))
            else:
                print("You have no messages. ")



        # Choose ID
        self.app.addLabel("NameLabel", "User: "******"Names")

        self.app.addLabel("NameEntryLabel", "Name: ", 1, 0)

        self.app.addEntry("NameEntry", 1, 1)
        self.app.setEntrySubmitFunction("NameEntry", on_button_name)
        self.app.stopLabelFrame()


        # Choose channel
        self.app.startLabelFrame('Change channel:')
        self.app.addLabel("Channel",text="Connected to channel: {}".format(self.channel), colspan=2)
        self.app.setLabelWidth('Channel', int(BUTTON_WIDTH*(5/3)))

        self.app.addButton('Increase', on_button_pressed_increase, 1, 0)
        self.app.setButtonWidth('Increase', BUTTON_WIDTH)

        self.app.addButton('Decrease', on_button_pressed_decrease, 1 , 1)
        self.app.setButtonWidth('Decrease', BUTTON_WIDTH)
        self.app.stopLabelFrame()

        # Start and stop recording
        self.app.startLabelFrame('Send messages')

        self.app.addButton('Start recording', on_button_pressed_start, 1, 0)
        self.app.setButtonWidth("Start recording", BUTTON_WIDTH)

        self.app.addButton('Stop and send', on_button_pressed_stop, 1, 1)
        self.app.setButtonWidth('Stop and send', BUTTON_WIDTH)

        #resend and exit button
        self.app.addButton('Resend', on_button_pressed_resend, colspan=2)
        self.app.setButtonWidth('Resend', BUTTON_WIDTH*2)
        self.app.addButton('Exit system', sys.exit, colspan=3)
        self.app.setButtonWidth('Exit system', BUTTON_WIDTH*2)


        self.app.addLabel("delivered", "")
        self.app.stopLabelFrame()


        # Replay last received message
        self.app.startLabelFrame('Replay message:')
        self.app.addOptionBox("Choose message", self.fileNameList, colspan=2)
        self.app.setOptionBoxWidth('Choose message', BUTTON_WIDTH)

        self.app.addButton('Replay', on_button_pressed_replay, 1, 0)
        self.app.setButtonWidth('Replay', BUTTON_WIDTH)
        self.app.addButton('Text Message', voiceToText, 1, 1)
        self.app.setButtonWidth('Text Message', BUTTON_WIDTH)
        self.app.stopLabelFrame()



        #Voice to text
        self.app.startFrame("message frame")
        self.app.setBg("white")
        self.app.addLabel("message", "No message data...")
        self.app.stopFrame()
        self.app.go()
        self.stop()


    def stop(self):
        """
        Stop the component.
        """
        self.mqtt_client.loop_stop()
        # Stop the state machine Driver
        self.driver.stop()