Пример #1
0
    def send_message(self, message="", **kwargs):
        """Send a message to a file."""
        with open(self.filepath, 'a') as file:
            if os.stat(self.filepath).st_size == 0:
                title = '{} notifications (Log started: {})\n{}\n'.format(
                    kwargs.get(ATTR_TITLE),
                    dt_util.utcnow().isoformat(), '-' * 80)
                file.write(title)

            if self.add_timestamp == 1:
                text = '{} {}\n'.format(dt_util.utcnow().isoformat(), message)
                file.write(text)
            else:
                text = '{}\n'.format(message)
                file.write(text)
Пример #2
0
    def run(self):
        """Start processing events to save."""
        self._setup_connection()
        self._setup_run()
        if self.purge_days is not None:
            track_point_in_utc_time(self.hass,
                                    lambda now: self._purge_old_data(),
                                    dt_util.utcnow() + timedelta(minutes=5))

        while True:
            event = self.queue.get()

            if event == self.quit_object:
                self._close_run()
                self._close_connection()
                self.queue.task_done()
                return

            elif event.event_type == EVENT_TIME_CHANGED:
                self.queue.task_done()
                continue

            event_id = self.record_event(event)

            if event.event_type == EVENT_STATE_CHANGED:
                self.record_state(event.data['entity_id'],
                                  event.data.get('new_state'), event_id)

            self.queue.task_done()
Пример #3
0
    def update(self):
        """Get the latest data from opendata.ch."""
        response = requests.get(
            _RESOURCE +
            'connections?' +
            'from=' + self.start + '&' +
            'to=' + self.destination + '&' +
            'fields[]=connections/from/departureTimestamp/&' +
            'fields[]=connections/',
            timeout=30)
        connections = response.json()['connections'][:2]

        try:
            self.times = [
                dt_util.as_local(
                    dt_util.utc_from_timestamp(
                        item['from']['departureTimestamp'])).strftime(
                            TIME_STR_FORMAT)
                for item in connections
            ]
            self.times.append(
                dt_util.as_local(
                    dt_util.utc_from_timestamp(
                        connections[0]['from']['departureTimestamp'])) -
                dt_util.as_local(dt_util.utcnow()))
        except KeyError:
            self.times = ['n/a']
Пример #4
0
    def record_state(self, entity_id, state, event_id):
        """Save a state to the database."""
        now = dt_util.utcnow()

        # State got deleted
        if state is None:
            state_state = ''
            state_domain = ''
            state_attr = '{}'
            last_changed = last_updated = now
        else:
            state_domain = state.domain
            state_state = state.state
            state_attr = json.dumps(dict(state.attributes))
            last_changed = state.last_changed
            last_updated = state.last_updated

        info = (entity_id, state_domain, state_state, state_attr, last_changed,
                last_updated, now, self.utc_offset, event_id)

        self.query(
            """
            INSERT INTO states (
            entity_id, domain, state, attributes, last_changed, last_updated,
            created, utc_offset, event_id)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            """, info)
Пример #5
0
    def run(self):
        """Start processing events to save."""
        self._setup_connection()
        self._setup_run()
        if self.purge_days is not None:
            track_point_in_utc_time(self.hass,
                                    lambda now: self._purge_old_data(),
                                    dt_util.utcnow() + timedelta(minutes=5))

        while True:
            event = self.queue.get()

            if event == self.quit_object:
                self._close_run()
                self._close_connection()
                self.queue.task_done()
                return

            elif event.event_type == EVENT_TIME_CHANGED:
                self.queue.task_done()
                continue

            event_id = self.record_event(event)

            if event.event_type == EVENT_STATE_CHANGED:
                self.record_state(
                    event.data['entity_id'], event.data.get('new_state'),
                    event_id)

            self.queue.task_done()
Пример #6
0
    def test_if_not_fires_on_entity_change_with_for(self):
        """Test for not firing on entity change with for."""
        assert _setup_component(
            self.hass, automation.DOMAIN, {
                automation.DOMAIN: {
                    'trigger': {
                        'platform': 'state',
                        'entity_id': 'test.entity',
                        'to': 'world',
                        'for': {
                            'seconds': 5
                        },
                    },
                    'action': {
                        'service': 'test.automation'
                    }
                }
            })

        self.hass.states.set('test.entity', 'world')
        self.hass.pool.block_till_done()
        self.hass.states.set('test.entity', 'not_world')
        self.hass.pool.block_till_done()
        fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10))
        self.hass.pool.block_till_done()
        self.assertEqual(0, len(self.calls))
Пример #7
0
    def send_message(self, message="", **kwargs):
        """Send a message to a file."""
        with open(self.filepath, 'a') as file:
            if os.stat(self.filepath).st_size == 0:
                title = '{} notifications (Log started: {})\n{}\n'.format(
                    kwargs.get(ATTR_TITLE),
                    dt_util.utcnow().isoformat(),
                    '-' * 80)
                file.write(title)

            if self.add_timestamp == 1:
                text = '{} {}\n'.format(dt_util.utcnow().isoformat(), message)
                file.write(text)
            else:
                text = '{}\n'.format(message)
                file.write(text)
