Python homeassistant.util.dt.utcnow() Examples

The following are 19 code examples of homeassistant.util.dt.utcnow(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module homeassistant.util.dt , or try the search function .
Example #1
Source File: sensor.py    From Xiaomi_Hygrothermo with MIT License 7 votes vote down vote up
def get_data(self, now = None):
        try:
            from bluepy import btle

            p = btle.Peripheral(self.address)

            #self.name = ''.join(map(chr, p.readCharacteristic(0x3)))
            #self.firmware = ''.join(map(chr, p.readCharacteristic(0x24)))
            if self.last_battery is None or (utcnow() - self.last_battery).seconds >= 3600:
                self.battery = p.readCharacteristic(0x18)[0]
                self.last_battery = utcnow()

            delegate = XiomiHygroThermoDelegate()
            p.withDelegate( delegate )
            p.writeCharacteristic(0x10, bytearray([1, 0]), True)
            while not delegate.received:
                p.waitForNotifications(30.0)

            self.temperature = delegate.temperature
            self.humidity = delegate.humidity

            ok = True
        except Exception as ex:
            if isinstance(ex, btle.BTLEException):
                _LOGGER.warning("BT connection error: {}".format(ex))
            else:
                _LOGGER.error("Unexpected error: {}".format(ex))
            ok = False

        for i in [0, 1]:
            changed = self.entities[i].set_state(ok, self.battery, self.temperature if i == 0 else self.humidity)
            if (not now is None) and changed:
                self.entities[i].async_schedule_update_ha_state() 
Example #2
Source File: audi_account.py    From audi_connect_ha with MIT License 6 votes vote down vote up
def _refresh_vehicle_data(self, vin):
        res = await self.connection.refresh_vehicle_data(vin)

        if res == True:
            await self.update(utcnow())

            self.hass.bus.fire(
                "{}_{}".format(DOMAIN, REFRESH_VEHICLE_DATA_COMPLETED_EVENT),
                {"vin": vin},
            )

        else:
            _LOGGER.exception("Error refreshing vehicle data %s", vin)
            self.hass.bus.fire(
                "{}_{}".format(DOMAIN, REFRESH_VEHICLE_DATA_FAILED_EVENT), {"vin": vin}
            ) 
Example #3
Source File: audi_account.py    From audi_connect_ha with MIT License 6 votes vote down vote up
def update(self, now):

        """Update status from the online service."""
        try:
            if not await self.connection.update(None):
                return False

            self.discover_vehicles(
                [x for x in self.connection._vehicles if x.vin not in self.vehicles]
            )

            async_dispatcher_send(self.hass, SIGNAL_STATE_UPDATED)

            for config_vehicle in self.config_vehicles:
                for instrument in config_vehicle.device_trackers:
                    async_dispatcher_send(self.hass, TRACKER_UPDATE, instrument)

            return True
        finally:
            async_track_point_in_utc_time(
                self.hass, self.update, utcnow() + timedelta(minutes=self.interval)
            ) 
Example #4
Source File: __init__.py    From audi_connect_ha with MIT License 6 votes vote down vote up
def async_setup_entry(hass, config_entry):
    """Set up this integration using UI."""

    if DOMAIN not in hass.data:
        hass.data[DOMAIN] = {}

    """Set up the Audi Connect component."""
    hass.data[DOMAIN]["devices"] = set()

    account = config_entry.data.get(CONF_USERNAME)

    unit_system = "metric"
    if hass.config.units.name == CONF_UNIT_SYSTEM_IMPERIAL:
        unit_system = "imperial"

    if account not in hass.data[DOMAIN]:
        data = hass.data[DOMAIN][account] = AudiAccount(hass, config_entry, unit_system=unit_system)
        data.init_connection()
    else:
        data = hass.data[DOMAIN][account]

    return await data.update(utcnow()) 
Example #5
Source File: sensor.py    From homeassistant-homeconnect with MIT License 6 votes vote down vote up
def async_update(self):
        """Update the sensos status."""
        status = self.device.appliance.status
        if self._key not in status:
            self._state = None
        else:
            if self.device_class == DEVICE_CLASS_TIMESTAMP:
                if "value" not in status[self._key]:
                    self._state = None
                elif (
                    self._state is not None
                    and self._sign == 1
                    and dt_util.parse_datetime(self._state) < dt_util.utcnow()
                ):
                    # if the date is supposed to be in the future but we're
                    # already past it, set state to None.
                    self._state = None
                else:
                    seconds = self._sign * float(status[self._key]["value"])
                    self._state = (
                        dt_util.utcnow() + timedelta(seconds=seconds)
                    ).isoformat()
            else:
                self._state = status[self._key].get("value")
        _LOGGER.debug("Updated, new state: %s", self._state) 
Example #6
Source File: device_tracker.py    From iphonedetect with MIT License 6 votes vote down vote up
def setup_scanner(hass, config, see, discovery_info=None):
    """Set up the Host objects and return the update function."""
    hosts = [Host(ip, dev_id, hass, config) for (dev_id, ip) in
             config[CONF_HOSTS].items()]
    interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL)

    _LOGGER.debug("Started iphonedetect with interval=%s on hosts: %s",
                  interval, ",".join([host.ip_address for host in hosts]))
    
    def update_interval(now):
        """Update all the hosts on every interval time."""
        try:
            for host in hosts:
                host.update(see)
        finally:
            hass.helpers.event.track_point_in_utc_time(
                update_interval, dt_util.utcnow() + interval)

    update_interval(None)
    return True 
