コード例 #1
0
ファイル: test_event.py プロジェクト: 1lann/home-assistant
    def test_periodic_task_hour(self):
        """Test periodic tasks per hour."""
        specific_runs = []

        track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), hour='/2')

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 0, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(2, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 25, 1, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(2, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(3, len(specific_runs))
コード例 #2
0
def setup(hass, config):
    """Set up the BMW connected drive components."""
    accounts = []
    for name, account_config in config[DOMAIN].items():
        username = account_config[CONF_USERNAME]
        password = account_config[CONF_PASSWORD]
        country = account_config[CONF_COUNTRY]
        _LOGGER.debug('Adding new account %s', name)
        bimmer = BMWConnectedDriveAccount(username, password, country, name)
        accounts.append(bimmer)

        # update every UPDATE_INTERVAL minutes, starting now
        # this should even out the load on the servers

        now = datetime.datetime.now()
        track_utc_time_change(
            hass, bimmer.update,
            minute=range(now.minute % UPDATE_INTERVAL, 60, UPDATE_INTERVAL),
            second=now.second)

    hass.data[DOMAIN] = accounts

    for account in accounts:
        account.update()

    for component in BMW_COMPONENTS:
        discovery.load_platform(hass, component, DOMAIN, {}, config)

    return True
コード例 #3
0
ファイル: myhome.py プロジェクト: darookee/hass-config
def register_presence_handlers(hass, config):
    """ Registers the event handlers that handle presence. """
    rfid_sensor = config[DOMAIN].get(CONF_RFID, None)
    if rfid_sensor is None:
        _LOGGER.warning('RFID sensor not configured.')
        return

    def rfid_seen(now=None):
        """ Calls see service periodically with state of RFID sensor. """
        rfid_state = hass.states.get(rfid_sensor)
        location = STATE_NOT_HOME
        if rfid_state is not None and str(rfid_state.state) == '1':
            location = STATE_HOME
        _LOGGER.debug('rfid %s state is %s', rfid_sensor, location)
        hass.services.call(DEVICE_TRACKER_DOMAIN, SERVICE_SEE, {
            ATTR_DEV_ID: split_entity_id(rfid_sensor)[1],
            ATTR_LOCATION_NAME: location,
        })

    helper.track_utc_time_change(hass, rfid_seen, second=0)

    def rfid_state_change(entity_id, old_state, new_state):
        """ Calls see service immediately with state of RFID sensor. """
        rfid_seen()

    helper.track_state_change(hass, rfid_sensor, rfid_state_change)
コード例 #4
0
ファイル: icloud.py プロジェクト: Martwall/home-assistant
    def __init__(self, hass, username, password, name, max_interval,
                 gps_accuracy_threshold, see):
        """Initialize an iCloud account."""
        self.hass = hass
        self.username = username
        self.password = password
        self.api = None
        self.accountname = name
        self.devices = {}
        self.seen_devices = {}
        self._overridestates = {}
        self._intervals = {}
        self._max_interval = max_interval
        self._gps_accuracy_threshold = gps_accuracy_threshold
        self.see = see

        self._trusted_device = None
        self._verification_code = None

        self._attrs = {}
        self._attrs[ATTR_ACCOUNTNAME] = name

        self.reset_account_icloud()

        randomseconds = random.randint(10, 59)
        track_utc_time_change(
            self.hass, self.keep_alive, second=randomseconds)
コード例 #5
0
ファイル: sun.py プロジェクト: BryonCLewis/home-assistant
    def __init__(self, hass, location):
        """Initialize the sun."""
        self.hass = hass
        self.location = location
        self._state = self.next_rising = self.next_setting = None
        self.solar_elevation = self.solar_azimuth = 0

        track_utc_time_change(hass, self.timer_update, second=30)
コード例 #6
0
ファイル: __init__.py プロジェクト: karliemeads/core
def setup_account(entry: ConfigEntry, hass,
                  name: str) -> BMWConnectedDriveAccount:
    """Set up a new BMWConnectedDriveAccount based on the config."""
    username = entry.data[CONF_USERNAME]
    password = entry.data[CONF_PASSWORD]
    region = entry.data[CONF_REGION]
    read_only = entry.options[CONF_READ_ONLY]
    use_location = entry.options[CONF_USE_LOCATION]

    _LOGGER.debug("Adding new account %s", name)

    pos = ((hass.config.latitude, hass.config.longitude) if use_location else
           (None, None))
    cd_account = BMWConnectedDriveAccount(username, password, region, name,
                                          read_only, *pos)

    def execute_service(call):
        """Execute a service for a vehicle."""
        vin = call.data[ATTR_VIN]
        vehicle = None
        # Double check for read_only accounts as another account could create the services
        for entry_data in [
                e for e in hass.data[DOMAIN][DATA_ENTRIES].values()
                if not e[CONF_ACCOUNT].read_only
        ]:
            vehicle = entry_data[CONF_ACCOUNT].account.get_vehicle(vin)
            if vehicle:
                break
        if not vehicle:
            _LOGGER.error("Could not find a vehicle for VIN %s", vin)
            return
        function_name = _SERVICE_MAP[call.service]
        function_call = getattr(vehicle.remote_services, function_name)
        function_call()

    if not read_only:
        # register the remote services
        for service in _SERVICE_MAP:
            hass.services.register(DOMAIN,
                                   service,
                                   execute_service,
                                   schema=SERVICE_SCHEMA)

    # update every UPDATE_INTERVAL minutes, starting now
    # this should even out the load on the servers
    now = dt_util.utcnow()
    track_utc_time_change(
        hass,
        cd_account.update,
        minute=range(now.minute % UPDATE_INTERVAL, 60, UPDATE_INTERVAL),
        second=now.second,
    )

    # Initialize
    cd_account.update()

    return cd_account
コード例 #7
0
    def __init__(self, hass, config, see, tesla_devices):
        """Initialize the Tesla device scanner."""
        self.hass = hass
        self.see = see
        self.devices = tesla_devices
        self._update_info()

        track_utc_time_change(
            self.hass, self._update_info, second=range(0, 60, 30))
コード例 #8
0
ファイル: core.py プロジェクト: Julian/home-assistant
    def track_utc_time_change(self, action, year=None, month=None, day=None, hour=None, minute=None, second=None):
        """Deprecated method as of 8/4/2015 to track UTC time change."""
        # pylint: disable=too-many-arguments
        _LOGGER.warning(
            "hass.track_utc_time_change is deprecated. " "Please use homeassistant.helpers.event.track_utc_time_change"
        )
        import homeassistant.helpers.event as helper

        helper.track_utc_time_change(self, action, year, month, day, hour, minute, second)
コード例 #9
0
    def test_periodic_task_wrong_input(self):
        specific_runs = []

        track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), year='/two')

        self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(0, len(specific_runs))
