当前位置: 首页>>代码示例>>Python>>正文


Python core.callback方法代码示例

本文整理汇总了Python中homeassistant.core.callback方法的典型用法代码示例。如果您正苦于以下问题:Python core.callback方法的具体用法?Python core.callback怎么用?Python core.callback使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在homeassistant.core的用法示例。


在下文中一共展示了core.callback方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: async_added_to_hass

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_added_to_hass(self):
        """Register callbacks."""

        @callback
        def update_state(_device, attr, value):
            _LOGGER.debug('all-siren-callback:' + self._name + ':' + attr + ':' + str(value)[:80])

            state = "off"
            for device in self._devices:
                if device.siren_state == "on":
                    state = "on"
            self._state = state

            self.async_schedule_update_ha_state()

        for device in self._devices:
            _LOGGER.debug("register all siren callbacks for {}".format(device.name))
            device.add_attr_callback('sirenState', update_state) 
开发者ID:pschmitt,项目名称:hass-config,代码行数:20,代码来源:switch.py

示例2: _async_start_observe

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def _async_start_observe(self, exc=None):
        """Start observation of light."""
        # pylint: disable=import-error
        from pytradfri.error import PytradfriError
        if exc:
            _LOGGER.warning("Observation failed for %s", self._name,
                            exc_info=exc)

        try:
            cmd = self._light.observe(callback=self._observe_update,
                                      err_callback=self._async_start_observe,
                                      duration=0)
            self.hass.async_add_job(self._api(cmd))
        except PytradfriError as err:
            _LOGGER.warning("Observation failed, trying again", exc_info=err)
            self._async_start_observe() 
开发者ID:gluap,项目名称:pyduofern,代码行数:18,代码来源:duofern.py

示例3: device_info

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def device_info(self):
        """Return information about the device."""
        return {
            'manufacturer': 'Visonic',
            "identifiers": {(DOMAIN, self._name)},
            "name": f"Visonic Sensor ({self.visonic_device.dname})",
            "model": self.visonic_device.stype,
            "via_device" : (DOMAIN, VISONIC_UNIQUE_ID),
        }

#    # Called when an entity has their entity_id and hass object assigned, before it is written to the state machine for the first time. 
#    #     Example uses: restore the state, subscribe to updates or set callback/dispatch function/listener.
#    async def async_added_to_hass(self):
#        await super().async_added_to_hass()
#        _LOGGER.info('binary sensor async_added_to_hass')
    
    # Called when an entity is about to be removed from Home Assistant. Example use: disconnect from the server or unsubscribe from updates. 
开发者ID:davesmeghead,项目名称:visonic,代码行数:19,代码来源:binary_sensor.py

示例4: async_added_to_hass

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_added_to_hass(self):
        """Register callbacks."""

        @callback
        def update_state(_device, attr, value):
            _LOGGER.debug('all-siren-callback:' + self._name + ':' + attr + ':' + str(value)[:80])

            state = "off"
            for device in self._devices:
                if device.siren_state == "on":
                    state = "on"
            self._state = state

            self.async_schedule_update_ha_state()

        for device in self._devices:
            _LOGGER.debug("register all siren callbacks for {}".format(device.name))
            device.add_attr_callback(SIREN_STATE_KEY, update_state) 
开发者ID:twrecked,项目名称:hass-aarlo,代码行数:20,代码来源:switch.py

示例5: async_added_to_hass

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_added_to_hass(self):
        """Register callbacks."""

        @callback
        def update_attr(_light, attr, value):
            _LOGGER.debug('callback:' + self._name + ':' + attr + ':' + str(value)[:80])
            if attr == LIGHT_BRIGHTNESS_KEY:
                self._brightness = value
            if attr == LIGHT_MODE_KEY:
                self._set_light_mode(value)
            self.async_schedule_update_ha_state()

        _LOGGER.info('ArloNightLight: %s registering callbacks', self._name)

        self._brightness = self._light.attribute(LIGHT_BRIGHTNESS_KEY, default=255)
        self._set_light_mode(self._light.attribute(LIGHT_MODE_KEY))

        self._light.add_attr_callback(LIGHT_BRIGHTNESS_KEY, update_attr)
        self._light.add_attr_callback(LIGHT_MODE_KEY, update_attr)
        await super().async_added_to_hass() 