Example #7
Source File: alarm_control_panel.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def alarm_trigger(self, code=None):
        if self._trigger_till is None:
            _LOGGER.info('%s: triggered', self._name)
            self._trigger_till = time.monotonic() + self._trigger_time.total_seconds()
            if int(self._alarm_volume) != 0:
                self._base.siren_on(duration=self._trigger_time.total_seconds(), volume=self._alarm_volume)
            self.async_schedule_update_ha_state()
            track_point_in_time(self.hass, self.async_update_ha_state, dt_util.utcnow() + self._trigger_time) 
Example #8
Source File: xboxone.py    From hassio-addons with MIT License 5 votes vote down vote up
def media_position_updated_at(self):
        """Last valid time of media position"""
        if self.state in [STATE_PLAYING, STATE_PAUSED]:
            return dt_util.utcnow() 
Example #9
Source File: switch.py    From hass-aarlo with GNU Lesser General Public License v3.0 5 votes vote down vote up
def turn_on(self, **kwargs):
        """Turn the switch on."""
        if self._on_until is None:
            self.do_on()
            self._on_until = time.monotonic() + self._on_for.total_seconds()
            self.async_schedule_update_ha_state()
            track_point_in_time(self.hass, self.async_update_ha_state, dt_util.utcnow() + self._on_for)
            _LOGGER.debug('turned on') 
Example #10
Source File: light.py    From ha-plejd with Apache License 2.0 5 votes vote down vote up
def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    cryptokey = binascii.a2b_hex(config.get(CONF_CRYPTO_KEY).replace('-', ''))
    plejdinfo = {"key": cryptokey}

    hass.data[DATA_PLEJD] = plejdinfo

    async def _ping(now):
        pi = hass.data[DATA_PLEJD]
        if(await plejd_ping(pi) == False):
            await connect(pi)
        plejdinfo["remove_timer"] = async_track_point_in_utc_time(hass, _ping, dt_util.utcnow() + timedelta(seconds = 300))

    async def _stop_plejd(event):
        if "remove_timer" in plejdinfo:
            plejdinfo["remove_timer"]()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _stop_plejd)

    plejdinfo["discovery_timeout"] = config[CONF_DISCOVERY_TIMEOUT]
    plejdinfo["dbus_address"] = config[CONF_DBUS_ADDRESS]

    await connect(plejdinfo)
    if plejdinfo["characteristics"] is not None:
        await _ping(dt_util.utcnow())
    else:
        raise PlatformNotReady

    devices = []
    for identity, entity_info in config[CONF_DEVICES].items():
        i = int(identity)
        _LOGGER.debug("Adding device %d (%s)" % (i, entity_info[CONF_NAME]))
        new = PlejdLight(entity_info[CONF_NAME], i)
        PLEJD_DEVICES[i] = new
        devices.append(new)

    async_add_entities(devices)
    _LOGGER.debug("All plejd setup completed") 
Example #11
Source File: sensor.py    From Home-Assistant-Sensor-Afvalbeheer with Apache License 2.0 5 votes vote down vote up
def schedule_update(self, interval):
        nxt = dt_util.utcnow() + interval
        async_track_point_in_utc_time(self.hass, self.async_update, nxt) 