コード例 #10
0
    def __init__(self, hass, config, see, tesla_devices):
        """Initialize the Tesla device scanner."""
        self.hass = hass
        self.see = see
        self.devices = tesla_devices
        self._update_info()

        track_utc_time_change(
            self.hass, self._update_info, second=range(0, 60, 30))
コード例 #11
0
ファイル: sun.py プロジェクト: zircop/home-assistant
    def __init__(self, hass, location):
        """Initialize the sun."""
        self.hass = hass
        self.location = location
        self._state = self.next_rising = self.next_setting = None
        self.next_dawn = self.next_dusk = None
        self.next_midnight = self.next_noon = None
        self.solar_elevation = self.solar_azimuth = 0

        track_utc_time_change(hass, self.timer_update, second=30)
コード例 #12
0
    def test_periodic_task_wrong_input(self):
        """Test periodic tasks with wrong input."""
        specific_runs = []

        track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), year='/two')

        self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(0, len(specific_runs))
コード例 #13
0
ファイル: alexa.py プロジェクト: eugenelai/custom_components
def setup_alexa(hass, config, add_devices_callback, login_obj):
    """Set up a alexa api based on host parameter."""
    alexa_clients = hass.data[ALEXA_DATA]
    # alexa_sessions = {}
    track_utc_time_change(hass, lambda now: update_devices(), second=30)

    url = config.get(CONF_URL)

    @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
    def update_devices():
        """Update the devices objects."""
        devices = AlexaAPI.get_devices(url, login_obj._session)
        bluetooth = AlexaAPI.get_bluetooth(url, login_obj._session).json()

        new_alexa_clients = []
        available_client_ids = []
        for device in devices:

            for b_state in bluetooth['bluetoothStates']:
                if device['serialNumber'] == b_state['deviceSerialNumber']:
                    device['bluetooth_state'] = b_state

            available_client_ids.append(device['serialNumber'])

            if device['serialNumber'] not in alexa_clients:
                new_client = AlexaClient(config, login_obj._session, device,
                                         update_devices, url)
                alexa_clients[device['serialNumber']] = new_client
                new_alexa_clients.append(new_client)
            else:
                alexa_clients[device['serialNumber']].refresh(device)

        if new_alexa_clients:
            def tts_handler(call):
                for alexa in service_to_entities(call):
                    if call.service == SERVICE_ALEXA_TTS:
                        message = call.data.get(ATTR_MESSAGE)
                        alexa.send_tts(message)

            def service_to_entities(call):
                """Return the known devices that a service call mentions."""
                entity_ids = extract_entity_ids(hass, call)
                if entity_ids:
                    entities = [entity for entity in new_alexa_clients
                                if entity.entity_id in entity_ids]
                else:
                    entities = None

                return entities

            hass.services.register(DOMAIN, SERVICE_ALEXA_TTS, tts_handler,
                                   schema=ALEXA_TTS_SCHEMA)
            add_devices_callback(new_alexa_clients)

    update_devices()
