Unexpected error refreshing default state

From the last couple of weeks, AD was freezing up every couple of days. I am not sure how to troubleshoot this issue. The only way to fix this issue was to restart AD docker container.

I appreciate any help.

2019-04-12 16:00:24.155253 WARNING AppDaemon: Unexpected error refreshing default state - retrying in 10 minutes
2019-04-12 16:00:24.180793 WARNING AppDaemon: Excessive time spent in utility loop: 300807.0ms
2019-04-12 16:05:30.155712 WARNING AppDaemon: Unexpected error refreshing default state - retrying in 10 minutes
2019-04-12 16:05:30.156430 WARNING AppDaemon: Excessive time spent in utility loop: 300974.0ms
2019-04-12 16:10:36.155701 WARNING AppDaemon: Unexpected error refreshing default state - retrying in 10 minutes

2019-04-12 19:16:53.964683 INFO AppDaemon Version 3.0.4 starting

System Health

arch x86_64
dev false
docker true
hassio false
os_name Linux
python_version 3.7.3
timezone America/Chicago
version 0.91.3
virtualenv false

I noticed these messages were posted every five minutes. I found two WatchDog apps that use five minutes internal to check on a couple of entities and if these entities were ON for more than five minutes then these entities get turned OFF.

For now, I commented out both these WatchDog apps.

Can you show the code of the WatchDog apps please?

Could you please also explain what the purpose of these WatchDog apps is?
Wouldn’t it be better to just use the duration parameters and listen for all these entities and as soon as they are turned on for more than five minutes you turn them off.

Here is the code. If any of the entities were turned on during the day time then they will turn off after the timer and also if the deck light is turned at night then after five minutes it gets turned off. This code worked before and I think I need to fine tune this and remove redundant code.

watch_dog_deck:
  module: watchdog
  class: WatchDog
  constrain_input_boolean: input_boolean.ad_watch_dog
  # in mins
  limit: 5
  # Deck light
  entities:
    - switch.ge_12722_onoff_relay_switch_switch

import appdaemon.plugins.hass.hassapi as hass
from datetime import datetime as dt
# from sane_app_logging import SaneLoggingApp

# LOG_DEBUG = False

__version__ = "1.2"

class WatchDog(hass.Hass):
# class WatchDog(hass.Hass, SaneLoggingApp):

  def initialize(self):

    # self._setup_logging(self.__class__.__name__, LOG_DEBUG)
    # self._log.info("Initializing WatchDog...")
    self.log("Initializing WatchDog...")

    self.handle = None

    self.utils = self.get_app('utils')

    if "entities" in self.args:
        for entity in self.args["entities"]:
            # self._log.debug("Entity : " + self.get_state(entity, attribute="friendly_name"))
            self.log("Entity : " + self.get_state(entity, attribute="friendly_name"))

            if self.name == 'watch_dog_hallway_light':
                if self.now_is_between("12:30:00", "sunrise") and self.get_state("sensor.house_mode") == "Night":
                    self.listen_state(self.light_event, entity)
                else:
                    # self._log.debug("Do not monitor entity : " + self.get_state(entity, attribute='friendly_name') + ". Right now it is within scheduled time or not in night mode.")
                    self.log("Do not monitor entity : " + self.get_state(entity, attribute='friendly_name') + ". Right now it is within scheduled time or not in night mode.")
            else:
                self.listen_state(self.light_event, entity)

    # if the light is turned on by motion detector then add addl logic to set brightness
    if self.name == 'watch_dog_hallway_light':
        self.listen_state(self.listenstate_hallway_light, "light.hallway_light_bulb_one")
    
    # self._log.info('Done initializing WatchDog.')
    self.log('Done initializing WatchDog.')


  def light_event(self, entity, attribute, old, new, kwargs):

    self.log('WatchDog: light_event Function triggered ')
    msg= "Watchdog : " + self.friendly_name(entity) + " turned : " + str(new)
    # self._log.debug(msg)
    self.log(msg)

    if "limit" in self.args:
        delay = self.args["limit"]
    else:
        # self._log.critical("Check the apps.yaml file for missing parameter.")
        self.log("Check the apps.yaml file for missing parameter.")
        return

    # start the timer only when the entity is turned on
    if self.get_state(entity) == "on":
        #self.log("Turn off entity - " + self.get_state(entity, attribute='friendly_name') + " - after " + str(delay) + " minutes")
        # self._log.debug(self.get_state(entity, attribute='friendly_name') + " will be turned OFF after " + str(delay) + " minutes")
        self.log(self.get_state(entity, attribute='friendly_name') + " will be turned OFF after " + str(delay) + " minutes")

        self.cancel_timer(self.handle)
        self.handle = self.run_in(self.runin_light_off, delay*60)
    else:
        # self._log.warning("Ignore. This entity : " + self.get_state(entity, attribute='friendly_name') + " is not turned on")
        self.log("Ignore. This entity : " + self.get_state(entity, attribute='friendly_name') + " is not turned on")


  def runin_light_off(self, kwargs):

    self.log('WatchDog: runin_light_off Function triggered ')
    # self._log.debug(self.args)
    # self.log(self.args)

    #2018-10-04 14:49:33.087437 INFO watch_dog_deck:
    #{'module': 'watchdog', 'class': 'WatchDog', 'constrain_input_boolean': 'input_boolean.ad_watch_dog', 'limit': 5, 'entities': ['switch.ge_12722_onoff_relay_switch_switch']}

    # turn off only if the entity is ON state
    for entity in self.args["entities"]:
        if self.get_state(entity) == "on":
            self.turn_off(entity)
            if (self.sun_up()):
                msg= self.get_state(entity, attribute='friendly_name') + " is ON during the day time. Saving power by turning it off!\n"
                self.set_state("sensor.appd_notify_message", state=msg)
            else:
                msg= self.get_state(entity, attribute='friendly_name') + " turned OFF "
                self.set_state("sensor.appd_notify_message", state=msg)
        else:
            # self._log.info("IGNORE - Entity : {} - state : {}".format(self.friendly_name(entity), self.get_state(entity)))
            self.log("IGNORE - Entity : {} - state : {}".format(self.friendly_name(entity), self.get_state(entity)))

  def listenstate_hallway_light(self, entity, attribute, old, new, kwargs):

    self.log('WatchDog: listenstate_hallway_light Function triggered ')

    # if "limit" in self.args:
    #     delay = self.args["limit"]
    # watch_dog_steps_light: Hallway light one - attribute: state - changed from on to off
    # self._log.info("{} - attribute: {} - changed from {} to {}".format(self.friendly_name(entity), attribute, old, new))
    self.log("{} - attribute: {} - changed from {} to {}".format(self.friendly_name(entity), attribute, old, new))

    if new == "on":
      # at night time if this light is turned on then set brightness to 50%
      #brightness is in 0 - 255, constrain to 255 to get percentage-of
      if self.get_state("sensor.house_mode") == "Night":
          blevel = round(int(float(50)) * 255 / 100)
        #   self._log.info("light.{} set to {}.".format(entity, blevel))
          self.log("light.{} set to {}.".format(entity, blevel))
          self.turn_on(entity, brightness=blevel)
      else:
        #   self._log.debug("It's not night time. Set the brightness level to default")
          self.log("It's not night time. Set the brightness level to default")

          # when light brightness was set to 50% from if logic
          # and tried to set brightness to full via Wink app then logic comes here ..Old = On  and New = On
          # because just brightness was changed
          blevel = round(int(float(100)) * 255 / 100)
          self.turn_on(entity, brightness=blevel)
    else:
    #   self.log(msg)
    #   self._log.debug("This entity turned off. Nothing to do here")
      self.log("This entity turned off. Nothing to do here")

