Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
sequence
start_point
sequence
end_point
sequence
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
ZerprocLight.async_added_to_hass
(self)
Run when entity about to be added to hass.
Run when entity about to be added to hass.
async def async_added_to_hass(self) -> None: """Run when entity about to be added to hass.""" self.async_on_remove( self.hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, self.on_hass_shutdown ) )
[ "async", "def", "async_added_to_hass", "(", "self", ")", "->", "None", ":", "self", ".", "async_on_remove", "(", "self", ".", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "self", ".", "on_hass_shutdown", ")", ")" ]
[ 109, 4 ]
[ 115, 9 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.async_will_remove_from_hass
(self)
Run when entity will be removed from hass.
Run when entity will be removed from hass.
async def async_will_remove_from_hass(self) -> None: """Run when entity will be removed from hass.""" await self.hass.async_add_executor_job(self._light.disconnect)
[ "async", "def", "async_will_remove_from_hass", "(", "self", ")", "->", "None", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "_light", ".", "disconnect", ")" ]
[ 117, 4 ]
[ 119, 70 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.on_hass_shutdown
(self, event)
Execute when Home Assistant is shutting down.
Execute when Home Assistant is shutting down.
def on_hass_shutdown(self, event): """Execute when Home Assistant is shutting down.""" self._light.disconnect()
[ "def", "on_hass_shutdown", "(", "self", ",", "event", ")", ":", "self", ".", "_light", ".", "disconnect", "(", ")" ]
[ 121, 4 ]
[ 123, 32 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.name
(self)
Return the display name of this light.
Return the display name of this light.
def name(self): """Return the display name of this light.""" return self._light.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_light", ".", "name" ]
[ 126, 4 ]
[ 128, 31 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.unique_id
(self)
Return the ID of this light.
Return the ID of this light.
def unique_id(self): """Return the ID of this light.""" return self._light.address
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_light", ".", "address" ]
[ 131, 4 ]
[ 133, 34 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.device_info
(self)
Device info for this light.
Device info for this light.
def device_info(self): """Device info for this light.""" return { "identifiers": {(DOMAIN, self.unique_id)}, "name": self.name, "manufacturer": "Zerproc", }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "unique_id", ")", "}", ",", "\"name\"", ":", "self", ".", "name", ",", "\"manufacturer\"", ":", "\"Zerproc\"", ",", "}" ]
[ 136, 4 ]
[ 142, 9 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.icon
(self)
Return the icon to use in the frontend.
Return the icon to use in the frontend.
def icon(self) -> Optional[str]: """Return the icon to use in the frontend.""" return "mdi:string-lights"
[ "def", "icon", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "\"mdi:string-lights\"" ]
[ 145, 4 ]
[ 147, 34 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" return SUPPORT_ZERPROC
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_ZERPROC" ]
[ 150, 4 ]
[ 152, 30 ]
python
en
['da', 'en', 'en']
True
ZerprocLight.brightness
(self)
Return the brightness of the light.
Return the brightness of the light.
def brightness(self): """Return the brightness of the light.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 155, 4 ]
[ 157, 31 ]
python
en
['en', 'no', 'en']
True
ZerprocLight.hs_color
(self)
Return the hs color.
Return the hs color.
def hs_color(self): """Return the hs color.""" return self._hs_color
[ "def", "hs_color", "(", "self", ")", ":", "return", "self", ".", "_hs_color" ]
[ 160, 4 ]
[ 162, 29 ]
python
en
['en', 'fr', 'en']
True
ZerprocLight.is_on
(self)
Return true if light is on.
Return true if light is on.
def is_on(self): """Return true if light is on.""" return self._is_on
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_is_on" ]
[ 165, 4 ]
[ 167, 26 ]
python
en
['en', 'et', 'en']
True
ZerprocLight.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self) -> bool: """Return True if entity is available.""" return self._available
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_available" ]
[ 170, 4 ]
[ 172, 30 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.turn_on
(self, **kwargs)
Instruct the light to turn on.
Instruct the light to turn on.
def turn_on(self, **kwargs): """Instruct the light to turn on.""" if ATTR_BRIGHTNESS in kwargs or ATTR_HS_COLOR in kwargs: default_hs = (0, 0) if self._hs_color is None else self._hs_color hue_sat = kwargs.get(ATTR_HS_COLOR, default_hs) default_brightness = 255 if self._brightness is None else self._brightness brightness = kwargs.get(ATTR_BRIGHTNESS, default_brightness) rgb = color_util.color_hsv_to_RGB(*hue_sat, brightness / 255 * 100) self._light.set_color(*rgb) else: self._light.turn_on()
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "ATTR_BRIGHTNESS", "in", "kwargs", "or", "ATTR_HS_COLOR", "in", "kwargs", ":", "default_hs", "=", "(", "0", ",", "0", ")", "if", "self", ".", "_hs_color", "is", "None", "else", "self", ".", "_hs_color", "hue_sat", "=", "kwargs", ".", "get", "(", "ATTR_HS_COLOR", ",", "default_hs", ")", "default_brightness", "=", "255", "if", "self", ".", "_brightness", "is", "None", "else", "self", ".", "_brightness", "brightness", "=", "kwargs", ".", "get", "(", "ATTR_BRIGHTNESS", ",", "default_brightness", ")", "rgb", "=", "color_util", ".", "color_hsv_to_RGB", "(", "*", "hue_sat", ",", "brightness", "/", "255", "*", "100", ")", "self", ".", "_light", ".", "set_color", "(", "*", "rgb", ")", "else", ":", "self", ".", "_light", ".", "turn_on", "(", ")" ]
[ 174, 4 ]
[ 186, 33 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.turn_off
(self, **kwargs)
Instruct the light to turn off.
Instruct the light to turn off.
def turn_off(self, **kwargs): """Instruct the light to turn off.""" self._light.turn_off()
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_light", ".", "turn_off", "(", ")" ]
[ 188, 4 ]
[ 190, 30 ]
python
en
['en', 'en', 'en']
True
ZerprocLight.update
(self)
Fetch new state data for this light.
Fetch new state data for this light.
def update(self): """Fetch new state data for this light.""" try: state = self._light.get_state() except pyzerproc.ZerprocException: if self._available: _LOGGER.warning("Unable to connect to %s", self.entity_id) self._available = False return if self._available is False: _LOGGER.info("Reconnected to %s", self.entity_id) self._available = True self._is_on = state.is_on hsv = color_util.color_RGB_to_hsv(*state.color) self._hs_color = hsv[:2] self._brightness = int(round((hsv[2] / 100) * 255))
[ "def", "update", "(", "self", ")", ":", "try", ":", "state", "=", "self", ".", "_light", ".", "get_state", "(", ")", "except", "pyzerproc", ".", "ZerprocException", ":", "if", "self", ".", "_available", ":", "_LOGGER", ".", "warning", "(", "\"Unable to connect to %s\"", ",", "self", ".", "entity_id", ")", "self", ".", "_available", "=", "False", "return", "if", "self", ".", "_available", "is", "False", ":", "_LOGGER", ".", "info", "(", "\"Reconnected to %s\"", ",", "self", ".", "entity_id", ")", "self", ".", "_available", "=", "True", "self", ".", "_is_on", "=", "state", ".", "is_on", "hsv", "=", "color_util", ".", "color_RGB_to_hsv", "(", "*", "state", ".", "color", ")", "self", ".", "_hs_color", "=", "hsv", "[", ":", "2", "]", "self", ".", "_brightness", "=", "int", "(", "round", "(", "(", "hsv", "[", "2", "]", "/", "100", ")", "*", "255", ")", ")" ]
[ 192, 4 ]
[ 207, 59 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up Abode integration.
Set up Abode integration.
async def async_setup(hass, config): """Set up Abode integration.""" if DOMAIN not in config: return True conf = config[DOMAIN] hass.async_create_task( hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=deepcopy(conf) ) ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "if", "DOMAIN", "not", "in", "config", ":", "return", "True", "conf", "=", "config", "[", "DOMAIN", "]", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_IMPORT", "}", ",", "data", "=", "deepcopy", "(", "conf", ")", ")", ")", "return", "True" ]
[ 91, 0 ]
[ 104, 15 ]
python
en
['en', 'da', 'en']
True
async_setup_entry
(hass, config_entry)
Set up Abode integration from a config entry.
Set up Abode integration from a config entry.
async def async_setup_entry(hass, config_entry): """Set up Abode integration from a config entry.""" username = config_entry.data.get(CONF_USERNAME) password = config_entry.data.get(CONF_PASSWORD) polling = config_entry.data.get(CONF_POLLING) try: cache = hass.config.path(DEFAULT_CACHEDB) abode = await hass.async_add_executor_job( Abode, username, password, True, True, True, cache ) hass.data[DOMAIN] = AbodeSystem(abode, polling) except (AbodeException, ConnectTimeout, HTTPError) as ex: LOGGER.error("Unable to connect to Abode: %s", str(ex)) raise ConfigEntryNotReady from ex for platform in ABODE_PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(config_entry, platform) ) await setup_hass_events(hass) await hass.async_add_executor_job(setup_hass_services, hass) await hass.async_add_executor_job(setup_abode_events, hass) return True
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ")", ":", "username", "=", "config_entry", ".", "data", ".", "get", "(", "CONF_USERNAME", ")", "password", "=", "config_entry", ".", "data", ".", "get", "(", "CONF_PASSWORD", ")", "polling", "=", "config_entry", ".", "data", ".", "get", "(", "CONF_POLLING", ")", "try", ":", "cache", "=", "hass", ".", "config", ".", "path", "(", "DEFAULT_CACHEDB", ")", "abode", "=", "await", "hass", ".", "async_add_executor_job", "(", "Abode", ",", "username", ",", "password", ",", "True", ",", "True", ",", "True", ",", "cache", ")", "hass", ".", "data", "[", "DOMAIN", "]", "=", "AbodeSystem", "(", "abode", ",", "polling", ")", "except", "(", "AbodeException", ",", "ConnectTimeout", ",", "HTTPError", ")", "as", "ex", ":", "LOGGER", ".", "error", "(", "\"Unable to connect to Abode: %s\"", ",", "str", "(", "ex", ")", ")", "raise", "ConfigEntryNotReady", "from", "ex", "for", "platform", "in", "ABODE_PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "config_entry", ",", "platform", ")", ")", "await", "setup_hass_events", "(", "hass", ")", "await", "hass", ".", "async_add_executor_job", "(", "setup_hass_services", ",", "hass", ")", "await", "hass", ".", "async_add_executor_job", "(", "setup_abode_events", ",", "hass", ")", "return", "True" ]
[ 107, 0 ]
[ 133, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass, config_entry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass, config_entry): """Unload a config entry.""" hass.services.async_remove(DOMAIN, SERVICE_SETTINGS) hass.services.async_remove(DOMAIN, SERVICE_CAPTURE_IMAGE) hass.services.async_remove(DOMAIN, SERVICE_TRIGGER_AUTOMATION) tasks = [] for platform in ABODE_PLATFORMS: tasks.append( hass.config_entries.async_forward_entry_unload(config_entry, platform) ) await gather(*tasks) await hass.async_add_executor_job(hass.data[DOMAIN].abode.events.stop) await hass.async_add_executor_job(hass.data[DOMAIN].abode.logout) hass.data[DOMAIN].logout_listener() hass.data.pop(DOMAIN) return True
[ "async", "def", "async_unload_entry", "(", "hass", ",", "config_entry", ")", ":", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "SERVICE_SETTINGS", ")", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "SERVICE_CAPTURE_IMAGE", ")", "hass", ".", "services", ".", "async_remove", "(", "DOMAIN", ",", "SERVICE_TRIGGER_AUTOMATION", ")", "tasks", "=", "[", "]", "for", "platform", "in", "ABODE_PLATFORMS", ":", "tasks", ".", "append", "(", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "config_entry", ",", "platform", ")", ")", "await", "gather", "(", "*", "tasks", ")", "await", "hass", ".", "async_add_executor_job", "(", "hass", ".", "data", "[", "DOMAIN", "]", ".", "abode", ".", "events", ".", "stop", ")", "await", "hass", ".", "async_add_executor_job", "(", "hass", ".", "data", "[", "DOMAIN", "]", ".", "abode", ".", "logout", ")", "hass", ".", "data", "[", "DOMAIN", "]", ".", "logout_listener", "(", ")", "hass", ".", "data", ".", "pop", "(", "DOMAIN", ")", "return", "True" ]
[ 136, 0 ]
[ 157, 15 ]
python
en
['en', 'es', 'en']
True
setup_hass_services
(hass)
Home Assistant services.
Home Assistant services.
def setup_hass_services(hass): """Home Assistant services.""" def change_setting(call): """Change an Abode system setting.""" setting = call.data.get(ATTR_SETTING) value = call.data.get(ATTR_VALUE) try: hass.data[DOMAIN].abode.set_setting(setting, value) except AbodeException as ex: LOGGER.warning(ex) def capture_image(call): """Capture a new image.""" entity_ids = call.data.get(ATTR_ENTITY_ID) target_entities = [ entity_id for entity_id in hass.data[DOMAIN].entity_ids if entity_id in entity_ids ] for entity_id in target_entities: signal = f"abode_camera_capture_{entity_id}" dispatcher_send(hass, signal) def trigger_automation(call): """Trigger an Abode automation.""" entity_ids = call.data.get(ATTR_ENTITY_ID) target_entities = [ entity_id for entity_id in hass.data[DOMAIN].entity_ids if entity_id in entity_ids ] for entity_id in target_entities: signal = f"abode_trigger_automation_{entity_id}" dispatcher_send(hass, signal) hass.services.register( DOMAIN, SERVICE_SETTINGS, change_setting, schema=CHANGE_SETTING_SCHEMA ) hass.services.register( DOMAIN, SERVICE_CAPTURE_IMAGE, capture_image, schema=CAPTURE_IMAGE_SCHEMA ) hass.services.register( DOMAIN, SERVICE_TRIGGER_AUTOMATION, trigger_automation, schema=AUTOMATION_SCHEMA )
[ "def", "setup_hass_services", "(", "hass", ")", ":", "def", "change_setting", "(", "call", ")", ":", "\"\"\"Change an Abode system setting.\"\"\"", "setting", "=", "call", ".", "data", ".", "get", "(", "ATTR_SETTING", ")", "value", "=", "call", ".", "data", ".", "get", "(", "ATTR_VALUE", ")", "try", ":", "hass", ".", "data", "[", "DOMAIN", "]", ".", "abode", ".", "set_setting", "(", "setting", ",", "value", ")", "except", "AbodeException", "as", "ex", ":", "LOGGER", ".", "warning", "(", "ex", ")", "def", "capture_image", "(", "call", ")", ":", "\"\"\"Capture a new image.\"\"\"", "entity_ids", "=", "call", ".", "data", ".", "get", "(", "ATTR_ENTITY_ID", ")", "target_entities", "=", "[", "entity_id", "for", "entity_id", "in", "hass", ".", "data", "[", "DOMAIN", "]", ".", "entity_ids", "if", "entity_id", "in", "entity_ids", "]", "for", "entity_id", "in", "target_entities", ":", "signal", "=", "f\"abode_camera_capture_{entity_id}\"", "dispatcher_send", "(", "hass", ",", "signal", ")", "def", "trigger_automation", "(", "call", ")", ":", "\"\"\"Trigger an Abode automation.\"\"\"", "entity_ids", "=", "call", ".", "data", ".", "get", "(", "ATTR_ENTITY_ID", ")", "target_entities", "=", "[", "entity_id", "for", "entity_id", "in", "hass", ".", "data", "[", "DOMAIN", "]", ".", "entity_ids", "if", "entity_id", "in", "entity_ids", "]", "for", "entity_id", "in", "target_entities", ":", "signal", "=", "f\"abode_trigger_automation_{entity_id}\"", "dispatcher_send", "(", "hass", ",", "signal", ")", "hass", ".", "services", ".", "register", "(", "DOMAIN", ",", "SERVICE_SETTINGS", ",", "change_setting", ",", "schema", "=", "CHANGE_SETTING_SCHEMA", ")", "hass", ".", "services", ".", "register", "(", "DOMAIN", ",", "SERVICE_CAPTURE_IMAGE", ",", "capture_image", ",", "schema", "=", "CAPTURE_IMAGE_SCHEMA", ")", "hass", ".", "services", ".", "register", "(", "DOMAIN", ",", "SERVICE_TRIGGER_AUTOMATION", ",", "trigger_automation", ",", "schema", "=", "AUTOMATION_SCHEMA", ")" ]
[ 160, 0 ]
[ 211, 5 ]
python
en
['fr', 'en', 'en']
True
setup_hass_events
(hass)
Home Assistant start and stop callbacks.
Home Assistant start and stop callbacks.
async def setup_hass_events(hass): """Home Assistant start and stop callbacks.""" def logout(event): """Logout of Abode.""" if not hass.data[DOMAIN].polling: hass.data[DOMAIN].abode.events.stop() hass.data[DOMAIN].abode.logout() LOGGER.info("Logged out of Abode") if not hass.data[DOMAIN].polling: await hass.async_add_executor_job(hass.data[DOMAIN].abode.events.start) hass.data[DOMAIN].logout_listener = hass.bus.async_listen_once( EVENT_HOMEASSISTANT_STOP, logout )
[ "async", "def", "setup_hass_events", "(", "hass", ")", ":", "def", "logout", "(", "event", ")", ":", "\"\"\"Logout of Abode.\"\"\"", "if", "not", "hass", ".", "data", "[", "DOMAIN", "]", ".", "polling", ":", "hass", ".", "data", "[", "DOMAIN", "]", ".", "abode", ".", "events", ".", "stop", "(", ")", "hass", ".", "data", "[", "DOMAIN", "]", ".", "abode", ".", "logout", "(", ")", "LOGGER", ".", "info", "(", "\"Logged out of Abode\"", ")", "if", "not", "hass", ".", "data", "[", "DOMAIN", "]", ".", "polling", ":", "await", "hass", ".", "async_add_executor_job", "(", "hass", ".", "data", "[", "DOMAIN", "]", ".", "abode", ".", "events", ".", "start", ")", "hass", ".", "data", "[", "DOMAIN", "]", ".", "logout_listener", "=", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "logout", ")" ]
[ 214, 0 ]
[ 230, 5 ]
python
en
['en', 'en', 'en']
True
setup_abode_events
(hass)
Event callbacks.
Event callbacks.
def setup_abode_events(hass): """Event callbacks.""" def event_callback(event, event_json): """Handle an event callback from Abode.""" data = { ATTR_DEVICE_ID: event_json.get(ATTR_DEVICE_ID, ""), ATTR_DEVICE_NAME: event_json.get(ATTR_DEVICE_NAME, ""), ATTR_DEVICE_TYPE: event_json.get(ATTR_DEVICE_TYPE, ""), ATTR_EVENT_CODE: event_json.get(ATTR_EVENT_CODE, ""), ATTR_EVENT_NAME: event_json.get(ATTR_EVENT_NAME, ""), ATTR_EVENT_TYPE: event_json.get(ATTR_EVENT_TYPE, ""), ATTR_EVENT_UTC: event_json.get(ATTR_EVENT_UTC, ""), ATTR_USER_NAME: event_json.get(ATTR_USER_NAME, ""), ATTR_APP_TYPE: event_json.get(ATTR_APP_TYPE, ""), ATTR_EVENT_BY: event_json.get(ATTR_EVENT_BY, ""), ATTR_DATE: event_json.get(ATTR_DATE, ""), ATTR_TIME: event_json.get(ATTR_TIME, ""), } hass.bus.fire(event, data) events = [ TIMELINE.ALARM_GROUP, TIMELINE.ALARM_END_GROUP, TIMELINE.PANEL_FAULT_GROUP, TIMELINE.PANEL_RESTORE_GROUP, TIMELINE.AUTOMATION_GROUP, TIMELINE.DISARM_GROUP, TIMELINE.ARM_GROUP, TIMELINE.ARM_FAULT_GROUP, TIMELINE.TEST_GROUP, TIMELINE.CAPTURE_GROUP, TIMELINE.DEVICE_GROUP, ] for event in events: hass.data[DOMAIN].abode.events.add_event_callback( event, partial(event_callback, event) )
[ "def", "setup_abode_events", "(", "hass", ")", ":", "def", "event_callback", "(", "event", ",", "event_json", ")", ":", "\"\"\"Handle an event callback from Abode.\"\"\"", "data", "=", "{", "ATTR_DEVICE_ID", ":", "event_json", ".", "get", "(", "ATTR_DEVICE_ID", ",", "\"\"", ")", ",", "ATTR_DEVICE_NAME", ":", "event_json", ".", "get", "(", "ATTR_DEVICE_NAME", ",", "\"\"", ")", ",", "ATTR_DEVICE_TYPE", ":", "event_json", ".", "get", "(", "ATTR_DEVICE_TYPE", ",", "\"\"", ")", ",", "ATTR_EVENT_CODE", ":", "event_json", ".", "get", "(", "ATTR_EVENT_CODE", ",", "\"\"", ")", ",", "ATTR_EVENT_NAME", ":", "event_json", ".", "get", "(", "ATTR_EVENT_NAME", ",", "\"\"", ")", ",", "ATTR_EVENT_TYPE", ":", "event_json", ".", "get", "(", "ATTR_EVENT_TYPE", ",", "\"\"", ")", ",", "ATTR_EVENT_UTC", ":", "event_json", ".", "get", "(", "ATTR_EVENT_UTC", ",", "\"\"", ")", ",", "ATTR_USER_NAME", ":", "event_json", ".", "get", "(", "ATTR_USER_NAME", ",", "\"\"", ")", ",", "ATTR_APP_TYPE", ":", "event_json", ".", "get", "(", "ATTR_APP_TYPE", ",", "\"\"", ")", ",", "ATTR_EVENT_BY", ":", "event_json", ".", "get", "(", "ATTR_EVENT_BY", ",", "\"\"", ")", ",", "ATTR_DATE", ":", "event_json", ".", "get", "(", "ATTR_DATE", ",", "\"\"", ")", ",", "ATTR_TIME", ":", "event_json", ".", "get", "(", "ATTR_TIME", ",", "\"\"", ")", ",", "}", "hass", ".", "bus", ".", "fire", "(", "event", ",", "data", ")", "events", "=", "[", "TIMELINE", ".", "ALARM_GROUP", ",", "TIMELINE", ".", "ALARM_END_GROUP", ",", "TIMELINE", ".", "PANEL_FAULT_GROUP", ",", "TIMELINE", ".", "PANEL_RESTORE_GROUP", ",", "TIMELINE", ".", "AUTOMATION_GROUP", ",", "TIMELINE", ".", "DISARM_GROUP", ",", "TIMELINE", ".", "ARM_GROUP", ",", "TIMELINE", ".", "ARM_FAULT_GROUP", ",", "TIMELINE", ".", "TEST_GROUP", ",", "TIMELINE", ".", "CAPTURE_GROUP", ",", "TIMELINE", ".", "DEVICE_GROUP", ",", "]", "for", "event", "in", "events", ":", "hass", ".", "data", "[", "DOMAIN", "]", ".", "abode", ".", "events", ".", "add_event_callback", "(", "event", ",", "partial", "(", "event_callback", ",", "event", ")", ")" ]
[ 233, 0 ]
[ 272, 9 ]
python
en
['en', 'bs', 'en']
False
AbodeSystem.__init__
(self, abode, polling)
Initialize the system.
Initialize the system.
def __init__(self, abode, polling): """Initialize the system.""" self.abode = abode self.polling = polling self.entity_ids = set() self.logout_listener = None
[ "def", "__init__", "(", "self", ",", "abode", ",", "polling", ")", ":", "self", ".", "abode", "=", "abode", "self", ".", "polling", "=", "polling", "self", ".", "entity_ids", "=", "set", "(", ")", "self", ".", "logout_listener", "=", "None" ]
[ 83, 4 ]
[ 88, 35 ]
python
en
['en', 'en', 'en']
True
AbodeEntity.__init__
(self, data)
Initialize Abode entity.
Initialize Abode entity.
def __init__(self, data): """Initialize Abode entity.""" self._data = data self._available = True
[ "def", "__init__", "(", "self", ",", "data", ")", ":", "self", ".", "_data", "=", "data", "self", ".", "_available", "=", "True" ]
[ 278, 4 ]
[ 281, 30 ]
python
es
['es', 'zu', 'it']
False
AbodeEntity.available
(self)
Return the available state.
Return the available state.
def available(self): """Return the available state.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
[ 284, 4 ]
[ 286, 30 ]
python
en
['en', 'en', 'en']
True
AbodeEntity.should_poll
(self)
Return the polling state.
Return the polling state.
def should_poll(self): """Return the polling state.""" return self._data.polling
[ "def", "should_poll", "(", "self", ")", ":", "return", "self", ".", "_data", ".", "polling" ]
[ 289, 4 ]
[ 291, 33 ]
python
en
['en', 'en', 'en']
True
AbodeEntity.async_added_to_hass
(self)
Subscribe to Abode connection status updates.
Subscribe to Abode connection status updates.
async def async_added_to_hass(self): """Subscribe to Abode connection status updates.""" await self.hass.async_add_executor_job( self._data.abode.events.add_connection_status_callback, self.unique_id, self._update_connection_status, ) self.hass.data[DOMAIN].entity_ids.add(self.entity_id)
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "_data", ".", "abode", ".", "events", ".", "add_connection_status_callback", ",", "self", ".", "unique_id", ",", "self", ".", "_update_connection_status", ",", ")", "self", ".", "hass", ".", "data", "[", "DOMAIN", "]", ".", "entity_ids", ".", "add", "(", "self", ".", "entity_id", ")" ]
[ 293, 4 ]
[ 301, 61 ]
python
en
['en', 'en', 'en']
True
AbodeEntity.async_will_remove_from_hass
(self)
Unsubscribe from Abode connection status updates.
Unsubscribe from Abode connection status updates.
async def async_will_remove_from_hass(self): """Unsubscribe from Abode connection status updates.""" await self.hass.async_add_executor_job( self._data.abode.events.remove_connection_status_callback, self.unique_id )
[ "async", "def", "async_will_remove_from_hass", "(", "self", ")", ":", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "_data", ".", "abode", ".", "events", ".", "remove_connection_status_callback", ",", "self", ".", "unique_id", ")" ]
[ 303, 4 ]
[ 307, 9 ]
python
en
['en', 'en', 'en']
True
AbodeEntity._update_connection_status
(self)
Update the entity available property.
Update the entity available property.
def _update_connection_status(self): """Update the entity available property.""" self._available = self._data.abode.events.connected self.schedule_update_ha_state()
[ "def", "_update_connection_status", "(", "self", ")", ":", "self", ".", "_available", "=", "self", ".", "_data", ".", "abode", ".", "events", ".", "connected", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 309, 4 ]
[ 312, 39 ]
python
en
['en', 'en', 'en']
True
AbodeDevice.__init__
(self, data, device)
Initialize Abode device.
Initialize Abode device.
def __init__(self, data, device): """Initialize Abode device.""" super().__init__(data) self._device = device
[ "def", "__init__", "(", "self", ",", "data", ",", "device", ")", ":", "super", "(", ")", ".", "__init__", "(", "data", ")", "self", ".", "_device", "=", "device" ]
[ 318, 4 ]
[ 321, 29 ]
python
en
['fr', 'en', 'it']
False
AbodeDevice.async_added_to_hass
(self)
Subscribe to device events.
Subscribe to device events.
async def async_added_to_hass(self): """Subscribe to device events.""" await super().async_added_to_hass() await self.hass.async_add_executor_job( self._data.abode.events.add_device_callback, self._device.device_id, self._update_callback, )
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_added_to_hass", "(", ")", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "_data", ".", "abode", ".", "events", ".", "add_device_callback", ",", "self", ".", "_device", ".", "device_id", ",", "self", ".", "_update_callback", ",", ")" ]
[ 323, 4 ]
[ 330, 9 ]
python
en
['it', 'en', 'en']
True
AbodeDevice.async_will_remove_from_hass
(self)
Unsubscribe from device events.
Unsubscribe from device events.
async def async_will_remove_from_hass(self): """Unsubscribe from device events.""" await super().async_will_remove_from_hass() await self.hass.async_add_executor_job( self._data.abode.events.remove_all_device_callbacks, self._device.device_id )
[ "async", "def", "async_will_remove_from_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_will_remove_from_hass", "(", ")", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "_data", ".", "abode", ".", "events", ".", "remove_all_device_callbacks", ",", "self", ".", "_device", ".", "device_id", ")" ]
[ 332, 4 ]
[ 337, 9 ]
python
en
['en', 'en', 'en']
True
AbodeDevice.update
(self)
Update device state.
Update device state.
def update(self): """Update device state.""" self._device.refresh()
[ "def", "update", "(", "self", ")", ":", "self", ".", "_device", ".", "refresh", "(", ")" ]
[ 339, 4 ]
[ 341, 30 ]
python
en
['fr', 'en', 'en']
True
AbodeDevice.name
(self)
Return the name of the device.
Return the name of the device.
def name(self): """Return the name of the device.""" return self._device.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "name" ]
[ 344, 4 ]
[ 346, 32 ]
python
en
['en', 'en', 'en']
True
AbodeDevice.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, "device_id": self._device.device_id, "battery_low": self._device.battery_low, "no_response": self._device.no_response, "device_type": self._device.type, }
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "\"device_id\"", ":", "self", ".", "_device", ".", "device_id", ",", "\"battery_low\"", ":", "self", ".", "_device", ".", "battery_low", ",", "\"no_response\"", ":", "self", ".", "_device", ".", "no_response", ",", "\"device_type\"", ":", "self", ".", "_device", ".", "type", ",", "}" ]
[ 349, 4 ]
[ 357, 9 ]
python
en
['en', 'en', 'en']
True
AbodeDevice.unique_id
(self)
Return a unique ID to use for this device.
Return a unique ID to use for this device.
def unique_id(self): """Return a unique ID to use for this device.""" return self._device.device_uuid
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "device_uuid" ]
[ 360, 4 ]
[ 362, 39 ]
python
en
['en', 'en', 'en']
True
AbodeDevice.device_info
(self)
Return device registry information for this entity.
Return device registry information for this entity.
def device_info(self): """Return device registry information for this entity.""" return { "identifiers": {(DOMAIN, self._device.device_id)}, "manufacturer": "Abode", "name": self._device.name, "device_type": self._device.type, }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "_device", ".", "device_id", ")", "}", ",", "\"manufacturer\"", ":", "\"Abode\"", ",", "\"name\"", ":", "self", ".", "_device", ".", "name", ",", "\"device_type\"", ":", "self", ".", "_device", ".", "type", ",", "}" ]
[ 365, 4 ]
[ 372, 9 ]
python
en
['en', 'en', 'en']
True
AbodeDevice._update_callback
(self, device)
Update the device state.
Update the device state.
def _update_callback(self, device): """Update the device state.""" self.schedule_update_ha_state()
[ "def", "_update_callback", "(", "self", ",", "device", ")", ":", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 374, 4 ]
[ 376, 39 ]
python
en
['en', 'en', 'en']
True
AbodeAutomation.__init__
(self, data, automation)
Initialize for Abode automation.
Initialize for Abode automation.
def __init__(self, data, automation): """Initialize for Abode automation.""" super().__init__(data) self._automation = automation
[ "def", "__init__", "(", "self", ",", "data", ",", "automation", ")", ":", "super", "(", ")", ".", "__init__", "(", "data", ")", "self", ".", "_automation", "=", "automation" ]
[ 382, 4 ]
[ 385, 37 ]
python
en
['en', 'en', 'en']
True
AbodeAutomation.update
(self)
Update automation state.
Update automation state.
def update(self): """Update automation state.""" self._automation.refresh()
[ "def", "update", "(", "self", ")", ":", "self", ".", "_automation", ".", "refresh", "(", ")" ]
[ 387, 4 ]
[ 389, 34 ]
python
en
['de', 'en', 'en']
True
AbodeAutomation.name
(self)
Return the name of the automation.
Return the name of the automation.
def name(self): """Return the name of the automation.""" return self._automation.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_automation", ".", "name" ]
[ 392, 4 ]
[ 394, 36 ]
python
en
['en', 'en', 'en']
True
AbodeAutomation.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: ATTRIBUTION, "type": "CUE automation"}
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "\"type\"", ":", "\"CUE automation\"", "}" ]
[ 397, 4 ]
[ 399, 72 ]
python
en
['en', 'en', 'en']
True
AbodeAutomation.unique_id
(self)
Return a unique ID to use for this automation.
Return a unique ID to use for this automation.
def unique_id(self): """Return a unique ID to use for this automation.""" return self._automation.automation_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_automation", ".", "automation_id" ]
[ 402, 4 ]
[ 404, 45 ]
python
en
['en', 'en', 'en']
True
test_platform_manually_configured
(hass)
Test that we do not discover anything or try to set up a gateway.
Test that we do not discover anything or try to set up a gateway.
async def test_platform_manually_configured(hass): """Test that we do not discover anything or try to set up a gateway.""" assert ( await async_setup_component( hass, LOCK_DOMAIN, {"lock": {"platform": DECONZ_DOMAIN}} ) is True ) assert DECONZ_DOMAIN not in hass.data
[ "async", "def", "test_platform_manually_configured", "(", "hass", ")", ":", "assert", "(", "await", "async_setup_component", "(", "hass", ",", "LOCK_DOMAIN", ",", "{", "\"lock\"", ":", "{", "\"platform\"", ":", "DECONZ_DOMAIN", "}", "}", ")", "is", "True", ")", "assert", "DECONZ_DOMAIN", "not", "in", "hass", ".", "data" ]
[ 35, 0 ]
[ 43, 41 ]
python
en
['en', 'en', 'en']
True
test_no_locks
(hass)
Test that no lock entities are created.
Test that no lock entities are created.
async def test_no_locks(hass): """Test that no lock entities are created.""" await setup_deconz_integration(hass) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_no_locks", "(", "hass", ")", ":", "await", "setup_deconz_integration", "(", "hass", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 46, 0 ]
[ 49, 44 ]
python
en
['en', 'en', 'en']
True
test_locks
(hass)
Test that all supported lock entities are created.
Test that all supported lock entities are created.
async def test_locks(hass): """Test that all supported lock entities are created.""" data = deepcopy(DECONZ_WEB_REQUEST) data["lights"] = deepcopy(LOCKS) config_entry = await setup_deconz_integration(hass, get_state_response=data) gateway = get_gateway_from_config_entry(hass, config_entry) assert len(hass.states.async_all()) == 1 assert hass.states.get("lock.door_lock").state == STATE_UNLOCKED door_lock = hass.states.get("lock.door_lock") assert door_lock.state == STATE_UNLOCKED state_changed_event = { "t": "event", "e": "changed", "r": "lights", "id": "1", "state": {"on": True}, } gateway.api.event_handler(state_changed_event) await hass.async_block_till_done() assert hass.states.get("lock.door_lock").state == STATE_LOCKED # Verify service calls door_lock_device = gateway.api.lights["1"] # Service lock door with patch.object(door_lock_device, "_request", return_value=True) as set_callback: await hass.services.async_call( LOCK_DOMAIN, SERVICE_LOCK, {ATTR_ENTITY_ID: "lock.door_lock"}, blocking=True, ) await hass.async_block_till_done() set_callback.assert_called_with("put", "/lights/1/state", json={"on": True}) # Service unlock door with patch.object(door_lock_device, "_request", return_value=True) as set_callback: await hass.services.async_call( LOCK_DOMAIN, SERVICE_UNLOCK, {ATTR_ENTITY_ID: "lock.door_lock"}, blocking=True, ) await hass.async_block_till_done() set_callback.assert_called_with("put", "/lights/1/state", json={"on": False}) await hass.config_entries.async_unload(config_entry.entry_id) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_locks", "(", "hass", ")", ":", "data", "=", "deepcopy", "(", "DECONZ_WEB_REQUEST", ")", "data", "[", "\"lights\"", "]", "=", "deepcopy", "(", "LOCKS", ")", "config_entry", "=", "await", "setup_deconz_integration", "(", "hass", ",", "get_state_response", "=", "data", ")", "gateway", "=", "get_gateway_from_config_entry", "(", "hass", ",", "config_entry", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "assert", "hass", ".", "states", ".", "get", "(", "\"lock.door_lock\"", ")", ".", "state", "==", "STATE_UNLOCKED", "door_lock", "=", "hass", ".", "states", ".", "get", "(", "\"lock.door_lock\"", ")", "assert", "door_lock", ".", "state", "==", "STATE_UNLOCKED", "state_changed_event", "=", "{", "\"t\"", ":", "\"event\"", ",", "\"e\"", ":", "\"changed\"", ",", "\"r\"", ":", "\"lights\"", ",", "\"id\"", ":", "\"1\"", ",", "\"state\"", ":", "{", "\"on\"", ":", "True", "}", ",", "}", "gateway", ".", "api", ".", "event_handler", "(", "state_changed_event", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "\"lock.door_lock\"", ")", ".", "state", "==", "STATE_LOCKED", "# Verify service calls", "door_lock_device", "=", "gateway", ".", "api", ".", "lights", "[", "\"1\"", "]", "# Service lock door", "with", "patch", ".", "object", "(", "door_lock_device", ",", "\"_request\"", ",", "return_value", "=", "True", ")", "as", "set_callback", ":", "await", "hass", ".", "services", ".", "async_call", "(", "LOCK_DOMAIN", ",", "SERVICE_LOCK", ",", "{", "ATTR_ENTITY_ID", ":", "\"lock.door_lock\"", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "set_callback", ".", "assert_called_with", "(", "\"put\"", ",", "\"/lights/1/state\"", ",", "json", "=", "{", "\"on\"", ":", "True", "}", ")", "# Service unlock door", "with", "patch", ".", "object", "(", "door_lock_device", ",", "\"_request\"", ",", "return_value", "=", "True", ")", "as", "set_callback", ":", "await", "hass", ".", "services", ".", "async_call", "(", "LOCK_DOMAIN", ",", "SERVICE_UNLOCK", ",", "{", "ATTR_ENTITY_ID", ":", "\"lock.door_lock\"", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "set_callback", ".", "assert_called_with", "(", "\"put\"", ",", "\"/lights/1/state\"", ",", "json", "=", "{", "\"on\"", ":", "False", "}", ")", "await", "hass", ".", "config_entries", ".", "async_unload", "(", "config_entry", ".", "entry_id", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 52, 0 ]
[ 107, 44 ]
python
en
['en', 'en', 'en']
True
mock_rflink
( hass, config, domain, monkeypatch, failures=None, failcommand=False )
Create mock RFLink asyncio protocol, test component setup.
Create mock RFLink asyncio protocol, test component setup.
async def mock_rflink( hass, config, domain, monkeypatch, failures=None, failcommand=False ): """Create mock RFLink asyncio protocol, test component setup.""" transport, protocol = (Mock(), Mock()) async def send_command_ack(*command): return not failcommand protocol.send_command_ack = Mock(wraps=send_command_ack) def send_command(*command): return not failcommand protocol.send_command = Mock(wraps=send_command) async def create_rflink_connection(*args, **kwargs): """Return mocked transport and protocol.""" # failures can be a list of booleans indicating in which sequence # creating a connection should success or fail if failures: fail = failures.pop() else: fail = False if fail: raise ConnectionRefusedError else: return transport, protocol mock_create = Mock(wraps=create_rflink_connection) monkeypatch.setattr( "homeassistant.components.rflink.create_rflink_connection", mock_create ) await async_setup_component(hass, "rflink", config) await async_setup_component(hass, domain, config) await hass.async_block_till_done() # hook into mock config for injecting events event_callback = mock_create.call_args_list[0][1]["event_callback"] assert event_callback disconnect_callback = mock_create.call_args_list[0][1]["disconnect_callback"] return event_callback, mock_create, protocol, disconnect_callback
[ "async", "def", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ",", "failures", "=", "None", ",", "failcommand", "=", "False", ")", ":", "transport", ",", "protocol", "=", "(", "Mock", "(", ")", ",", "Mock", "(", ")", ")", "async", "def", "send_command_ack", "(", "*", "command", ")", ":", "return", "not", "failcommand", "protocol", ".", "send_command_ack", "=", "Mock", "(", "wraps", "=", "send_command_ack", ")", "def", "send_command", "(", "*", "command", ")", ":", "return", "not", "failcommand", "protocol", ".", "send_command", "=", "Mock", "(", "wraps", "=", "send_command", ")", "async", "def", "create_rflink_connection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Return mocked transport and protocol.\"\"\"", "# failures can be a list of booleans indicating in which sequence", "# creating a connection should success or fail", "if", "failures", ":", "fail", "=", "failures", ".", "pop", "(", ")", "else", ":", "fail", "=", "False", "if", "fail", ":", "raise", "ConnectionRefusedError", "else", ":", "return", "transport", ",", "protocol", "mock_create", "=", "Mock", "(", "wraps", "=", "create_rflink_connection", ")", "monkeypatch", ".", "setattr", "(", "\"homeassistant.components.rflink.create_rflink_connection\"", ",", "mock_create", ")", "await", "async_setup_component", "(", "hass", ",", "\"rflink\"", ",", "config", ")", "await", "async_setup_component", "(", "hass", ",", "domain", ",", "config", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# hook into mock config for injecting events", "event_callback", "=", "mock_create", ".", "call_args_list", "[", "0", "]", "[", "1", "]", "[", "\"event_callback\"", "]", "assert", "event_callback", "disconnect_callback", "=", "mock_create", ".", "call_args_list", "[", "0", "]", "[", "1", "]", "[", "\"disconnect_callback\"", "]", "return", "event_callback", ",", "mock_create", ",", "protocol", ",", "disconnect_callback" ]
[ 20, 0 ]
[ 65, 69 ]
python
ceb
['es', 'ceb', 'en']
False
test_version_banner
(hass, monkeypatch)
Test sending unknown commands doesn't cause issues.
Test sending unknown commands doesn't cause issues.
async def test_version_banner(hass, monkeypatch): """Test sending unknown commands doesn't cause issues.""" # use sensor domain during testing main platform domain = "sensor" config = { "rflink": {"port": "/dev/ttyABC0"}, domain: { "platform": "rflink", "devices": {"test": {"name": "test", "sensor_type": "temperature"}}, }, } # setup mocking rflink module event_callback, _, _, _ = await mock_rflink(hass, config, domain, monkeypatch) event_callback( { "hardware": "Nodo RadioFrequencyLink", "firmware": "RFLink Gateway", "version": "1.1", "revision": "45", } )
[ "async", "def", "test_version_banner", "(", "hass", ",", "monkeypatch", ")", ":", "# use sensor domain during testing main platform", "domain", "=", "\"sensor\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", "}", ",", "domain", ":", "{", "\"platform\"", ":", "\"rflink\"", ",", "\"devices\"", ":", "{", "\"test\"", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"sensor_type\"", ":", "\"temperature\"", "}", "}", ",", "}", ",", "}", "# setup mocking rflink module", "event_callback", ",", "_", ",", "_", ",", "_", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ")", "event_callback", "(", "{", "\"hardware\"", ":", "\"Nodo RadioFrequencyLink\"", ",", "\"firmware\"", ":", "\"RFLink Gateway\"", ",", "\"version\"", ":", "\"1.1\"", ",", "\"revision\"", ":", "\"45\"", ",", "}", ")" ]
[ 68, 0 ]
[ 90, 5 ]
python
en
['en', 'en', 'en']
True
test_send_no_wait
(hass, monkeypatch)
Test command sending without ack.
Test command sending without ack.
async def test_send_no_wait(hass, monkeypatch): """Test command sending without ack.""" domain = "switch" config = { "rflink": {"port": "/dev/ttyABC0", "wait_for_ack": False}, domain: { "platform": "rflink", "devices": { "protocol_0_0": {"name": "test", "aliases": ["test_alias_0_0"]} }, }, } # setup mocking rflink module _, _, protocol, _ = await mock_rflink(hass, config, domain, monkeypatch) hass.async_create_task( hass.services.async_call( domain, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "switch.test"} ) ) await hass.async_block_till_done() assert protocol.send_command.call_args_list[0][0][0] == "protocol_0_0" assert protocol.send_command.call_args_list[0][0][1] == "off"
[ "async", "def", "test_send_no_wait", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"switch\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", ",", "\"wait_for_ack\"", ":", "False", "}", ",", "domain", ":", "{", "\"platform\"", ":", "\"rflink\"", ",", "\"devices\"", ":", "{", "\"protocol_0_0\"", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"aliases\"", ":", "[", "\"test_alias_0_0\"", "]", "}", "}", ",", "}", ",", "}", "# setup mocking rflink module", "_", ",", "_", ",", "protocol", ",", "_", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ")", "hass", ".", "async_create_task", "(", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_TURN_OFF", ",", "{", "ATTR_ENTITY_ID", ":", "\"switch.test\"", "}", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "protocol", ".", "send_command", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]", "==", "\"protocol_0_0\"", "assert", "protocol", ".", "send_command", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "1", "]", "==", "\"off\"" ]
[ 93, 0 ]
[ 116, 65 ]
python
en
['en', 'en', 'en']
True
test_cover_send_no_wait
(hass, monkeypatch)
Test command sending to a cover device without ack.
Test command sending to a cover device without ack.
async def test_cover_send_no_wait(hass, monkeypatch): """Test command sending to a cover device without ack.""" domain = "cover" config = { "rflink": {"port": "/dev/ttyABC0", "wait_for_ack": False}, domain: { "platform": "rflink", "devices": { "RTS_0100F2_0": {"name": "test", "aliases": ["test_alias_0_0"]} }, }, } # setup mocking rflink module _, _, protocol, _ = await mock_rflink(hass, config, domain, monkeypatch) hass.async_create_task( hass.services.async_call( domain, SERVICE_STOP_COVER, {ATTR_ENTITY_ID: "cover.test"} ) ) await hass.async_block_till_done() assert protocol.send_command.call_args_list[0][0][0] == "RTS_0100F2_0" assert protocol.send_command.call_args_list[0][0][1] == "STOP"
[ "async", "def", "test_cover_send_no_wait", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"cover\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", ",", "\"wait_for_ack\"", ":", "False", "}", ",", "domain", ":", "{", "\"platform\"", ":", "\"rflink\"", ",", "\"devices\"", ":", "{", "\"RTS_0100F2_0\"", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"aliases\"", ":", "[", "\"test_alias_0_0\"", "]", "}", "}", ",", "}", ",", "}", "# setup mocking rflink module", "_", ",", "_", ",", "protocol", ",", "_", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ")", "hass", ".", "async_create_task", "(", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_STOP_COVER", ",", "{", "ATTR_ENTITY_ID", ":", "\"cover.test\"", "}", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "protocol", ".", "send_command", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]", "==", "\"RTS_0100F2_0\"", "assert", "protocol", ".", "send_command", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "1", "]", "==", "\"STOP\"" ]
[ 119, 0 ]
[ 142, 66 ]
python
en
['en', 'en', 'en']
True
test_send_command
(hass, monkeypatch)
Test send_command service.
Test send_command service.
async def test_send_command(hass, monkeypatch): """Test send_command service.""" domain = "rflink" config = {"rflink": {"port": "/dev/ttyABC0"}} # setup mocking rflink module _, _, protocol, _ = await mock_rflink(hass, config, domain, monkeypatch) hass.async_create_task( hass.services.async_call( domain, SERVICE_SEND_COMMAND, {"device_id": "newkaku_0000c6c2_1", "command": "on"}, ) ) await hass.async_block_till_done() assert protocol.send_command_ack.call_args_list[0][0][0] == "newkaku_0000c6c2_1" assert protocol.send_command_ack.call_args_list[0][0][1] == "on"
[ "async", "def", "test_send_command", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"rflink\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", "}", "}", "# setup mocking rflink module", "_", ",", "_", ",", "protocol", ",", "_", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ")", "hass", ".", "async_create_task", "(", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_SEND_COMMAND", ",", "{", "\"device_id\"", ":", "\"newkaku_0000c6c2_1\"", ",", "\"command\"", ":", "\"on\"", "}", ",", ")", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "protocol", ".", "send_command_ack", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]", "==", "\"newkaku_0000c6c2_1\"", "assert", "protocol", ".", "send_command_ack", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "1", "]", "==", "\"on\"" ]
[ 145, 0 ]
[ 162, 68 ]
python
en
['en', 'fr', 'en']
True
test_send_command_invalid_arguments
(hass, monkeypatch)
Test send_command service.
Test send_command service.
async def test_send_command_invalid_arguments(hass, monkeypatch): """Test send_command service.""" domain = "rflink" config = {"rflink": {"port": "/dev/ttyABC0"}} # setup mocking rflink module _, _, protocol, _ = await mock_rflink(hass, config, domain, monkeypatch) # one argument missing with pytest.raises(MultipleInvalid): await hass.services.async_call(domain, SERVICE_SEND_COMMAND, {"command": "on"}) with pytest.raises(MultipleInvalid): await hass.services.async_call( domain, SERVICE_SEND_COMMAND, {"device_id": "newkaku_0000c6c2_1"} ) # no arguments with pytest.raises(MultipleInvalid): await hass.services.async_call(domain, SERVICE_SEND_COMMAND, {}) await hass.async_block_till_done() assert protocol.send_command_ack.call_args_list == [] # bad command (no_command) success = await hass.services.async_call( domain, SERVICE_SEND_COMMAND, {"device_id": "newkaku_0000c6c2_1", "command": "no_command"}, ) assert not success, "send command should not succeed for unknown command"
[ "async", "def", "test_send_command_invalid_arguments", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"rflink\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", "}", "}", "# setup mocking rflink module", "_", ",", "_", ",", "protocol", ",", "_", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ")", "# one argument missing", "with", "pytest", ".", "raises", "(", "MultipleInvalid", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_SEND_COMMAND", ",", "{", "\"command\"", ":", "\"on\"", "}", ")", "with", "pytest", ".", "raises", "(", "MultipleInvalid", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_SEND_COMMAND", ",", "{", "\"device_id\"", ":", "\"newkaku_0000c6c2_1\"", "}", ")", "# no arguments", "with", "pytest", ".", "raises", "(", "MultipleInvalid", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_SEND_COMMAND", ",", "{", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "protocol", ".", "send_command_ack", ".", "call_args_list", "==", "[", "]", "# bad command (no_command)", "success", "=", "await", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_SEND_COMMAND", ",", "{", "\"device_id\"", ":", "\"newkaku_0000c6c2_1\"", ",", "\"command\"", ":", "\"no_command\"", "}", ",", ")", "assert", "not", "success", ",", "\"send command should not succeed for unknown command\"" ]
[ 165, 0 ]
[ 195, 77 ]
python
en
['en', 'fr', 'en']
True
test_reconnecting_after_disconnect
(hass, monkeypatch)
An unexpected disconnect should cause a reconnect.
An unexpected disconnect should cause a reconnect.
async def test_reconnecting_after_disconnect(hass, monkeypatch): """An unexpected disconnect should cause a reconnect.""" domain = "sensor" config = { "rflink": {"port": "/dev/ttyABC0", CONF_RECONNECT_INTERVAL: 0}, domain: {"platform": "rflink"}, } # setup mocking rflink module _, mock_create, _, disconnect_callback = await mock_rflink( hass, config, domain, monkeypatch ) assert disconnect_callback, "disconnect callback not passed to rflink" # rflink initiated disconnect disconnect_callback(None) await hass.async_block_till_done() # we expect 2 call, the initial and reconnect assert mock_create.call_count == 2
[ "async", "def", "test_reconnecting_after_disconnect", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"sensor\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", ",", "CONF_RECONNECT_INTERVAL", ":", "0", "}", ",", "domain", ":", "{", "\"platform\"", ":", "\"rflink\"", "}", ",", "}", "# setup mocking rflink module", "_", ",", "mock_create", ",", "_", ",", "disconnect_callback", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ")", "assert", "disconnect_callback", ",", "\"disconnect callback not passed to rflink\"", "# rflink initiated disconnect", "disconnect_callback", "(", "None", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# we expect 2 call, the initial and reconnect", "assert", "mock_create", ".", "call_count", "==", "2" ]
[ 198, 0 ]
[ 219, 38 ]
python
en
['en', 'en', 'en']
True
test_reconnecting_after_failure
(hass, monkeypatch)
A failure to reconnect should be retried.
A failure to reconnect should be retried.
async def test_reconnecting_after_failure(hass, monkeypatch): """A failure to reconnect should be retried.""" domain = "sensor" config = { "rflink": {"port": "/dev/ttyABC0", CONF_RECONNECT_INTERVAL: 0}, domain: {"platform": "rflink"}, } # success first time but fail second failures = [False, True, False] # setup mocking rflink module _, mock_create, _, disconnect_callback = await mock_rflink( hass, config, domain, monkeypatch, failures=failures ) # rflink initiated disconnect disconnect_callback(None) # wait for reconnects to have happened await hass.async_block_till_done() await hass.async_block_till_done() # we expect 3 calls, the initial and 2 reconnects assert mock_create.call_count == 3
[ "async", "def", "test_reconnecting_after_failure", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"sensor\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", ",", "CONF_RECONNECT_INTERVAL", ":", "0", "}", ",", "domain", ":", "{", "\"platform\"", ":", "\"rflink\"", "}", ",", "}", "# success first time but fail second", "failures", "=", "[", "False", ",", "True", ",", "False", "]", "# setup mocking rflink module", "_", ",", "mock_create", ",", "_", ",", "disconnect_callback", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ",", "failures", "=", "failures", ")", "# rflink initiated disconnect", "disconnect_callback", "(", "None", ")", "# wait for reconnects to have happened", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# we expect 3 calls, the initial and 2 reconnects", "assert", "mock_create", ".", "call_count", "==", "3" ]
[ 222, 0 ]
[ 246, 38 ]
python
en
['en', 'en', 'en']
True
test_error_when_not_connected
(hass, monkeypatch)
Sending command should error when not connected.
Sending command should error when not connected.
async def test_error_when_not_connected(hass, monkeypatch): """Sending command should error when not connected.""" domain = "switch" config = { "rflink": {"port": "/dev/ttyABC0", CONF_RECONNECT_INTERVAL: 0}, domain: { "platform": "rflink", "devices": { "protocol_0_0": {"name": "test", "aliases": ["test_alias_0_0"]} }, }, } # success first time but fail second failures = [False, True, False] # setup mocking rflink module _, _, _, disconnect_callback = await mock_rflink( hass, config, domain, monkeypatch, failures=failures ) # rflink initiated disconnect disconnect_callback(None) success = await hass.services.async_call( domain, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "switch.test"} ) assert not success, "changing state should not succeed when disconnected"
[ "async", "def", "test_error_when_not_connected", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"switch\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", ",", "CONF_RECONNECT_INTERVAL", ":", "0", "}", ",", "domain", ":", "{", "\"platform\"", ":", "\"rflink\"", ",", "\"devices\"", ":", "{", "\"protocol_0_0\"", ":", "{", "\"name\"", ":", "\"test\"", ",", "\"aliases\"", ":", "[", "\"test_alias_0_0\"", "]", "}", "}", ",", "}", ",", "}", "# success first time but fail second", "failures", "=", "[", "False", ",", "True", ",", "False", "]", "# setup mocking rflink module", "_", ",", "_", ",", "_", ",", "disconnect_callback", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ",", "failures", "=", "failures", ")", "# rflink initiated disconnect", "disconnect_callback", "(", "None", ")", "success", "=", "await", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_TURN_OFF", ",", "{", "ATTR_ENTITY_ID", ":", "\"switch.test\"", "}", ")", "assert", "not", "success", ",", "\"changing state should not succeed when disconnected\"" ]
[ 249, 0 ]
[ 276, 77 ]
python
en
['en', 'en', 'en']
True
test_async_send_command_error
(hass, monkeypatch)
Sending command should error when protocol fails.
Sending command should error when protocol fails.
async def test_async_send_command_error(hass, monkeypatch): """Sending command should error when protocol fails.""" domain = "rflink" config = {"rflink": {"port": "/dev/ttyABC0"}} # setup mocking rflink module _, _, protocol, _ = await mock_rflink( hass, config, domain, monkeypatch, failcommand=True ) success = await hass.services.async_call( domain, SERVICE_SEND_COMMAND, {"device_id": "newkaku_0000c6c2_1", "command": SERVICE_TURN_OFF}, ) await hass.async_block_till_done() assert not success, "send command should not succeed if failcommand=True" assert protocol.send_command_ack.call_args_list[0][0][0] == "newkaku_0000c6c2_1" assert protocol.send_command_ack.call_args_list[0][0][1] == SERVICE_TURN_OFF
[ "async", "def", "test_async_send_command_error", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"rflink\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", "}", "}", "# setup mocking rflink module", "_", ",", "_", ",", "protocol", ",", "_", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ",", "failcommand", "=", "True", ")", "success", "=", "await", "hass", ".", "services", ".", "async_call", "(", "domain", ",", "SERVICE_SEND_COMMAND", ",", "{", "\"device_id\"", ":", "\"newkaku_0000c6c2_1\"", ",", "\"command\"", ":", "SERVICE_TURN_OFF", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "success", ",", "\"send command should not succeed if failcommand=True\"", "assert", "protocol", ".", "send_command_ack", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "0", "]", "==", "\"newkaku_0000c6c2_1\"", "assert", "protocol", ".", "send_command_ack", ".", "call_args_list", "[", "0", "]", "[", "0", "]", "[", "1", "]", "==", "SERVICE_TURN_OFF" ]
[ 279, 0 ]
[ 297, 80 ]
python
en
['en', 'it', 'en']
True
test_race_condition
(hass, monkeypatch)
Test race condition for unknown components.
Test race condition for unknown components.
async def test_race_condition(hass, monkeypatch): """Test race condition for unknown components.""" domain = "light" config = {"rflink": {"port": "/dev/ttyABC0"}, domain: {"platform": "rflink"}} tmp_entity = TMP_ENTITY.format("test3") # setup mocking rflink module event_callback, _, _, _ = await mock_rflink(hass, config, domain, monkeypatch) # test event for new unconfigured sensor event_callback({"id": "test3", "command": "off"}) event_callback({"id": "test3", "command": "on"}) # tmp_entity added to EVENT_KEY_COMMAND assert tmp_entity in hass.data[DATA_ENTITY_LOOKUP][EVENT_KEY_COMMAND]["test3"] # tmp_entity must no be added to EVENT_KEY_SENSOR assert tmp_entity not in hass.data[DATA_ENTITY_LOOKUP][EVENT_KEY_SENSOR]["test3"] await hass.async_block_till_done() # test state of new sensor new_sensor = hass.states.get(f"{domain}.test3") assert new_sensor assert new_sensor.state == "off" event_callback({"id": "test3", "command": "on"}) await hass.async_block_till_done() # tmp_entity must be deleted from EVENT_KEY_COMMAND assert tmp_entity not in hass.data[DATA_ENTITY_LOOKUP][EVENT_KEY_COMMAND]["test3"] # test state of new sensor new_sensor = hass.states.get(f"{domain}.test3") assert new_sensor assert new_sensor.state == "on"
[ "async", "def", "test_race_condition", "(", "hass", ",", "monkeypatch", ")", ":", "domain", "=", "\"light\"", "config", "=", "{", "\"rflink\"", ":", "{", "\"port\"", ":", "\"/dev/ttyABC0\"", "}", ",", "domain", ":", "{", "\"platform\"", ":", "\"rflink\"", "}", "}", "tmp_entity", "=", "TMP_ENTITY", ".", "format", "(", "\"test3\"", ")", "# setup mocking rflink module", "event_callback", ",", "_", ",", "_", ",", "_", "=", "await", "mock_rflink", "(", "hass", ",", "config", ",", "domain", ",", "monkeypatch", ")", "# test event for new unconfigured sensor", "event_callback", "(", "{", "\"id\"", ":", "\"test3\"", ",", "\"command\"", ":", "\"off\"", "}", ")", "event_callback", "(", "{", "\"id\"", ":", "\"test3\"", ",", "\"command\"", ":", "\"on\"", "}", ")", "# tmp_entity added to EVENT_KEY_COMMAND", "assert", "tmp_entity", "in", "hass", ".", "data", "[", "DATA_ENTITY_LOOKUP", "]", "[", "EVENT_KEY_COMMAND", "]", "[", "\"test3\"", "]", "# tmp_entity must no be added to EVENT_KEY_SENSOR", "assert", "tmp_entity", "not", "in", "hass", ".", "data", "[", "DATA_ENTITY_LOOKUP", "]", "[", "EVENT_KEY_SENSOR", "]", "[", "\"test3\"", "]", "await", "hass", ".", "async_block_till_done", "(", ")", "# test state of new sensor", "new_sensor", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.test3\"", ")", "assert", "new_sensor", "assert", "new_sensor", ".", "state", "==", "\"off\"", "event_callback", "(", "{", "\"id\"", ":", "\"test3\"", ",", "\"command\"", ":", "\"on\"", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "# tmp_entity must be deleted from EVENT_KEY_COMMAND", "assert", "tmp_entity", "not", "in", "hass", ".", "data", "[", "DATA_ENTITY_LOOKUP", "]", "[", "EVENT_KEY_COMMAND", "]", "[", "\"test3\"", "]", "# test state of new sensor", "new_sensor", "=", "hass", ".", "states", ".", "get", "(", "f\"{domain}.test3\"", ")", "assert", "new_sensor", "assert", "new_sensor", ".", "state", "==", "\"on\"" ]
[ 300, 0 ]
[ 333, 35 ]
python
en
['en', 'en', 'en']
True
test_not_connected
(hass, monkeypatch)
Test Error when sending commands to a disconnected device.
Test Error when sending commands to a disconnected device.
async def test_not_connected(hass, monkeypatch): """Test Error when sending commands to a disconnected device.""" import pytest from homeassistant.core import HomeAssistantError test_device = RflinkCommand("DUMMY_DEVICE") RflinkCommand.set_rflink_protocol(None) with pytest.raises(HomeAssistantError): await test_device._async_handle_command("turn_on")
[ "async", "def", "test_not_connected", "(", "hass", ",", "monkeypatch", ")", ":", "import", "pytest", "from", "homeassistant", ".", "core", "import", "HomeAssistantError", "test_device", "=", "RflinkCommand", "(", "\"DUMMY_DEVICE\"", ")", "RflinkCommand", ".", "set_rflink_protocol", "(", "None", ")", "with", "pytest", ".", "raises", "(", "HomeAssistantError", ")", ":", "await", "test_device", ".", "_async_handle_command", "(", "\"turn_on\"", ")" ]
[ 336, 0 ]
[ 345, 58 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Deluge switch.
Set up the Deluge switch.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Deluge switch.""" name = config[CONF_NAME] host = config[CONF_HOST] username = config[CONF_USERNAME] password = config[CONF_PASSWORD] port = config[CONF_PORT] deluge_api = DelugeRPCClient(host, port, username, password) try: deluge_api.connect() except ConnectionRefusedError as err: _LOGGER.error("Connection to Deluge Daemon failed") raise PlatformNotReady from err add_entities([DelugeSwitch(deluge_api, name)])
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "name", "=", "config", "[", "CONF_NAME", "]", "host", "=", "config", "[", "CONF_HOST", "]", "username", "=", "config", "[", "CONF_USERNAME", "]", "password", "=", "config", "[", "CONF_PASSWORD", "]", "port", "=", "config", "[", "CONF_PORT", "]", "deluge_api", "=", "DelugeRPCClient", "(", "host", ",", "port", ",", "username", ",", "password", ")", "try", ":", "deluge_api", ".", "connect", "(", ")", "except", "ConnectionRefusedError", "as", "err", ":", "_LOGGER", ".", "error", "(", "\"Connection to Deluge Daemon failed\"", ")", "raise", "PlatformNotReady", "from", "err", "add_entities", "(", "[", "DelugeSwitch", "(", "deluge_api", ",", "name", ")", "]", ")" ]
[ 36, 0 ]
[ 52, 50 ]
python
en
['en', 'en', 'en']
True
DelugeSwitch.__init__
(self, deluge_client, name)
Initialize the Deluge switch.
Initialize the Deluge switch.
def __init__(self, deluge_client, name): """Initialize the Deluge switch.""" self._name = name self.deluge_client = deluge_client self._state = STATE_OFF self._available = False
[ "def", "__init__", "(", "self", ",", "deluge_client", ",", "name", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "deluge_client", "=", "deluge_client", "self", ".", "_state", "=", "STATE_OFF", "self", ".", "_available", "=", "False" ]
[ 58, 4 ]
[ 63, 31 ]
python
en
['en', 'en', 'en']
True
DelugeSwitch.name
(self)
Return the name of the switch.
Return the name of the switch.
def name(self): """Return the name of the switch.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 66, 4 ]
[ 68, 25 ]
python
en
['en', 'en', 'en']
True
DelugeSwitch.state
(self)
Return the state of the device.
Return the state of the device.
def state(self): """Return the state of the device.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 71, 4 ]
[ 73, 26 ]
python
en
['en', 'en', 'en']
True
DelugeSwitch.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self._state == STATE_ON
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state", "==", "STATE_ON" ]
[ 76, 4 ]
[ 78, 38 ]
python
en
['en', 'fy', 'en']
True
DelugeSwitch.available
(self)
Return true if device is available.
Return true if device is available.
def available(self): """Return true if device is available.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
[ 81, 4 ]
[ 83, 30 ]
python
en
['en', 'en', 'en']
True
DelugeSwitch.turn_on
(self, **kwargs)
Turn the device on.
Turn the device on.
def turn_on(self, **kwargs): """Turn the device on.""" torrent_ids = self.deluge_client.call("core.get_session_state") self.deluge_client.call("core.resume_torrent", torrent_ids)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "torrent_ids", "=", "self", ".", "deluge_client", ".", "call", "(", "\"core.get_session_state\"", ")", "self", ".", "deluge_client", ".", "call", "(", "\"core.resume_torrent\"", ",", "torrent_ids", ")" ]
[ 85, 4 ]
[ 88, 67 ]
python
en
['en', 'en', 'en']
True
DelugeSwitch.turn_off
(self, **kwargs)
Turn the device off.
Turn the device off.
def turn_off(self, **kwargs): """Turn the device off.""" torrent_ids = self.deluge_client.call("core.get_session_state") self.deluge_client.call("core.pause_torrent", torrent_ids)
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "torrent_ids", "=", "self", ".", "deluge_client", ".", "call", "(", "\"core.get_session_state\"", ")", "self", ".", "deluge_client", ".", "call", "(", "\"core.pause_torrent\"", ",", "torrent_ids", ")" ]
[ 90, 4 ]
[ 93, 66 ]
python
en
['en', 'en', 'en']
True
DelugeSwitch.update
(self)
Get the latest data from deluge and updates the state.
Get the latest data from deluge and updates the state.
def update(self): """Get the latest data from deluge and updates the state.""" try: torrent_list = self.deluge_client.call( "core.get_torrents_status", {}, ["paused"] ) self._available = True except FailedToReconnectException: _LOGGER.error("Connection to Deluge Daemon Lost") self._available = False return for torrent in torrent_list.values(): item = torrent.popitem() if not item[1]: self._state = STATE_ON return self._state = STATE_OFF
[ "def", "update", "(", "self", ")", ":", "try", ":", "torrent_list", "=", "self", ".", "deluge_client", ".", "call", "(", "\"core.get_torrents_status\"", ",", "{", "}", ",", "[", "\"paused\"", "]", ")", "self", ".", "_available", "=", "True", "except", "FailedToReconnectException", ":", "_LOGGER", ".", "error", "(", "\"Connection to Deluge Daemon Lost\"", ")", "self", ".", "_available", "=", "False", "return", "for", "torrent", "in", "torrent_list", ".", "values", "(", ")", ":", "item", "=", "torrent", ".", "popitem", "(", ")", "if", "not", "item", "[", "1", "]", ":", "self", ".", "_state", "=", "STATE_ON", "return", "self", ".", "_state", "=", "STATE_OFF" ]
[ 95, 4 ]
[ 113, 31 ]
python
en
['en', 'en', 'en']
True
setup
(hass, config)
Set up Eufy devices.
Set up Eufy devices.
def setup(hass, config): """Set up Eufy devices.""" if CONF_USERNAME in config[DOMAIN] and CONF_PASSWORD in config[DOMAIN]: data = lakeside.get_devices( config[DOMAIN][CONF_USERNAME], config[DOMAIN][CONF_PASSWORD] ) for device in data: kind = device["type"] if kind not in EUFY_DISPATCH: continue discovery.load_platform(hass, EUFY_DISPATCH[kind], DOMAIN, device, config) for device_info in config[DOMAIN][CONF_DEVICES]: kind = device_info["type"] if kind not in EUFY_DISPATCH: continue device = {} device["address"] = device_info["address"] device["code"] = device_info["access_token"] device["type"] = device_info["type"] device["name"] = device_info["name"] discovery.load_platform(hass, EUFY_DISPATCH[kind], DOMAIN, device, config) return True
[ "def", "setup", "(", "hass", ",", "config", ")", ":", "if", "CONF_USERNAME", "in", "config", "[", "DOMAIN", "]", "and", "CONF_PASSWORD", "in", "config", "[", "DOMAIN", "]", ":", "data", "=", "lakeside", ".", "get_devices", "(", "config", "[", "DOMAIN", "]", "[", "CONF_USERNAME", "]", ",", "config", "[", "DOMAIN", "]", "[", "CONF_PASSWORD", "]", ")", "for", "device", "in", "data", ":", "kind", "=", "device", "[", "\"type\"", "]", "if", "kind", "not", "in", "EUFY_DISPATCH", ":", "continue", "discovery", ".", "load_platform", "(", "hass", ",", "EUFY_DISPATCH", "[", "kind", "]", ",", "DOMAIN", ",", "device", ",", "config", ")", "for", "device_info", "in", "config", "[", "DOMAIN", "]", "[", "CONF_DEVICES", "]", ":", "kind", "=", "device_info", "[", "\"type\"", "]", "if", "kind", "not", "in", "EUFY_DISPATCH", ":", "continue", "device", "=", "{", "}", "device", "[", "\"address\"", "]", "=", "device_info", "[", "\"address\"", "]", "device", "[", "\"code\"", "]", "=", "device_info", "[", "\"access_token\"", "]", "device", "[", "\"type\"", "]", "=", "device_info", "[", "\"type\"", "]", "device", "[", "\"name\"", "]", "=", "device_info", "[", "\"name\"", "]", "discovery", ".", "load_platform", "(", "hass", ",", "EUFY_DISPATCH", "[", "kind", "]", ",", "DOMAIN", ",", "device", ",", "config", ")", "return", "True" ]
[ 53, 0 ]
[ 77, 15 ]
python
en
['en', 'en', 'en']
True
catch_request_errors
()
Catch asyncio.TimeoutError, aiohttp.ClientError errors.
Catch asyncio.TimeoutError, aiohttp.ClientError errors.
def catch_request_errors(): """Catch asyncio.TimeoutError, aiohttp.ClientError errors.""" def call_wrapper(func): """Call wrapper for decorator.""" @functools.wraps(func) async def wrapper(self, *args, **kwargs): """Catch asyncio.TimeoutError, aiohttp.ClientError errors.""" try: return await func(self, *args, **kwargs) except (asyncio.TimeoutError, aiohttp.ClientError): _LOGGER.error("Error during call %s", func.__name__) return wrapper return call_wrapper
[ "def", "catch_request_errors", "(", ")", ":", "def", "call_wrapper", "(", "func", ")", ":", "\"\"\"Call wrapper for decorator.\"\"\"", "@", "functools", ".", "wraps", "(", "func", ")", "async", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Catch asyncio.TimeoutError, aiohttp.ClientError errors.\"\"\"", "try", ":", "return", "await", "func", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "asyncio", ".", "TimeoutError", ",", "aiohttp", ".", "ClientError", ")", ":", "_LOGGER", ".", "error", "(", "\"Error during call %s\"", ",", "func", ".", "__name__", ")", "return", "wrapper", "return", "call_wrapper" ]
[ 94, 0 ]
[ 110, 23 ]
python
it
['cy', 'it', 'it']
True
async_start_event_handler
( hass: HomeAssistantType, server_host: str, server_port: int, requester, callback_url_override: Optional[str] = None, )
Register notify view.
Register notify view.
async def async_start_event_handler( hass: HomeAssistantType, server_host: str, server_port: int, requester, callback_url_override: Optional[str] = None, ): """Register notify view.""" hass_data = hass.data[DLNA_DMR_DATA] if "event_handler" in hass_data: return hass_data["event_handler"] # start event handler server = AiohttpNotifyServer( requester, listen_port=server_port, listen_host=server_host, callback_url=callback_url_override, ) await server.start_server() _LOGGER.info("UPNP/DLNA event handler listening, url: %s", server.callback_url) hass_data["notify_server"] = server hass_data["event_handler"] = server.event_handler # register for graceful shutdown async def async_stop_server(event): """Stop server.""" _LOGGER.debug("Stopping UPNP/DLNA event handler") await server.stop_server() hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, async_stop_server) return hass_data["event_handler"]
[ "async", "def", "async_start_event_handler", "(", "hass", ":", "HomeAssistantType", ",", "server_host", ":", "str", ",", "server_port", ":", "int", ",", "requester", ",", "callback_url_override", ":", "Optional", "[", "str", "]", "=", "None", ",", ")", ":", "hass_data", "=", "hass", ".", "data", "[", "DLNA_DMR_DATA", "]", "if", "\"event_handler\"", "in", "hass_data", ":", "return", "hass_data", "[", "\"event_handler\"", "]", "# start event handler", "server", "=", "AiohttpNotifyServer", "(", "requester", ",", "listen_port", "=", "server_port", ",", "listen_host", "=", "server_host", ",", "callback_url", "=", "callback_url_override", ",", ")", "await", "server", ".", "start_server", "(", ")", "_LOGGER", ".", "info", "(", "\"UPNP/DLNA event handler listening, url: %s\"", ",", "server", ".", "callback_url", ")", "hass_data", "[", "\"notify_server\"", "]", "=", "server", "hass_data", "[", "\"event_handler\"", "]", "=", "server", ".", "event_handler", "# register for graceful shutdown", "async", "def", "async_stop_server", "(", "event", ")", ":", "\"\"\"Stop server.\"\"\"", "_LOGGER", ".", "debug", "(", "\"Stopping UPNP/DLNA event handler\"", ")", "await", "server", ".", "stop_server", "(", ")", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "async_stop_server", ")", "return", "hass_data", "[", "\"event_handler\"", "]" ]
[ 113, 0 ]
[ 145, 37 ]
python
en
['en', 'de', 'en']
True
async_setup_platform
( hass: HomeAssistantType, config, async_add_entities, discovery_info=None )
Set up DLNA DMR platform.
Set up DLNA DMR platform.
async def async_setup_platform( hass: HomeAssistantType, config, async_add_entities, discovery_info=None ): """Set up DLNA DMR platform.""" if config.get(CONF_URL) is not None: url = config[CONF_URL] name = config.get(CONF_NAME) elif discovery_info is not None: url = discovery_info["ssdp_description"] name = discovery_info.get("name") if DLNA_DMR_DATA not in hass.data: hass.data[DLNA_DMR_DATA] = {} if "lock" not in hass.data[DLNA_DMR_DATA]: hass.data[DLNA_DMR_DATA]["lock"] = asyncio.Lock() # build upnp/aiohttp requester session = async_get_clientsession(hass) requester = AiohttpSessionRequester(session, True) # ensure event handler has been started async with hass.data[DLNA_DMR_DATA]["lock"]: server_host = config.get(CONF_LISTEN_IP) if server_host is None: server_host = get_local_ip() server_port = config.get(CONF_LISTEN_PORT, DEFAULT_LISTEN_PORT) callback_url_override = config.get(CONF_CALLBACK_URL_OVERRIDE) event_handler = await async_start_event_handler( hass, server_host, server_port, requester, callback_url_override ) # create upnp device factory = UpnpFactory(requester, disable_state_variable_validation=True) try: upnp_device = await factory.async_create_device(url) except (asyncio.TimeoutError, aiohttp.ClientError) as err: raise PlatformNotReady() from err # wrap with DmrDevice dlna_device = DmrDevice(upnp_device, event_handler) # create our own device device = DlnaDmrDevice(dlna_device, name) _LOGGER.debug("Adding device: %s", device) async_add_entities([device], True)
[ "async", "def", "async_setup_platform", "(", "hass", ":", "HomeAssistantType", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "if", "config", ".", "get", "(", "CONF_URL", ")", "is", "not", "None", ":", "url", "=", "config", "[", "CONF_URL", "]", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "elif", "discovery_info", "is", "not", "None", ":", "url", "=", "discovery_info", "[", "\"ssdp_description\"", "]", "name", "=", "discovery_info", ".", "get", "(", "\"name\"", ")", "if", "DLNA_DMR_DATA", "not", "in", "hass", ".", "data", ":", "hass", ".", "data", "[", "DLNA_DMR_DATA", "]", "=", "{", "}", "if", "\"lock\"", "not", "in", "hass", ".", "data", "[", "DLNA_DMR_DATA", "]", ":", "hass", ".", "data", "[", "DLNA_DMR_DATA", "]", "[", "\"lock\"", "]", "=", "asyncio", ".", "Lock", "(", ")", "# build upnp/aiohttp requester", "session", "=", "async_get_clientsession", "(", "hass", ")", "requester", "=", "AiohttpSessionRequester", "(", "session", ",", "True", ")", "# ensure event handler has been started", "async", "with", "hass", ".", "data", "[", "DLNA_DMR_DATA", "]", "[", "\"lock\"", "]", ":", "server_host", "=", "config", ".", "get", "(", "CONF_LISTEN_IP", ")", "if", "server_host", "is", "None", ":", "server_host", "=", "get_local_ip", "(", ")", "server_port", "=", "config", ".", "get", "(", "CONF_LISTEN_PORT", ",", "DEFAULT_LISTEN_PORT", ")", "callback_url_override", "=", "config", ".", "get", "(", "CONF_CALLBACK_URL_OVERRIDE", ")", "event_handler", "=", "await", "async_start_event_handler", "(", "hass", ",", "server_host", ",", "server_port", ",", "requester", ",", "callback_url_override", ")", "# create upnp device", "factory", "=", "UpnpFactory", "(", "requester", ",", "disable_state_variable_validation", "=", "True", ")", "try", ":", "upnp_device", "=", "await", "factory", ".", "async_create_device", "(", "url", ")", "except", "(", "asyncio", ".", "TimeoutError", ",", "aiohttp", ".", "ClientError", ")", "as", "err", ":", "raise", "PlatformNotReady", "(", ")", "from", "err", "# wrap with DmrDevice", "dlna_device", "=", "DmrDevice", "(", "upnp_device", ",", "event_handler", ")", "# create our own device", "device", "=", "DlnaDmrDevice", "(", "dlna_device", ",", "name", ")", "_LOGGER", ".", "debug", "(", "\"Adding device: %s\"", ",", "device", ")", "async_add_entities", "(", "[", "device", "]", ",", "True", ")" ]
[ 148, 0 ]
[ 193, 38 ]
python
en
['en', 'da', 'en']
True
DlnaDmrDevice.__init__
(self, dmr_device, name=None)
Initialize DLNA DMR device.
Initialize DLNA DMR device.
def __init__(self, dmr_device, name=None): """Initialize DLNA DMR device.""" self._device = dmr_device self._name = name self._available = False self._subscription_renew_time = None
[ "def", "__init__", "(", "self", ",", "dmr_device", ",", "name", "=", "None", ")", ":", "self", ".", "_device", "=", "dmr_device", "self", ".", "_name", "=", "name", "self", ".", "_available", "=", "False", "self", ".", "_subscription_renew_time", "=", "None" ]
[ 199, 4 ]
[ 205, 44 ]
python
es
['es', 'pl', 'it']
False
DlnaDmrDevice.async_added_to_hass
(self)
Handle addition.
Handle addition.
async def async_added_to_hass(self): """Handle addition.""" self._device.on_event = self._on_event # Register unsubscribe on stop bus = self.hass.bus bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self._async_on_hass_stop)
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "self", ".", "_device", ".", "on_event", "=", "self", ".", "_on_event", "# Register unsubscribe on stop", "bus", "=", "self", ".", "hass", ".", "bus", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "self", ".", "_async_on_hass_stop", ")" ]
[ 207, 4 ]
[ 213, 81 ]
python
en
['en', 'ja', 'en']
False
DlnaDmrDevice.available
(self)
Device is available.
Device is available.
def available(self): """Device is available.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
[ 216, 4 ]
[ 218, 30 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice._async_on_hass_stop
(self, event)
Event handler on Home Assistant stop.
Event handler on Home Assistant stop.
async def _async_on_hass_stop(self, event): """Event handler on Home Assistant stop.""" async with self.hass.data[DLNA_DMR_DATA]["lock"]: await self._device.async_unsubscribe_services()
[ "async", "def", "_async_on_hass_stop", "(", "self", ",", "event", ")", ":", "async", "with", "self", ".", "hass", ".", "data", "[", "DLNA_DMR_DATA", "]", "[", "\"lock\"", "]", ":", "await", "self", ".", "_device", ".", "async_unsubscribe_services", "(", ")" ]
[ 220, 4 ]
[ 223, 59 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.async_update
(self)
Retrieve the latest data.
Retrieve the latest data.
async def async_update(self): """Retrieve the latest data.""" was_available = self._available try: await self._device.async_update() self._available = True except (asyncio.TimeoutError, aiohttp.ClientError): self._available = False _LOGGER.debug("Device unavailable") return # do we need to (re-)subscribe? now = dt_util.utcnow() should_renew = ( self._subscription_renew_time and now >= self._subscription_renew_time ) if should_renew or not was_available and self._available: try: timeout = await self._device.async_subscribe_services() self._subscription_renew_time = dt_util.utcnow() + timeout / 2 except (asyncio.TimeoutError, aiohttp.ClientError): self._available = False _LOGGER.debug("Could not (re)subscribe")
[ "async", "def", "async_update", "(", "self", ")", ":", "was_available", "=", "self", ".", "_available", "try", ":", "await", "self", ".", "_device", ".", "async_update", "(", ")", "self", ".", "_available", "=", "True", "except", "(", "asyncio", ".", "TimeoutError", ",", "aiohttp", ".", "ClientError", ")", ":", "self", ".", "_available", "=", "False", "_LOGGER", ".", "debug", "(", "\"Device unavailable\"", ")", "return", "# do we need to (re-)subscribe?", "now", "=", "dt_util", ".", "utcnow", "(", ")", "should_renew", "=", "(", "self", ".", "_subscription_renew_time", "and", "now", ">=", "self", ".", "_subscription_renew_time", ")", "if", "should_renew", "or", "not", "was_available", "and", "self", ".", "_available", ":", "try", ":", "timeout", "=", "await", "self", ".", "_device", ".", "async_subscribe_services", "(", ")", "self", ".", "_subscription_renew_time", "=", "dt_util", ".", "utcnow", "(", ")", "+", "timeout", "/", "2", "except", "(", "asyncio", ".", "TimeoutError", ",", "aiohttp", ".", "ClientError", ")", ":", "self", ".", "_available", "=", "False", "_LOGGER", ".", "debug", "(", "\"Could not (re)subscribe\"", ")" ]
[ 225, 4 ]
[ 248, 56 ]
python
en
['en', 'ga', 'en']
True
DlnaDmrDevice._on_event
(self, service, state_variables)
State variable(s) changed, let home-assistant know.
State variable(s) changed, let home-assistant know.
def _on_event(self, service, state_variables): """State variable(s) changed, let home-assistant know.""" self.schedule_update_ha_state()
[ "def", "_on_event", "(", "self", ",", "service", ",", "state_variables", ")", ":", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 250, 4 ]
[ 252, 39 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.supported_features
(self)
Flag media player features that are supported.
Flag media player features that are supported.
def supported_features(self): """Flag media player features that are supported.""" supported_features = 0 if self._device.has_volume_level: supported_features |= SUPPORT_VOLUME_SET if self._device.has_volume_mute: supported_features |= SUPPORT_VOLUME_MUTE if self._device.has_play: supported_features |= SUPPORT_PLAY if self._device.has_pause: supported_features |= SUPPORT_PAUSE if self._device.has_stop: supported_features |= SUPPORT_STOP if self._device.has_previous: supported_features |= SUPPORT_PREVIOUS_TRACK if self._device.has_next: supported_features |= SUPPORT_NEXT_TRACK if self._device.has_play_media: supported_features |= SUPPORT_PLAY_MEDIA if self._device.has_seek_rel_time: supported_features |= SUPPORT_SEEK return supported_features
[ "def", "supported_features", "(", "self", ")", ":", "supported_features", "=", "0", "if", "self", ".", "_device", ".", "has_volume_level", ":", "supported_features", "|=", "SUPPORT_VOLUME_SET", "if", "self", ".", "_device", ".", "has_volume_mute", ":", "supported_features", "|=", "SUPPORT_VOLUME_MUTE", "if", "self", ".", "_device", ".", "has_play", ":", "supported_features", "|=", "SUPPORT_PLAY", "if", "self", ".", "_device", ".", "has_pause", ":", "supported_features", "|=", "SUPPORT_PAUSE", "if", "self", ".", "_device", ".", "has_stop", ":", "supported_features", "|=", "SUPPORT_STOP", "if", "self", ".", "_device", ".", "has_previous", ":", "supported_features", "|=", "SUPPORT_PREVIOUS_TRACK", "if", "self", ".", "_device", ".", "has_next", ":", "supported_features", "|=", "SUPPORT_NEXT_TRACK", "if", "self", ".", "_device", ".", "has_play_media", ":", "supported_features", "|=", "SUPPORT_PLAY_MEDIA", "if", "self", ".", "_device", ".", "has_seek_rel_time", ":", "supported_features", "|=", "SUPPORT_SEEK", "return", "supported_features" ]
[ 255, 4 ]
[ 278, 33 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.volume_level
(self)
Volume level of the media player (0..1).
Volume level of the media player (0..1).
def volume_level(self): """Volume level of the media player (0..1).""" return self._device.volume_level
[ "def", "volume_level", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "volume_level" ]
[ 281, 4 ]
[ 283, 40 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.async_set_volume_level
(self, volume)
Set volume level, range 0..1.
Set volume level, range 0..1.
async def async_set_volume_level(self, volume): """Set volume level, range 0..1.""" await self._device.async_set_volume_level(volume)
[ "async", "def", "async_set_volume_level", "(", "self", ",", "volume", ")", ":", "await", "self", ".", "_device", ".", "async_set_volume_level", "(", "volume", ")" ]
[ 286, 4 ]
[ 288, 57 ]
python
en
['fr', 'zu', 'en']
False
DlnaDmrDevice.is_volume_muted
(self)
Boolean if volume is currently muted.
Boolean if volume is currently muted.
def is_volume_muted(self): """Boolean if volume is currently muted.""" return self._device.is_volume_muted
[ "def", "is_volume_muted", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "is_volume_muted" ]
[ 291, 4 ]
[ 293, 43 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.async_mute_volume
(self, mute)
Mute the volume.
Mute the volume.
async def async_mute_volume(self, mute): """Mute the volume.""" desired_mute = bool(mute) await self._device.async_mute_volume(desired_mute)
[ "async", "def", "async_mute_volume", "(", "self", ",", "mute", ")", ":", "desired_mute", "=", "bool", "(", "mute", ")", "await", "self", ".", "_device", ".", "async_mute_volume", "(", "desired_mute", ")" ]
[ 296, 4 ]
[ 299, 58 ]
python
en
['en', 'sn', 'en']
True
DlnaDmrDevice.async_media_pause
(self)
Send pause command.
Send pause command.
async def async_media_pause(self): """Send pause command.""" if not self._device.can_pause: _LOGGER.debug("Cannot do Pause") return await self._device.async_pause()
[ "async", "def", "async_media_pause", "(", "self", ")", ":", "if", "not", "self", ".", "_device", ".", "can_pause", ":", "_LOGGER", ".", "debug", "(", "\"Cannot do Pause\"", ")", "return", "await", "self", ".", "_device", ".", "async_pause", "(", ")" ]
[ 302, 4 ]
[ 308, 40 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.async_media_play
(self)
Send play command.
Send play command.
async def async_media_play(self): """Send play command.""" if not self._device.can_play: _LOGGER.debug("Cannot do Play") return await self._device.async_play()
[ "async", "def", "async_media_play", "(", "self", ")", ":", "if", "not", "self", ".", "_device", ".", "can_play", ":", "_LOGGER", ".", "debug", "(", "\"Cannot do Play\"", ")", "return", "await", "self", ".", "_device", ".", "async_play", "(", ")" ]
[ 311, 4 ]
[ 317, 39 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.async_media_stop
(self)
Send stop command.
Send stop command.
async def async_media_stop(self): """Send stop command.""" if not self._device.can_stop: _LOGGER.debug("Cannot do Stop") return await self._device.async_stop()
[ "async", "def", "async_media_stop", "(", "self", ")", ":", "if", "not", "self", ".", "_device", ".", "can_stop", ":", "_LOGGER", ".", "debug", "(", "\"Cannot do Stop\"", ")", "return", "await", "self", ".", "_device", ".", "async_stop", "(", ")" ]
[ 320, 4 ]
[ 326, 39 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.async_media_seek
(self, position)
Send seek command.
Send seek command.
async def async_media_seek(self, position): """Send seek command.""" if not self._device.can_seek_rel_time: _LOGGER.debug("Cannot do Seek/rel_time") return time = timedelta(seconds=position) await self._device.async_seek_rel_time(time)
[ "async", "def", "async_media_seek", "(", "self", ",", "position", ")", ":", "if", "not", "self", ".", "_device", ".", "can_seek_rel_time", ":", "_LOGGER", ".", "debug", "(", "\"Cannot do Seek/rel_time\"", ")", "return", "time", "=", "timedelta", "(", "seconds", "=", "position", ")", "await", "self", ".", "_device", ".", "async_seek_rel_time", "(", "time", ")" ]
[ 329, 4 ]
[ 336, 52 ]
python
en
['en', 'ig', 'en']
True
DlnaDmrDevice.async_play_media
(self, media_type, media_id, **kwargs)
Play a piece of media.
Play a piece of media.
async def async_play_media(self, media_type, media_id, **kwargs): """Play a piece of media.""" title = "Home Assistant" mime_type = HOME_ASSISTANT_UPNP_MIME_TYPE_MAPPING.get(media_type, media_type) upnp_class = HOME_ASSISTANT_UPNP_CLASS_MAPPING.get( media_type, UPNP_CLASS_DEFAULT ) # Stop current playing media if self._device.can_stop: await self.async_media_stop() # Queue media await self._device.async_set_transport_uri( media_id, title, mime_type, upnp_class ) await self._device.async_wait_for_can_play() # If already playing, no need to call Play if self._device.state == DeviceState.PLAYING: return # Play it await self.async_media_play()
[ "async", "def", "async_play_media", "(", "self", ",", "media_type", ",", "media_id", ",", "*", "*", "kwargs", ")", ":", "title", "=", "\"Home Assistant\"", "mime_type", "=", "HOME_ASSISTANT_UPNP_MIME_TYPE_MAPPING", ".", "get", "(", "media_type", ",", "media_type", ")", "upnp_class", "=", "HOME_ASSISTANT_UPNP_CLASS_MAPPING", ".", "get", "(", "media_type", ",", "UPNP_CLASS_DEFAULT", ")", "# Stop current playing media", "if", "self", ".", "_device", ".", "can_stop", ":", "await", "self", ".", "async_media_stop", "(", ")", "# Queue media", "await", "self", ".", "_device", ".", "async_set_transport_uri", "(", "media_id", ",", "title", ",", "mime_type", ",", "upnp_class", ")", "await", "self", ".", "_device", ".", "async_wait_for_can_play", "(", ")", "# If already playing, no need to call Play", "if", "self", ".", "_device", ".", "state", "==", "DeviceState", ".", "PLAYING", ":", "return", "# Play it", "await", "self", ".", "async_media_play", "(", ")" ]
[ 339, 4 ]
[ 362, 37 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.async_media_previous_track
(self)
Send previous track command.
Send previous track command.
async def async_media_previous_track(self): """Send previous track command.""" if not self._device.can_previous: _LOGGER.debug("Cannot do Previous") return await self._device.async_previous()
[ "async", "def", "async_media_previous_track", "(", "self", ")", ":", "if", "not", "self", ".", "_device", ".", "can_previous", ":", "_LOGGER", ".", "debug", "(", "\"Cannot do Previous\"", ")", "return", "await", "self", ".", "_device", ".", "async_previous", "(", ")" ]
[ 365, 4 ]
[ 371, 43 ]
python
en
['en', 'it', 'en']
True
DlnaDmrDevice.async_media_next_track
(self)
Send next track command.
Send next track command.
async def async_media_next_track(self): """Send next track command.""" if not self._device.can_next: _LOGGER.debug("Cannot do Next") return await self._device.async_next()
[ "async", "def", "async_media_next_track", "(", "self", ")", ":", "if", "not", "self", ".", "_device", ".", "can_next", ":", "_LOGGER", ".", "debug", "(", "\"Cannot do Next\"", ")", "return", "await", "self", ".", "_device", ".", "async_next", "(", ")" ]
[ 374, 4 ]
[ 380, 39 ]
python
en
['en', 'pt', 'en']
True
DlnaDmrDevice.media_title
(self)
Title of current playing media.
Title of current playing media.
def media_title(self): """Title of current playing media.""" return self._device.media_title
[ "def", "media_title", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "media_title" ]
[ 383, 4 ]
[ 385, 39 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.media_image_url
(self)
Image url of current playing media.
Image url of current playing media.
def media_image_url(self): """Image url of current playing media.""" return self._device.media_image_url
[ "def", "media_image_url", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "media_image_url" ]
[ 388, 4 ]
[ 390, 43 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.state
(self)
State of the player.
State of the player.
def state(self): """State of the player.""" if not self._available: return STATE_OFF if self._device.state is None: return STATE_ON if self._device.state == DeviceState.PLAYING: return STATE_PLAYING if self._device.state == DeviceState.PAUSED: return STATE_PAUSED return STATE_IDLE
[ "def", "state", "(", "self", ")", ":", "if", "not", "self", ".", "_available", ":", "return", "STATE_OFF", "if", "self", ".", "_device", ".", "state", "is", "None", ":", "return", "STATE_ON", "if", "self", ".", "_device", ".", "state", "==", "DeviceState", ".", "PLAYING", ":", "return", "STATE_PLAYING", "if", "self", ".", "_device", ".", "state", "==", "DeviceState", ".", "PAUSED", ":", "return", "STATE_PAUSED", "return", "STATE_IDLE" ]
[ 393, 4 ]
[ 405, 25 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.media_duration
(self)
Duration of current playing media in seconds.
Duration of current playing media in seconds.
def media_duration(self): """Duration of current playing media in seconds.""" return self._device.media_duration
[ "def", "media_duration", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "media_duration" ]
[ 408, 4 ]
[ 410, 42 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.media_position
(self)
Position of current playing media in seconds.
Position of current playing media in seconds.
def media_position(self): """Position of current playing media in seconds.""" return self._device.media_position
[ "def", "media_position", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "media_position" ]
[ 413, 4 ]
[ 415, 42 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.media_position_updated_at
(self)
When was the position of the current playing media valid. Returns value from homeassistant.util.dt.utcnow().
When was the position of the current playing media valid.
def media_position_updated_at(self): """When was the position of the current playing media valid. Returns value from homeassistant.util.dt.utcnow(). """ return self._device.media_position_updated_at
[ "def", "media_position_updated_at", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "media_position_updated_at" ]
[ 418, 4 ]
[ 423, 53 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.name
(self)
Return the name of the device.
Return the name of the device.
def name(self) -> str: """Return the name of the device.""" if self._name: return self._name return self._device.name
[ "def", "name", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_name", ":", "return", "self", ".", "_name", "return", "self", ".", "_device", ".", "name" ]
[ 426, 4 ]
[ 430, 32 ]
python
en
['en', 'en', 'en']
True
DlnaDmrDevice.unique_id
(self)
Return an unique ID.
Return an unique ID.
def unique_id(self) -> str: """Return an unique ID.""" return self._device.udn
[ "def", "unique_id", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_device", ".", "udn" ]
[ 433, 4 ]
[ 435, 31 ]
python
fr
['fr', 'fr', 'en']
True
setup
(hass, config)
Create the ViCare component.
Create the ViCare component.
def setup(hass, config): """Create the ViCare component.""" conf = config[DOMAIN] params = {"token_file": hass.config.path(STORAGE_DIR, "vicare_token.save")} if conf.get(CONF_CIRCUIT) is not None: params["circuit"] = conf[CONF_CIRCUIT] params["cacheDuration"] = conf.get(CONF_SCAN_INTERVAL) heating_type = conf[CONF_HEATING_TYPE] try: if heating_type == HeatingType.gas: vicare_api = GazBoiler(conf[CONF_USERNAME], conf[CONF_PASSWORD], **params) elif heating_type == HeatingType.heatpump: vicare_api = HeatPump(conf[CONF_USERNAME], conf[CONF_PASSWORD], **params) else: vicare_api = Device(conf[CONF_USERNAME], conf[CONF_PASSWORD], **params) except AttributeError: _LOGGER.error( "Failed to create PyViCare API client. Please check your credentials" ) return False hass.data[DOMAIN] = {} hass.data[DOMAIN][VICARE_API] = vicare_api hass.data[DOMAIN][VICARE_NAME] = conf[CONF_NAME] hass.data[DOMAIN][VICARE_HEATING_TYPE] = heating_type for platform in VICARE_PLATFORMS: discovery.load_platform(hass, platform, DOMAIN, {}, config) return True
[ "def", "setup", "(", "hass", ",", "config", ")", ":", "conf", "=", "config", "[", "DOMAIN", "]", "params", "=", "{", "\"token_file\"", ":", "hass", ".", "config", ".", "path", "(", "STORAGE_DIR", ",", "\"vicare_token.save\"", ")", "}", "if", "conf", ".", "get", "(", "CONF_CIRCUIT", ")", "is", "not", "None", ":", "params", "[", "\"circuit\"", "]", "=", "conf", "[", "CONF_CIRCUIT", "]", "params", "[", "\"cacheDuration\"", "]", "=", "conf", ".", "get", "(", "CONF_SCAN_INTERVAL", ")", "heating_type", "=", "conf", "[", "CONF_HEATING_TYPE", "]", "try", ":", "if", "heating_type", "==", "HeatingType", ".", "gas", ":", "vicare_api", "=", "GazBoiler", "(", "conf", "[", "CONF_USERNAME", "]", ",", "conf", "[", "CONF_PASSWORD", "]", ",", "*", "*", "params", ")", "elif", "heating_type", "==", "HeatingType", ".", "heatpump", ":", "vicare_api", "=", "HeatPump", "(", "conf", "[", "CONF_USERNAME", "]", ",", "conf", "[", "CONF_PASSWORD", "]", ",", "*", "*", "params", ")", "else", ":", "vicare_api", "=", "Device", "(", "conf", "[", "CONF_USERNAME", "]", ",", "conf", "[", "CONF_PASSWORD", "]", ",", "*", "*", "params", ")", "except", "AttributeError", ":", "_LOGGER", ".", "error", "(", "\"Failed to create PyViCare API client. Please check your credentials\"", ")", "return", "False", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "VICARE_API", "]", "=", "vicare_api", "hass", ".", "data", "[", "DOMAIN", "]", "[", "VICARE_NAME", "]", "=", "conf", "[", "CONF_NAME", "]", "hass", ".", "data", "[", "DOMAIN", "]", "[", "VICARE_HEATING_TYPE", "]", "=", "heating_type", "for", "platform", "in", "VICARE_PLATFORMS", ":", "discovery", ".", "load_platform", "(", "hass", ",", "platform", ",", "DOMAIN", ",", "{", "}", ",", "config", ")", "return", "True" ]
[ 63, 0 ]
[ 95, 15 ]
python
en
['en', 'en', 'en']
True
request_stream
(hass, stream_source, *, fmt="hls", keepalive=False, options=None)
Set up stream with token.
Set up stream with token.
def request_stream(hass, stream_source, *, fmt="hls", keepalive=False, options=None): """Set up stream with token.""" if DOMAIN not in hass.config.components: raise HomeAssistantError("Stream integration is not set up.") if options is None: options = {} # For RTSP streams, prefer TCP if isinstance(stream_source, str) and stream_source[:7] == "rtsp://": options = { "rtsp_flags": "prefer_tcp", "stimeout": "5000000", **options, } try: streams = hass.data[DOMAIN][ATTR_STREAMS] stream = streams.get(stream_source) if not stream: stream = Stream(hass, stream_source, options=options, keepalive=keepalive) streams[stream_source] = stream else: # Update keepalive option on existing stream stream.keepalive = keepalive # Add provider stream.add_provider(fmt) if not stream.access_token: stream.access_token = secrets.token_hex() stream.start() return hass.data[DOMAIN][ATTR_ENDPOINTS][fmt].format(stream.access_token) except Exception as err: raise HomeAssistantError("Unable to get stream") from err
[ "def", "request_stream", "(", "hass", ",", "stream_source", ",", "*", ",", "fmt", "=", "\"hls\"", ",", "keepalive", "=", "False", ",", "options", "=", "None", ")", ":", "if", "DOMAIN", "not", "in", "hass", ".", "config", ".", "components", ":", "raise", "HomeAssistantError", "(", "\"Stream integration is not set up.\"", ")", "if", "options", "is", "None", ":", "options", "=", "{", "}", "# For RTSP streams, prefer TCP", "if", "isinstance", "(", "stream_source", ",", "str", ")", "and", "stream_source", "[", ":", "7", "]", "==", "\"rtsp://\"", ":", "options", "=", "{", "\"rtsp_flags\"", ":", "\"prefer_tcp\"", ",", "\"stimeout\"", ":", "\"5000000\"", ",", "*", "*", "options", ",", "}", "try", ":", "streams", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_STREAMS", "]", "stream", "=", "streams", ".", "get", "(", "stream_source", ")", "if", "not", "stream", ":", "stream", "=", "Stream", "(", "hass", ",", "stream_source", ",", "options", "=", "options", ",", "keepalive", "=", "keepalive", ")", "streams", "[", "stream_source", "]", "=", "stream", "else", ":", "# Update keepalive option on existing stream", "stream", ".", "keepalive", "=", "keepalive", "# Add provider", "stream", ".", "add_provider", "(", "fmt", ")", "if", "not", "stream", ".", "access_token", ":", "stream", ".", "access_token", "=", "secrets", ".", "token_hex", "(", ")", "stream", ".", "start", "(", ")", "return", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_ENDPOINTS", "]", "[", "fmt", "]", ".", "format", "(", "stream", ".", "access_token", ")", "except", "Exception", "as", "err", ":", "raise", "HomeAssistantError", "(", "\"Unable to get stream\"", ")", "from", "err" ]
[ 43, 0 ]
[ 77, 65 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up stream.
Set up stream.
async def async_setup(hass, config): """Set up stream.""" # Set log level to error for libav logging.getLogger("libav").setLevel(logging.ERROR) logging.getLogger("libav.mp4").setLevel(logging.ERROR) # Keep import here so that we can import stream integration without installing reqs # pylint: disable=import-outside-toplevel from .recorder import async_setup_recorder hass.data[DOMAIN] = {} hass.data[DOMAIN][ATTR_ENDPOINTS] = {} hass.data[DOMAIN][ATTR_STREAMS] = {} # Setup HLS hls_endpoint = async_setup_hls(hass) hass.data[DOMAIN][ATTR_ENDPOINTS]["hls"] = hls_endpoint # Setup Recorder async_setup_recorder(hass) @callback def shutdown(event): """Stop all stream workers.""" for stream in hass.data[DOMAIN][ATTR_STREAMS].values(): stream.keepalive = False stream.stop() _LOGGER.info("Stopped stream workers") hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shutdown) async def async_record(call): """Call record stream service handler.""" await async_handle_record_service(hass, call) hass.services.async_register( DOMAIN, SERVICE_RECORD, async_record, schema=SERVICE_RECORD_SCHEMA ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "# Set log level to error for libav", "logging", ".", "getLogger", "(", "\"libav\"", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "logging", ".", "getLogger", "(", "\"libav.mp4\"", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "# Keep import here so that we can import stream integration without installing reqs", "# pylint: disable=import-outside-toplevel", "from", ".", "recorder", "import", "async_setup_recorder", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_ENDPOINTS", "]", "=", "{", "}", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_STREAMS", "]", "=", "{", "}", "# Setup HLS", "hls_endpoint", "=", "async_setup_hls", "(", "hass", ")", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_ENDPOINTS", "]", "[", "\"hls\"", "]", "=", "hls_endpoint", "# Setup Recorder", "async_setup_recorder", "(", "hass", ")", "@", "callback", "def", "shutdown", "(", "event", ")", ":", "\"\"\"Stop all stream workers.\"\"\"", "for", "stream", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_STREAMS", "]", ".", "values", "(", ")", ":", "stream", ".", "keepalive", "=", "False", "stream", ".", "stop", "(", ")", "_LOGGER", ".", "info", "(", "\"Stopped stream workers\"", ")", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "shutdown", ")", "async", "def", "async_record", "(", "call", ")", ":", "\"\"\"Call record stream service handler.\"\"\"", "await", "async_handle_record_service", "(", "hass", ",", "call", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_RECORD", ",", "async_record", ",", "schema", "=", "SERVICE_RECORD_SCHEMA", ")", "return", "True" ]
[ 80, 0 ]
[ 119, 15 ]
python
en
['en', 'ky', 'en']
True
async_handle_record_service
(hass, call)
Handle save video service calls.
Handle save video service calls.
async def async_handle_record_service(hass, call): """Handle save video service calls.""" stream_source = call.data[CONF_STREAM_SOURCE] video_path = call.data[CONF_FILENAME] duration = call.data[CONF_DURATION] lookback = call.data[CONF_LOOKBACK] # Check for file access if not hass.config.is_allowed_path(video_path): raise HomeAssistantError(f"Can't write {video_path}, no access to path!") # Check for active stream streams = hass.data[DOMAIN][ATTR_STREAMS] stream = streams.get(stream_source) if not stream: stream = Stream(hass, stream_source) streams[stream_source] = stream # Add recorder recorder = stream.outputs.get("recorder") if recorder: raise HomeAssistantError(f"Stream already recording to {recorder.video_path}!") recorder = stream.add_provider("recorder") recorder.video_path = video_path recorder.timeout = duration stream.start() # Take advantage of lookback hls = stream.outputs.get("hls") if lookback > 0 and hls: num_segments = min(int(lookback // hls.target_duration), MAX_SEGMENTS) # Wait for latest segment, then add the lookback await hls.recv() recorder.prepend(list(hls.get_segment())[-num_segments:])
[ "async", "def", "async_handle_record_service", "(", "hass", ",", "call", ")", ":", "stream_source", "=", "call", ".", "data", "[", "CONF_STREAM_SOURCE", "]", "video_path", "=", "call", ".", "data", "[", "CONF_FILENAME", "]", "duration", "=", "call", ".", "data", "[", "CONF_DURATION", "]", "lookback", "=", "call", ".", "data", "[", "CONF_LOOKBACK", "]", "# Check for file access", "if", "not", "hass", ".", "config", ".", "is_allowed_path", "(", "video_path", ")", ":", "raise", "HomeAssistantError", "(", "f\"Can't write {video_path}, no access to path!\"", ")", "# Check for active stream", "streams", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "ATTR_STREAMS", "]", "stream", "=", "streams", ".", "get", "(", "stream_source", ")", "if", "not", "stream", ":", "stream", "=", "Stream", "(", "hass", ",", "stream_source", ")", "streams", "[", "stream_source", "]", "=", "stream", "# Add recorder", "recorder", "=", "stream", ".", "outputs", ".", "get", "(", "\"recorder\"", ")", "if", "recorder", ":", "raise", "HomeAssistantError", "(", "f\"Stream already recording to {recorder.video_path}!\"", ")", "recorder", "=", "stream", ".", "add_provider", "(", "\"recorder\"", ")", "recorder", ".", "video_path", "=", "video_path", "recorder", ".", "timeout", "=", "duration", "stream", ".", "start", "(", ")", "# Take advantage of lookback", "hls", "=", "stream", ".", "outputs", ".", "get", "(", "\"hls\"", ")", "if", "lookback", ">", "0", "and", "hls", ":", "num_segments", "=", "min", "(", "int", "(", "lookback", "//", "hls", ".", "target_duration", ")", ",", "MAX_SEGMENTS", ")", "# Wait for latest segment, then add the lookback", "await", "hls", ".", "recv", "(", ")", "recorder", ".", "prepend", "(", "list", "(", "hls", ".", "get_segment", "(", ")", ")", "[", "-", "num_segments", ":", "]", ")" ]
[ 204, 0 ]
[ 239, 65 ]
python
en
['en', 'en', 'en']
True