コード例 #14
0
 def __init__(self, hass, config: dict, see) -> None:
     """Initialize the Traccar device scanner."""
     self.hass = hass
     self._host = config.get(CONF_HOST)
     self._username = config.get(CONF_USERNAME)
     self._password = config.get(CONF_PASSWORD)
     self.see = see
     self._update_info()
     track_utc_time_change(self.hass,
                           self._update_info,
                           second=range(0, 60, 30))
コード例 #15
0
    def _start_polling(self):
        """ Start polling entities if necessary. """
        if self.is_polling or \
           not any(entity.should_poll for entity in self.entities.values()):
            return

        self.is_polling = True

        track_utc_time_change(self.hass,
                              self._update_entity_states,
                              second=range(0, 60, self.scan_interval))
コード例 #16
0
ファイル: test_event.py プロジェクト: MoshonkaKita/Golovastik
    def test_periodic_task_wrong_input(self):
        """Test periodic tasks with wrong input."""
        specific_runs = []

        with pytest.raises(ValueError):
            track_utc_time_change(
                self.hass, lambda x: specific_runs.append(1), hour='/two')

        self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
        self.hass.block_till_done()
        assert 0 == len(specific_runs)
コード例 #17
0
ファイル: core.py プロジェクト: yuetianle/home-assistant
 def track_utc_time_change(self, action,
                           year=None, month=None, day=None,
                           hour=None, minute=None, second=None):
     """Deprecated method as of 8/4/2015 to track UTC time change."""
     # pylint: disable=too-many-arguments
     _LOGGER.warning(
         'hass.track_utc_time_change is deprecated. '
         'Please use homeassistant.helpers.event.track_utc_time_change')
     import homeassistant.helpers.event as helper
     helper.track_utc_time_change(self, action, year, month, day, hour,
                                  minute, second)
コード例 #18
0
ファイル: test_event.py プロジェクト: tmcarr/home-assistant
    def test_periodic_task_wrong_input(self):
        """Test periodic tasks with wrong input."""
        specific_runs = []

        with pytest.raises(ValueError):
            track_utc_time_change(
                self.hass, lambda x: specific_runs.append(1), year='/two')

        self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(0, len(specific_runs))
コード例 #19
0
ファイル: feedreader.py プロジェクト: 1lann/home-assistant
 def __init__(self, url, hass):
     """Initialize the FeedManager object, poll every hour."""
     self._url = url
     self._feed = None
     self._hass = hass
     # Initialize last entry timestamp as epoch time
     self._last_entry_timestamp = datetime.utcfromtimestamp(0).timetuple()
     _LOGGER.debug('Loading feed %s', self._url)
     self._update()
     track_utc_time_change(hass, lambda now: self._update(),
                           minute=0, second=0)
コード例 #20
0
    def __init__(self, hass, config, see, vw):
        """Initialize the Volkswagen device scanner."""
        self.hass = hass
        self.see = see
        self.vw = vw
        self.vehicles = self.vw.vehicles
        self._update_location()

        track_utc_time_change(self.hass,
                              self._update_location,
                              second=range(0, 60, 30))
コード例 #21
0
    def _start_polling(self):
        """ Start polling entities if necessary. """
        if self.is_polling or \
           not any(entity.should_poll for entity in self.entities.values()):
            return

        self.is_polling = True

        track_utc_time_change(
            self.hass, self._update_entity_states,
            second=range(0, 60, self.scan_interval))
コード例 #22
0
    def __init__(self, hass, config, see):
        """Initialize the Life360 scanner."""
        self.hass = hass
        self.see = see

        self.username = config.get(CONF_USERNAME)
        self.password = config.get(CONF_PASSWORD)

        self._update_info()

        track_utc_time_change(
            self.hass, self._update_info, second=range(0, 60, 30))