Пример #8
0
    def update(self):
        """Get the latest data and updates the states."""
        time_date = dt_util.utcnow()
        time = dt_util.as_local(time_date).strftime(TIME_STR_FORMAT)
        time_utc = time_date.strftime(TIME_STR_FORMAT)
        date = dt_util.as_local(time_date).date().isoformat()

        # Calculate Swatch Internet Time.
        time_bmt = time_date + timedelta(hours=1)
        delta = timedelta(hours=time_bmt.hour,
                          minutes=time_bmt.minute,
                          seconds=time_bmt.second,
                          microseconds=time_bmt.microsecond)
        beat = int((delta.seconds + delta.microseconds / 1000000.0) / 86.4)

        if self.type == 'time':
            self._state = time
        elif self.type == 'date':
            self._state = date
        elif self.type == 'date_time':
            self._state = date + ', ' + time
        elif self.type == 'time_date':
            self._state = time + ', ' + date
        elif self.type == 'time_utc':
            self._state = time_utc
        elif self.type == 'beat':
            self._state = '@{0:03d}'.format(beat)
Пример #9
0
    def _purge_old_data(self):
        """Purge events and states older than purge_days ago."""
        if not self.purge_days or self.purge_days < 1:
            _LOGGER.debug("purge_days set to %s, will not purge any old data.",
                          self.purge_days)
            return

        purge_before = dt_util.utcnow() - timedelta(days=self.purge_days)

        _LOGGER.info("Purging events created before %s", purge_before)
        deleted_rows = self.query(
            sql_query="DELETE FROM events WHERE created < ?;",
            data=(int(purge_before.timestamp()), ),
            return_value=RETURN_ROWCOUNT)
        _LOGGER.debug("Deleted %s events", deleted_rows)

        _LOGGER.info("Purging states created before %s", purge_before)
        deleted_rows = self.query(
            sql_query="DELETE FROM states WHERE created < ?;",
            data=(int(purge_before.timestamp()), ),
            return_value=RETURN_ROWCOUNT)
        _LOGGER.debug("Deleted %s states", deleted_rows)

        # Execute sqlite vacuum command to free up space on disk
        self.query("VACUUM;")
Пример #10
0
    def test_notify_file(self, mock_utcnow):
        """Test the notify file output."""
        mock_utcnow.return_value = dt_util.as_utc(dt_util.now())

        with tempfile.TemporaryDirectory() as tempdirname:
            filename = os.path.join(tempdirname, 'notify.txt')
            message = 'one, two, testing, testing'
            self.assertTrue(
                notify.setup(
                    self.hass, {
                        'notify': {
                            'name': 'test',
                            'platform': 'file',
                            'filename': filename,
                            'timestamp': 0
                        }
                    }))
            title = '{} notifications (Log started: {})\n{}\n'.format(
                ATTR_TITLE_DEFAULT,
                dt_util.utcnow().isoformat(), '-' * 80)

            self.hass.services.call('notify',
                                    'test', {'message': message},
                                    blocking=True)

            result = open(filename).read()
            self.assertEqual(result, "{}{}\n".format(title, message))
Пример #11
0
    def test_humanify_filter_sensor(self):
        """Test humanify filter too frequent sensor values."""
        entity_id = 'sensor.bla'

        pointA = dt_util.utcnow().replace(minute=2)
        pointB = pointA.replace(minute=5)
        pointC = pointA + timedelta(minutes=logbook.GROUP_BY_MINUTES)

        eventA = self.create_state_changed_event(pointA, entity_id, 10)
        eventB = self.create_state_changed_event(pointB, entity_id, 20)
        eventC = self.create_state_changed_event(pointC, entity_id, 30)

        entries = list(logbook.humanify((eventA, eventB, eventC)))

        self.assertEqual(2, len(entries))
        self.assert_entry(entries[0],
                          pointB,
                          'bla',
                          domain='sensor',
                          entity_id=entity_id)

        self.assert_entry(entries[1],
                          pointC,
                          'bla',
                          domain='sensor',
                          entity_id=entity_id)
Пример #12
0
    def test_cancel_while_delay(self):
        """Test the cancelling while the delay is present."""
        event = 'test_event'
        events = []

        def record_event(event):
            """Add recorded event to set."""
            events.append(event)

        self.hass.bus.listen(event, record_event)

        script_obj = script.Script(self.hass, [
            {'delay': {'seconds': 5}},
            {'event': event}])

        script_obj.run()

        self.hass.pool.block_till_done()

        assert script_obj.is_running
        assert len(events) == 0

        script_obj.stop()

        assert not script_obj.is_running

        # Make sure the script is really stopped.
        future = dt_util.utcnow() + timedelta(seconds=5)
        fire_time_changed(self.hass, future)
        self.hass.pool.block_till_done()

        assert not script_obj.is_running
        assert len(events) == 0