Example #12
Source File: device_tracker.py    From homeassistant-config with The Unlicense 5 votes vote down vote up
def __init__(self, hass, config, see, interval, home_place_name, api):
        """Initialize Life360Scanner."""
        self._hass = hass
        self._see = see
        self._show_as_state = config[CONF_SHOW_AS_STATE]
        self._home_place_name = home_place_name
        self._max_gps_accuracy = config.get(CONF_MAX_GPS_ACCURACY)
        self._max_update_wait = config.get(CONF_MAX_UPDATE_WAIT)
        prefix = config.get(CONF_PREFIX)
        self._prefix = '' if not prefix else prefix + '_'
        self._members = config.get(CONF_MEMBERS)
        self._driving_speed = config.get(CONF_DRIVING_SPEED)
        self._time_as = config[CONF_TIME_AS]
        self._api = api

        self._errs = {}
        self._error_threshold = config[CONF_ERROR_THRESHOLD]
        self._warning_threshold = config.get(
            CONF_WARNING_THRESHOLD, self._error_threshold)

        self._max_errs = self._error_threshold + 2
        self._dev_data = {}
        if self._time_as in [TZ_DEVICE_UTC, TZ_DEVICE_LOCAL]:
            from timezonefinderL import TimezoneFinder
            self._tf = TimezoneFinder()

        self._seen_members = set()

        if self._members is not None:
            _LOGGER.debug(
                'Including: %s',
                ', '.join([
                    self._prefix
                    + slugify(name.replace(',', '_').replace('-', '_'))
                    for name in self._members]))

        self._started = dt_util.utcnow()
        self._update_life360()
        track_time_interval(self._hass, self._update_life360, interval) 
Example #13
Source File: __init__.py    From homeassistant-config with The Unlicense 5 votes vote down vote up
def async_setup(hass, config):
    """Track the state of the sun."""
    if config.get(CONF_ELEVATION) is not None:
        _LOGGER.warning(
            "Elevation is now configured in home assistant core. "
            "See https://home-assistant.io/docs/configuration/basic/")

    sun = Sun(hass, get_astral_location(hass), config[DOMAIN])
    sun.point_in_time_listener(dt_util.utcnow())

    return True 
Example #14
Source File: alarm_control_panel.py    From hass-config with GNU General Public License v3.0 5 votes vote down vote up
def alarm_trigger(self, code=None):
        if self._trigger_till is None:
            _LOGGER.info('%s: triggered', self._name)
            self._trigger_till = time.monotonic() + self._trigger_time.total_seconds()
            if int(self._alarm_volume) != 0:
                self._base.siren_on(duration=self._trigger_time.total_seconds(), volume=self._alarm_volume)
            self.async_schedule_update_ha_state()
            track_point_in_time(self.hass, self.async_update_ha_state, dt_util.utcnow() + self._trigger_time) 
Example #15
Source File: camera.py    From hass-config with GNU General Public License v3.0 5 votes vote down vote up
def start_recording(self, duration):

        def _stop_recording(_now):
            self.stop_recording()

        if self._camera.get_stream() is not None:
            self._camera.start_recording()
            async_track_point_in_time(self.hass, _stop_recording, dt_util.utcnow() + timedelta(seconds=duration)) 
Example #16
Source File: switch.py    From hass-config with GNU General Public License v3.0 5 votes vote down vote up
def turn_on(self, **kwargs):
        """Turn the switch on."""
        if self._on_until is None:
            self.do_on()
            self._on_until = time.monotonic() + self._on_for.total_seconds()
            self.async_schedule_update_ha_state()
            track_point_in_time(self.hass, self.async_update_ha_state, dt_util.utcnow() + self._on_for)
            _LOGGER.debug('turned on') 