コード例 #23
0
ファイル: feedreader.py プロジェクト: BrtBnn/home-assistant
 def __init__(self, url, hass):
     """Initialize the FeedManager object, poll every hour."""
     self._url = url
     self._feed = None
     self._hass = hass
     self._firstrun = True
     # Initialize last entry timestamp as epoch time
     self._last_entry_timestamp = datetime.utcfromtimestamp(0).timetuple()
     hass.bus.listen_once(EVENT_HOMEASSISTANT_START,
                          lambda _: self._update())
     track_utc_time_change(hass, lambda now: self._update(),
                           minute=0, second=0)
コード例 #24
0
ファイル: trackr.py プロジェクト: mysticbalance/homeassistant
    def __init__(self, hass, config: dict, see) -> None:
        """Initialize the TrackR device scanner."""
        from pytrackr.api import trackrApiInterface
        self.hass = hass
        self.api = trackrApiInterface(config.get(CONF_USERNAME),
                                      config.get(CONF_PASSWORD))
        self.see = see
        self.devices = self.api.get_trackrs()
        self._update_info()

        track_utc_time_change(self.hass, self._update_info,
                              second=range(0, 60, 30))
コード例 #25
0
 def __init__(self, url, distance, latitude, longitude, interval, hass):
     """Initialize the data object."""
     self._url = url
     self._maxdist = distance
     self._feed = None
     self._lastmsg_time = None
     self._restart = True
     self._hass = hass
     self._lat = latitude
     self._lon = longitude
     track_utc_time_change(hass, lambda now: self._update(),
                           second=range(1, 59, interval))
コード例 #26
0
 def __init__(self, url, hass, storage):
     """Initialize the FeedManager object, poll every hour."""
     self._url = url
     self._feed = None
     self._hass = hass
     self._firstrun = True
     self._storage = storage
     self._last_entry_timestamp = None
     self._has_published_parsed = False
     hass.bus.listen_once(
         EVENT_HOMEASSISTANT_START, lambda _: self._update())
     track_utc_time_change(
         hass, lambda now: self._update(), minute=0, second=0)
コード例 #27
0
ファイル: feedreader.py プロジェクト: xpo172/home-assistant
 def __init__(self, url, hass):
     """Initialize the FeedManager object, poll every hour."""
     self._url = url
     self._feed = None
     self._hass = hass
     self._firstrun = True
     # Initialize last entry timestamp as epoch time
     self._last_entry_timestamp = datetime.utcfromtimestamp(0).timetuple()
     hass.bus.listen_once(EVENT_HOMEASSISTANT_START,
                          lambda _: self._update())
     track_utc_time_change(hass,
                           lambda now: self._update(),
                           minute=0,
                           second=0)
コード例 #28
0
    def test_track_time_change(self):
        """Test tracking time change."""
        wildcard_runs = []
        specific_runs = []

        unsub = track_time_change(self.hass, lambda x: wildcard_runs.append(1))
        unsub_utc = track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), second=[0, 30])

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))
        self.assertEqual(1, len(wildcard_runs))

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 15))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))
        self.assertEqual(2, len(wildcard_runs))

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))
        self.assertEqual(3, len(wildcard_runs))

        unsub()
        unsub_utc()

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))
        self.assertEqual(3, len(wildcard_runs))
コード例 #29
0
    def test_periodic_task_clock_rollback(self):
        """Test periodic tasks with the time rolling backwards."""
        specific_runs = []

        unsub = track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), hour='/2', minute=0,
            second=0)

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.block_till_done()
        assert 2 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 24, 0, 0, 0))
        self.hass.block_till_done()
        assert 3 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.block_till_done()
        assert 4 == len(specific_runs)

        unsub()

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.block_till_done()
        assert 4 == len(specific_runs)