Пример #13
0
    def update(self):
        """Get the latest data and updates the states."""
        time_date = dt_util.utcnow()
        time = dt_util.as_local(time_date).strftime(TIME_STR_FORMAT)
        time_utc = time_date.strftime(TIME_STR_FORMAT)
        date = dt_util.as_local(time_date).date().isoformat()

        # Calculate Swatch Internet Time.
        time_bmt = time_date + timedelta(hours=1)
        delta = timedelta(hours=time_bmt.hour,
                          minutes=time_bmt.minute,
                          seconds=time_bmt.second,
                          microseconds=time_bmt.microsecond)
        beat = int((delta.seconds + delta.microseconds / 1000000.0) / 86.4)

        if self.type == 'time':
            self._state = time
        elif self.type == 'date':
            self._state = date
        elif self.type == 'date_time':
            self._state = date + ', ' + time
        elif self.type == 'time_date':
            self._state = time + ', ' + date
        elif self.type == 'time_utc':
            self._state = time_utc
        elif self.type == 'beat':
            self._state = '@{0:03d}'.format(beat)
Пример #14
0
    def state(self):
        """Return the state of the device."""
        if self._state in (STATE_ALARM_ARMED_HOME,
                           STATE_ALARM_ARMED_AWAY) and \
           self._pending_time and self._state_ts + self._pending_time > \
           dt_util.utcnow():
            return STATE_ALARM_PENDING

        if self._state == STATE_ALARM_TRIGGERED and self._trigger_time:
            if self._state_ts + self._pending_time > dt_util.utcnow():
                return STATE_ALARM_PENDING
            elif (self._state_ts + self._pending_time +
                  self._trigger_time) < dt_util.utcnow():
                return STATE_ALARM_DISARMED

        return self._state
Пример #15
0
 def __init__(self, event_type, data=None, origin=EventOrigin.local,
              time_fired=None):
     """Initialize a new event."""
     self.event_type = event_type
     self.data = data or {}
     self.origin = origin
     self.time_fired = time_fired or dt_util.utcnow()
Пример #16
0
    def test_disarm_during_trigger_with_invalid_code(self):
        """Test disarming while code is invalid."""
        self.assertTrue(alarm_control_panel.setup(self.hass, {
            'alarm_control_panel': {
                'platform': 'virtual',
                'name': 'test',
                'pending_time': 5,
                'code': CODE + '2'
            }}))

        entity_id = 'alarm_control_panel.test'

        self.assertEqual(STATE_ALARM_DISARMED,
                         self.hass.states.get(entity_id).state)

        alarm_control_panel.alarm_trigger(self.hass)
        self.hass.pool.block_till_done()

        self.assertEqual(STATE_ALARM_PENDING,
                         self.hass.states.get(entity_id).state)

        alarm_control_panel.alarm_disarm(self.hass, entity_id=entity_id)
        self.hass.pool.block_till_done()

        self.assertEqual(STATE_ALARM_PENDING,
                         self.hass.states.get(entity_id).state)

        future = dt_util.utcnow() + timedelta(seconds=5)
        with patch(('blumate.components.alarm_control_panel.virtual.'
                    'dt_util.utcnow'), return_value=future):
            fire_time_changed(self.hass, future)
            self.hass.pool.block_till_done()

        self.assertEqual(STATE_ALARM_TRIGGERED,
                         self.hass.states.get(entity_id).state)
Пример #17
0
    def test_if_not_fires_using_wrong_after(self):
        """YAML translates time values to total seconds.

        This should break the before rule.
        """
        assert not _setup_component(
            self.hass,
            automation.DOMAIN,
            {
                automation.DOMAIN: {
                    'trigger': {
                        'platform': 'time',
                        'after': 3605,
                        # Total seconds. Hour = 3600 second
                    },
                    'action': {
                        'service': 'test.automation'
                    }
                }
            })

        fire_time_changed(self.hass,
                          dt_util.utcnow().replace(hour=1, minute=0, second=5))

        self.hass.pool.block_till_done()
        self.assertEqual(0, len(self.calls))
Пример #18
0
    def test_arm_home_with_pending(self):
        """Test arm home method."""
        self.assertTrue(alarm_control_panel.setup(self.hass, {
            'alarm_control_panel': {
                'platform': 'virtual',
                'name': 'test',
                'code': CODE,
                'pending_time': 1
            }}))

        entity_id = 'alarm_control_panel.test'

        self.assertEqual(STATE_ALARM_DISARMED,
                         self.hass.states.get(entity_id).state)

        alarm_control_panel.alarm_arm_home(self.hass, CODE, entity_id)
        self.hass.pool.block_till_done()

        self.assertEqual(STATE_ALARM_PENDING,
                         self.hass.states.get(entity_id).state)

        future = dt_util.utcnow() + timedelta(seconds=1)
        with patch(('blumate.components.alarm_control_panel.virtual.'
                    'dt_util.utcnow'), return_value=future):
            fire_time_changed(self.hass, future)
            self.hass.pool.block_till_done()

        self.assertEqual(STATE_ALARM_ARMED_HOME,
                         self.hass.states.get(entity_id).state)