I would try something like the below. Please be aware that I didn’t test it.

import appdaemon.plugins.hass.hassapi as hass

class WatchDog(hass.Hass):
    def initialize(self):

        self.log("Initializing WatchDog...")

        if "limit" not in self.args:
            self.log("Check the apps.yaml file for missing parameter.")
            return

        if "entities" in self.args:
            for name, entity in self.args["entities"].items():
                self.listen_state(self.light_event,
                                  entity,
                                  new='on',
                                  duration=self.args['limit'] * 60,
                                  friendly_name=name)

    def light_event(self, entity, attribute, old, new, kwargs):
        if kwargs['friendly_name'] == 'hallway_light':
            if (self.now_is_between("12:30:00", "sunrise") and
                    self.get_state("sensor.house_mode") == "Night"):
                self.turn_lights_off(entity)
            else:
                self.log(f"Do not turn off entity: "
                         f"{self.friendly_name(entity)}."
                         f"Right now it is within scheduled time "
                         f"or not in night mode.")
        else:
            self.turn_lights_off(entity)

    def turn_lights_off(self, entity):
        self.turn_off(entity)
        if self.sun_up():
            msg = (f"{self.friendly_name(entity)} is ON during the day time. "
                   f"Saving power by turning it off!")
            self.set_state("sensor.appd_notify_message", state=msg)
        else:
            msg = f"{self.friendly_name(entity)} turned OFF."
            self.set_state("sensor.appd_notify_message", state=msg)

and the config would look like this:

watch_dog_deck:
  module: watchdog
  class: WatchDog
  constrain_input_boolean.ad_watch_dog
  limit: 5
  entities:
    hallway_light: switch.ge_12722_onoff_relay_switch_switch
    entityxys: switch.xyz

This way it will listen for the state of the specified entities and as soon as one of the specified entities is turned on for longer than the specified limit, the light event function will be called. The light event function then checks if it is the hallway light. If it is the hallway light it will only turn off if the time is between 12:30 and sunrise and the house mode is night. If it is another light it will just turn it off.

I would separate the motion based brightness for the lights into another app.

1 Like

What would be the status of AD docker container when these errors show up in the log file?

2019-04-12 16:00:24.155253 WARNING AppDaemon: Unexpected error refreshing default state - retrying in 10 minutes

I have a script to check the status of home-assistant docker container and send me a notification if that container stopped for any reason. I would like to use the same one for AD.

Thank you for your reply. I will simplify watchdog class as you mentioned and separate the motion lights logic.

Do you also get an error in the appdaemon error log?

If you get an error in the appdaemon error log, then you could write an app that will send a notification as soon as there is an error in the log.