コード例 #30
0
ファイル: test_event.py プロジェクト: smilepc/Home-assistant
    def test_periodic_task_year(self):
        """Test periodic tasks per year."""
        specific_runs = []

        unsub = track_utc_time_change(self.hass,
                                      lambda x: specific_runs.append(1),
                                      year='/2')

        self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2015, 5, 2, 0, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2016, 5, 2, 0, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(2, len(specific_runs))

        unsub()

        self._send_time_changed(datetime(2016, 5, 2, 0, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(2, len(specific_runs))
コード例 #31
0
ファイル: cover.py プロジェクト: KapJI/home-assistant
 def _start_watcher(self, command):
     """Start watcher."""
     _LOGGER.debug("Starting Watcher for command: %s ", command)
     if self._unsub_listener_cover is None:
         self._unsub_listener_cover = track_utc_time_change(
             self.hass, self._check_state
         )
コード例 #32
0
    def test_periodic_task_clock_rollback(self):
        """Test periodic tasks with the time rolling backwards."""
        specific_runs = []

        unsub = track_utc_time_change(self.hass,
                                      lambda x: specific_runs.append(1),
                                      hour='/2',
                                      minute=0,
                                      second=0)

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(3, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(4, len(specific_runs))

        unsub()

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(4, len(specific_runs))
コード例 #33
0
ファイル: flux.py プロジェクト: 12-hak/hak-assistant
 def turn_on(self, **kwargs):
     """Turn on flux."""
     self._state = True
     self.tracker = track_utc_time_change(self.hass,
                                          self.flux_update,
                                          second=[0, 30])
     self.update_ha_state()
コード例 #34
0
ファイル: test_event.py プロジェクト: MoshonkaKita/Golovastik
    def test_periodic_task_hour(self):
        """Test periodic tasks per hour."""
        specific_runs = []

        unsub = track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), hour='/2',
            minute=0, second=0)

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 25, 0, 0, 0))
        self.hass.block_till_done()
        assert 2 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 25, 1, 0, 0))
        self.hass.block_till_done()
        assert 2 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.block_till_done()
        assert 3 == len(specific_runs)

        unsub()

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.block_till_done()
        assert 3 == len(specific_runs)
コード例 #35
0
    def test_periodic_task_hour(self):
        """Test periodic tasks per hour."""
        specific_runs = []

        unsub = track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), hour='/2')

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 23, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 25, 1, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(3, len(specific_runs))

        unsub()

        self._send_time_changed(datetime(2014, 5, 25, 2, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(3, len(specific_runs))
コード例 #36
0
    def test_periodic_task_day(self):
        """Test periodic tasks per day."""
        specific_runs = []

        unsub = track_utc_time_change(self.hass,
                                      lambda x: specific_runs.append(1),
                                      day='/2')

        self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 3, 12, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 4, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))

        unsub()

        self._send_time_changed(datetime(2014, 5, 4, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))
コード例 #37
0
    def test_periodic_task_minute(self):
        """Test periodic tasks per minute."""
        specific_runs = []

        unsub = track_utc_time_change(self.hass,
                                      lambda x: specific_runs.append(1),
                                      minute='/5')

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 12, 3, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))

        unsub()

        self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))
コード例 #38
0
    def test_periodic_task_minute(self):
        """Test periodic tasks per minute."""
        specific_runs = []

        unsub = track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), minute='/5',
            second=0)

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 24, 12, 3, 0))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0))
        self.hass.block_till_done()
        assert 2 == len(specific_runs)

        unsub()

        self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0))
        self.hass.block_till_done()
        assert 2 == len(specific_runs)
コード例 #39
0
ファイル: test_event.py プロジェクト: tmcarr/home-assistant
    def test_track_time_change(self):
        """Test tracking time change."""
        wildcard_runs = []
        specific_runs = []

        unsub = track_time_change(self.hass, lambda x: wildcard_runs.append(1))
        unsub_utc = track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), second=[0, 30])

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))
        self.assertEqual(1, len(wildcard_runs))

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 15))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))
        self.assertEqual(2, len(wildcard_runs))

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))
        self.assertEqual(3, len(wildcard_runs))

        unsub()
        unsub_utc()

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 30))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))
        self.assertEqual(3, len(wildcard_runs))
コード例 #40
0
ファイル: flux.py プロジェクト: shootersanks/home-assistant-1
 def turn_on(self, **kwargs):
     """Turn on flux."""
     self._state = True
     self.unsub_tracker = track_utc_time_change(self.hass,
                                                self.flux_update,
                                                second=[0, 30])
     self.update_ha_state()
コード例 #41
0
    def __init__(self, hass, device_scanner, seconds, track_new_devices):
        self.hass = hass

        self.device_scanner = device_scanner

        self.lock = threading.Lock()

        # Do we track new devices by default?
        self.track_new_devices = track_new_devices

        # Dictionary to keep track of known devices and devices we track
        self.tracked = {}
        self.untracked_devices = set()

        # Did we encounter an invalid known devices file
        self.invalid_known_devices_file = False

        # Wrap it in a func instead of lambda so it can be identified in
        # the bus by its __name__ attribute.
        def update_device_state(now):
            """ Triggers update of the device states. """
            self.update_devices(now)

        dev_group = group.Group(
            hass, GROUP_NAME_ALL_DEVICES, user_defined=False)

        def reload_known_devices_service(service):
            """ Reload known devices file. """
            self._read_known_devices_file()

            self.update_devices(dt_util.utcnow())

            dev_group.update_tracked_entity_ids(self.device_entity_ids)

        reload_known_devices_service(None)

        if self.invalid_known_devices_file:
            return

        seconds = range(0, 60, seconds)

        _LOGGER.info("Device tracker interval second=%s", seconds)
        track_utc_time_change(hass, update_device_state, second=seconds)

        hass.services.register(DOMAIN,
                               SERVICE_DEVICE_TRACKER_RELOAD,
                               reload_known_devices_service)