Пример #19
0
    def test_notify_file(self, mock_utcnow):
        """Test the notify file output."""
        mock_utcnow.return_value = dt_util.as_utc(dt_util.now())

        with tempfile.TemporaryDirectory() as tempdirname:
            filename = os.path.join(tempdirname, 'notify.txt')
            message = 'one, two, testing, testing'
            self.assertTrue(notify.setup(self.hass, {
                'notify': {
                    'name': 'test',
                    'platform': 'file',
                    'filename': filename,
                    'timestamp': 0
                }
            }))
            title = '{} notifications (Log started: {})\n{}\n'.format(
                ATTR_TITLE_DEFAULT,
                dt_util.utcnow().isoformat(),
                '-' * 80)

            self.hass.services.call('notify', 'test', {'message': message},
                                    blocking=True)

            result = open(filename).read()
            self.assertEqual(result, "{}{}\n".format(title, message))
Пример #20
0
    def test_arm_home_with_pending(self):
        """Test arm home method."""
        self.assertTrue(
            alarm_control_panel.setup(
                self.hass, {
                    'alarm_control_panel': {
                        'platform': 'virtual',
                        'name': 'test',
                        'code': CODE,
                        'pending_time': 1
                    }
                }))

        entity_id = 'alarm_control_panel.test'

        self.assertEqual(STATE_ALARM_DISARMED,
                         self.hass.states.get(entity_id).state)

        alarm_control_panel.alarm_arm_home(self.hass, CODE, entity_id)
        self.hass.pool.block_till_done()

        self.assertEqual(STATE_ALARM_PENDING,
                         self.hass.states.get(entity_id).state)

        future = dt_util.utcnow() + timedelta(seconds=1)
        with patch(('blumate.components.alarm_control_panel.virtual.'
                    'dt_util.utcnow'),
                   return_value=future):
            fire_time_changed(self.hass, future)
            self.hass.pool.block_till_done()

        self.assertEqual(STATE_ALARM_ARMED_HOME,
                         self.hass.states.get(entity_id).state)
Пример #21
0
    def _purge_old_data(self):
        """Purge events and states older than purge_days ago."""
        if not self.purge_days or self.purge_days < 1:
            _LOGGER.debug("purge_days set to %s, will not purge any old data.",
                          self.purge_days)
            return

        purge_before = dt_util.utcnow() - timedelta(days=self.purge_days)

        _LOGGER.info("Purging events created before %s", purge_before)
        deleted_rows = self.query(
            sql_query="DELETE FROM events WHERE created < ?;",
            data=(int(purge_before.timestamp()),),
            return_value=RETURN_ROWCOUNT)
        _LOGGER.debug("Deleted %s events", deleted_rows)

        _LOGGER.info("Purging states created before %s", purge_before)
        deleted_rows = self.query(
            sql_query="DELETE FROM states WHERE created < ?;",
            data=(int(purge_before.timestamp()),),
            return_value=RETURN_ROWCOUNT)
        _LOGGER.debug("Deleted %s states", deleted_rows)

        # Execute sqlite vacuum command to free up space on disk
        self.query("VACUUM;")
Пример #22
0
    def test_if_fires_on_for_condition(self):
        """Test for firing if contition is on."""
        point1 = dt_util.utcnow()
        point2 = point1 + timedelta(seconds=10)
        with patch('blumate.core.dt_util.utcnow') as mock_utcnow:
            mock_utcnow.return_value = point1
            self.hass.states.set('test.entity', 'on')
            assert _setup_component(self.hass, automation.DOMAIN, {
                automation.DOMAIN: {
                    'trigger': {
                        'platform': 'event',
                        'event_type': 'test_event',
                    },
                    'condition': {
                        'platform': 'state',
                        'entity_id': 'test.entity',
                        'state': 'on',
                        'for': {
                            'seconds': 5
                        },
                    },
                    'action': {'service': 'test.automation'},
                }
            })

            # not enough time has passed
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()
            self.assertEqual(0, len(self.calls))

            # Time travel 10 secs into the future
            mock_utcnow.return_value = point2
            self.hass.bus.fire('test_event')
            self.hass.pool.block_till_done()
            self.assertEqual(1, len(self.calls))
Пример #23
0
    def test_if_fires_using_after(self):
        """Test for firing after."""
        assert _setup_component(
            self.hass, automation.DOMAIN, {
                automation.DOMAIN: {
                    'trigger': {
                        'platform': 'time',
                        'after': '5:00:00',
                    },
                    'action': {
                        'service': 'test.automation',
                        'data_template': {
                            'some':
                            '{{ trigger.platform }} - '
                            '{{ trigger.now.hour }}'
                        },
                    }
                }
            })

        fire_time_changed(self.hass,
                          dt_util.utcnow().replace(hour=5, minute=0, second=0))

        self.hass.pool.block_till_done()
        self.assertEqual(1, len(self.calls))
        self.assertEqual('time - 5', self.calls[0].data['some'])
