Help with Run_in and Cancel_timer

I have the app below and it works in it’s current form, it’s really just an automation. I am would like to amend the application to wait 5 minutes to power down the amp but if the state changes back to playing I would like the 5 minute timer to be canceled. I am not quite sure how to go about this. This is my first app and my first experience with python.

import appdaemon.plugins.hass.hassapi as hass
## Subon
class sub(hass.Hass):

    def initialize(self):
        self.listen_state(self.control)

    def control(self, entity, attribute, old, new, kwargs):
        #Gets the state of media_player.mpd
        state = self.get_state("media_player.mpd")
        #If the state of media_player.mpd is playing turn the office amp on
        if state == "playing":
            self.turn_on("switch.office_amp")
        #If the state of media_player.mpd is paused turn the office amp off
        elif state == "paused":
            self.turn_off("switch.office_amp")
        #If the state of media_player.mpd is off turn the office amp off
        elif state == "off":
            self.turn_off("switch.office_amp")

I thought about adding a new def like this one but then after 5 minutes the amp will shutoff even if the playback has resumed. :

def paused(self, entity, attribute, old, new, kwargs):
    self.run_in(self.amp_off, 300)

I think I could use the self.cancel_timer(handle) but I’m really confused on how to implement self.cancel_timer especially the handler part.

Thanks for help and reading this lengthy post.

Hell @warllo54,

You need the duration parameter as described here

So

def initialize(self):
        self.listen_state(self.control)

Should be

def initialize(self):
        self.listen_state(self.control, "media_player.mpd", new = "off", duration = 300)#wait for 5 mins
        self.listen_state(self.control, "media_player.mpd", new = "playing")
        self.listen_state(self.control, "media_player.mpd", new = "paused", duration = 120 )# wait for 2 mins

def control(self, entity, attribute, old, new, kwargs):
        #If the state of media_player.mpd is playing turn the office amp on
        if new == "playing":
            self.turn_on("switch.office_amp")
        #If the state of media_player.mpd is paused turn the office amp off
        elif new == "paused":
            self.turn_off("switch.office_amp")
        #If the state of media_player.mpd is off turn the office amp off
        elif new == "off":
            self.turn_off("switch.office_amp")
1 Like

Thank you very much for your post. Things are working exactly as desired.