コード例 #42
0
ファイル: __init__.py プロジェクト: pedrolamas/home-assistant
def setup_account(account_config: dict, hass,
                  name: str) -> "BMWConnectedDriveAccount":
    """Set up a new BMWConnectedDriveAccount based on the config."""
    username = account_config[CONF_USERNAME]
    password = account_config[CONF_PASSWORD]
    region = account_config[CONF_REGION]
    read_only = account_config[CONF_READ_ONLY]

    _LOGGER.debug("Adding new account %s", name)
    cd_account = BMWConnectedDriveAccount(username, password, region, name,
                                          read_only)

    def execute_service(call):
        """Execute a service for a vehicle.

        This must be a member function as we need access to the cd_account
        object here.
        """
        vin = call.data[ATTR_VIN]
        vehicle = cd_account.account.get_vehicle(vin)
        if not vehicle:
            _LOGGER.error("Could not find a vehicle for VIN %s", vin)
            return
        function_name = _SERVICE_MAP[call.service]
        function_call = getattr(vehicle.remote_services, function_name)
        function_call()

    if not read_only:
        # register the remote services
        for service in _SERVICE_MAP:
            hass.services.register(DOMAIN,
                                   service,
                                   execute_service,
                                   schema=SERVICE_SCHEMA)

    # update every UPDATE_INTERVAL minutes, starting now
    # this should even out the load on the servers
    now = datetime.datetime.now()
    track_utc_time_change(
        hass,
        cd_account.update,
        minute=range(now.minute % UPDATE_INTERVAL, 60, UPDATE_INTERVAL),
        second=now.second,
    )

    return cd_account
コード例 #43
0
    def add_entities(self, new_entities):
        """Add entities for a single platform."""
        with self.component.lock:
            for entity in new_entities:
                if self.component.add_entity(entity, self):
                    self.platform_entities.append(entity)

            self.component.update_group()

            if self.is_polling or not any(entity.should_poll for entity in self.platform_entities):
                return

            self.is_polling = True

            track_utc_time_change(
                self.component.hass, self._update_entity_states, second=range(0, 60, self.scan_interval)
            )
コード例 #44
0
    def test_periodic_task_day(self):
        specific_runs = []

        track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), day='/2')

        self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 3, 12, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 4, 0, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(2, len(specific_runs))
コード例 #45
0
ファイル: test_event.py プロジェクト: 1lann/home-assistant
    def test_periodic_task_minute(self):
        """Test periodic tasks per minute."""
        specific_runs = []

        track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), minute='/5')

        self._send_time_changed(datetime(2014, 5, 24, 12, 0, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 12, 3, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2014, 5, 24, 12, 5, 0))
        self.hass.pool.block_till_done()
        self.assertEqual(2, len(specific_runs))
コード例 #46
0
def setup_account(account_config: dict, hass, name: str) -> "KiaUvoAccount":
    """Set up a new KiaUvoAccount based on the config."""
    username = account_config[CONF_USERNAME]
    password = account_config[CONF_PASSWORD]

    _LOGGER.debug("Adding new account %s", name)
    cd_account = KiaUvoAccount(username, password, name)

    # update every UPDATE_INTERVAL minutes, starting now
    # this should even out the load on the servers
    now = datetime.datetime.now()
    track_utc_time_change(
        hass,
        cd_account.update,
        minute=range(now.minute % UPDATE_INTERVAL, 60, UPDATE_INTERVAL),
        second=now.second,
    )

    return cd_account
コード例 #47
0
    def add_entities(self, new_entities):
        """Add entities for a single platform."""
        with self.component.lock:
            for entity in new_entities:
                if self.component.add_entity(entity):
                    self.platform_entities.append(entity)

            self.component.update_group()

            if self.is_polling or \
               not any(entity.should_poll for entity
                       in self.platform_entities):
                return

            self.is_polling = True

            track_utc_time_change(self.component.hass,
                                  self._update_entity_states,
                                  second=range(0, 60, self.scan_interval))