Пример #24
0
    def test_if_not_fires_on_entity_change_with_for(self):
        """Test for not firing on entity change with for."""
        assert _setup_component(self.hass, automation.DOMAIN, {
            automation.DOMAIN: {
                'trigger': {
                    'platform': 'state',
                    'entity_id': 'test.entity',
                    'to': 'world',
                    'for': {
                        'seconds': 5
                    },
                },
                'action': {
                    'service': 'test.automation'
                }
            }
        })

        self.hass.states.set('test.entity', 'world')
        self.hass.pool.block_till_done()
        self.hass.states.set('test.entity', 'not_world')
        self.hass.pool.block_till_done()
        fire_time_changed(self.hass, dt_util.utcnow() + timedelta(seconds=10))
        self.hass.pool.block_till_done()
        self.assertEqual(0, len(self.calls))
Пример #25
0
    def test_delay(self):
        """Test the delay."""
        event = 'test_event'
        events = []

        def record_event(event):
            """Add recorded event to set."""
            events.append(event)

        self.hass.bus.listen(event, record_event)

        script_obj = script.Script(self.hass, [
            {'event': event},
            {'delay': {'seconds': 5}},
            {'event': event}])

        script_obj.run()

        self.hass.pool.block_till_done()

        assert script_obj.is_running
        assert script_obj.can_cancel
        assert script_obj.last_action == event
        assert len(events) == 1

        future = dt_util.utcnow() + timedelta(seconds=5)
        fire_time_changed(self.hass, future)
        self.hass.pool.block_till_done()

        assert not script_obj.is_running
        assert len(events) == 2
Пример #26
0
    def state(self):
        """Return the state of the device."""
        if self._state in (STATE_ALARM_ARMED_HOME,
                           STATE_ALARM_ARMED_AWAY) and \
           self._pending_time and self._state_ts + self._pending_time > \
           dt_util.utcnow():
            return STATE_ALARM_PENDING

        if self._state == STATE_ALARM_TRIGGERED and self._trigger_time:
            if self._state_ts + self._pending_time > dt_util.utcnow():
                return STATE_ALARM_PENDING
            elif (self._state_ts + self._pending_time +
                  self._trigger_time) < dt_util.utcnow():
                return STATE_ALARM_DISARMED

        return self._state