开发者ID:twrecked,项目名称:hass-aarlo,代码行数:22,代码来源:light.py

示例6: async_added_to_hass

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_added_to_hass(self):
        """Register callbacks."""

        @callback
        def update_state(_device, attr, value):
            _LOGGER.debug('callback:' + attr + ':' + str(value)[:80])
            self._state = value
            self.async_schedule_update_ha_state()

        if self._attr is not None:
            self._state = self._device.attribute(self._attr)
            self._device.add_attr_callback(self._attr, update_state) 
开发者ID:pschmitt,项目名称:hass-config,代码行数:14,代码来源:binary_sensor.py

示例7: async_added_to_hass

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_added_to_hass(self):
        """Register callbacks."""

        @callback
        def update_state(_device, attr, value):
            _LOGGER.debug('callback:' + self._name + ':' + attr + ':' + str(value)[:80])

            # set state 
            if attr == 'activityState' or attr == 'connectionState':
                if value == 'thermalShutdownCold':
                    self._state = 'Offline, Too Cold'
                elif value == 'userStreamActive':
                    self._state = STATE_STREAMING
                elif value == 'alertStreamActive':
                    self._state = STATE_RECORDING
                elif value == 'unavailable':
                    self._state = 'Unavailable'
                else:
                    self._state = STATE_IDLE
            if attr == 'recentActivity':
                self._recent = value

            self.async_schedule_update_ha_state()

        self._camera.add_attr_callback('privacyActive', update_state)
        self._camera.add_attr_callback('recentActivity', update_state)
        self._camera.add_attr_callback('activityState', update_state)
        self._camera.add_attr_callback('connectionState', update_state)
        self._camera.add_attr_callback('presignedLastImageData', update_state)
        self._camera.add_attr_callback('mediaUploadNotification', update_state)
        self._camera.add_attr_callback('chargingState', update_state)
        self._camera.add_attr_callback('chargingTech', update_state) 
开发者ID:pschmitt,项目名称:hass-config,代码行数:34,代码来源:camera.py

示例8: async_added_to_hass

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_added_to_hass(self):
        """Register callbacks."""

        @callback
        def update_state(_device, attr, value):
            _LOGGER.debug('callback:' + attr + ':' + str(value))
            self._state = self._get_state_from_ha(self._base.attribute('activeMode'))
            self.async_schedule_update_ha_state()

        self._state = self._get_state_from_ha(self._base.attribute('activeMode', ARMED))
        self._base.add_attr_callback('activeMode', update_state) 
开发者ID:pschmitt,项目名称:hass-config,代码行数:13,代码来源:alarm_control_panel.py

示例9: async_added_to_hass

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_added_to_hass(self):
        """Register callbacks."""

        @callback
        def update_state(_device, attr, props):
            _LOGGER.info('media_player callback:' + attr + ':' + str(props)[:80])
            if attr == "status":
                status = props.get('status')
                if status == 'playing':
                    self._state = STATE_PLAYING
                elif status == 'paused':
                    self._state = STATE_PAUSED
                else:
                    _LOGGER.debug('Unknown status:' + status)
                    self._state = STATE_IDLE
                self._position = props.get('position', 0)
                self._track_id = props.get('trackId', None)
            elif attr == "speaker":
                vol = props.get('volume')
                if vol is not None:
                    self._volume = vol / 100
                self._muted = props.get('mute', self._muted)
            elif attr == "config":
                config = props.get('config', {})
                self._shuffle = config.get('shuffleActive', self._shuffle)
            elif attr == "playlist":
                self._playlist = props

            self.async_schedule_update_ha_state()

        self._device.add_attr_callback("config", update_state)
        self._device.add_attr_callback("speaker", update_state)
        self._device.add_attr_callback("status", update_state)
        self._device.add_attr_callback("playlist", update_state)
        self._device.get_audio_playback_status() 