Example #17
Source File: __init__.py    From home-assistant-custom-components with MIT License 4 votes vote down vote up
def setup(hass, config):
    """Setup Volkswagen Carnet component"""

    username = config[DOMAIN].get(CONF_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD)
    interval = config[DOMAIN].get(CONF_UPDATE_INTERVAL)
    state = hass.data[DATA_KEY] = VolkswagenData(config)

    # create carnet connection
    connection = Connection(username, password)
    # login to carnet
    _LOGGER.debug("Creating connection to carnet")
    connection._login()
    if not connection.logged_in:
        _LOGGER.warning('Could not login to carnet')

    def discover_vehicle(vehicle):
        """Load relevant platforms."""
        state.entities[vehicle.vin] = []
        for attr, (component, *_) in RESOURCES.items():
            if (getattr(vehicle, attr + '_supported', True) and
                    attr in config[DOMAIN].get(CONF_RESOURCES, [attr])):
                discovery.load_platform(
                    hass, component, DOMAIN, (vehicle.vin, attr), config)

    def update_vehicle(vehicle):
        """Review updated information on vehicle."""
        state.vehicles[vehicle.vin] = vehicle
        if vehicle.vin not in state.entities:
            discover_vehicle(vehicle)

        for entity in state.entities[vehicle.vin]:
            entity.schedule_update_ha_state()

        dispatcher_send(hass, SIGNAL_VEHICLE_SEEN, vehicle)

    def update(now):
        """Update status from Volkswagen Carnet"""
        try:
            if not connection.logged_in:
                connection._login()
                if not connection.logged_in:
                    _LOGGER.warning('Could not login to carnet')
            else:
                if not connection.update():
                    _LOGGER.warning("Could not query carnet")
                    return False
                else:
                    _LOGGER.debug("Updating data from carnet")

                for vehicle in connection.vehicles:
                    update_vehicle(vehicle)

            return True

        finally:
            track_point_in_utc_time(hass, update, utcnow() + interval)

    _LOGGER.info("Starting service")
    return update(utcnow()) 
Example #18
Source File: airplay.py    From HomeAssistant_Components with Apache License 2.0 4 votes vote down vote up
def async_setup(hass, config):
    """Set up the AirPlay component."""
    _LOGGER.debug('Begin setup AirPlay')
    ap = airplay()
    regDevices = []

    @asyncio.coroutine
    def scan_devices(now):
        devices = yield from hass.loop.run_in_executor(
            None, ap.discover_MediaPlayer)

        for device in devices:
            isFind = False

            address = device.get("address")
            port = device.get("port")

            for regDevice in regDevices:
                regAddress = regDevice.get("address")
                regPort = regDevice.get("port")

                if regAddress == address and regPort == port:
                    isFind = True

            if isFind == False:
                regDevices.append(device)
                load_platform(hass, "media_player", MEDIA_PLAYER_DOMAIN, device)
                _LOGGER.debug("find device:%@", device)




        async_track_point_in_utc_time(hass, scan_devices,
                                      dt_util.utcnow() + SCAN_INTERVAL)

    @callback
    def schedule_first(event):
        """Schedule the first discovery when Home Assistant starts up."""
        async_track_point_in_utc_time(hass, scan_devices, dt_util.utcnow())

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, schedule_first)

    return True 
Example #19
Source File: dlna.py    From HomeAssistant_Components with Apache License 2.0 4 votes vote down vote up
def async_setup(hass, config):

    dlna = Dlnadriver()
    regDevices = []

    @asyncio.coroutine
    def scan_devices(now):
        """Scan for MediaPlayer."""
        devices = yield from hass.loop.run_in_executor(
            None, dlna.discover_MediaPlayer)



        for device in devices:
            isFind = False
            devUUID = device.get('uuid')

            for regDev in regDevices:
                regUUID = regDev.get('uuid')
                if devUUID == regUUID:
                    isFind = True

            if isFind == False:
                regDevices.append(device)
                load_platform(hass, 'media_player', DOMAIN, device)
                _LOGGER.info('RegDevice:{}'.format(device.get('friendly_name')))
            else:
                isFind = False

            # if device not in regDevices:
            #     regDevices.append(device)
            #     load_platform(hass,'media_player',DOMAIN,device)
            #     _LOGGER.info('RegDevice:{}'.format(device.get('friendly_name')))

            uuid = device.get('uuid')
            if uuid != '':
                hass.data[uuid] = device

        async_track_point_in_utc_time(hass, scan_devices,
                                      dt_util.utcnow() + SCAN_INTERVAL)

    @callback
    def schedule_first(event):
        """Schedule the first discovery when Home Assistant starts up."""
        async_track_point_in_utc_time(hass, scan_devices, dt_util.utcnow())

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, schedule_first)

    return True