Пример #27
0
    def record_state(self, entity_id, state, event_id):
        """Save a state to the database."""
        now = dt_util.utcnow()

        # State got deleted
        if state is None:
            state_state = ''
            state_domain = ''
            state_attr = '{}'
            last_changed = last_updated = now
        else:
            state_domain = state.domain
            state_state = state.state
            state_attr = json.dumps(dict(state.attributes))
            last_changed = state.last_changed
            last_updated = state.last_updated

        info = (
            entity_id, state_domain, state_state, state_attr,
            last_changed, last_updated,
            now, self.utc_offset, event_id)

        self.query(
            """
            INSERT INTO states (
            entity_id, domain, state, attributes, last_changed, last_updated,
            created, utc_offset, event_id)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
            info)
Пример #28
0
    def camera_image(self):
        """Return a faked still image response."""
        now = dt_util.utcnow()

        image_path = os.path.join(os.path.dirname(__file__),
                                  'demo_{}.jpg'.format(now.second % 4))
        with open(image_path, 'rb') as file:
            return file.read()
Пример #29
0
    def alarm_disarm(self, code=None):
        """Send disarm command."""
        if not self._validate_code(code, STATE_ALARM_DISARMED):
            return

        self._state = STATE_ALARM_DISARMED
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()
Пример #30
0
    def alarm_disarm(self, code=None):
        """Send disarm command."""
        if not self._validate_code(code, STATE_ALARM_DISARMED):
            return

        self._state = STATE_ALARM_DISARMED
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()
Пример #31
0
    def test_as_local_with_utc_object(self):
        """Test local time with UTC object."""
        dt_util.set_default_time_zone(dt_util.get_time_zone(TEST_TIME_ZONE))

        utcnow = dt_util.utcnow()
        localnow = dt_util.as_local(utcnow)

        self.assertEqual(localnow, utcnow)
        self.assertNotEqual(localnow.tzinfo, utcnow.tzinfo)
Пример #32
0
 def test_entry_to_dict(self):
     """Test conversion of entry to dict."""
     entry = logbook.Entry(dt_util.utcnow(), 'Alarm', 'is triggered',
                           'switch', 'test_switch')
     data = entry.as_dict()
     self.assertEqual('Alarm', data.get(logbook.ATTR_NAME))
     self.assertEqual('is triggered', data.get(logbook.ATTR_MESSAGE))
     self.assertEqual('switch', data.get(logbook.ATTR_DOMAIN))
     self.assertEqual('test_switch', data.get(logbook.ATTR_ENTITY_ID))
Пример #33
0
    def test_parse_datetime_converts_correctly(self):
        """Test parse_datetime converts strings."""
        assert \
            datetime(1986, 7, 9, 12, 0, 0, tzinfo=dt_util.UTC) == \
            dt_util.parse_datetime("1986-07-09T12:00:00Z")

        utcnow = dt_util.utcnow()

        assert utcnow == dt_util.parse_datetime(utcnow.isoformat())
Пример #34
0
    def test_eq(self):
        """Test events."""
        now = dt_util.utcnow()
        data = {'some': 'attr'}
        event1, event2 = [
            ha.Event('some_type', data, time_fired=now) for _ in range(2)
        ]

        self.assertEqual(event1, event2)
Пример #35
0
 def test_entry_to_dict(self):
     """Test conversion of entry to dict."""
     entry = logbook.Entry(
         dt_util.utcnow(), 'Alarm', 'is triggered', 'switch', 'test_switch'
     )
     data = entry.as_dict()
     self.assertEqual('Alarm', data.get(logbook.ATTR_NAME))
     self.assertEqual('is triggered', data.get(logbook.ATTR_MESSAGE))
     self.assertEqual('switch', data.get(logbook.ATTR_DOMAIN))
     self.assertEqual('test_switch', data.get(logbook.ATTR_ENTITY_ID))
Пример #36
0
    def record_event(self, event):
        """Save an event to the database."""
        info = (event.event_type, json.dumps(event.data, cls=JSONEncoder),
                str(event.origin), dt_util.utcnow(), event.time_fired,
                self.utc_offset)

        return self.query(
            "INSERT INTO events ("
            "event_type, event_data, origin, created, time_fired, utc_offset"
            ") VALUES (?, ?, ?, ?, ?, ?)", info, RETURN_LASTROWID)
Пример #37
0
    def test_eq(self):
        """Test events."""
        now = dt_util.utcnow()
        data = {'some': 'attr'}
        event1, event2 = [
            ha.Event('some_type', data, time_fired=now)
            for _ in range(2)
        ]

        self.assertEqual(event1, event2)
Пример #38
0
    def test_last_changed_not_updated_on_same_state(self):
        """Test to not update the existing, same state."""
        state = self.states.get('light.Bowl')

        future = dt_util.utcnow() + timedelta(hours=10)

        with patch('blumate.util.dt.utcnow', return_value=future):
            self.states.set("light.Bowl", "on", {'attr': 'triggers_change'})

        self.assertEqual(state.last_changed,
                         self.states.get('light.Bowl').last_changed)
Пример #39
0
    def test_last_changed_not_updated_on_same_state(self):
        """Test to not update the existing, same state."""
        state = self.states.get('light.Bowl')

        future = dt_util.utcnow() + timedelta(hours=10)

        with patch('blumate.util.dt.utcnow', return_value=future):
            self.states.set("light.Bowl", "on", {'attr': 'triggers_change'})

        self.assertEqual(state.last_changed,
                         self.states.get('light.Bowl').last_changed)
Пример #40
0
    def test_time_event_does_not_send_message(self, mock_pub):
        """"Test the sending of a new message if time event."""
        self.assertTrue(self.add_eventstream(pub_topic='bar'))
        self.hass.pool.block_till_done()

        # Reset the mock because it will have already gotten calls for the
        # mqtt_eventstream state change on initialization, etc.
        mock_pub.reset_mock()

        fire_time_changed(self.hass, dt_util.utcnow())
        self.assertFalse(mock_pub.called)
Пример #41
0
    def test_time_event_does_not_send_message(self, mock_pub):
        """"Test the sending of a new message if time event."""
        self.assertTrue(self.add_eventstream(pub_topic='bar'))
        self.hass.pool.block_till_done()

        # Reset the mock because it will have already gotten calls for the
        # mqtt_eventstream state change on initialization, etc.
        mock_pub.reset_mock()

        fire_time_changed(self.hass, dt_util.utcnow())
        self.assertFalse(mock_pub.called)
Пример #42
0
 def value_changed(self, value):
     """Called when a value has changed on the network."""
     if self._value.value_id == value.value_id:
         self.update_ha_state()
         if value.data:
             # only allow this value to be true for re_arm secs
             self.invalidate_after = dt_util.utcnow() + datetime.timedelta(
                 seconds=self.re_arm_sec)
             track_point_in_time(
                 self._hass, self.update_ha_state,
                 self.invalidate_after)
Пример #43
0
    def test_json_encoder(self):
        """Test the JSON Encoder."""
        ha_json_enc = remote.JSONEncoder()
        state = hass.states.get('test.test')

        self.assertEqual(state.as_dict(), ha_json_enc.default(state))

        # Default method raises TypeError if non HA object
        self.assertRaises(TypeError, ha_json_enc.default, 1)

        now = dt_util.utcnow()
        self.assertEqual(now.isoformat(), ha_json_enc.default(now))
Пример #44
0
 def update(self):
     """Get the latest system information."""
     import psutil
     if self.type == 'disk_use_percent':
         self._state = psutil.disk_usage(self.argument).percent
     elif self.type == 'disk_use':
         self._state = round(psutil.disk_usage(self.argument).used /
                             1024**3, 1)
     elif self.type == 'disk_free':
         self._state = round(psutil.disk_usage(self.argument).free /
                             1024**3, 1)
     elif self.type == 'memory_use_percent':
         self._state = psutil.virtual_memory().percent
     elif self.type == 'memory_use':
         self._state = round((psutil.virtual_memory().total -
                              psutil.virtual_memory().available) /
                             1024**2, 1)
     elif self.type == 'memory_free':
         self._state = round(psutil.virtual_memory().available / 1024**2, 1)
     elif self.type == 'swap_use_percent':
         self._state = psutil.swap_memory().percent
     elif self.type == 'swap_use':
         self._state = round(psutil.swap_memory().used / 1024**3, 1)
     elif self.type == 'swap_free':
         self._state = round(psutil.swap_memory().free / 1024**3, 1)
     elif self.type == 'processor_use':
         self._state = round(psutil.cpu_percent(interval=None))
     elif self.type == 'process':
         if any(self.argument in l.name() for l in psutil.process_iter()):
             self._state = STATE_ON
         else:
             self._state = STATE_OFF
     elif self.type == 'network_out':
         self._state = round(psutil.net_io_counters(pernic=True)
                             [self.argument][0] / 1024**2, 1)
     elif self.type == 'network_in':
         self._state = round(psutil.net_io_counters(pernic=True)
                             [self.argument][1] / 1024**2, 1)
     elif self.type == 'packets_out':
         self._state = psutil.net_io_counters(pernic=True)[self.argument][2]
     elif self.type == 'packets_in':
         self._state = psutil.net_io_counters(pernic=True)[self.argument][3]
     elif self.type == 'ipv4_address':
         self._state = psutil.net_if_addrs()[self.argument][0][1]
     elif self.type == 'ipv6_address':
         self._state = psutil.net_if_addrs()[self.argument][1][1]
     elif self.type == 'last_boot':
         self._state = dt_util.as_local(
             dt_util.utc_from_timestamp(psutil.boot_time())
         ).date().isoformat()
     elif self.type == 'since_last_boot':
         self._state = dt_util.utcnow() - dt_util.utc_from_timestamp(
             psutil.boot_time())
Пример #45
0
    def alarm_arm_home(self, code=None):
        """Send arm home command."""
        if not self._validate_code(code, STATE_ALARM_ARMED_HOME):
            return

        self._state = STATE_ALARM_ARMED_HOME
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._pending_time:
            track_point_in_time(self._bmss, self.update_ha_state,
                                self._state_ts + self._pending_time)
Пример #46
0
    def test_json_encoder(self):
        """Test the JSON Encoder."""
        ha_json_enc = remote.JSONEncoder()
        state = hass.states.get('test.test')

        self.assertEqual(state.as_dict(), ha_json_enc.default(state))

        # Default method raises TypeError if non HA object
        self.assertRaises(TypeError, ha_json_enc.default, 1)

        now = dt_util.utcnow()
        self.assertEqual(now.isoformat(), ha_json_enc.default(now))
Пример #47
0
    def _setup_run(self):
        """Log the start of the current run."""
        if self.query("""UPDATE recorder_runs SET end=?, closed_incorrect=1
                      WHERE end IS NULL""", (self.recording_start, ),
                      return_value=RETURN_ROWCOUNT):

            _LOGGER.warning("Found unfinished sessions")

        self.query(
            """INSERT INTO recorder_runs (start, created, utc_offset)
               VALUES (?, ?, ?)""",
            (self.recording_start, dt_util.utcnow(), self.utc_offset))
Пример #48
0
    def record_event(self, event):
        """Save an event to the database."""
        info = (
            event.event_type, json.dumps(event.data, cls=JSONEncoder),
            str(event.origin), dt_util.utcnow(), event.time_fired,
            self.utc_offset
        )

        return self.query(
            "INSERT INTO events ("
            "event_type, event_data, origin, created, time_fired, utc_offset"
            ") VALUES (?, ?, ?, ?, ?, ?)", info, RETURN_LASTROWID)
Пример #49
0
 def __init__(self, sensor_value, sensor_class, hass, re_arm_sec=60):
     """Initialize the sensor."""
     super(ZWaveTriggerSensor, self).__init__(sensor_value, sensor_class)
     self._hass = hass
     self.re_arm_sec = re_arm_sec
     self.invalidate_after = dt_util.utcnow() + datetime.timedelta(
         seconds=self.re_arm_sec)
     # If it's active make sure that we set the timeout tracker
     if sensor_value.data:
         track_point_in_time(
             self._hass, self.update_ha_state,
             self.invalidate_after)
Пример #50
0
    def _setup_run(self):
        """Log the start of the current run."""
        if self.query("""UPDATE recorder_runs SET end=?, closed_incorrect=1
                      WHERE end IS NULL""", (self.recording_start, ),
                      return_value=RETURN_ROWCOUNT):

            _LOGGER.warning("Found unfinished sessions")

        self.query(
            """INSERT INTO recorder_runs (start, created, utc_offset)
               VALUES (?, ?, ?)""",
            (self.recording_start, dt_util.utcnow(), self.utc_offset))
Пример #51
0
    def alarm_arm_home(self, code=None):
        """Send arm home command."""
        if not self._validate_code(code, STATE_ALARM_ARMED_HOME):
            return

        self._state = STATE_ALARM_ARMED_HOME
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._pending_time:
            track_point_in_time(
                self._bmss, self.update_ha_state,
                self._state_ts + self._pending_time)
Пример #52
0
    def alarm_trigger(self, code=None):
        """Send alarm trigger command. No code needed."""
        self._state = STATE_ALARM_TRIGGERED
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._trigger_time:
            track_point_in_time(self._bmss, self.update_ha_state,
                                self._state_ts + self._pending_time)

            track_point_in_time(
                self._bmss, self.update_ha_state,
                self._state_ts + self._pending_time + self._trigger_time)
Пример #53
0
    def test_throttle(self):
        """Test the add cooldown decorator."""
        calls1 = []
        calls2 = []

        @util.Throttle(timedelta(seconds=4))
        def test_throttle1():
            calls1.append(1)

        @util.Throttle(timedelta(seconds=4), timedelta(seconds=2))
        def test_throttle2():
            calls2.append(1)

        now = dt_util.utcnow()
        plus3 = now + timedelta(seconds=3)
        plus5 = plus3 + timedelta(seconds=2)

        # Call first time and ensure methods got called
        test_throttle1()
        test_throttle2()

        self.assertEqual(1, len(calls1))
        self.assertEqual(1, len(calls2))

        # Call second time. Methods should not get called
        test_throttle1()
        test_throttle2()

        self.assertEqual(1, len(calls1))
        self.assertEqual(1, len(calls2))

        # Call again, overriding throttle, only first one should fire
        test_throttle1(no_throttle=True)
        test_throttle2(no_throttle=True)

        self.assertEqual(2, len(calls1))
        self.assertEqual(1, len(calls2))

        with patch('blumate.util.utcnow', return_value=plus3):
            test_throttle1()
            test_throttle2()

        self.assertEqual(2, len(calls1))
        self.assertEqual(1, len(calls2))

        with patch('blumate.util.utcnow', return_value=plus5):
            test_throttle1()
            test_throttle2()

        self.assertEqual(3, len(calls1))
        self.assertEqual(2, len(calls2))
Пример #54
0
    def test_throttle(self):
        """Test the add cooldown decorator."""
        calls1 = []
        calls2 = []

        @util.Throttle(timedelta(seconds=4))
        def test_throttle1():
            calls1.append(1)

        @util.Throttle(timedelta(seconds=4), timedelta(seconds=2))
        def test_throttle2():
            calls2.append(1)

        now = dt_util.utcnow()
        plus3 = now + timedelta(seconds=3)
        plus5 = plus3 + timedelta(seconds=2)

        # Call first time and ensure methods got called
        test_throttle1()
        test_throttle2()

        self.assertEqual(1, len(calls1))
        self.assertEqual(1, len(calls2))

        # Call second time. Methods should not get called
        test_throttle1()
        test_throttle2()

        self.assertEqual(1, len(calls1))
        self.assertEqual(1, len(calls2))

        # Call again, overriding throttle, only first one should fire
        test_throttle1(no_throttle=True)
        test_throttle2(no_throttle=True)

        self.assertEqual(2, len(calls1))
        self.assertEqual(1, len(calls2))

        with patch('blumate.util.utcnow', return_value=plus3):
            test_throttle1()
            test_throttle2()

        self.assertEqual(2, len(calls1))
        self.assertEqual(1, len(calls2))

        with patch('blumate.util.utcnow', return_value=plus5):
            test_throttle1()
            test_throttle2()

        self.assertEqual(3, len(calls1))
        self.assertEqual(2, len(calls2))
Пример #55
0
    def __init__(self, entity_id, state, attributes=None, last_changed=None,
                 last_updated=None):
        """Initialize a new state."""
        if not valid_entity_id(entity_id):
            raise InvalidEntityFormatError((
                "Invalid entity id encountered: {}. "
                "Format should be <domain>.<object_id>").format(entity_id))

        self.entity_id = entity_id.lower()
        self.state = str(state)
        self.attributes = MappingProxyType(attributes or {})
        self.last_updated = last_updated or dt_util.utcnow()

        self.last_changed = last_changed or self.last_updated
Пример #56
0
    def test_as_dict(self):
        """Test as dictionary."""
        event_type = 'some_type'
        now = dt_util.utcnow()
        data = {'some': 'attr'}

        event = ha.Event(event_type, data, ha.EventOrigin.local, now)
        expected = {
            'event_type': event_type,
            'data': data,
            'origin': 'LOCAL',
            'time_fired': now,
        }
        self.assertEqual(expected, event.as_dict())