开发者ID:pschmitt,项目名称:hass-config,代码行数:37,代码来源:media_player.py

示例10: async_setup_entry

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_setup_entry( hass: HomeAssistant, entry: ConfigEntry, async_add_entities ) -> None:
    """Set up the Visonic Alarm Binary Sensors"""
    
    _LOGGER.info("************* binary sensor async_setup_entry **************")
    #_LOGGER.info("     options {0}".format(entry.options))
    #_LOGGER.info("     data    {0}".format(entry.data))
    
#    @callback
#    def async_add_binary_sensor(binary_sensor):
#        """Add Visonic binary sensor."""
#        _LOGGER.info(f"   got device {binary_sensor.getDeviceID()}")
#        async_add_entities([binary_sensor], True)

#    async_dispatcher_connect(hass, "visonic_new_binary_sensor", async_add_binary_sensor)

    if DOMAIN in hass.data:
        _LOGGER.info("   In binary sensor async_setup_entry")
        sensors = [
            VisonicSensor(device)
            for device in hass.data[DOMAIN]['binary_sensor']   
        ]
        # empty the list as we have copied the entries so far in to sensors
        hass.data[DOMAIN]["binary_sensor"] = list()       
        async_add_entities(sensors, True)

#   Each Sensor in Visonic Alarms can be Armed/Bypassed individually 
开发者ID:davesmeghead,项目名称:visonic,代码行数:28,代码来源:binary_sensor.py

示例11: _call

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def _call(self, callback, message_type, **extra_args):
        _id = self._next_id()
        self._handlers[_id] = callback
        try:
            await self._connection.send_json(
                {'id': _id, 'type': message_type, **extra_args})
        except aiohttp.client_exceptions.ClientError as err:
            _LOGGER.error('remote websocket connection closed: %s', err)
            await self._disconnected() 
开发者ID:lukas-hetzenecker,项目名称:home-assistant-remote,代码行数:11,代码来源:__init__.py

示例12: async_turn_on_with_timer

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def async_turn_on_with_timer(self, minutes, notify_service):
        """Turn the switch on with 15/30/45/60 minutes timer."""
        _LOGGER.debug('received turn on request')
        """Skips next update after state changed, usefull for slow devices. if intial interval value was bigger or equals to 30, skip request will be ignored"""
        self._skip_update = True
        self._state, self._current_power_w, self._current_power_a, self._auto_off_time_left, self._auto_off_config = yield from self.hass.async_add_job(self.async_send_command_to_device,  "1", minutes)
        if self._state is None:
            self._skip_update = False
        elif not notify_service is None:
            """Handle notification services turned on request"""
            ON_DATA = TIMER_TURN_ON_NOTIFICATION_DATA
            ON_DATA["message"] = ON_DATA["message"].format(self._name, minutes)
            self.hass.async_add_job(self.hass.services.async_call(NOTIFY_DOMAIN, notify_service, ON_DATA))
            _LOGGER.debug('turned on notification sent to ' + notify_service)

            """Handle notification services turned off registration"""
            OFF_DATA = TIMER_TURN_OFF_NOTIFICATION_DATA
            OFF_DATA["message"] = OFF_DATA["message"].format(self._name)
            
            @callback
            def send_turn_off_notification(entity, from_state, to_state):
                """Callback function for handling state changes"""
                _LOGGER.debug("received track event: " + str(entity) + " has changed state from " + str(from_state) + " to " + str(to_state))
                self.hass.async_add_job(self.hass.services.async_call(NOTIFY_DOMAIN, notify_service, OFF_DATA))
                _LOGGER.debug('turned off notification sent to ' + notify_service)
                if not self._listenr_remove_func is None:
                    """Remove listener for recieving anymore state changes tracking"""
                    self._listenr_remove_func()
                    self._listenr_remove_func = None
                    _LOGGER.debug('state change listener removed')

            """Register callback function for state change tracking"""
            if not self._listenr_remove_func is None:
                self._listenr_remove_func()
            self._listenr_remove_func = async_track_state_change(self.hass, self.entity_id, send_turn_off_notification, to_state=STATE_OFF)
            _LOGGER.debug('turned off notification registered to ' + notify_service)

        yield from self.async_update_ha_state() 
