How to use the appdaemon.plugins.hass.hassapi function in appdaemon

To help you get started, we’ve selected a few appdaemon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jantman / home-automation-configs / appdaemon / apps / activitywatch_state_updater.py View on Github external
'device_tracker.rf8m22eq54n': 'aw-watcher-hass-device',
    'sensor.desk_standing': 'aw-watcher-hass-desk-standing'
}

#: The host that ActivityWatch is running on
AW_HOST = '192.168.0.24'

#: The port that ActivityWatch is running on
AW_PORT = 5600

#: Default for info-as-debug logging via LogWrapper; can be overridden
#: at runtime via events. See ``sane_app_logging.py``.
LOG_DEBUG = True


class ActivityWatchStateUpdater(hass.Hass, SaneLoggingApp):
    """
    ActivityWatch state updater
    """

    def initialize(self):
        self._setup_logging(self.__class__.__name__, LOG_DEBUG)
        self._log.info("Initializing ActivityWatchDeviceTracker...")
        self._base_url = 'http://%s:%d/api/0/' % (AW_HOST, AW_PORT)
        self.current_states = {}
        for entity_id, bucket_id in ENTITY_IDS_TO_BUCKETS.items():
            self._create_bucket(bucket_id)
            self.current_states[entity_id] = self.get_state(entity_id)
            self.listen_state(self.state_change, entity_id)
            self.send_heartbeat(bucket_id, self.current_states[entity_id])
        self._timer = self.run_minutely(
            self._timer_callback, time(0, 0, 12)
github fronzbot / githass / apps / flux.py View on Github external
'''

import appdaemon.plugins.hass.hassapi as hass
import datetime as dt
import pytz

DEBUG = False


def utc_to_est(datetime_obj):
    """Naive timezone conversion because I'm lazy AF."""
    tz_offset = dt.timedelta(hours=-5)
    return datetime_obj + tz_offset


class Flux(hass.Hass):

    def initialize(self):
        # Colors dict contains:
        # Color temperature
        # Starting offset in minutes
        self.colors = {
            'sunrise': {'temp': 3000, 'offset': -45},
            'day': {'temp': 4000, 'offset': 30},
            'sunset': {'temp': 3000, 'offset': -45},
            'night': {'temp': 2400, 'offset': 60}
        }
        self.offsets = {}
        for key, value in self.colors.items():
            self.offsets[key] = dt.timedelta(minutes=value['offset'])

        self.current_time = utc_to_est(dt.datetime.now()).time()
github eifinger / appdaemon-scripts / pollenNotifier / pollenNotifier.py View on Github external
#   Use consistent message variable
#
# Version 1.3:
#   use Notify App
#
# Version 1.2:
#   message now directly in own yaml instead of message module
#
# Version 1.1:
#   Added notify_threshold
#
# Version 1.0:
#   Initial Version


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

        self.timer_handle_list = []
        self.listen_event_handle_list = []
        self.listen_state_handle_list = []

        self.app_switch = globals.get_arg(self.args, "app_switch")
        self.pollen_sensor = globals.get_arg(self.args, "pollen_sensor")
        self.pollen_name = globals.get_arg(self.args, "pollen_name")
        self.notify_name = globals.get_arg(self.args, "notify_name")
        self.notify_time = globals.get_arg(self.args, "notify_time")
        self.notify_threshold = globals.get_arg(self.args, "notify_threshold")
        self.message = globals.get_arg(self.args, "message")
        self.message_no_data = globals.get_arg(self.args, "message_no_data")

        self.mappingsdict = {}
github jantman / home-automation-configs / appdaemon / apps / unioncam_time_setter.py View on Github external
generate a TZ string to send to the camera in the "name-offset" format that
    it expects (i.e. for the America/New_York TZ, "EST-5:00:00").
    """
    now = datetime.datetime.now()
    tz = get_localzone()
    name = tz.tzname(now)
    offset = tz.utcoffset(now)
    secs = offset.total_seconds()
    hours = int(secs / 3600.0)
    secs = secs % 3600.0
    mins = int(secs / 60.0)
    secs = int(secs % 60.0)
    return '{0:}{1:d}:{2:0>2d}:{3:0>2d}'.format(name, hours, mins, secs)


class UnionCamTimeSetter(hass.Hass, SaneLoggingApp):

    def initialize(self):
        self._setup_logging(self.__class__.__name__, LOG_DEBUG)
        self._log.info("Initializing UnionCamTimeSetter...")
        self.run_hourly(self._set_times, datetime.time(0, 12, 0))
        self._log.info('Done initializing UnionCamTimeSetter')
        self.listen_event(self._set_times, event='UNIONCAM_TIME_SETTER')

    def _set_times(self, *args, **kwargs):
        tz = get_timezone_string()
        self._log.info(
            'Setting date/time on UnionCam Cameras (timezone: %s)...', tz
        )
        dt = datetime.datetime.now()
        for host in CAMERA_HOSTS:
            self._log.info('Connecting to camera: %s', host)
github eifinger / appdaemon-scripts / turnOffBarAfterRestart / turnOffBarAfterRestart.py View on Github external
#
# Will turn the bar table green and then off when homeassistant restarts to indicate the restart went well
#
#
# Args:
#
# light: light. example: light.bar_table
#
# Release Notes
#
# Version 1.0:
#   Initial Version


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

        self.timer_handle_list = []
        self.listen_event_handle_list = []
        self.listen_state_handle_list = []

        self.light = globals.get_arg(self.args, "light")

        self.timer_handle_list.append(self.run_in(self.turn_green_callback, 1))

    def turn_off_callback(self, kwargs):
        """Turn off light"""
        try:
            self.log("Turning {} off".format(self.friendly_name(self.light)))
            self.turn_off(self.light)
        except requests.exceptions.HTTPError as exception:
github aneisch / home-assistant-config / extras / appdaemon / apps / algo_timer.py View on Github external
import appdaemon.plugins.hass.hassapi as hass, sqlite3
from datetime import datetime, timedelta

#
# https://github.com/aneisch/home-assistant-config/blob/master/extras/appdaemon/apps/algo_timer.py
# Automatically turn off entity after averaged amount of time
#

class SmartTimer(hass.Hass):
  def initialize(self):
    
    # Path to our DB as defined in apps.yaml
    db_location = self.args["db_location"]

    # Set up callback and listen for state change of desired switch
    self.listen_state(self.calculate_times, self.args["entity_id"], db_location=db_location)
    self.log("Initializing.. DB located at: %s" % db_location)


  # Calculate the average amount of time a switch is on
  def calculate_times(self, entity, attribute, old, new, kwargs):

    # Only execute if turned on
    if new == "on":
github zlalanne / home-assistant-config / config / appdaemon / apps / home_notification.py View on Github external
import appdaemon.plugins.hass.hassapi as hass


class HomeNotification(hass.Hass):
    def initialize(self):
        self.log("Starting up")

        self.garage_door = self.args["garage_door"]
        self.lights = self.args["lights"]

        self.listen_state(self.start_toggle, entity=self.garage_door, new="open")

    def start_toggle(self, entity, attribute, old, new, kwargs):
        self.log("Garage door open, starting to toggle lights")
        self.flashcount = 0
        self.run_in(self.flash, 1)

    def flash(self, kwargs):
        self.toggle(self.lights)
        self.flashcount += 1
github aneisch / home-assistant-config / extras / appdaemon / apps / light_automation.py View on Github external
import appdaemon.plugins.hass.hassapi as hass


#Turn on a scene at given time (specified in apps.yaml)
class DeviceOn(hass.Hass):
    def initialize(self):
      time_on = self.parse_time(self.args["time_on"])
      self.run_daily(self.on, time_on)

    def on(self, kwargs):
        if self.args["dependent_entity"]:
            if self.get_state(self.args["dependent_entity"]) == "on":
                for entity in self.split_device_list(self.args["entity"]):
                    self.log("Turning on " + entity)
                    self.turn_on(entity)
        else:
            if self.get_state(self.args["device_tracker"]) == "home":
                for entity in self.split_device_list(self.args["entity"]):
                    self.log("Turning on" + entity)
                    self.turn_on(entity)
github eifinger / appdaemon-scripts / isHomeDeterminer / isHomeDeterminer.py View on Github external
# Release Notes
#
# Version 1.3:
#   message now a list
#
# Version 1.2:
#   message now directly in own yaml instead of message module
#
# Version 1.1:
#   Added app_switch
#
# Version 1.0:
#   Initial Version


class IsHomeDeterminer(hass.Hass):
    def initialize(self):
        self.listen_state_handle_list = []

        self.app_switch = globals.get_arg(self.args, "app_switch")
        self.ishome = globals.get_arg(self.args, "ishome")
        self.input_booleans = globals.get_arg_list(self.args, "input_booleans")
        self.message = globals.get_arg_list(self.args, "message")

        if self.get_state(self.app_switch) == "on":
            for input_boolean in self.input_booleans:
                self.log(
                    "{} is {}".format(input_boolean, self.get_state(input_boolean))
                )
                self.listen_state_handle_list.append(
                    self.listen_state(self.state_change, input_boolean)
                )
github aneisch / home-assistant-config / extras / appdaemon / apps / ac_automation.py View on Github external
import appdaemon.plugins.hass.hassapi as hass
import datetime

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

        # Add api endpoints for REST https://appdaemon.readthedocs.io/en/latest/APPGUIDE.html?#restful-api-support
        self.register_endpoint(self.adjust_night, "adjust_night")
        self.register_endpoint(self.adjust_morning, "adjust_morning")

        # Compute our times
        self.morning_adjust_weekday = datetime.datetime.strptime(self.args["morning_adjust_weekday"], '%H:%M:%S').time()
        self.night_adjust_weekday = datetime.datetime.strptime(self.args["night_adjust_weekday"], '%H:%M:%S').time()
        self.morning_adjust_weekend = datetime.datetime.strptime(self.args["morning_adjust_weekend"], '%H:%M:%S').time()
        self.night_adjust_weekend = datetime.datetime.strptime(self.args["night_adjust_weekend"], '%H:%M:%S').time()

        # Set our time callbacks
        self.run_daily(self.adjust_morning, self.morning_adjust_weekday, constrain_days="mon,tue,wed,thu,fri")
        self.run_daily(self.adjust_night, self.night_adjust_weekday, constrain_days="mon,tue,wed,thu,fri")
        self.run_daily(self.adjust_morning, self.morning_adjust_weekend, constrain_days="sat,sun")