コード例 #48
0
ファイル: __init__.py プロジェクト: tmcarr/home-assistant
def setup_account(account_config: dict, hass, name: str) \
        -> 'BMWConnectedDriveAccount':
    """Set up a new BMWConnectedDriveAccount based on the config."""
    username = account_config[CONF_USERNAME]
    password = account_config[CONF_PASSWORD]
    region = account_config[CONF_REGION]
    read_only = account_config[CONF_READ_ONLY]
    _LOGGER.debug('Adding new account %s', name)
    cd_account = BMWConnectedDriveAccount(username, password, region, name,
                                          read_only)

    def execute_service(call):
        """Execute a service for a vehicle.

        This must be a member function as we need access to the cd_account
        object here.
        """
        vin = call.data[ATTR_VIN]
        vehicle = cd_account.account.get_vehicle(vin)
        if not vehicle:
            _LOGGER.error('Could not find a vehicle for VIN "%s"!', vin)
            return
        function_name = _SERVICE_MAP[call.service]
        function_call = getattr(vehicle.remote_services, function_name)
        function_call()
    if not read_only:
        # register the remote services
        for service in _SERVICE_MAP:
            hass.services.register(
                DOMAIN, service,
                execute_service,
                schema=SERVICE_SCHEMA)

    # update every UPDATE_INTERVAL minutes, starting now
    # this should even out the load on the servers
    now = datetime.datetime.now()
    track_utc_time_change(
        hass, cd_account.update,
        minute=range(now.minute % UPDATE_INTERVAL, 60, UPDATE_INTERVAL),
        second=now.second)

    return cd_account
コード例 #49
0
ファイル: __init__.py プロジェクト: cellerich/home-assistant
def setup_scanner_platform(hass, config, scanner, see_device):
    """Helper method to connect scanner-based platform to device tracker."""
    interval = util.convert(config.get(CONF_SCAN_INTERVAL), int, DEFAULT_SCAN_INTERVAL)

    # Initial scan of each mac we also tell about host name for config
    seen = set()

    def device_tracker_scan(now):
        """Called when interval matches."""
        for mac in scanner.scan_devices():
            if mac in seen:
                host_name = None
            else:
                host_name = scanner.get_device_name(mac)
                seen.add(mac)
            see_device(mac=mac, host_name=host_name)

    track_utc_time_change(hass, device_tracker_scan, second=range(0, 60, interval))

    device_tracker_scan(None)
コード例 #50
0
    def __init__(self, hass, config: dict, see) -> None:
        """Initialize the automatic device scanner."""
        self.hass = hass
        self._devices = config.get(CONF_DEVICES, None)
        self._access_token_payload = {
            "username": config.get(CONF_USERNAME),
            "password": config.get(CONF_PASSWORD),
            "client_id": config.get(CONF_CLIENT_ID),
            "client_secret": config.get(CONF_SECRET),
            "grant_type": "password",
            "scope": SCOPE,
        }
        self._headers = None
        self._token_expires = dt_util.now()
        self.last_results = {}
        self.last_trips = {}
        self.see = see

        self._update_info()

        track_utc_time_change(self.hass, self._update_info, second=range(0, 60, 30))
コード例 #51
0
ファイル: __init__.py プロジェクト: duwke/home-assistant
def setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
                           scanner: Any, see_device: Callable):
    """Helper method to connect scanner-based platform to device tracker."""
    interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)

    # Initial scan of each mac we also tell about host name for config
    seen = set()  # type: Any

    def device_tracker_scan(now: dt_util.dt.datetime):
        """Called when interval matches."""
        for mac in scanner.scan_devices():
            if mac in seen:
                host_name = None
            else:
                host_name = scanner.get_device_name(mac)
                seen.add(mac)
            see_device(mac=mac, host_name=host_name)

    track_utc_time_change(hass, device_tracker_scan, second=range(0, 60,
                                                                  interval))

    device_tracker_scan(None)
コード例 #52
0
ファイル: __init__.py プロジェクト: sandro1005/home-assistant
def setup_scanner_platform(hass, config, scanner, see_device):
    """ Helper method to connect scanner-based platform to device tracker. """
    interval = util.convert(config.get(CONF_SCAN_INTERVAL), int,
                            DEFAULT_SCAN_INTERVAL)

    # Initial scan of each mac we also tell about host name for config
    seen = set()

    def device_tracker_scan(now):
        """ Called when interval matches. """
        for mac in scanner.scan_devices():
            if mac in seen:
                host_name = None
            else:
                host_name = scanner.get_device_name(mac)
                seen.add(mac)
            see_device(mac=mac, host_name=host_name)

    track_utc_time_change(hass, device_tracker_scan, second=range(0, 60,
                                                                  interval))

    device_tracker_scan(None)