开发者ID:TomerFi,项目名称:home-assistant-custom-components,代码行数:40,代码来源:switch.py

示例13: get

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def get(self, request):  # pylint: disable=no-self-use
        """Finish OAuth callback request."""
        hass = request.app['hass']
        params = request.query
        response = web.HTTPFound('/states')

        if 'state' not in params or 'code' not in params:
            if 'error' in params:
                _LOGGER.error(
                    "Error authorizing Automatic: %s", params['error'])
                return response
            _LOGGER.error(
                "Error authorizing Automatic. Invalid response returned")
            return response

        if DATA_CONFIGURING not in hass.data or \
                params['state'] not in hass.data[DATA_CONFIGURING]:
            _LOGGER.error("Automatic configuration request not found")
            return response

        code = params['code']
        state = params['state']
        account = hass.data[DATA_CONFIGURING][state]
        hass.async_create_task(account.initialize_callback(code, state))

        return response 
开发者ID:Teagan42,项目名称:HomeAssistantConfig,代码行数:28,代码来源:device_tracker.py

示例14: update

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def update(self, time):
        """ queue step forward and refresh timer display. 
            define callback to run in main thread.
        """
        self._queue.next()  # queue handler
        # refresh timer display when task is running
        if self.get_state(self._ui[UI_SWITCH]) == 'on':
            entity_id = self._entity_id
            if entity_id is None:
                _LOGGER.info("Function task: friendly_name(%s) not found in dic !", entity_id)
                return
            task = self._get_task(entity_id)
            remaining_time = self._queue.get_remaining_time(task['handle'])
            # task finish
            if remaining_time is None:
                remaining_time = task['remaining']
                if remaining_time == '0:00:00':
                    self.set_state(self._ui[UI_INPUT_DURATION], state = task['duration'])
                else:
                    self.set_state(self._ui[UI_INPUT_DURATION], state = str(remaining_time))
                self.set_state(self._ui[UI_SWITCH], state = 'off', context = CONTEXT_IGNORE)
            # task waite
            else:
                self.set_state(self._ui[UI_INPUT_DURATION], state = str(remaining_time))

    # @asyncio.coroutine 
开发者ID:cnk700i,项目名称:common_timer,代码行数:28,代码来源:__init__.py

示例15: insert

# 需要导入模块: from homeassistant import core [as 别名]
# 或者: from homeassistant.core import callback [as 别名]
def insert(self, task_id, duration, callback, operation = 'turn_off', **kwargs):
        """ add new task into queue """
        if duration == "0:00:00":
            return None
        second = time_period_str(duration).total_seconds()
        loop = second / len(self.__queue)
        slot = (second + self.__current_slot - 1) % len(self.__queue)
        delayQueueTask = DelayQueueTask(task_id, operation, int(slot), loop, callback, kwargs = kwargs)
        self.__queue[delayQueueTask.slot].append(delayQueueTask)
        _LOGGER.debug("create task:{}/{}".format(delayQueueTask.slot, delayQueueTask.loop))
        return delayQueueTask 
开发者ID:cnk700i,项目名称:common_timer,代码行数:13,代码来源:__init__.py


注:本文中的homeassistant.core.callback方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。