コード例 #53
0
def setup_scanner_platform(hass: HomeAssistantType, config: ConfigType,
                           scanner: Any, see_device: Callable):
    """Helper method to connect scanner-based platform to device tracker."""
    interval = config.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)

    # Initial scan of each mac we also tell about host name for config
    seen = set()  # type: Any

    def device_tracker_scan(now: dt_util.dt.datetime):
        """Called when interval matches."""
        for mac in scanner.scan_devices():
            if mac in seen:
                host_name = None
            else:
                host_name = scanner.get_device_name(mac)
                seen.add(mac)
            see_device(mac=mac, host_name=host_name)

    track_utc_time_change(hass, device_tracker_scan, second=range(0, 60,
                                                                  interval))

    device_tracker_scan(None)
コード例 #54
0
    def add_entities(self, new_entities):
        """
        Takes in a list of new entities. For each entity will see if it already
        exists. If not, will add it, set it up and push the first state.
        """
        with self.lock:
            for entity in new_entities:
                if entity is None or entity in self.entities.values():
                    continue

                entity.hass = self.hass

                if getattr(entity, 'entity_id', None) is None:
                    entity.entity_id = generate_entity_id(
                        self.entity_id_format, entity.name,
                        self.entities.keys())

                self.entities[entity.entity_id] = entity

                entity.update_ha_state()

            if self.group is None and self.group_name is not None:
                self.group = group.Group(self.hass, self.group_name,
                                         user_defined=False)

            if self.group is not None:
                self.group.update_tracked_entity_ids(self.entities.keys())

            if self.is_polling or \
               not any(entity.should_poll for entity
                       in self.entities.values()):
                return

            self.is_polling = True

            track_utc_time_change(
                self.hass, self._update_entity_states,
                second=range(0, 60, self.scan_interval))
コード例 #55
0
ファイル: tile.py プロジェクト: JiShangShiDai/home-assistant
    def __init__(self, hass, config, see):
        """Initialize."""
        from pytile import Client

        _LOGGER.debug('Received configuration data: %s', config)

        # Load the client UUID (if it exists):
        config_data = load_json(hass.config.path(CLIENT_UUID_CONFIG_FILE))
        if config_data:
            _LOGGER.debug('Using existing client UUID')
            self._client = Client(
                config[CONF_USERNAME],
                config[CONF_PASSWORD],
                config_data['client_uuid'])
        else:
            _LOGGER.debug('Generating new client UUID')
            self._client = Client(
                config[CONF_USERNAME],
                config[CONF_PASSWORD])

            if not save_json(
                    hass.config.path(CLIENT_UUID_CONFIG_FILE),
                    {'client_uuid': self._client.client_uuid}):
                _LOGGER.error("Failed to save configuration file")

        _LOGGER.debug('Client UUID: %s', self._client.client_uuid)
        _LOGGER.debug('User UUID: %s', self._client.user_uuid)

        self._types = config.get(CONF_MONITORED_VARIABLES)

        self.devices = {}
        self.see = see

        track_utc_time_change(
            hass, self._update_info, second=range(0, 60, 30))

        self._update_info()
コード例 #56
0
    def test_periodic_task_duplicate_time(self):
        """Test periodic tasks not triggering on duplicate time."""
        specific_runs = []

        unsub = track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), hour='/2', minute=0,
            second=0)

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 24, 22, 0, 0))
        self.hass.block_till_done()
        assert 1 == len(specific_runs)

        self._send_time_changed(datetime(2014, 5, 25, 0, 0, 0))
        self.hass.block_till_done()
        assert 2 == len(specific_runs)

        unsub()
コード例 #57
0
ファイル: test_event.py プロジェクト: tmcarr/home-assistant
    def test_periodic_task_year(self):
        """Test periodic tasks per year."""
        specific_runs = []

        unsub = track_utc_time_change(
            self.hass, lambda x: specific_runs.append(1), year='/2')

        self._send_time_changed(datetime(2014, 5, 2, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2015, 5, 2, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(1, len(specific_runs))

        self._send_time_changed(datetime(2016, 5, 2, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))

        unsub()

        self._send_time_changed(datetime(2016, 5, 2, 0, 0, 0))
        self.hass.block_till_done()
        self.assertEqual(2, len(specific_runs))