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
LoginFlow.async_step_select_mfa_module
( self, user_input: Optional[Dict[str, str]] = None )
Handle the step of select mfa module.
Handle the step of select mfa module.
async def async_step_select_mfa_module( self, user_input: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """Handle the step of select mfa module.""" errors = {} if user_input is not None: auth_module = user_input.get("multi_factor_auth_module") if auth_module in self.available_mfa_modules: self._auth_module_id = auth_module return await self.async_step_mfa() errors["base"] = "invalid_auth_module" if len(self.available_mfa_modules) == 1: self._auth_module_id = list(self.available_mfa_modules)[0] return await self.async_step_mfa() return self.async_show_form( step_id="select_mfa_module", data_schema=vol.Schema( {"multi_factor_auth_module": vol.In(self.available_mfa_modules)} ), errors=errors, )
[ "async", "def", "async_step_select_mfa_module", "(", "self", ",", "user_input", ":", "Optional", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "auth_module", "=", "user_input", ".", "get", "(", "\"multi_factor_auth_module\"", ")", "if", "auth_module", "in", "self", ".", "available_mfa_modules", ":", "self", ".", "_auth_module_id", "=", "auth_module", "return", "await", "self", ".", "async_step_mfa", "(", ")", "errors", "[", "\"base\"", "]", "=", "\"invalid_auth_module\"", "if", "len", "(", "self", ".", "available_mfa_modules", ")", "==", "1", ":", "self", ".", "_auth_module_id", "=", "list", "(", "self", ".", "available_mfa_modules", ")", "[", "0", "]", "return", "await", "self", ".", "async_step_mfa", "(", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"select_mfa_module\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "\"multi_factor_auth_module\"", ":", "vol", ".", "In", "(", "self", ".", "available_mfa_modules", ")", "}", ")", ",", "errors", "=", "errors", ",", ")" ]
[ 195, 4 ]
[ 218, 9 ]
python
en
['en', 'en', 'en']
True
LoginFlow.async_step_mfa
( self, user_input: Optional[Dict[str, str]] = None )
Handle the step of mfa validation.
Handle the step of mfa validation.
async def async_step_mfa( self, user_input: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """Handle the step of mfa validation.""" assert self.user errors = {} assert self._auth_module_id is not None auth_module = self._auth_manager.get_auth_mfa_module(self._auth_module_id) if auth_module is None: # Given an invalid input to async_step_select_mfa_module # will show invalid_auth_module error return await self.async_step_select_mfa_module(user_input={}) if user_input is None and hasattr( auth_module, "async_initialize_login_mfa_step" ): try: await auth_module.async_initialize_login_mfa_step( # type: ignore self.user.id ) except HomeAssistantError: _LOGGER.exception("Error initializing MFA step") return self.async_abort(reason="unknown_error") if user_input is not None: expires = self.created_at + MFA_SESSION_EXPIRATION if dt_util.utcnow() > expires: return self.async_abort(reason="login_expired") result = await auth_module.async_validate(self.user.id, user_input) if not result: errors["base"] = "invalid_code" self.invalid_mfa_times += 1 if self.invalid_mfa_times >= auth_module.MAX_RETRY_TIME > 0: return self.async_abort(reason="too_many_retry") if not errors: return await self.async_finish(self.user) description_placeholders: Dict[str, Optional[str]] = { "mfa_module_name": auth_module.name, "mfa_module_id": auth_module.id, } return self.async_show_form( step_id="mfa", data_schema=auth_module.input_schema, description_placeholders=description_placeholders, errors=errors, )
[ "async", "def", "async_step_mfa", "(", "self", ",", "user_input", ":", "Optional", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "assert", "self", ".", "user", "errors", "=", "{", "}", "assert", "self", ".", "_auth_module_id", "is", "not", "None", "auth_module", "=", "self", ".", "_auth_manager", ".", "get_auth_mfa_module", "(", "self", ".", "_auth_module_id", ")", "if", "auth_module", "is", "None", ":", "# Given an invalid input to async_step_select_mfa_module", "# will show invalid_auth_module error", "return", "await", "self", ".", "async_step_select_mfa_module", "(", "user_input", "=", "{", "}", ")", "if", "user_input", "is", "None", "and", "hasattr", "(", "auth_module", ",", "\"async_initialize_login_mfa_step\"", ")", ":", "try", ":", "await", "auth_module", ".", "async_initialize_login_mfa_step", "(", "# type: ignore", "self", ".", "user", ".", "id", ")", "except", "HomeAssistantError", ":", "_LOGGER", ".", "exception", "(", "\"Error initializing MFA step\"", ")", "return", "self", ".", "async_abort", "(", "reason", "=", "\"unknown_error\"", ")", "if", "user_input", "is", "not", "None", ":", "expires", "=", "self", ".", "created_at", "+", "MFA_SESSION_EXPIRATION", "if", "dt_util", ".", "utcnow", "(", ")", ">", "expires", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"login_expired\"", ")", "result", "=", "await", "auth_module", ".", "async_validate", "(", "self", ".", "user", ".", "id", ",", "user_input", ")", "if", "not", "result", ":", "errors", "[", "\"base\"", "]", "=", "\"invalid_code\"", "self", ".", "invalid_mfa_times", "+=", "1", "if", "self", ".", "invalid_mfa_times", ">=", "auth_module", ".", "MAX_RETRY_TIME", ">", "0", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"too_many_retry\"", ")", "if", "not", "errors", ":", "return", "await", "self", ".", "async_finish", "(", "self", ".", "user", ")", "description_placeholders", ":", "Dict", "[", "str", ",", "Optional", "[", "str", "]", "]", "=", "{", "\"mfa_module_name\"", ":", "auth_module", ".", "name", ",", "\"mfa_module_id\"", ":", "auth_module", ".", "id", ",", "}", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"mfa\"", ",", "data_schema", "=", "auth_module", ".", "input_schema", ",", "description_placeholders", "=", "description_placeholders", ",", "errors", "=", "errors", ",", ")" ]
[ 220, 4 ]
[ 271, 9 ]
python
en
['en', 'en', 'en']
True
LoginFlow.async_finish
(self, flow_result: Any)
Handle the pass of login flow.
Handle the pass of login flow.
async def async_finish(self, flow_result: Any) -> Dict: """Handle the pass of login flow.""" return self.async_create_entry(title=self._auth_provider.name, data=flow_result)
[ "async", "def", "async_finish", "(", "self", ",", "flow_result", ":", "Any", ")", "->", "Dict", ":", "return", "self", ".", "async_create_entry", "(", "title", "=", "self", ".", "_auth_provider", ".", "name", ",", "data", "=", "flow_result", ")" ]
[ 273, 4 ]
[ 275, 88 ]
python
en
['en', 'en', 'en']
True
clip_pad_images
(tensor, pad_shape, pad=0)
Clip clip_pad_images of the pad area. :param tensor: [c, H, W] :param pad_shape: [h, w] :return: [c, h, w]
Clip clip_pad_images of the pad area. :param tensor: [c, H, W] :param pad_shape: [h, w] :return: [c, h, w]
def clip_pad_images(tensor, pad_shape, pad=0): """ Clip clip_pad_images of the pad area. :param tensor: [c, H, W] :param pad_shape: [h, w] :return: [c, h, w] """ if not isinstance(tensor, torch.Tensor): tensor = torch.as_tensor(tensor) H, W = tensor.shape[1:] h = pad_shape[1] w = pad_shape[2] tensor_ret = torch.zeros((tensor.shape[0], h, w), dtype=tensor.dtype) + pad tensor_ret[:, :min(h, H), :min(w, W)] = tensor[:, :min(h, H), :min(w, W)] return tensor_ret
[ "def", "clip_pad_images", "(", "tensor", ",", "pad_shape", ",", "pad", "=", "0", ")", ":", "if", "not", "isinstance", "(", "tensor", ",", "torch", ".", "Tensor", ")", ":", "tensor", "=", "torch", ".", "as_tensor", "(", "tensor", ")", "H", ",", "W", "=", "tensor", ".", "shape", "[", "1", ":", "]", "h", "=", "pad_shape", "[", "1", "]", "w", "=", "pad_shape", "[", "2", "]", "tensor_ret", "=", "torch", ".", "zeros", "(", "(", "tensor", ".", "shape", "[", "0", "]", ",", "h", ",", "w", ")", ",", "dtype", "=", "tensor", ".", "dtype", ")", "+", "pad", "tensor_ret", "[", ":", ",", ":", "min", "(", "h", ",", "H", ")", ",", ":", "min", "(", "w", ",", "W", ")", "]", "=", "tensor", "[", ":", ",", ":", "min", "(", "h", ",", "H", ")", ",", ":", "min", "(", "w", ",", "W", ")", "]", "return", "tensor_ret" ]
[ 3, 0 ]
[ 19, 21 ]
python
en
['en', 'error', 'th']
False
clip_pad_boxes
(tensor, pad_length, pad=0)
Clip boxes of the pad area. :param tensor: [k, d] :param pad_shape: K :return: [K, d]
Clip boxes of the pad area. :param tensor: [k, d] :param pad_shape: K :return: [K, d]
def clip_pad_boxes(tensor, pad_length, pad=0): """ Clip boxes of the pad area. :param tensor: [k, d] :param pad_shape: K :return: [K, d] """ if not isinstance(tensor, torch.Tensor): tensor = torch.as_tensor(tensor) k = tensor.shape[0] d = tensor.shape[1] K = pad_length tensor_ret = torch.zeros((K, d), dtype=tensor.dtype) + pad tensor_ret[:min(k, K), :] = tensor[:min(k, K), :] return tensor_ret
[ "def", "clip_pad_boxes", "(", "tensor", ",", "pad_length", ",", "pad", "=", "0", ")", ":", "if", "not", "isinstance", "(", "tensor", ",", "torch", ".", "Tensor", ")", ":", "tensor", "=", "torch", ".", "as_tensor", "(", "tensor", ")", "k", "=", "tensor", ".", "shape", "[", "0", "]", "d", "=", "tensor", ".", "shape", "[", "1", "]", "K", "=", "pad_length", "tensor_ret", "=", "torch", ".", "zeros", "(", "(", "K", ",", "d", ")", ",", "dtype", "=", "tensor", ".", "dtype", ")", "+", "pad", "tensor_ret", "[", ":", "min", "(", "k", ",", "K", ")", ",", ":", "]", "=", "tensor", "[", ":", "min", "(", "k", ",", "K", ")", ",", ":", "]", "return", "tensor_ret" ]
[ 22, 0 ]
[ 37, 21 ]
python
en
['en', 'error', 'th']
False
_convert_states
(states)
Convert state definitions to State objects.
Convert state definitions to State objects.
def _convert_states(states): """Convert state definitions to State objects.""" result = {} for entity_id, info in states.items(): entity_id = cv.entity_id(entity_id) if isinstance(info, dict): entity_attrs = info.copy() state = entity_attrs.pop(ATTR_STATE, None) attributes = entity_attrs else: state = info attributes = {} # YAML translates 'on' to a boolean # http://yaml.org/type/bool.html if isinstance(state, bool): state = STATE_ON if state else STATE_OFF elif not isinstance(state, str): raise vol.Invalid(f"State for {entity_id} should be a string") result[entity_id] = State(entity_id, state, attributes) return result
[ "def", "_convert_states", "(", "states", ")", ":", "result", "=", "{", "}", "for", "entity_id", ",", "info", "in", "states", ".", "items", "(", ")", ":", "entity_id", "=", "cv", ".", "entity_id", "(", "entity_id", ")", "if", "isinstance", "(", "info", ",", "dict", ")", ":", "entity_attrs", "=", "info", ".", "copy", "(", ")", "state", "=", "entity_attrs", ".", "pop", "(", "ATTR_STATE", ",", "None", ")", "attributes", "=", "entity_attrs", "else", ":", "state", "=", "info", "attributes", "=", "{", "}", "# YAML translates 'on' to a boolean", "# http://yaml.org/type/bool.html", "if", "isinstance", "(", "state", ",", "bool", ")", ":", "state", "=", "STATE_ON", "if", "state", "else", "STATE_OFF", "elif", "not", "isinstance", "(", "state", ",", "str", ")", ":", "raise", "vol", ".", "Invalid", "(", "f\"State for {entity_id} should be a string\"", ")", "result", "[", "entity_id", "]", "=", "State", "(", "entity_id", ",", "state", ",", "attributes", ")", "return", "result" ]
[ 33, 0 ]
[ 57, 17 ]
python
en
['en', 'en', 'en']
True
_ensure_no_intersection
(value)
Validate that entities and snapshot_entities do not overlap.
Validate that entities and snapshot_entities do not overlap.
def _ensure_no_intersection(value): """Validate that entities and snapshot_entities do not overlap.""" if ( CONF_SNAPSHOT not in value or CONF_ENTITIES not in value or all( entity_id not in value[CONF_SNAPSHOT] for entity_id in value[CONF_ENTITIES] ) ): return value raise vol.Invalid("entities and snapshot_entities must not overlap")
[ "def", "_ensure_no_intersection", "(", "value", ")", ":", "if", "(", "CONF_SNAPSHOT", "not", "in", "value", "or", "CONF_ENTITIES", "not", "in", "value", "or", "all", "(", "entity_id", "not", "in", "value", "[", "CONF_SNAPSHOT", "]", "for", "entity_id", "in", "value", "[", "CONF_ENTITIES", "]", ")", ")", ":", "return", "value", "raise", "vol", ".", "Invalid", "(", "\"entities and snapshot_entities must not overlap\"", ")" ]
[ 60, 0 ]
[ 71, 72 ]
python
en
['en', 'en', 'en']
True
scenes_with_entity
(hass: HomeAssistant, entity_id: str)
Return all scenes that reference the entity.
Return all scenes that reference the entity.
def scenes_with_entity(hass: HomeAssistant, entity_id: str) -> List[str]: """Return all scenes that reference the entity.""" if DATA_PLATFORM not in hass.data: return [] platform = hass.data[DATA_PLATFORM] return [ scene_entity.entity_id for scene_entity in platform.entities.values() if entity_id in scene_entity.scene_config.states ]
[ "def", "scenes_with_entity", "(", "hass", ":", "HomeAssistant", ",", "entity_id", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "DATA_PLATFORM", "not", "in", "hass", ".", "data", ":", "return", "[", "]", "platform", "=", "hass", ".", "data", "[", "DATA_PLATFORM", "]", "return", "[", "scene_entity", ".", "entity_id", "for", "scene_entity", "in", "platform", ".", "entities", ".", "values", "(", ")", "if", "entity_id", "in", "scene_entity", ".", "scene_config", ".", "states", "]" ]
[ 120, 0 ]
[ 131, 5 ]
python
en
['en', 'en', 'en']
True
entities_in_scene
(hass: HomeAssistant, entity_id: str)
Return all entities in a scene.
Return all entities in a scene.
def entities_in_scene(hass: HomeAssistant, entity_id: str) -> List[str]: """Return all entities in a scene.""" if DATA_PLATFORM not in hass.data: return [] platform = hass.data[DATA_PLATFORM] entity = platform.entities.get(entity_id) if entity is None: return [] return list(entity.scene_config.states)
[ "def", "entities_in_scene", "(", "hass", ":", "HomeAssistant", ",", "entity_id", ":", "str", ")", "->", "List", "[", "str", "]", ":", "if", "DATA_PLATFORM", "not", "in", "hass", ".", "data", ":", "return", "[", "]", "platform", "=", "hass", ".", "data", "[", "DATA_PLATFORM", "]", "entity", "=", "platform", ".", "entities", ".", "get", "(", "entity_id", ")", "if", "entity", "is", "None", ":", "return", "[", "]", "return", "list", "(", "entity", ".", "scene_config", ".", "states", ")" ]
[ 135, 0 ]
[ 147, 43 ]
python
en
['en', 'fy', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up Home Assistant scene entries.
Set up Home Assistant scene entries.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up Home Assistant scene entries.""" _process_scenes_config(hass, async_add_entities, config) # This platform can be loaded multiple times. Only first time register the service. if hass.services.has_service(SCENE_DOMAIN, SERVICE_RELOAD): return # Store platform for later. platform = hass.data[DATA_PLATFORM] = entity_platform.current_platform.get() async def reload_config(call): """Reload the scene config.""" try: conf = await conf_util.async_hass_config_yaml(hass) except HomeAssistantError as err: _LOGGER.error(err) return integration = await async_get_integration(hass, SCENE_DOMAIN) conf = await conf_util.async_process_component_config(hass, conf, integration) if not (conf and platform): return await platform.async_reset() # Extract only the config for the Home Assistant platform, ignore the rest. for p_type, p_config in config_per_platform(conf, SCENE_DOMAIN): if p_type != HA_DOMAIN: continue _process_scenes_config(hass, async_add_entities, p_config) hass.bus.async_fire(EVENT_SCENE_RELOADED, context=call.context) hass.helpers.service.async_register_admin_service( SCENE_DOMAIN, SERVICE_RELOAD, reload_config ) async def apply_service(call): """Apply a scene.""" reproduce_options = {} if ATTR_TRANSITION in call.data: reproduce_options[ATTR_TRANSITION] = call.data.get(ATTR_TRANSITION) await async_reproduce_state( hass, call.data[CONF_ENTITIES].values(), context=call.context, reproduce_options=reproduce_options, ) hass.services.async_register( SCENE_DOMAIN, SERVICE_APPLY, apply_service, vol.Schema( { vol.Optional(ATTR_TRANSITION): vol.All( vol.Coerce(float), vol.Clamp(min=0, max=6553) ), vol.Required(CONF_ENTITIES): STATES_SCHEMA, } ), ) async def create_service(call): """Create a scene.""" snapshot = call.data[CONF_SNAPSHOT] entities = call.data[CONF_ENTITIES] for entity_id in snapshot: state = hass.states.get(entity_id) if state is None: _LOGGER.warning( "Entity %s does not exist and therefore cannot be snapshotted", entity_id, ) continue entities[entity_id] = State(entity_id, state.state, state.attributes) if not entities: _LOGGER.warning("Empty scenes are not allowed") return scene_config = SCENECONFIG(None, call.data[CONF_SCENE_ID], None, entities) entity_id = f"{SCENE_DOMAIN}.{scene_config.name}" old = platform.entities.get(entity_id) if old is not None: if not old.from_service: _LOGGER.warning("The scene %s already exists", entity_id) return await platform.async_remove_entity(entity_id) async_add_entities([HomeAssistantScene(hass, scene_config, from_service=True)]) hass.services.async_register( SCENE_DOMAIN, SERVICE_CREATE, create_service, CREATE_SCENE_SCHEMA )
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "_process_scenes_config", "(", "hass", ",", "async_add_entities", ",", "config", ")", "# This platform can be loaded multiple times. Only first time register the service.", "if", "hass", ".", "services", ".", "has_service", "(", "SCENE_DOMAIN", ",", "SERVICE_RELOAD", ")", ":", "return", "# Store platform for later.", "platform", "=", "hass", ".", "data", "[", "DATA_PLATFORM", "]", "=", "entity_platform", ".", "current_platform", ".", "get", "(", ")", "async", "def", "reload_config", "(", "call", ")", ":", "\"\"\"Reload the scene config.\"\"\"", "try", ":", "conf", "=", "await", "conf_util", ".", "async_hass_config_yaml", "(", "hass", ")", "except", "HomeAssistantError", "as", "err", ":", "_LOGGER", ".", "error", "(", "err", ")", "return", "integration", "=", "await", "async_get_integration", "(", "hass", ",", "SCENE_DOMAIN", ")", "conf", "=", "await", "conf_util", ".", "async_process_component_config", "(", "hass", ",", "conf", ",", "integration", ")", "if", "not", "(", "conf", "and", "platform", ")", ":", "return", "await", "platform", ".", "async_reset", "(", ")", "# Extract only the config for the Home Assistant platform, ignore the rest.", "for", "p_type", ",", "p_config", "in", "config_per_platform", "(", "conf", ",", "SCENE_DOMAIN", ")", ":", "if", "p_type", "!=", "HA_DOMAIN", ":", "continue", "_process_scenes_config", "(", "hass", ",", "async_add_entities", ",", "p_config", ")", "hass", ".", "bus", ".", "async_fire", "(", "EVENT_SCENE_RELOADED", ",", "context", "=", "call", ".", "context", ")", "hass", ".", "helpers", ".", "service", ".", "async_register_admin_service", "(", "SCENE_DOMAIN", ",", "SERVICE_RELOAD", ",", "reload_config", ")", "async", "def", "apply_service", "(", "call", ")", ":", "\"\"\"Apply a scene.\"\"\"", "reproduce_options", "=", "{", "}", "if", "ATTR_TRANSITION", "in", "call", ".", "data", ":", "reproduce_options", "[", "ATTR_TRANSITION", "]", "=", "call", ".", "data", ".", "get", "(", "ATTR_TRANSITION", ")", "await", "async_reproduce_state", "(", "hass", ",", "call", ".", "data", "[", "CONF_ENTITIES", "]", ".", "values", "(", ")", ",", "context", "=", "call", ".", "context", ",", "reproduce_options", "=", "reproduce_options", ",", ")", "hass", ".", "services", ".", "async_register", "(", "SCENE_DOMAIN", ",", "SERVICE_APPLY", ",", "apply_service", ",", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "ATTR_TRANSITION", ")", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "float", ")", ",", "vol", ".", "Clamp", "(", "min", "=", "0", ",", "max", "=", "6553", ")", ")", ",", "vol", ".", "Required", "(", "CONF_ENTITIES", ")", ":", "STATES_SCHEMA", ",", "}", ")", ",", ")", "async", "def", "create_service", "(", "call", ")", ":", "\"\"\"Create a scene.\"\"\"", "snapshot", "=", "call", ".", "data", "[", "CONF_SNAPSHOT", "]", "entities", "=", "call", ".", "data", "[", "CONF_ENTITIES", "]", "for", "entity_id", "in", "snapshot", ":", "state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "if", "state", "is", "None", ":", "_LOGGER", ".", "warning", "(", "\"Entity %s does not exist and therefore cannot be snapshotted\"", ",", "entity_id", ",", ")", "continue", "entities", "[", "entity_id", "]", "=", "State", "(", "entity_id", ",", "state", ".", "state", ",", "state", ".", "attributes", ")", "if", "not", "entities", ":", "_LOGGER", ".", "warning", "(", "\"Empty scenes are not allowed\"", ")", "return", "scene_config", "=", "SCENECONFIG", "(", "None", ",", "call", ".", "data", "[", "CONF_SCENE_ID", "]", ",", "None", ",", "entities", ")", "entity_id", "=", "f\"{SCENE_DOMAIN}.{scene_config.name}\"", "old", "=", "platform", ".", "entities", ".", "get", "(", "entity_id", ")", "if", "old", "is", "not", "None", ":", "if", "not", "old", ".", "from_service", ":", "_LOGGER", ".", "warning", "(", "\"The scene %s already exists\"", ",", "entity_id", ")", "return", "await", "platform", ".", "async_remove_entity", "(", "entity_id", ")", "async_add_entities", "(", "[", "HomeAssistantScene", "(", "hass", ",", "scene_config", ",", "from_service", "=", "True", ")", "]", ")", "hass", ".", "services", ".", "async_register", "(", "SCENE_DOMAIN", ",", "SERVICE_CREATE", ",", "create_service", ",", "CREATE_SCENE_SCHEMA", ")" ]
[ 150, 0 ]
[ 250, 5 ]
python
en
['en', 'en', 'en']
True
_process_scenes_config
(hass, async_add_entities, config)
Process multiple scenes and add them.
Process multiple scenes and add them.
def _process_scenes_config(hass, async_add_entities, config): """Process multiple scenes and add them.""" scene_config = config[STATES] # Check empty list if not scene_config: return async_add_entities( HomeAssistantScene( hass, SCENECONFIG( scene.get(CONF_ID), scene[CONF_NAME], scene.get(CONF_ICON), scene[CONF_ENTITIES], ), ) for scene in scene_config )
[ "def", "_process_scenes_config", "(", "hass", ",", "async_add_entities", ",", "config", ")", ":", "scene_config", "=", "config", "[", "STATES", "]", "# Check empty list", "if", "not", "scene_config", ":", "return", "async_add_entities", "(", "HomeAssistantScene", "(", "hass", ",", "SCENECONFIG", "(", "scene", ".", "get", "(", "CONF_ID", ")", ",", "scene", "[", "CONF_NAME", "]", ",", "scene", ".", "get", "(", "CONF_ICON", ")", ",", "scene", "[", "CONF_ENTITIES", "]", ",", ")", ",", ")", "for", "scene", "in", "scene_config", ")" ]
[ 253, 0 ]
[ 272, 5 ]
python
en
['en', 'en', 'en']
True
HomeAssistantScene.__init__
(self, hass, scene_config, from_service=False)
Initialize the scene.
Initialize the scene.
def __init__(self, hass, scene_config, from_service=False): """Initialize the scene.""" self.hass = hass self.scene_config = scene_config self.from_service = from_service
[ "def", "__init__", "(", "self", ",", "hass", ",", "scene_config", ",", "from_service", "=", "False", ")", ":", "self", ".", "hass", "=", "hass", "self", ".", "scene_config", "=", "scene_config", "self", ".", "from_service", "=", "from_service" ]
[ 278, 4 ]
[ 282, 40 ]
python
en
['en', 'it', 'en']
True
HomeAssistantScene.name
(self)
Return the name of the scene.
Return the name of the scene.
def name(self): """Return the name of the scene.""" return self.scene_config.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "scene_config", ".", "name" ]
[ 285, 4 ]
[ 287, 37 ]
python
en
['en', 'ig', 'en']
True
HomeAssistantScene.icon
(self)
Return the icon of the scene.
Return the icon of the scene.
def icon(self): """Return the icon of the scene.""" return self.scene_config.icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "scene_config", ".", "icon" ]
[ 290, 4 ]
[ 292, 37 ]
python
en
['en', 'en', 'en']
True
HomeAssistantScene.unique_id
(self)
Return unique ID.
Return unique ID.
def unique_id(self): """Return unique ID.""" return self.scene_config.id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "scene_config", ".", "id" ]
[ 295, 4 ]
[ 297, 35 ]
python
en
['fr', 'la', 'en']
False
HomeAssistantScene.device_state_attributes
(self)
Return the scene state attributes.
Return the scene state attributes.
def device_state_attributes(self): """Return the scene state attributes.""" attributes = {ATTR_ENTITY_ID: list(self.scene_config.states)} unique_id = self.unique_id if unique_id is not None: attributes[CONF_ID] = unique_id return attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "attributes", "=", "{", "ATTR_ENTITY_ID", ":", "list", "(", "self", ".", "scene_config", ".", "states", ")", "}", "unique_id", "=", "self", ".", "unique_id", "if", "unique_id", "is", "not", "None", ":", "attributes", "[", "CONF_ID", "]", "=", "unique_id", "return", "attributes" ]
[ 300, 4 ]
[ 306, 25 ]
python
en
['en', 'it', 'en']
True
HomeAssistantScene.async_activate
(self, **kwargs: Any)
Activate scene. Try to get entities into requested state.
Activate scene. Try to get entities into requested state.
async def async_activate(self, **kwargs: Any) -> None: """Activate scene. Try to get entities into requested state.""" await async_reproduce_state( self.hass, self.scene_config.states.values(), context=self._context, reproduce_options=kwargs, )
[ "async", "def", "async_activate", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "await", "async_reproduce_state", "(", "self", ".", "hass", ",", "self", ".", "scene_config", ".", "states", ".", "values", "(", ")", ",", "context", "=", "self", ".", "_context", ",", "reproduce_options", "=", "kwargs", ",", ")" ]
[ 308, 4 ]
[ 315, 9 ]
python
en
['en', 'en', 'en']
True
build
(release)
Compile TypeScript modules and copy or symlink to nni_node directory. `release` is the version number without leading letter "v". If `release` is None or empty, this is a development build and uses symlinks on Linux/macOS; otherwise this is a release build and copies files instead. On Windows it always copies files because creating symlink requires extra privilege.
Compile TypeScript modules and copy or symlink to nni_node directory.
def build(release): """ Compile TypeScript modules and copy or symlink to nni_node directory. `release` is the version number without leading letter "v". If `release` is None or empty, this is a development build and uses symlinks on Linux/macOS; otherwise this is a release build and copies files instead. On Windows it always copies files because creating symlink requires extra privilege. """ if release or not os.environ.get('GLOBAL_TOOLCHAIN'): download_toolchain() prepare_nni_node() compile_ts() if release or sys.platform == 'win32': copy_nni_node(release) else: symlink_nni_node()
[ "def", "build", "(", "release", ")", ":", "if", "release", "or", "not", "os", ".", "environ", ".", "get", "(", "'GLOBAL_TOOLCHAIN'", ")", ":", "download_toolchain", "(", ")", "prepare_nni_node", "(", ")", "compile_ts", "(", ")", "if", "release", "or", "sys", ".", "platform", "==", "'win32'", ":", "copy_nni_node", "(", "release", ")", "else", ":", "symlink_nni_node", "(", ")" ]
[ 28, 0 ]
[ 45, 26 ]
python
en
['en', 'error', 'th']
False
clean
(clean_all=False)
Remove TypeScript-related intermediate files. Python intermediate files are not touched here.
Remove TypeScript-related intermediate files. Python intermediate files are not touched here.
def clean(clean_all=False): """ Remove TypeScript-related intermediate files. Python intermediate files are not touched here. """ shutil.rmtree('nni_node', ignore_errors=True) for file_or_dir in generated_files: path = Path(file_or_dir) if path.is_symlink() or path.is_file(): path.unlink() elif path.is_dir(): shutil.rmtree(path) if clean_all: shutil.rmtree('toolchain', ignore_errors=True)
[ "def", "clean", "(", "clean_all", "=", "False", ")", ":", "shutil", ".", "rmtree", "(", "'nni_node'", ",", "ignore_errors", "=", "True", ")", "for", "file_or_dir", "in", "generated_files", ":", "path", "=", "Path", "(", "file_or_dir", ")", "if", "path", ".", "is_symlink", "(", ")", "or", "path", ".", "is_file", "(", ")", ":", "path", ".", "unlink", "(", ")", "elif", "path", ".", "is_dir", "(", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "if", "clean_all", ":", "shutil", ".", "rmtree", "(", "'toolchain'", ",", "ignore_errors", "=", "True", ")" ]
[ 47, 0 ]
[ 62, 54 ]
python
en
['en', 'error', 'th']
False
download_toolchain
()
Download and extract node and yarn.
Download and extract node and yarn.
def download_toolchain(): """ Download and extract node and yarn. """ if Path('toolchain/node', node_executable_in_tarball).is_file(): return Path('toolchain').mkdir(exist_ok=True) import requests # place it here so setup.py can install it before importing _print(f'Downloading node.js from {node_download_url}') resp = requests.get(node_download_url) resp.raise_for_status() _print('Extracting node.js') tarball = node_extractor(resp.content) tarball.extractall('toolchain') shutil.rmtree('toolchain/node', ignore_errors=True) Path('toolchain', node_spec).rename('toolchain/node') _print(f'Downloading yarn from {yarn_download_url}') resp = requests.get(yarn_download_url) resp.raise_for_status() _print('Extracting yarn') tarball = tarfile.open(fileobj=BytesIO(resp.content), mode='r:gz') tarball.extractall('toolchain') shutil.rmtree('toolchain/yarn', ignore_errors=True) Path(f'toolchain/yarn-{yarn_version}').rename('toolchain/yarn')
[ "def", "download_toolchain", "(", ")", ":", "if", "Path", "(", "'toolchain/node'", ",", "node_executable_in_tarball", ")", ".", "is_file", "(", ")", ":", "return", "Path", "(", "'toolchain'", ")", ".", "mkdir", "(", "exist_ok", "=", "True", ")", "import", "requests", "# place it here so setup.py can install it before importing", "_print", "(", "f'Downloading node.js from {node_download_url}'", ")", "resp", "=", "requests", ".", "get", "(", "node_download_url", ")", "resp", ".", "raise_for_status", "(", ")", "_print", "(", "'Extracting node.js'", ")", "tarball", "=", "node_extractor", "(", "resp", ".", "content", ")", "tarball", ".", "extractall", "(", "'toolchain'", ")", "shutil", ".", "rmtree", "(", "'toolchain/node'", ",", "ignore_errors", "=", "True", ")", "Path", "(", "'toolchain'", ",", "node_spec", ")", ".", "rename", "(", "'toolchain/node'", ")", "_print", "(", "f'Downloading yarn from {yarn_download_url}'", ")", "resp", "=", "requests", ".", "get", "(", "yarn_download_url", ")", "resp", ".", "raise_for_status", "(", ")", "_print", "(", "'Extracting yarn'", ")", "tarball", "=", "tarfile", ".", "open", "(", "fileobj", "=", "BytesIO", "(", "resp", ".", "content", ")", ",", "mode", "=", "'r:gz'", ")", "tarball", ".", "extractall", "(", "'toolchain'", ")", "shutil", ".", "rmtree", "(", "'toolchain/yarn'", ",", "ignore_errors", "=", "True", ")", "Path", "(", "f'toolchain/yarn-{yarn_version}'", ")", ".", "rename", "(", "'toolchain/yarn'", ")" ]
[ 93, 0 ]
[ 119, 67 ]
python
en
['en', 'error', 'th']
False
prepare_nni_node
()
Create clean nni_node diretory, then copy node runtime to it.
Create clean nni_node diretory, then copy node runtime to it.
def prepare_nni_node(): """ Create clean nni_node diretory, then copy node runtime to it. """ shutil.rmtree('nni_node', ignore_errors=True) Path('nni_node').mkdir() Path('nni_node/__init__.py').write_text('"""NNI node.js modules."""\n') node_src = Path('toolchain/node', node_executable_in_tarball) node_dst = Path('nni_node', node_executable) shutil.copy(node_src, node_dst)
[ "def", "prepare_nni_node", "(", ")", ":", "shutil", ".", "rmtree", "(", "'nni_node'", ",", "ignore_errors", "=", "True", ")", "Path", "(", "'nni_node'", ")", ".", "mkdir", "(", ")", "Path", "(", "'nni_node/__init__.py'", ")", ".", "write_text", "(", "'\"\"\"NNI node.js modules.\"\"\"\\n'", ")", "node_src", "=", "Path", "(", "'toolchain/node'", ",", "node_executable_in_tarball", ")", "node_dst", "=", "Path", "(", "'nni_node'", ",", "node_executable", ")", "shutil", ".", "copy", "(", "node_src", ",", "node_dst", ")" ]
[ 122, 0 ]
[ 133, 35 ]
python
en
['en', 'error', 'th']
False
compile_ts
()
Use yarn to download dependencies and compile TypeScript code.
Use yarn to download dependencies and compile TypeScript code.
def compile_ts(): """ Use yarn to download dependencies and compile TypeScript code. """ _print('Building NNI manager') _yarn('ts/nni_manager') _yarn('ts/nni_manager', 'build') # todo: I don't think these should be here shutil.rmtree('ts/nni_manager/dist/config', ignore_errors=True) shutil.copytree('ts/nni_manager/config', 'ts/nni_manager/dist/config') _print('Building web UI') _yarn('ts/webui') _yarn('ts/webui', 'build') _print('Building NAS UI') _yarn('ts/nasui') _yarn('ts/nasui', 'build')
[ "def", "compile_ts", "(", ")", ":", "_print", "(", "'Building NNI manager'", ")", "_yarn", "(", "'ts/nni_manager'", ")", "_yarn", "(", "'ts/nni_manager'", ",", "'build'", ")", "# todo: I don't think these should be here", "shutil", ".", "rmtree", "(", "'ts/nni_manager/dist/config'", ",", "ignore_errors", "=", "True", ")", "shutil", ".", "copytree", "(", "'ts/nni_manager/config'", ",", "'ts/nni_manager/dist/config'", ")", "_print", "(", "'Building web UI'", ")", "_yarn", "(", "'ts/webui'", ")", "_yarn", "(", "'ts/webui'", ",", "'build'", ")", "_print", "(", "'Building NAS UI'", ")", "_yarn", "(", "'ts/nasui'", ")", "_yarn", "(", "'ts/nasui'", ",", "'build'", ")" ]
[ 136, 0 ]
[ 153, 30 ]
python
en
['en', 'error', 'th']
False
symlink_nni_node
()
Create symlinks to compiled JS files. If you manually modify and compile TS source files you don't need to install again.
Create symlinks to compiled JS files. If you manually modify and compile TS source files you don't need to install again.
def symlink_nni_node(): """ Create symlinks to compiled JS files. If you manually modify and compile TS source files you don't need to install again. """ _print('Creating symlinks') for path in Path('ts/nni_manager/dist').iterdir(): _symlink(path, Path('nni_node', path.name)) _symlink('ts/nni_manager/package.json', 'nni_node/package.json') _symlink('ts/nni_manager/node_modules', 'nni_node/node_modules') _symlink('ts/webui/build', 'nni_node/static') Path('nni_node/nasui').mkdir(exist_ok=True) _symlink('ts/nasui/build', 'nni_node/nasui/build') _symlink('ts/nasui/server.js', 'nni_node/nasui/server.js')
[ "def", "symlink_nni_node", "(", ")", ":", "_print", "(", "'Creating symlinks'", ")", "for", "path", "in", "Path", "(", "'ts/nni_manager/dist'", ")", ".", "iterdir", "(", ")", ":", "_symlink", "(", "path", ",", "Path", "(", "'nni_node'", ",", "path", ".", "name", ")", ")", "_symlink", "(", "'ts/nni_manager/package.json'", ",", "'nni_node/package.json'", ")", "_symlink", "(", "'ts/nni_manager/node_modules'", ",", "'nni_node/node_modules'", ")", "_symlink", "(", "'ts/webui/build'", ",", "'nni_node/static'", ")", "Path", "(", "'nni_node/nasui'", ")", ".", "mkdir", "(", "exist_ok", "=", "True", ")", "_symlink", "(", "'ts/nasui/build'", ",", "'nni_node/nasui/build'", ")", "_symlink", "(", "'ts/nasui/server.js'", ",", "'nni_node/nasui/server.js'", ")" ]
[ 156, 0 ]
[ 172, 62 ]
python
en
['en', 'error', 'th']
False
copy_nni_node
(version)
Copy compiled JS files to nni_node. This is meant for building release package, so you need to provide version string. The version will written to `package.json` in nni_node directory, while `package.json` in ts directory will be left unchanged.
Copy compiled JS files to nni_node. This is meant for building release package, so you need to provide version string. The version will written to `package.json` in nni_node directory, while `package.json` in ts directory will be left unchanged.
def copy_nni_node(version): """ Copy compiled JS files to nni_node. This is meant for building release package, so you need to provide version string. The version will written to `package.json` in nni_node directory, while `package.json` in ts directory will be left unchanged. """ _print('Copying files') # copytree(..., dirs_exist_ok=True) is not supported by Python 3.6 for path in Path('ts/nni_manager/dist').iterdir(): if path.is_file(): shutil.copyfile(path, Path('nni_node', path.name)) else: shutil.copytree(path, Path('nni_node', path.name)) package_json = json.load(open('ts/nni_manager/package.json')) if version: while len(version.split('.')) < 3: # node.js semver requires at least three parts version = version + '.0' package_json['version'] = version json.dump(package_json, open('nni_node/package.json', 'w'), indent=2) # reinstall without development dependencies _yarn('ts/nni_manager', '--prod', '--cwd', str(Path('nni_node').resolve())) shutil.copytree('ts/webui/build', 'nni_node/static') Path('nni_node/nasui').mkdir(exist_ok=True) shutil.copytree('ts/nasui/build', 'nni_node/nasui/build') shutil.copyfile('ts/nasui/server.js', 'nni_node/nasui/server.js')
[ "def", "copy_nni_node", "(", "version", ")", ":", "_print", "(", "'Copying files'", ")", "# copytree(..., dirs_exist_ok=True) is not supported by Python 3.6", "for", "path", "in", "Path", "(", "'ts/nni_manager/dist'", ")", ".", "iterdir", "(", ")", ":", "if", "path", ".", "is_file", "(", ")", ":", "shutil", ".", "copyfile", "(", "path", ",", "Path", "(", "'nni_node'", ",", "path", ".", "name", ")", ")", "else", ":", "shutil", ".", "copytree", "(", "path", ",", "Path", "(", "'nni_node'", ",", "path", ".", "name", ")", ")", "package_json", "=", "json", ".", "load", "(", "open", "(", "'ts/nni_manager/package.json'", ")", ")", "if", "version", ":", "while", "len", "(", "version", ".", "split", "(", "'.'", ")", ")", "<", "3", ":", "# node.js semver requires at least three parts", "version", "=", "version", "+", "'.0'", "package_json", "[", "'version'", "]", "=", "version", "json", ".", "dump", "(", "package_json", ",", "open", "(", "'nni_node/package.json'", ",", "'w'", ")", ",", "indent", "=", "2", ")", "# reinstall without development dependencies", "_yarn", "(", "'ts/nni_manager'", ",", "'--prod'", ",", "'--cwd'", ",", "str", "(", "Path", "(", "'nni_node'", ")", ".", "resolve", "(", ")", ")", ")", "shutil", ".", "copytree", "(", "'ts/webui/build'", ",", "'nni_node/static'", ")", "Path", "(", "'nni_node/nasui'", ")", ".", "mkdir", "(", "exist_ok", "=", "True", ")", "shutil", ".", "copytree", "(", "'ts/nasui/build'", ",", "'nni_node/nasui/build'", ")", "shutil", ".", "copyfile", "(", "'ts/nasui/server.js'", ",", "'nni_node/nasui/server.js'", ")" ]
[ 175, 0 ]
[ 205, 69 ]
python
en
['en', 'error', 'th']
False
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities )
Get all binary sensor and multi level sensor devices and setup them via config entry.
Get all binary sensor and multi level sensor devices and setup them via config entry.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Get all binary sensor and multi level sensor devices and setup them via config entry.""" entities = [] for gateway in hass.data[DOMAIN][entry.entry_id]["gateways"]: for device in gateway.binary_sensor_devices: for binary_sensor in device.binary_sensor_property: entities.append( DevoloBinaryDeviceEntity( homecontrol=gateway, device_instance=device, element_uid=binary_sensor, ) ) for device in gateway.devices.values(): if hasattr(device, "remote_control_property"): for remote in device.remote_control_property: for index in range( 1, device.remote_control_property[remote].key_count + 1 ): entities.append( DevoloRemoteControl( homecontrol=gateway, device_instance=device, element_uid=remote, key=index, ) ) async_add_entities(entities, False)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "entities", "=", "[", "]", "for", "gateway", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "entry_id", "]", "[", "\"gateways\"", "]", ":", "for", "device", "in", "gateway", ".", "binary_sensor_devices", ":", "for", "binary_sensor", "in", "device", ".", "binary_sensor_property", ":", "entities", ".", "append", "(", "DevoloBinaryDeviceEntity", "(", "homecontrol", "=", "gateway", ",", "device_instance", "=", "device", ",", "element_uid", "=", "binary_sensor", ",", ")", ")", "for", "device", "in", "gateway", ".", "devices", ".", "values", "(", ")", ":", "if", "hasattr", "(", "device", ",", "\"remote_control_property\"", ")", ":", "for", "remote", "in", "device", ".", "remote_control_property", ":", "for", "index", "in", "range", "(", "1", ",", "device", ".", "remote_control_property", "[", "remote", "]", ".", "key_count", "+", "1", ")", ":", "entities", ".", "append", "(", "DevoloRemoteControl", "(", "homecontrol", "=", "gateway", ",", "device_instance", "=", "device", ",", "element_uid", "=", "remote", ",", "key", "=", "index", ",", ")", ")", "async_add_entities", "(", "entities", ",", "False", ")" ]
[ 24, 0 ]
[ 54, 39 ]
python
en
['en', 'pt', 'en']
True
DevoloBinaryDeviceEntity.__init__
(self, homecontrol, device_instance, element_uid)
Initialize a devolo binary sensor.
Initialize a devolo binary sensor.
def __init__(self, homecontrol, device_instance, element_uid): """Initialize a devolo binary sensor.""" self._binary_sensor_property = device_instance.binary_sensor_property.get( element_uid ) super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=element_uid, ) self._device_class = DEVICE_CLASS_MAPPING.get( self._binary_sensor_property.sub_type or self._binary_sensor_property.sensor_type ) if self._device_class is None: if device_instance.binary_sensor_property.get(element_uid).sub_type != "": self._name += f" {device_instance.binary_sensor_property.get(element_uid).sub_type}" else: self._name += f" {device_instance.binary_sensor_property.get(element_uid).sensor_type}" self._value = self._binary_sensor_property.state if element_uid.startswith("devolo.WarningBinaryFI:"): self._enabled_default = False
[ "def", "__init__", "(", "self", ",", "homecontrol", ",", "device_instance", ",", "element_uid", ")", ":", "self", ".", "_binary_sensor_property", "=", "device_instance", ".", "binary_sensor_property", ".", "get", "(", "element_uid", ")", "super", "(", ")", ".", "__init__", "(", "homecontrol", "=", "homecontrol", ",", "device_instance", "=", "device_instance", ",", "element_uid", "=", "element_uid", ",", ")", "self", ".", "_device_class", "=", "DEVICE_CLASS_MAPPING", ".", "get", "(", "self", ".", "_binary_sensor_property", ".", "sub_type", "or", "self", ".", "_binary_sensor_property", ".", "sensor_type", ")", "if", "self", ".", "_device_class", "is", "None", ":", "if", "device_instance", ".", "binary_sensor_property", ".", "get", "(", "element_uid", ")", ".", "sub_type", "!=", "\"\"", ":", "self", ".", "_name", "+=", "f\" {device_instance.binary_sensor_property.get(element_uid).sub_type}\"", "else", ":", "self", ".", "_name", "+=", "f\" {device_instance.binary_sensor_property.get(element_uid).sensor_type}\"", "self", ".", "_value", "=", "self", ".", "_binary_sensor_property", ".", "state", "if", "element_uid", ".", "startswith", "(", "\"devolo.WarningBinaryFI:\"", ")", ":", "self", ".", "_enabled_default", "=", "False" ]
[ 60, 4 ]
[ 86, 41 ]
python
it
['it', 'it', 'it']
True
DevoloBinaryDeviceEntity.is_on
(self)
Return the state.
Return the state.
def is_on(self): """Return the state.""" return self._value
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_value" ]
[ 89, 4 ]
[ 91, 26 ]
python
en
['en', 'en', 'en']
True
DevoloBinaryDeviceEntity.device_class
(self)
Return device class.
Return device class.
def device_class(self): """Return device class.""" return self._device_class
[ "def", "device_class", "(", "self", ")", ":", "return", "self", ".", "_device_class" ]
[ 94, 4 ]
[ 96, 33 ]
python
en
['es', 'zh', 'en']
False
DevoloRemoteControl.__init__
(self, homecontrol, device_instance, element_uid, key)
Initialize a devolo remote control.
Initialize a devolo remote control.
def __init__(self, homecontrol, device_instance, element_uid, key): """Initialize a devolo remote control.""" self._remote_control_property = device_instance.remote_control_property.get( element_uid ) super().__init__( homecontrol=homecontrol, device_instance=device_instance, element_uid=f"{element_uid}_{key}", ) self._key = key self._state = False
[ "def", "__init__", "(", "self", ",", "homecontrol", ",", "device_instance", ",", "element_uid", ",", "key", ")", ":", "self", ".", "_remote_control_property", "=", "device_instance", ".", "remote_control_property", ".", "get", "(", "element_uid", ")", "super", "(", ")", ".", "__init__", "(", "homecontrol", "=", "homecontrol", ",", "device_instance", "=", "device_instance", ",", "element_uid", "=", "f\"{element_uid}_{key}\"", ",", ")", "self", ".", "_key", "=", "key", "self", ".", "_state", "=", "False" ]
[ 102, 4 ]
[ 115, 27 ]
python
it
['it', 'it', 'it']
True
DevoloRemoteControl.is_on
(self)
Return the state.
Return the state.
def is_on(self): """Return the state.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 118, 4 ]
[ 120, 26 ]
python
en
['en', 'en', 'en']
True
DevoloRemoteControl._sync
(self, message)
Update the binary sensor state.
Update the binary sensor state.
def _sync(self, message): """Update the binary sensor state.""" if ( message[0] == self._remote_control_property.element_uid and message[1] == self._key ): self._state = True elif ( message[0] == self._remote_control_property.element_uid and message[1] == 0 ): self._state = False else: self._generic_message(message) self.schedule_update_ha_state()
[ "def", "_sync", "(", "self", ",", "message", ")", ":", "if", "(", "message", "[", "0", "]", "==", "self", ".", "_remote_control_property", ".", "element_uid", "and", "message", "[", "1", "]", "==", "self", ".", "_key", ")", ":", "self", ".", "_state", "=", "True", "elif", "(", "message", "[", "0", "]", "==", "self", ".", "_remote_control_property", ".", "element_uid", "and", "message", "[", "1", "]", "==", "0", ")", ":", "self", ".", "_state", "=", "False", "else", ":", "self", ".", "_generic_message", "(", "message", ")", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 122, 4 ]
[ 135, 39 ]
python
en
['en', 'sn', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up all entries for Wolf Platform.
Set up all entries for Wolf Platform.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up all entries for Wolf Platform.""" coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR] parameters = hass.data[DOMAIN][config_entry.entry_id][PARAMETERS] device_id = hass.data[DOMAIN][config_entry.entry_id][DEVICE_ID] entities = [] for parameter in parameters: if isinstance(parameter, Temperature): entities.append(WolfLinkTemperature(coordinator, parameter, device_id)) if isinstance(parameter, Pressure): entities.append(WolfLinkPressure(coordinator, parameter, device_id)) if isinstance(parameter, PercentageParameter): entities.append(WolfLinkPercentage(coordinator, parameter, device_id)) if isinstance(parameter, ListItemParameter): entities.append(WolfLinkState(coordinator, parameter, device_id)) if isinstance(parameter, HoursParameter): entities.append(WolfLinkHours(coordinator, parameter, device_id)) if isinstance(parameter, SimpleParameter): entities.append(WolfLinkSensor(coordinator, parameter, device_id)) async_add_entities(entities, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "coordinator", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "COORDINATOR", "]", "parameters", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "PARAMETERS", "]", "device_id", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "[", "DEVICE_ID", "]", "entities", "=", "[", "]", "for", "parameter", "in", "parameters", ":", "if", "isinstance", "(", "parameter", ",", "Temperature", ")", ":", "entities", ".", "append", "(", "WolfLinkTemperature", "(", "coordinator", ",", "parameter", ",", "device_id", ")", ")", "if", "isinstance", "(", "parameter", ",", "Pressure", ")", ":", "entities", ".", "append", "(", "WolfLinkPressure", "(", "coordinator", ",", "parameter", ",", "device_id", ")", ")", "if", "isinstance", "(", "parameter", ",", "PercentageParameter", ")", ":", "entities", ".", "append", "(", "WolfLinkPercentage", "(", "coordinator", ",", "parameter", ",", "device_id", ")", ")", "if", "isinstance", "(", "parameter", ",", "ListItemParameter", ")", ":", "entities", ".", "append", "(", "WolfLinkState", "(", "coordinator", ",", "parameter", ",", "device_id", ")", ")", "if", "isinstance", "(", "parameter", ",", "HoursParameter", ")", ":", "entities", ".", "append", "(", "WolfLinkHours", "(", "coordinator", ",", "parameter", ",", "device_id", ")", ")", "if", "isinstance", "(", "parameter", ",", "SimpleParameter", ")", ":", "entities", ".", "append", "(", "WolfLinkSensor", "(", "coordinator", ",", "parameter", ",", "device_id", ")", ")", "async_add_entities", "(", "entities", ",", "True", ")" ]
[ 23, 0 ]
[ 45, 38 ]
python
en
['en', 'en', 'en']
True
WolfLinkSensor.__init__
(self, coordinator, wolf_object: Parameter, device_id)
Initialize.
Initialize.
def __init__(self, coordinator, wolf_object: Parameter, device_id): """Initialize.""" super().__init__(coordinator) self.wolf_object = wolf_object self.device_id = device_id self._state = None
[ "def", "__init__", "(", "self", ",", "coordinator", ",", "wolf_object", ":", "Parameter", ",", "device_id", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "wolf_object", "=", "wolf_object", "self", ".", "device_id", "=", "device_id", "self", ".", "_state", "=", "None" ]
[ 51, 4 ]
[ 56, 26 ]
python
en
['en', 'en', 'it']
False
WolfLinkSensor.name
(self)
Return the name.
Return the name.
def name(self): """Return the name.""" return f"{self.wolf_object.name}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self.wolf_object.name}\"" ]
[ 59, 4 ]
[ 61, 41 ]
python
en
['en', 'ig', 'en']
True
WolfLinkSensor.state
(self)
Return the state. Wolf Client is returning only changed values so we need to store old value here.
Return the state. Wolf Client is returning only changed values so we need to store old value here.
def state(self): """Return the state. Wolf Client is returning only changed values so we need to store old value here.""" if self.wolf_object.value_id in self.coordinator.data: self._state = self.coordinator.data[self.wolf_object.value_id] return self._state
[ "def", "state", "(", "self", ")", ":", "if", "self", ".", "wolf_object", ".", "value_id", "in", "self", ".", "coordinator", ".", "data", ":", "self", ".", "_state", "=", "self", ".", "coordinator", ".", "data", "[", "self", ".", "wolf_object", ".", "value_id", "]", "return", "self", ".", "_state" ]
[ 64, 4 ]
[ 68, 26 ]
python
en
['en', 'en', 'en']
True
WolfLinkSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return { "parameter_id": self.wolf_object.parameter_id, "value_id": self.wolf_object.value_id, "parent": self.wolf_object.parent, }
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "\"parameter_id\"", ":", "self", ".", "wolf_object", ".", "parameter_id", ",", "\"value_id\"", ":", "self", ".", "wolf_object", ".", "value_id", ",", "\"parent\"", ":", "self", ".", "wolf_object", ".", "parent", ",", "}" ]
[ 71, 4 ]
[ 77, 9 ]
python
en
['en', 'en', 'en']
True
WolfLinkSensor.unique_id
(self)
Return a unique_id for this entity.
Return a unique_id for this entity.
def unique_id(self): """Return a unique_id for this entity.""" return f"{self.device_id}:{self.wolf_object.parameter_id}"
[ "def", "unique_id", "(", "self", ")", ":", "return", "f\"{self.device_id}:{self.wolf_object.parameter_id}\"" ]
[ 80, 4 ]
[ 82, 66 ]
python
en
['en', 'en', 'en']
True
WolfLinkHours.icon
(self)
Icon to display in the front Aend.
Icon to display in the front Aend.
def icon(self): """Icon to display in the front Aend.""" return "mdi:clock"
[ "def", "icon", "(", "self", ")", ":", "return", "\"mdi:clock\"" ]
[ 89, 4 ]
[ 91, 26 ]
python
en
['en', 'en', 'en']
True
WolfLinkHours.unit_of_measurement
(self)
Return the unit the value is expressed in.
Return the unit the value is expressed in.
def unit_of_measurement(self): """Return the unit the value is expressed in.""" return TIME_HOURS
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "TIME_HOURS" ]
[ 94, 4 ]
[ 96, 25 ]
python
en
['en', 'en', 'en']
True
WolfLinkTemperature.device_class
(self)
Return the device_class.
Return the device_class.
def device_class(self): """Return the device_class.""" return DEVICE_CLASS_TEMPERATURE
[ "def", "device_class", "(", "self", ")", ":", "return", "DEVICE_CLASS_TEMPERATURE" ]
[ 103, 4 ]
[ 105, 39 ]
python
en
['en', 'en', 'en']
True
WolfLinkTemperature.unit_of_measurement
(self)
Return the unit the value is expressed in.
Return the unit the value is expressed in.
def unit_of_measurement(self): """Return the unit the value is expressed in.""" return TEMP_CELSIUS
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "TEMP_CELSIUS" ]
[ 108, 4 ]
[ 110, 27 ]
python
en
['en', 'en', 'en']
True
WolfLinkPressure.device_class
(self)
Return the device_class.
Return the device_class.
def device_class(self): """Return the device_class.""" return DEVICE_CLASS_PRESSURE
[ "def", "device_class", "(", "self", ")", ":", "return", "DEVICE_CLASS_PRESSURE" ]
[ 117, 4 ]
[ 119, 36 ]
python
en
['en', 'en', 'en']
True
WolfLinkPressure.unit_of_measurement
(self)
Return the unit the value is expressed in.
Return the unit the value is expressed in.
def unit_of_measurement(self): """Return the unit the value is expressed in.""" return PRESSURE_BAR
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "PRESSURE_BAR" ]
[ 122, 4 ]
[ 124, 27 ]
python
en
['en', 'en', 'en']
True
WolfLinkPercentage.unit_of_measurement
(self)
Return the unit the value is expressed in.
Return the unit the value is expressed in.
def unit_of_measurement(self): """Return the unit the value is expressed in.""" return self.wolf_object.unit
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "self", ".", "wolf_object", ".", "unit" ]
[ 131, 4 ]
[ 133, 36 ]
python
en
['en', 'en', 'en']
True
WolfLinkState.device_class
(self)
Return the device class.
Return the device class.
def device_class(self): """Return the device class.""" return "wolflink__state"
[ "def", "device_class", "(", "self", ")", ":", "return", "\"wolflink__state\"" ]
[ 140, 4 ]
[ 142, 32 ]
python
en
['en', 'en', 'en']
True
WolfLinkState.state
(self)
Return the state converting with supported values.
Return the state converting with supported values.
def state(self): """Return the state converting with supported values.""" state = super().state resolved_state = [ item for item in self.wolf_object.items if item.value == int(state) ] if resolved_state: resolved_name = resolved_state[0].name return STATES.get(resolved_name, resolved_name) return state
[ "def", "state", "(", "self", ")", ":", "state", "=", "super", "(", ")", ".", "state", "resolved_state", "=", "[", "item", "for", "item", "in", "self", ".", "wolf_object", ".", "items", "if", "item", ".", "value", "==", "int", "(", "state", ")", "]", "if", "resolved_state", ":", "resolved_name", "=", "resolved_state", "[", "0", "]", ".", "name", "return", "STATES", ".", "get", "(", "resolved_name", ",", "resolved_name", ")", "return", "state" ]
[ 145, 4 ]
[ 154, 20 ]
python
en
['en', 'en', 'en']
True
setup_bridge
(hass, mock_bridge)
Load the Hue light platform with the provided bridge.
Load the Hue light platform with the provided bridge.
async def setup_bridge(hass, mock_bridge): """Load the Hue light platform with the provided bridge.""" hass.config.components.add(hue.DOMAIN) config_entry = config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, ) mock_bridge.config_entry = config_entry hass.data[hue.DOMAIN] = {config_entry.entry_id: mock_bridge} await hass.config_entries.async_forward_entry_setup(config_entry, "light") # To flush out the service call to update the group await hass.async_block_till_done()
[ "async", "def", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", ":", "hass", ".", "config", ".", "components", ".", "add", "(", "hue", ".", "DOMAIN", ")", "config_entry", "=", "config_entries", ".", "ConfigEntry", "(", "1", ",", "hue", ".", "DOMAIN", ",", "\"Mock Title\"", ",", "{", "\"host\"", ":", "\"mock-host\"", "}", ",", "\"test\"", ",", "config_entries", ".", "CONN_CLASS_LOCAL_POLL", ",", "system_options", "=", "{", "}", ",", ")", "mock_bridge", ".", "config_entry", "=", "config_entry", "hass", ".", "data", "[", "hue", ".", "DOMAIN", "]", "=", "{", "config_entry", ".", "entry_id", ":", "mock_bridge", "}", "await", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "config_entry", ",", "\"light\"", ")", "# To flush out the service call to update the group", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 172, 0 ]
[ 188, 38 ]
python
en
['en', 'en', 'en']
True
test_not_load_groups_if_old_bridge
(hass, mock_bridge)
Test that we don't try to load gorups if bridge runs old software.
Test that we don't try to load gorups if bridge runs old software.
async def test_not_load_groups_if_old_bridge(hass, mock_bridge): """Test that we don't try to load gorups if bridge runs old software.""" mock_bridge.api.config.apiversion = "1.12.0" mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append(GROUP_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 1 assert len(hass.states.async_all()) == 0
[ "async", "def", "test_not_load_groups_if_old_bridge", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "api", ".", "config", ".", "apiversion", "=", "\"1.12.0\"", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "GROUP_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "1", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 191, 0 ]
[ 198, 44 ]
python
en
['en', 'en', 'en']
True
test_no_lights_or_groups
(hass, mock_bridge)
Test the update_lights function when no lights are found.
Test the update_lights function when no lights are found.
async def test_no_lights_or_groups(hass, mock_bridge): """Test the update_lights function when no lights are found.""" mock_bridge.allow_groups = True mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append({}) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 2 assert len(hass.states.async_all()) == 0
[ "async", "def", "test_no_lights_or_groups", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "allow_groups", "=", "True", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "{", "}", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "2", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 201, 0 ]
[ 208, 44 ]
python
en
['en', 'en', 'en']
True
test_lights
(hass, mock_bridge)
Test the update_lights function with some lights.
Test the update_lights function with some lights.
async def test_lights(hass, mock_bridge): """Test the update_lights function with some lights.""" mock_bridge.mock_light_responses.append(LIGHT_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 1 # 2 lights assert len(hass.states.async_all()) == 2 lamp_1 = hass.states.get("light.hue_lamp_1") assert lamp_1 is not None assert lamp_1.state == "on" assert lamp_1.attributes["brightness"] == 145 assert lamp_1.attributes["hs_color"] == (36.067, 69.804) lamp_2 = hass.states.get("light.hue_lamp_2") assert lamp_2 is not None assert lamp_2.state == "off"
[ "async", "def", "test_lights", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "LIGHT_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "1", "# 2 lights", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "lamp_1", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_1\"", ")", "assert", "lamp_1", "is", "not", "None", "assert", "lamp_1", ".", "state", "==", "\"on\"", "assert", "lamp_1", ".", "attributes", "[", "\"brightness\"", "]", "==", "145", "assert", "lamp_1", ".", "attributes", "[", "\"hs_color\"", "]", "==", "(", "36.067", ",", "69.804", ")", "lamp_2", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_2\"", ")", "assert", "lamp_2", "is", "not", "None", "assert", "lamp_2", ".", "state", "==", "\"off\"" ]
[ 211, 0 ]
[ 227, 32 ]
python
en
['en', 'en', 'en']
True
test_lights_color_mode
(hass, mock_bridge)
Test that lights only report appropriate color mode.
Test that lights only report appropriate color mode.
async def test_lights_color_mode(hass, mock_bridge): """Test that lights only report appropriate color mode.""" mock_bridge.mock_light_responses.append(LIGHT_RESPONSE) await setup_bridge(hass, mock_bridge) lamp_1 = hass.states.get("light.hue_lamp_1") assert lamp_1 is not None assert lamp_1.state == "on" assert lamp_1.attributes["brightness"] == 145 assert lamp_1.attributes["hs_color"] == (36.067, 69.804) assert "color_temp" not in lamp_1.attributes new_light1_on = LIGHT_1_ON.copy() new_light1_on["state"] = new_light1_on["state"].copy() new_light1_on["state"]["colormode"] = "ct" mock_bridge.mock_light_responses.append({"1": new_light1_on}) mock_bridge.mock_group_responses.append({}) # Calling a service will trigger the updates to run await hass.services.async_call( "light", "turn_on", {"entity_id": "light.hue_lamp_2"}, blocking=True ) # 2x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 3 lamp_1 = hass.states.get("light.hue_lamp_1") assert lamp_1 is not None assert lamp_1.state == "on" assert lamp_1.attributes["brightness"] == 145 assert lamp_1.attributes["color_temp"] == 467 assert "hs_color" not in lamp_1.attributes
[ "async", "def", "test_lights_color_mode", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "LIGHT_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "lamp_1", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_1\"", ")", "assert", "lamp_1", "is", "not", "None", "assert", "lamp_1", ".", "state", "==", "\"on\"", "assert", "lamp_1", ".", "attributes", "[", "\"brightness\"", "]", "==", "145", "assert", "lamp_1", ".", "attributes", "[", "\"hs_color\"", "]", "==", "(", "36.067", ",", "69.804", ")", "assert", "\"color_temp\"", "not", "in", "lamp_1", ".", "attributes", "new_light1_on", "=", "LIGHT_1_ON", ".", "copy", "(", ")", "new_light1_on", "[", "\"state\"", "]", "=", "new_light1_on", "[", "\"state\"", "]", ".", "copy", "(", ")", "new_light1_on", "[", "\"state\"", "]", "[", "\"colormode\"", "]", "=", "\"ct\"", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "\"1\"", ":", "new_light1_on", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "{", "}", ")", "# Calling a service will trigger the updates to run", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.hue_lamp_2\"", "}", ",", "blocking", "=", "True", ")", "# 2x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "3", "lamp_1", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_1\"", ")", "assert", "lamp_1", "is", "not", "None", "assert", "lamp_1", ".", "state", "==", "\"on\"", "assert", "lamp_1", ".", "attributes", "[", "\"brightness\"", "]", "==", "145", "assert", "lamp_1", ".", "attributes", "[", "\"color_temp\"", "]", "==", "467", "assert", "\"hs_color\"", "not", "in", "lamp_1", ".", "attributes" ]
[ 230, 0 ]
[ 260, 46 ]
python
en
['en', 'en', 'en']
True
test_groups
(hass, mock_bridge)
Test the update_lights function with some lights.
Test the update_lights function with some lights.
async def test_groups(hass, mock_bridge): """Test the update_lights function with some lights.""" mock_bridge.allow_groups = True mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append(GROUP_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 2 # 2 hue group lights assert len(hass.states.async_all()) == 2 lamp_1 = hass.states.get("light.group_1") assert lamp_1 is not None assert lamp_1.state == "on" assert lamp_1.attributes["brightness"] == 255 assert lamp_1.attributes["color_temp"] == 250 lamp_2 = hass.states.get("light.group_2") assert lamp_2 is not None assert lamp_2.state == "on"
[ "async", "def", "test_groups", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "allow_groups", "=", "True", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "GROUP_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "2", "# 2 hue group lights", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "lamp_1", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_1\"", ")", "assert", "lamp_1", "is", "not", "None", "assert", "lamp_1", ".", "state", "==", "\"on\"", "assert", "lamp_1", ".", "attributes", "[", "\"brightness\"", "]", "==", "255", "assert", "lamp_1", ".", "attributes", "[", "\"color_temp\"", "]", "==", "250", "lamp_2", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_2\"", ")", "assert", "lamp_2", "is", "not", "None", "assert", "lamp_2", ".", "state", "==", "\"on\"" ]
[ 263, 0 ]
[ 282, 31 ]
python
en
['en', 'en', 'en']
True
test_new_group_discovered
(hass, mock_bridge)
Test if 2nd update has a new group.
Test if 2nd update has a new group.
async def test_new_group_discovered(hass, mock_bridge): """Test if 2nd update has a new group.""" mock_bridge.allow_groups = True mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append(GROUP_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 2 assert len(hass.states.async_all()) == 2 new_group_response = dict(GROUP_RESPONSE) new_group_response["3"] = { "name": "Group 3", "lights": ["3", "4", "5"], "type": "LightGroup", "action": { "on": True, "bri": 153, "hue": 4345, "sat": 254, "effect": "none", "xy": [0.5, 0.5], "ct": 250, "alert": "select", "colormode": "ct", }, "state": {"any_on": True, "all_on": False}, } mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append(new_group_response) # Calling a service will trigger the updates to run await hass.services.async_call( "light", "turn_on", {"entity_id": "light.group_1"}, blocking=True ) # 2x group update, 1x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 4 assert len(hass.states.async_all()) == 3 new_group = hass.states.get("light.group_3") assert new_group is not None assert new_group.state == "on" assert new_group.attributes["brightness"] == 154 assert new_group.attributes["color_temp"] == 250
[ "async", "def", "test_new_group_discovered", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "allow_groups", "=", "True", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "GROUP_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "2", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "new_group_response", "=", "dict", "(", "GROUP_RESPONSE", ")", "new_group_response", "[", "\"3\"", "]", "=", "{", "\"name\"", ":", "\"Group 3\"", ",", "\"lights\"", ":", "[", "\"3\"", ",", "\"4\"", ",", "\"5\"", "]", ",", "\"type\"", ":", "\"LightGroup\"", ",", "\"action\"", ":", "{", "\"on\"", ":", "True", ",", "\"bri\"", ":", "153", ",", "\"hue\"", ":", "4345", ",", "\"sat\"", ":", "254", ",", "\"effect\"", ":", "\"none\"", ",", "\"xy\"", ":", "[", "0.5", ",", "0.5", "]", ",", "\"ct\"", ":", "250", ",", "\"alert\"", ":", "\"select\"", ",", "\"colormode\"", ":", "\"ct\"", ",", "}", ",", "\"state\"", ":", "{", "\"any_on\"", ":", "True", ",", "\"all_on\"", ":", "False", "}", ",", "}", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "new_group_response", ")", "# Calling a service will trigger the updates to run", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.group_1\"", "}", ",", "blocking", "=", "True", ")", "# 2x group update, 1x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "4", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "3", "new_group", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_3\"", ")", "assert", "new_group", "is", "not", "None", "assert", "new_group", ".", "state", "==", "\"on\"", "assert", "new_group", ".", "attributes", "[", "\"brightness\"", "]", "==", "154", "assert", "new_group", ".", "attributes", "[", "\"color_temp\"", "]", "==", "250" ]
[ 285, 0 ]
[ 329, 52 ]
python
en
['en', 'en', 'en']
True
test_new_light_discovered
(hass, mock_bridge)
Test if 2nd update has a new light.
Test if 2nd update has a new light.
async def test_new_light_discovered(hass, mock_bridge): """Test if 2nd update has a new light.""" mock_bridge.mock_light_responses.append(LIGHT_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 1 assert len(hass.states.async_all()) == 2 new_light_response = dict(LIGHT_RESPONSE) new_light_response["3"] = { "state": { "on": False, "bri": 0, "hue": 0, "sat": 0, "xy": [0, 0], "ct": 0, "alert": "none", "effect": "none", "colormode": "hs", "reachable": True, }, "capabilities": LIGHT_1_CAPABILITIES, "type": "Extended color light", "name": "Hue Lamp 3", "modelid": "LCT001", "swversion": "66009461", "manufacturername": "Philips", "uniqueid": "789", } mock_bridge.mock_light_responses.append(new_light_response) # Calling a service will trigger the updates to run await hass.services.async_call( "light", "turn_on", {"entity_id": "light.hue_lamp_1"}, blocking=True ) # 2x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 3 assert len(hass.states.async_all()) == 3 light = hass.states.get("light.hue_lamp_3") assert light is not None assert light.state == "off"
[ "async", "def", "test_new_light_discovered", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "LIGHT_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "1", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "new_light_response", "=", "dict", "(", "LIGHT_RESPONSE", ")", "new_light_response", "[", "\"3\"", "]", "=", "{", "\"state\"", ":", "{", "\"on\"", ":", "False", ",", "\"bri\"", ":", "0", ",", "\"hue\"", ":", "0", ",", "\"sat\"", ":", "0", ",", "\"xy\"", ":", "[", "0", ",", "0", "]", ",", "\"ct\"", ":", "0", ",", "\"alert\"", ":", "\"none\"", ",", "\"effect\"", ":", "\"none\"", ",", "\"colormode\"", ":", "\"hs\"", ",", "\"reachable\"", ":", "True", ",", "}", ",", "\"capabilities\"", ":", "LIGHT_1_CAPABILITIES", ",", "\"type\"", ":", "\"Extended color light\"", ",", "\"name\"", ":", "\"Hue Lamp 3\"", ",", "\"modelid\"", ":", "\"LCT001\"", ",", "\"swversion\"", ":", "\"66009461\"", ",", "\"manufacturername\"", ":", "\"Philips\"", ",", "\"uniqueid\"", ":", "\"789\"", ",", "}", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "new_light_response", ")", "# Calling a service will trigger the updates to run", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.hue_lamp_1\"", "}", ",", "blocking", "=", "True", ")", "# 2x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "3", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "3", "light", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_3\"", ")", "assert", "light", "is", "not", "None", "assert", "light", ".", "state", "==", "\"off\"" ]
[ 332, 0 ]
[ 375, 31 ]
python
en
['en', 'lb', 'en']
True
test_group_removed
(hass, mock_bridge)
Test if 2nd update has removed group.
Test if 2nd update has removed group.
async def test_group_removed(hass, mock_bridge): """Test if 2nd update has removed group.""" mock_bridge.allow_groups = True mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append(GROUP_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 2 assert len(hass.states.async_all()) == 2 mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append({"1": GROUP_RESPONSE["1"]}) # Calling a service will trigger the updates to run await hass.services.async_call( "light", "turn_on", {"entity_id": "light.group_1"}, blocking=True ) # 2x group update, 1x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 4 assert len(hass.states.async_all()) == 1 group = hass.states.get("light.group_1") assert group is not None removed_group = hass.states.get("light.group_2") assert removed_group is None
[ "async", "def", "test_group_removed", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "allow_groups", "=", "True", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "GROUP_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "2", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "{", "\"1\"", ":", "GROUP_RESPONSE", "[", "\"1\"", "]", "}", ")", "# Calling a service will trigger the updates to run", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.group_1\"", "}", ",", "blocking", "=", "True", ")", "# 2x group update, 1x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "4", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "group", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_1\"", ")", "assert", "group", "is", "not", "None", "removed_group", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_2\"", ")", "assert", "removed_group", "is", "None" ]
[ 378, 0 ]
[ 404, 32 ]
python
en
['en', 'en', 'en']
True
test_light_removed
(hass, mock_bridge)
Test if 2nd update has removed light.
Test if 2nd update has removed light.
async def test_light_removed(hass, mock_bridge): """Test if 2nd update has removed light.""" mock_bridge.mock_light_responses.append(LIGHT_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 1 assert len(hass.states.async_all()) == 2 mock_bridge.mock_light_responses.clear() mock_bridge.mock_light_responses.append({"1": LIGHT_RESPONSE.get("1")}) # Calling a service will trigger the updates to run await hass.services.async_call( "light", "turn_on", {"entity_id": "light.hue_lamp_1"}, blocking=True ) # 2x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 3 assert len(hass.states.async_all()) == 1 light = hass.states.get("light.hue_lamp_1") assert light is not None removed_light = hass.states.get("light.hue_lamp_2") assert removed_light is None
[ "async", "def", "test_light_removed", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "LIGHT_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "1", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "mock_bridge", ".", "mock_light_responses", ".", "clear", "(", ")", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "\"1\"", ":", "LIGHT_RESPONSE", ".", "get", "(", "\"1\"", ")", "}", ")", "# Calling a service will trigger the updates to run", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.hue_lamp_1\"", "}", ",", "blocking", "=", "True", ")", "# 2x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "3", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "light", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_1\"", ")", "assert", "light", "is", "not", "None", "removed_light", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_2\"", ")", "assert", "removed_light", "is", "None" ]
[ 407, 0 ]
[ 431, 32 ]
python
en
['en', 'en', 'en']
True
test_other_group_update
(hass, mock_bridge)
Test changing one group that will impact the state of other light.
Test changing one group that will impact the state of other light.
async def test_other_group_update(hass, mock_bridge): """Test changing one group that will impact the state of other light.""" mock_bridge.allow_groups = True mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append(GROUP_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 2 assert len(hass.states.async_all()) == 2 group_2 = hass.states.get("light.group_2") assert group_2 is not None assert group_2.name == "Group 2" assert group_2.state == "on" assert group_2.attributes["brightness"] == 154 assert group_2.attributes["color_temp"] == 250 updated_group_response = dict(GROUP_RESPONSE) updated_group_response["2"] = { "name": "Group 2 new", "lights": ["3", "4", "5"], "type": "LightGroup", "action": { "on": False, "bri": 0, "hue": 0, "sat": 0, "effect": "none", "xy": [0, 0], "ct": 0, "alert": "none", "colormode": "ct", }, "state": {"any_on": False, "all_on": False}, } mock_bridge.mock_light_responses.append({}) mock_bridge.mock_group_responses.append(updated_group_response) # Calling a service will trigger the updates to run await hass.services.async_call( "light", "turn_on", {"entity_id": "light.group_1"}, blocking=True ) # 2x group update, 1x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 4 assert len(hass.states.async_all()) == 2 group_2 = hass.states.get("light.group_2") assert group_2 is not None assert group_2.name == "Group 2 new" assert group_2.state == "off"
[ "async", "def", "test_other_group_update", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "allow_groups", "=", "True", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "GROUP_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "2", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "group_2", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_2\"", ")", "assert", "group_2", "is", "not", "None", "assert", "group_2", ".", "name", "==", "\"Group 2\"", "assert", "group_2", ".", "state", "==", "\"on\"", "assert", "group_2", ".", "attributes", "[", "\"brightness\"", "]", "==", "154", "assert", "group_2", ".", "attributes", "[", "\"color_temp\"", "]", "==", "250", "updated_group_response", "=", "dict", "(", "GROUP_RESPONSE", ")", "updated_group_response", "[", "\"2\"", "]", "=", "{", "\"name\"", ":", "\"Group 2 new\"", ",", "\"lights\"", ":", "[", "\"3\"", ",", "\"4\"", ",", "\"5\"", "]", ",", "\"type\"", ":", "\"LightGroup\"", ",", "\"action\"", ":", "{", "\"on\"", ":", "False", ",", "\"bri\"", ":", "0", ",", "\"hue\"", ":", "0", ",", "\"sat\"", ":", "0", ",", "\"effect\"", ":", "\"none\"", ",", "\"xy\"", ":", "[", "0", ",", "0", "]", ",", "\"ct\"", ":", "0", ",", "\"alert\"", ":", "\"none\"", ",", "\"colormode\"", ":", "\"ct\"", ",", "}", ",", "\"state\"", ":", "{", "\"any_on\"", ":", "False", ",", "\"all_on\"", ":", "False", "}", ",", "}", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "{", "}", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "updated_group_response", ")", "# Calling a service will trigger the updates to run", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.group_1\"", "}", ",", "blocking", "=", "True", ")", "# 2x group update, 1x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "4", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "group_2", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_2\"", ")", "assert", "group_2", "is", "not", "None", "assert", "group_2", ".", "name", "==", "\"Group 2 new\"", "assert", "group_2", ".", "state", "==", "\"off\"" ]
[ 434, 0 ]
[ 484, 33 ]
python
en
['en', 'en', 'en']
True
test_other_light_update
(hass, mock_bridge)
Test changing one light that will impact state of other light.
Test changing one light that will impact state of other light.
async def test_other_light_update(hass, mock_bridge): """Test changing one light that will impact state of other light.""" mock_bridge.mock_light_responses.append(LIGHT_RESPONSE) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 1 assert len(hass.states.async_all()) == 2 lamp_2 = hass.states.get("light.hue_lamp_2") assert lamp_2 is not None assert lamp_2.name == "Hue Lamp 2" assert lamp_2.state == "off" updated_light_response = dict(LIGHT_RESPONSE) updated_light_response["2"] = { "state": { "on": True, "bri": 100, "hue": 13088, "sat": 210, "xy": [0.5, 0.4], "ct": 420, "alert": "none", "effect": "none", "colormode": "hs", "reachable": True, }, "capabilities": LIGHT_2_CAPABILITIES, "type": "Extended color light", "name": "Hue Lamp 2 new", "modelid": "LCT001", "swversion": "66009461", "manufacturername": "Philips", "uniqueid": "123", } mock_bridge.mock_light_responses.append(updated_light_response) # Calling a service will trigger the updates to run await hass.services.async_call( "light", "turn_on", {"entity_id": "light.hue_lamp_1"}, blocking=True ) # 2x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 3 assert len(hass.states.async_all()) == 2 lamp_2 = hass.states.get("light.hue_lamp_2") assert lamp_2 is not None assert lamp_2.name == "Hue Lamp 2 new" assert lamp_2.state == "on" assert lamp_2.attributes["brightness"] == 100
[ "async", "def", "test_other_light_update", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "LIGHT_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "1", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "lamp_2", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_2\"", ")", "assert", "lamp_2", "is", "not", "None", "assert", "lamp_2", ".", "name", "==", "\"Hue Lamp 2\"", "assert", "lamp_2", ".", "state", "==", "\"off\"", "updated_light_response", "=", "dict", "(", "LIGHT_RESPONSE", ")", "updated_light_response", "[", "\"2\"", "]", "=", "{", "\"state\"", ":", "{", "\"on\"", ":", "True", ",", "\"bri\"", ":", "100", ",", "\"hue\"", ":", "13088", ",", "\"sat\"", ":", "210", ",", "\"xy\"", ":", "[", "0.5", ",", "0.4", "]", ",", "\"ct\"", ":", "420", ",", "\"alert\"", ":", "\"none\"", ",", "\"effect\"", ":", "\"none\"", ",", "\"colormode\"", ":", "\"hs\"", ",", "\"reachable\"", ":", "True", ",", "}", ",", "\"capabilities\"", ":", "LIGHT_2_CAPABILITIES", ",", "\"type\"", ":", "\"Extended color light\"", ",", "\"name\"", ":", "\"Hue Lamp 2 new\"", ",", "\"modelid\"", ":", "\"LCT001\"", ",", "\"swversion\"", ":", "\"66009461\"", ",", "\"manufacturername\"", ":", "\"Philips\"", ",", "\"uniqueid\"", ":", "\"123\"", ",", "}", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "updated_light_response", ")", "# Calling a service will trigger the updates to run", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.hue_lamp_1\"", "}", ",", "blocking", "=", "True", ")", "# 2x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "3", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "lamp_2", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_2\"", ")", "assert", "lamp_2", "is", "not", "None", "assert", "lamp_2", ".", "name", "==", "\"Hue Lamp 2 new\"", "assert", "lamp_2", ".", "state", "==", "\"on\"", "assert", "lamp_2", ".", "attributes", "[", "\"brightness\"", "]", "==", "100" ]
[ 487, 0 ]
[ 537, 49 ]
python
en
['en', 'en', 'en']
True
test_update_timeout
(hass, mock_bridge)
Test bridge marked as not available if timeout error during update.
Test bridge marked as not available if timeout error during update.
async def test_update_timeout(hass, mock_bridge): """Test bridge marked as not available if timeout error during update.""" mock_bridge.api.lights.update = Mock(side_effect=asyncio.TimeoutError) mock_bridge.api.groups.update = Mock(side_effect=asyncio.TimeoutError) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 0 assert len(hass.states.async_all()) == 0
[ "async", "def", "test_update_timeout", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "api", ".", "lights", ".", "update", "=", "Mock", "(", "side_effect", "=", "asyncio", ".", "TimeoutError", ")", "mock_bridge", ".", "api", ".", "groups", ".", "update", "=", "Mock", "(", "side_effect", "=", "asyncio", ".", "TimeoutError", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "0", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 540, 0 ]
[ 546, 44 ]
python
en
['en', 'en', 'en']
True
test_update_unauthorized
(hass, mock_bridge)
Test bridge marked as not authorized if unauthorized during update.
Test bridge marked as not authorized if unauthorized during update.
async def test_update_unauthorized(hass, mock_bridge): """Test bridge marked as not authorized if unauthorized during update.""" mock_bridge.api.lights.update = Mock(side_effect=aiohue.Unauthorized) mock_bridge.api.groups.update = Mock(side_effect=aiohue.Unauthorized) await setup_bridge(hass, mock_bridge) assert len(mock_bridge.mock_requests) == 0 assert len(hass.states.async_all()) == 0 assert len(mock_bridge.handle_unauthorized_error.mock_calls) == 1
[ "async", "def", "test_update_unauthorized", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "api", ".", "lights", ".", "update", "=", "Mock", "(", "side_effect", "=", "aiohue", ".", "Unauthorized", ")", "mock_bridge", ".", "api", ".", "groups", ".", "update", "=", "Mock", "(", "side_effect", "=", "aiohue", ".", "Unauthorized", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "0", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0", "assert", "len", "(", "mock_bridge", ".", "handle_unauthorized_error", ".", "mock_calls", ")", "==", "1" ]
[ 549, 0 ]
[ 556, 69 ]
python
en
['en', 'en', 'en']
True
test_light_turn_on_service
(hass, mock_bridge)
Test calling the turn on service on a light.
Test calling the turn on service on a light.
async def test_light_turn_on_service(hass, mock_bridge): """Test calling the turn on service on a light.""" mock_bridge.mock_light_responses.append(LIGHT_RESPONSE) await setup_bridge(hass, mock_bridge) light = hass.states.get("light.hue_lamp_2") assert light is not None assert light.state == "off" updated_light_response = dict(LIGHT_RESPONSE) updated_light_response["2"] = LIGHT_2_ON mock_bridge.mock_light_responses.append(updated_light_response) await hass.services.async_call( "light", "turn_on", {"entity_id": "light.hue_lamp_2", "brightness": 100, "color_temp": 300}, blocking=True, ) # 2x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 3 assert mock_bridge.mock_requests[1]["json"] == { "bri": 100, "on": True, "ct": 300, "alert": "none", } assert len(hass.states.async_all()) == 2 light = hass.states.get("light.hue_lamp_2") assert light is not None assert light.state == "on" # test hue gamut in turn_on service await hass.services.async_call( "light", "turn_on", {"entity_id": "light.hue_lamp_2", "rgb_color": [0, 0, 255]}, blocking=True, ) assert len(mock_bridge.mock_requests) == 5 assert mock_bridge.mock_requests[3]["json"] == { "on": True, "xy": (0.138, 0.08), "alert": "none", }
[ "async", "def", "test_light_turn_on_service", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "LIGHT_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "light", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_2\"", ")", "assert", "light", "is", "not", "None", "assert", "light", ".", "state", "==", "\"off\"", "updated_light_response", "=", "dict", "(", "LIGHT_RESPONSE", ")", "updated_light_response", "[", "\"2\"", "]", "=", "LIGHT_2_ON", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "updated_light_response", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.hue_lamp_2\"", ",", "\"brightness\"", ":", "100", ",", "\"color_temp\"", ":", "300", "}", ",", "blocking", "=", "True", ",", ")", "# 2x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "3", "assert", "mock_bridge", ".", "mock_requests", "[", "1", "]", "[", "\"json\"", "]", "==", "{", "\"bri\"", ":", "100", ",", "\"on\"", ":", "True", ",", "\"ct\"", ":", "300", ",", "\"alert\"", ":", "\"none\"", ",", "}", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "light", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_2\"", ")", "assert", "light", "is", "not", "None", "assert", "light", ".", "state", "==", "\"on\"", "# test hue gamut in turn_on service", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_on\"", ",", "{", "\"entity_id\"", ":", "\"light.hue_lamp_2\"", ",", "\"rgb_color\"", ":", "[", "0", ",", "0", ",", "255", "]", "}", ",", "blocking", "=", "True", ",", ")", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "5", "assert", "mock_bridge", ".", "mock_requests", "[", "3", "]", "[", "\"json\"", "]", "==", "{", "\"on\"", ":", "True", ",", "\"xy\"", ":", "(", "0.138", ",", "0.08", ")", ",", "\"alert\"", ":", "\"none\"", ",", "}" ]
[ 559, 0 ]
[ 608, 5 ]
python
en
['en', 'en', 'en']
True
test_light_turn_off_service
(hass, mock_bridge)
Test calling the turn on service on a light.
Test calling the turn on service on a light.
async def test_light_turn_off_service(hass, mock_bridge): """Test calling the turn on service on a light.""" mock_bridge.mock_light_responses.append(LIGHT_RESPONSE) await setup_bridge(hass, mock_bridge) light = hass.states.get("light.hue_lamp_1") assert light is not None assert light.state == "on" updated_light_response = dict(LIGHT_RESPONSE) updated_light_response["1"] = LIGHT_1_OFF mock_bridge.mock_light_responses.append(updated_light_response) await hass.services.async_call( "light", "turn_off", {"entity_id": "light.hue_lamp_1"}, blocking=True ) # 2x light update, 1 turn on request assert len(mock_bridge.mock_requests) == 3 assert mock_bridge.mock_requests[1]["json"] == {"on": False, "alert": "none"} assert len(hass.states.async_all()) == 2 light = hass.states.get("light.hue_lamp_1") assert light is not None assert light.state == "off"
[ "async", "def", "test_light_turn_off_service", "(", "hass", ",", "mock_bridge", ")", ":", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "LIGHT_RESPONSE", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "light", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_1\"", ")", "assert", "light", "is", "not", "None", "assert", "light", ".", "state", "==", "\"on\"", "updated_light_response", "=", "dict", "(", "LIGHT_RESPONSE", ")", "updated_light_response", "[", "\"1\"", "]", "=", "LIGHT_1_OFF", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "updated_light_response", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"light\"", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "\"light.hue_lamp_1\"", "}", ",", "blocking", "=", "True", ")", "# 2x light update, 1 turn on request", "assert", "len", "(", "mock_bridge", ".", "mock_requests", ")", "==", "3", "assert", "mock_bridge", ".", "mock_requests", "[", "1", "]", "[", "\"json\"", "]", "==", "{", "\"on\"", ":", "False", ",", "\"alert\"", ":", "\"none\"", "}", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "2", "light", "=", "hass", ".", "states", ".", "get", "(", "\"light.hue_lamp_1\"", ")", "assert", "light", "is", "not", "None", "assert", "light", ".", "state", "==", "\"off\"" ]
[ 611, 0 ]
[ 636, 31 ]
python
en
['en', 'en', 'en']
True
test_available
()
Test available property.
Test available property.
def test_available(): """Test available property.""" light = hue_light.HueLight( light=Mock( state={"reachable": False}, raw=LIGHT_RAW, colorgamuttype=LIGHT_GAMUT_TYPE, colorgamut=LIGHT_GAMUT, ), coordinator=Mock(last_update_success=True), bridge=Mock(allow_unreachable=False), is_group=False, supported_features=hue_light.SUPPORT_HUE_EXTENDED, ) assert light.available is False light = hue_light.HueLight( light=Mock( state={"reachable": False}, raw=LIGHT_RAW, colorgamuttype=LIGHT_GAMUT_TYPE, colorgamut=LIGHT_GAMUT, ), coordinator=Mock(last_update_success=True), bridge=Mock(allow_unreachable=True), is_group=False, supported_features=hue_light.SUPPORT_HUE_EXTENDED, ) assert light.available is True light = hue_light.HueLight( light=Mock( state={"reachable": False}, raw=LIGHT_RAW, colorgamuttype=LIGHT_GAMUT_TYPE, colorgamut=LIGHT_GAMUT, ), coordinator=Mock(last_update_success=True), bridge=Mock(allow_unreachable=False), is_group=True, supported_features=hue_light.SUPPORT_HUE_EXTENDED, ) assert light.available is True
[ "def", "test_available", "(", ")", ":", "light", "=", "hue_light", ".", "HueLight", "(", "light", "=", "Mock", "(", "state", "=", "{", "\"reachable\"", ":", "False", "}", ",", "raw", "=", "LIGHT_RAW", ",", "colorgamuttype", "=", "LIGHT_GAMUT_TYPE", ",", "colorgamut", "=", "LIGHT_GAMUT", ",", ")", ",", "coordinator", "=", "Mock", "(", "last_update_success", "=", "True", ")", ",", "bridge", "=", "Mock", "(", "allow_unreachable", "=", "False", ")", ",", "is_group", "=", "False", ",", "supported_features", "=", "hue_light", ".", "SUPPORT_HUE_EXTENDED", ",", ")", "assert", "light", ".", "available", "is", "False", "light", "=", "hue_light", ".", "HueLight", "(", "light", "=", "Mock", "(", "state", "=", "{", "\"reachable\"", ":", "False", "}", ",", "raw", "=", "LIGHT_RAW", ",", "colorgamuttype", "=", "LIGHT_GAMUT_TYPE", ",", "colorgamut", "=", "LIGHT_GAMUT", ",", ")", ",", "coordinator", "=", "Mock", "(", "last_update_success", "=", "True", ")", ",", "bridge", "=", "Mock", "(", "allow_unreachable", "=", "True", ")", ",", "is_group", "=", "False", ",", "supported_features", "=", "hue_light", ".", "SUPPORT_HUE_EXTENDED", ",", ")", "assert", "light", ".", "available", "is", "True", "light", "=", "hue_light", ".", "HueLight", "(", "light", "=", "Mock", "(", "state", "=", "{", "\"reachable\"", ":", "False", "}", ",", "raw", "=", "LIGHT_RAW", ",", "colorgamuttype", "=", "LIGHT_GAMUT_TYPE", ",", "colorgamut", "=", "LIGHT_GAMUT", ",", ")", ",", "coordinator", "=", "Mock", "(", "last_update_success", "=", "True", ")", ",", "bridge", "=", "Mock", "(", "allow_unreachable", "=", "False", ")", ",", "is_group", "=", "True", ",", "supported_features", "=", "hue_light", ".", "SUPPORT_HUE_EXTENDED", ",", ")", "assert", "light", ".", "available", "is", "True" ]
[ 639, 0 ]
[ 684, 34 ]
python
en
['fr', 'en', 'en']
True
test_hs_color
()
Test hs_color property.
Test hs_color property.
def test_hs_color(): """Test hs_color property.""" light = hue_light.HueLight( light=Mock( state={"colormode": "ct", "hue": 1234, "sat": 123}, raw=LIGHT_RAW, colorgamuttype=LIGHT_GAMUT_TYPE, colorgamut=LIGHT_GAMUT, ), coordinator=Mock(last_update_success=True), bridge=Mock(), is_group=False, supported_features=hue_light.SUPPORT_HUE_EXTENDED, ) assert light.hs_color is None light = hue_light.HueLight( light=Mock( state={"colormode": "hs", "hue": 1234, "sat": 123}, raw=LIGHT_RAW, colorgamuttype=LIGHT_GAMUT_TYPE, colorgamut=LIGHT_GAMUT, ), coordinator=Mock(last_update_success=True), bridge=Mock(), is_group=False, supported_features=hue_light.SUPPORT_HUE_EXTENDED, ) assert light.hs_color is None light = hue_light.HueLight( light=Mock( state={"colormode": "xy", "hue": 1234, "sat": 123, "xy": [0.4, 0.5]}, raw=LIGHT_RAW, colorgamuttype=LIGHT_GAMUT_TYPE, colorgamut=LIGHT_GAMUT, ), coordinator=Mock(last_update_success=True), bridge=Mock(), is_group=False, supported_features=hue_light.SUPPORT_HUE_EXTENDED, ) assert light.hs_color == color.color_xy_to_hs(0.4, 0.5, LIGHT_GAMUT)
[ "def", "test_hs_color", "(", ")", ":", "light", "=", "hue_light", ".", "HueLight", "(", "light", "=", "Mock", "(", "state", "=", "{", "\"colormode\"", ":", "\"ct\"", ",", "\"hue\"", ":", "1234", ",", "\"sat\"", ":", "123", "}", ",", "raw", "=", "LIGHT_RAW", ",", "colorgamuttype", "=", "LIGHT_GAMUT_TYPE", ",", "colorgamut", "=", "LIGHT_GAMUT", ",", ")", ",", "coordinator", "=", "Mock", "(", "last_update_success", "=", "True", ")", ",", "bridge", "=", "Mock", "(", ")", ",", "is_group", "=", "False", ",", "supported_features", "=", "hue_light", ".", "SUPPORT_HUE_EXTENDED", ",", ")", "assert", "light", ".", "hs_color", "is", "None", "light", "=", "hue_light", ".", "HueLight", "(", "light", "=", "Mock", "(", "state", "=", "{", "\"colormode\"", ":", "\"hs\"", ",", "\"hue\"", ":", "1234", ",", "\"sat\"", ":", "123", "}", ",", "raw", "=", "LIGHT_RAW", ",", "colorgamuttype", "=", "LIGHT_GAMUT_TYPE", ",", "colorgamut", "=", "LIGHT_GAMUT", ",", ")", ",", "coordinator", "=", "Mock", "(", "last_update_success", "=", "True", ")", ",", "bridge", "=", "Mock", "(", ")", ",", "is_group", "=", "False", ",", "supported_features", "=", "hue_light", ".", "SUPPORT_HUE_EXTENDED", ",", ")", "assert", "light", ".", "hs_color", "is", "None", "light", "=", "hue_light", ".", "HueLight", "(", "light", "=", "Mock", "(", "state", "=", "{", "\"colormode\"", ":", "\"xy\"", ",", "\"hue\"", ":", "1234", ",", "\"sat\"", ":", "123", ",", "\"xy\"", ":", "[", "0.4", ",", "0.5", "]", "}", ",", "raw", "=", "LIGHT_RAW", ",", "colorgamuttype", "=", "LIGHT_GAMUT_TYPE", ",", "colorgamut", "=", "LIGHT_GAMUT", ",", ")", ",", "coordinator", "=", "Mock", "(", "last_update_success", "=", "True", ")", ",", "bridge", "=", "Mock", "(", ")", ",", "is_group", "=", "False", ",", "supported_features", "=", "hue_light", ".", "SUPPORT_HUE_EXTENDED", ",", ")", "assert", "light", ".", "hs_color", "==", "color", ".", "color_xy_to_hs", "(", "0.4", ",", "0.5", ",", "LIGHT_GAMUT", ")" ]
[ 687, 0 ]
[ 732, 72 ]
python
en
['ro', 'fr', 'en']
False
test_group_features
(hass, mock_bridge)
Test group features.
Test group features.
async def test_group_features(hass, mock_bridge): """Test group features.""" color_temp_type = "Color temperature light" extended_color_type = "Extended color light" group_response = { "1": { "name": "Group 1", "lights": ["1", "2"], "type": "Room", "action": { "on": True, "bri": 254, "hue": 10000, "sat": 254, "effect": "none", "xy": [0.5, 0.5], "ct": 250, "alert": "select", "colormode": "ct", }, "state": {"any_on": True, "all_on": False}, }, "2": { "name": "Group 2", "lights": ["3", "4"], "type": "Room", "action": { "on": True, "bri": 153, "hue": 4345, "sat": 254, "effect": "none", "xy": [0.5, 0.5], "ct": 250, "alert": "select", "colormode": "ct", }, "state": {"any_on": True, "all_on": False}, }, "3": { "name": "Group 3", "lights": ["1", "3"], "type": "Room", "action": { "on": True, "bri": 153, "hue": 4345, "sat": 254, "effect": "none", "xy": [0.5, 0.5], "ct": 250, "alert": "select", "colormode": "ct", }, "state": {"any_on": True, "all_on": False}, }, } light_1 = { "state": { "on": True, "bri": 144, "ct": 467, "alert": "none", "effect": "none", "reachable": True, }, "capabilities": { "control": { "colorgamuttype": "A", "colorgamut": [[0.704, 0.296], [0.2151, 0.7106], [0.138, 0.08]], } }, "type": color_temp_type, "name": "Hue Lamp 1", "modelid": "LCT001", "swversion": "66009461", "manufacturername": "Philips", "uniqueid": "456", } light_2 = { "state": { "on": False, "bri": 0, "ct": 0, "alert": "none", "effect": "none", "colormode": "xy", "reachable": True, }, "capabilities": { "control": { "colorgamuttype": "A", "colorgamut": [[0.704, 0.296], [0.2151, 0.7106], [0.138, 0.08]], } }, "type": color_temp_type, "name": "Hue Lamp 2", "modelid": "LCT001", "swversion": "66009461", "manufacturername": "Philips", "uniqueid": "4567", } light_3 = { "state": { "on": False, "bri": 0, "hue": 0, "sat": 0, "xy": [0, 0], "ct": 0, "alert": "none", "effect": "none", "colormode": "hs", "reachable": True, }, "capabilities": { "control": { "colorgamuttype": "A", "colorgamut": [[0.704, 0.296], [0.2151, 0.7106], [0.138, 0.08]], } }, "type": extended_color_type, "name": "Hue Lamp 3", "modelid": "LCT001", "swversion": "66009461", "manufacturername": "Philips", "uniqueid": "123", } light_4 = { "state": { "on": True, "bri": 100, "hue": 13088, "sat": 210, "xy": [0.5, 0.4], "ct": 420, "alert": "none", "effect": "none", "colormode": "hs", "reachable": True, }, "capabilities": { "control": { "colorgamuttype": "A", "colorgamut": [[0.704, 0.296], [0.2151, 0.7106], [0.138, 0.08]], } }, "type": extended_color_type, "name": "Hue Lamp 4", "modelid": "LCT001", "swversion": "66009461", "manufacturername": "Philips", "uniqueid": "1234", } light_response = { "1": light_1, "2": light_2, "3": light_3, "4": light_4, } mock_bridge.allow_groups = True mock_bridge.mock_light_responses.append(light_response) mock_bridge.mock_group_responses.append(group_response) await setup_bridge(hass, mock_bridge) color_temp_feature = hue_light.SUPPORT_HUE["Color temperature light"] extended_color_feature = hue_light.SUPPORT_HUE["Extended color light"] group_1 = hass.states.get("light.group_1") assert group_1.attributes["supported_features"] == color_temp_feature group_2 = hass.states.get("light.group_2") assert group_2.attributes["supported_features"] == extended_color_feature group_3 = hass.states.get("light.group_3") assert group_3.attributes["supported_features"] == extended_color_feature
[ "async", "def", "test_group_features", "(", "hass", ",", "mock_bridge", ")", ":", "color_temp_type", "=", "\"Color temperature light\"", "extended_color_type", "=", "\"Extended color light\"", "group_response", "=", "{", "\"1\"", ":", "{", "\"name\"", ":", "\"Group 1\"", ",", "\"lights\"", ":", "[", "\"1\"", ",", "\"2\"", "]", ",", "\"type\"", ":", "\"Room\"", ",", "\"action\"", ":", "{", "\"on\"", ":", "True", ",", "\"bri\"", ":", "254", ",", "\"hue\"", ":", "10000", ",", "\"sat\"", ":", "254", ",", "\"effect\"", ":", "\"none\"", ",", "\"xy\"", ":", "[", "0.5", ",", "0.5", "]", ",", "\"ct\"", ":", "250", ",", "\"alert\"", ":", "\"select\"", ",", "\"colormode\"", ":", "\"ct\"", ",", "}", ",", "\"state\"", ":", "{", "\"any_on\"", ":", "True", ",", "\"all_on\"", ":", "False", "}", ",", "}", ",", "\"2\"", ":", "{", "\"name\"", ":", "\"Group 2\"", ",", "\"lights\"", ":", "[", "\"3\"", ",", "\"4\"", "]", ",", "\"type\"", ":", "\"Room\"", ",", "\"action\"", ":", "{", "\"on\"", ":", "True", ",", "\"bri\"", ":", "153", ",", "\"hue\"", ":", "4345", ",", "\"sat\"", ":", "254", ",", "\"effect\"", ":", "\"none\"", ",", "\"xy\"", ":", "[", "0.5", ",", "0.5", "]", ",", "\"ct\"", ":", "250", ",", "\"alert\"", ":", "\"select\"", ",", "\"colormode\"", ":", "\"ct\"", ",", "}", ",", "\"state\"", ":", "{", "\"any_on\"", ":", "True", ",", "\"all_on\"", ":", "False", "}", ",", "}", ",", "\"3\"", ":", "{", "\"name\"", ":", "\"Group 3\"", ",", "\"lights\"", ":", "[", "\"1\"", ",", "\"3\"", "]", ",", "\"type\"", ":", "\"Room\"", ",", "\"action\"", ":", "{", "\"on\"", ":", "True", ",", "\"bri\"", ":", "153", ",", "\"hue\"", ":", "4345", ",", "\"sat\"", ":", "254", ",", "\"effect\"", ":", "\"none\"", ",", "\"xy\"", ":", "[", "0.5", ",", "0.5", "]", ",", "\"ct\"", ":", "250", ",", "\"alert\"", ":", "\"select\"", ",", "\"colormode\"", ":", "\"ct\"", ",", "}", ",", "\"state\"", ":", "{", "\"any_on\"", ":", "True", ",", "\"all_on\"", ":", "False", "}", ",", "}", ",", "}", "light_1", "=", "{", "\"state\"", ":", "{", "\"on\"", ":", "True", ",", "\"bri\"", ":", "144", ",", "\"ct\"", ":", "467", ",", "\"alert\"", ":", "\"none\"", ",", "\"effect\"", ":", "\"none\"", ",", "\"reachable\"", ":", "True", ",", "}", ",", "\"capabilities\"", ":", "{", "\"control\"", ":", "{", "\"colorgamuttype\"", ":", "\"A\"", ",", "\"colorgamut\"", ":", "[", "[", "0.704", ",", "0.296", "]", ",", "[", "0.2151", ",", "0.7106", "]", ",", "[", "0.138", ",", "0.08", "]", "]", ",", "}", "}", ",", "\"type\"", ":", "color_temp_type", ",", "\"name\"", ":", "\"Hue Lamp 1\"", ",", "\"modelid\"", ":", "\"LCT001\"", ",", "\"swversion\"", ":", "\"66009461\"", ",", "\"manufacturername\"", ":", "\"Philips\"", ",", "\"uniqueid\"", ":", "\"456\"", ",", "}", "light_2", "=", "{", "\"state\"", ":", "{", "\"on\"", ":", "False", ",", "\"bri\"", ":", "0", ",", "\"ct\"", ":", "0", ",", "\"alert\"", ":", "\"none\"", ",", "\"effect\"", ":", "\"none\"", ",", "\"colormode\"", ":", "\"xy\"", ",", "\"reachable\"", ":", "True", ",", "}", ",", "\"capabilities\"", ":", "{", "\"control\"", ":", "{", "\"colorgamuttype\"", ":", "\"A\"", ",", "\"colorgamut\"", ":", "[", "[", "0.704", ",", "0.296", "]", ",", "[", "0.2151", ",", "0.7106", "]", ",", "[", "0.138", ",", "0.08", "]", "]", ",", "}", "}", ",", "\"type\"", ":", "color_temp_type", ",", "\"name\"", ":", "\"Hue Lamp 2\"", ",", "\"modelid\"", ":", "\"LCT001\"", ",", "\"swversion\"", ":", "\"66009461\"", ",", "\"manufacturername\"", ":", "\"Philips\"", ",", "\"uniqueid\"", ":", "\"4567\"", ",", "}", "light_3", "=", "{", "\"state\"", ":", "{", "\"on\"", ":", "False", ",", "\"bri\"", ":", "0", ",", "\"hue\"", ":", "0", ",", "\"sat\"", ":", "0", ",", "\"xy\"", ":", "[", "0", ",", "0", "]", ",", "\"ct\"", ":", "0", ",", "\"alert\"", ":", "\"none\"", ",", "\"effect\"", ":", "\"none\"", ",", "\"colormode\"", ":", "\"hs\"", ",", "\"reachable\"", ":", "True", ",", "}", ",", "\"capabilities\"", ":", "{", "\"control\"", ":", "{", "\"colorgamuttype\"", ":", "\"A\"", ",", "\"colorgamut\"", ":", "[", "[", "0.704", ",", "0.296", "]", ",", "[", "0.2151", ",", "0.7106", "]", ",", "[", "0.138", ",", "0.08", "]", "]", ",", "}", "}", ",", "\"type\"", ":", "extended_color_type", ",", "\"name\"", ":", "\"Hue Lamp 3\"", ",", "\"modelid\"", ":", "\"LCT001\"", ",", "\"swversion\"", ":", "\"66009461\"", ",", "\"manufacturername\"", ":", "\"Philips\"", ",", "\"uniqueid\"", ":", "\"123\"", ",", "}", "light_4", "=", "{", "\"state\"", ":", "{", "\"on\"", ":", "True", ",", "\"bri\"", ":", "100", ",", "\"hue\"", ":", "13088", ",", "\"sat\"", ":", "210", ",", "\"xy\"", ":", "[", "0.5", ",", "0.4", "]", ",", "\"ct\"", ":", "420", ",", "\"alert\"", ":", "\"none\"", ",", "\"effect\"", ":", "\"none\"", ",", "\"colormode\"", ":", "\"hs\"", ",", "\"reachable\"", ":", "True", ",", "}", ",", "\"capabilities\"", ":", "{", "\"control\"", ":", "{", "\"colorgamuttype\"", ":", "\"A\"", ",", "\"colorgamut\"", ":", "[", "[", "0.704", ",", "0.296", "]", ",", "[", "0.2151", ",", "0.7106", "]", ",", "[", "0.138", ",", "0.08", "]", "]", ",", "}", "}", ",", "\"type\"", ":", "extended_color_type", ",", "\"name\"", ":", "\"Hue Lamp 4\"", ",", "\"modelid\"", ":", "\"LCT001\"", ",", "\"swversion\"", ":", "\"66009461\"", ",", "\"manufacturername\"", ":", "\"Philips\"", ",", "\"uniqueid\"", ":", "\"1234\"", ",", "}", "light_response", "=", "{", "\"1\"", ":", "light_1", ",", "\"2\"", ":", "light_2", ",", "\"3\"", ":", "light_3", ",", "\"4\"", ":", "light_4", ",", "}", "mock_bridge", ".", "allow_groups", "=", "True", "mock_bridge", ".", "mock_light_responses", ".", "append", "(", "light_response", ")", "mock_bridge", ".", "mock_group_responses", ".", "append", "(", "group_response", ")", "await", "setup_bridge", "(", "hass", ",", "mock_bridge", ")", "color_temp_feature", "=", "hue_light", ".", "SUPPORT_HUE", "[", "\"Color temperature light\"", "]", "extended_color_feature", "=", "hue_light", ".", "SUPPORT_HUE", "[", "\"Extended color light\"", "]", "group_1", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_1\"", ")", "assert", "group_1", ".", "attributes", "[", "\"supported_features\"", "]", "==", "color_temp_feature", "group_2", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_2\"", ")", "assert", "group_2", ".", "attributes", "[", "\"supported_features\"", "]", "==", "extended_color_feature", "group_3", "=", "hass", ".", "states", ".", "get", "(", "\"light.group_3\"", ")", "assert", "group_3", ".", "attributes", "[", "\"supported_features\"", "]", "==", "extended_color_feature" ]
[ 735, 0 ]
[ 914, 77 ]
python
en
['en', 'en', 'en']
True
_gelu_python
(x)
Original Implementation of the GELU activation function in Google BERT repo when initially created. For information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in torch.nn.functional Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
Original Implementation of the GELU activation function in Google BERT repo when initially created. For information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in torch.nn.functional Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
def _gelu_python(x): """ Original Implementation of the GELU activation function in Google BERT repo when initially created. For information: OpenAI GPT's GELU is slightly different (and gives slightly different results): 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) This is now written in C in torch.nn.functional Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415 """ return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
[ "def", "_gelu_python", "(", "x", ")", ":", "return", "x", "*", "0.5", "*", "(", "1.0", "+", "torch", ".", "erf", "(", "x", "/", "math", ".", "sqrt", "(", "2.0", ")", ")", ")" ]
[ 26, 0 ]
[ 33, 58 ]
python
en
['en', 'error', 'th']
False
gelu_new
(x)
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
def gelu_new(x): """ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415 """ return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
[ "def", "gelu_new", "(", "x", ")", ":", "return", "0.5", "*", "x", "*", "(", "1.0", "+", "torch", ".", "tanh", "(", "math", ".", "sqrt", "(", "2.0", "/", "math", ".", "pi", ")", "*", "(", "x", "+", "0.044715", "*", "torch", ".", "pow", "(", "x", ",", "3.0", ")", ")", ")", ")" ]
[ 36, 0 ]
[ 41, 102 ]
python
en
['en', 'error', 'th']
False
_silu_python
(x)
See Gaussian Error Linear Units (Hendrycks et al., https://arxiv.org/abs/1606.08415) where the SiLU (Sigmoid Linear Unit) was originally introduced and coined, and see Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning (Elfwing et al., https://arxiv.org/abs/1702.03118) and Swish: a Self-Gated Activation Function (Ramachandran et al., https://arxiv.org/abs/1710.05941v1) where the SiLU was experimented with later.
See Gaussian Error Linear Units (Hendrycks et al., https://arxiv.org/abs/1606.08415) where the SiLU (Sigmoid Linear Unit) was originally introduced and coined, and see Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning (Elfwing et al., https://arxiv.org/abs/1702.03118) and Swish: a Self-Gated Activation Function (Ramachandran et al., https://arxiv.org/abs/1710.05941v1) where the SiLU was experimented with later.
def _silu_python(x): """ See Gaussian Error Linear Units (Hendrycks et al., https://arxiv.org/abs/1606.08415) where the SiLU (Sigmoid Linear Unit) was originally introduced and coined, and see Sigmoid-Weighted Linear Units for Neural Network Function Approximation in Reinforcement Learning (Elfwing et al., https://arxiv.org/abs/1702.03118) and Swish: a Self-Gated Activation Function (Ramachandran et al., https://arxiv.org/abs/1710.05941v1) where the SiLU was experimented with later. """ return x * torch.sigmoid(x)
[ "def", "_silu_python", "(", "x", ")", ":", "return", "x", "*", "torch", ".", "sigmoid", "(", "x", ")" ]
[ 54, 0 ]
[ 62, 31 ]
python
en
['en', 'error', 'th']
False
device_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def device_reg(hass): """Return an empty, loaded, registry.""" return mock_device_registry(hass)
[ "def", "device_reg", "(", "hass", ")", ":", "return", "mock_device_registry", "(", "hass", ")" ]
[ 21, 0 ]
[ 23, 37 ]
python
en
['en', 'fy', 'en']
True
entity_reg
(hass)
Return an empty, loaded, registry.
Return an empty, loaded, registry.
def entity_reg(hass): """Return an empty, loaded, registry.""" return mock_registry(hass)
[ "def", "entity_reg", "(", "hass", ")", ":", "return", "mock_registry", "(", "hass", ")" ]
[ 27, 0 ]
[ 29, 30 ]
python
en
['en', 'fy', 'en']
True
calls
(hass)
Track calls to a mock service.
Track calls to a mock service.
def calls(hass): """Track calls to a mock service.""" return async_mock_service(hass, "test", "automation")
[ "def", "calls", "(", "hass", ")", ":", "return", "async_mock_service", "(", "hass", ",", "\"test\"", ",", "\"automation\"", ")" ]
[ 33, 0 ]
[ 35, 57 ]
python
en
['en', 'en', 'en']
True
test_get_actions
(hass, device_reg, entity_reg)
Test we get the expected actions from a switch.
Test we get the expected actions from a switch.
async def test_get_actions(hass, device_reg, entity_reg): """Test we get the expected actions from a switch.""" config_entry = MockConfigEntry(domain="test", data={}) config_entry.add_to_hass(hass) device_entry = device_reg.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_reg.async_get_or_create(DOMAIN, "test", "5678", device_id=device_entry.id) expected_actions = [ { "domain": DOMAIN, "type": "turn_off", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_5678", }, { "domain": DOMAIN, "type": "turn_on", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_5678", }, { "domain": DOMAIN, "type": "toggle", "device_id": device_entry.id, "entity_id": f"{DOMAIN}.test_5678", }, ] actions = await async_get_device_automations(hass, "action", device_entry.id) assert actions == expected_actions
[ "async", "def", "test_get_actions", "(", "hass", ",", "device_reg", ",", "entity_reg", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "\"test\"", ",", "data", "=", "{", "}", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "device_entry", "=", "device_reg", ".", "async_get_or_create", "(", "config_entry_id", "=", "config_entry", ".", "entry_id", ",", "connections", "=", "{", "(", "device_registry", ".", "CONNECTION_NETWORK_MAC", ",", "\"12:34:56:AB:CD:EF\"", ")", "}", ",", ")", "entity_reg", ".", "async_get_or_create", "(", "DOMAIN", ",", "\"test\"", ",", "\"5678\"", ",", "device_id", "=", "device_entry", ".", "id", ")", "expected_actions", "=", "[", "{", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"turn_off\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "f\"{DOMAIN}.test_5678\"", ",", "}", ",", "{", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"turn_on\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "f\"{DOMAIN}.test_5678\"", ",", "}", ",", "{", "\"domain\"", ":", "DOMAIN", ",", "\"type\"", ":", "\"toggle\"", ",", "\"device_id\"", ":", "device_entry", ".", "id", ",", "\"entity_id\"", ":", "f\"{DOMAIN}.test_5678\"", ",", "}", ",", "]", "actions", "=", "await", "async_get_device_automations", "(", "hass", ",", "\"action\"", ",", "device_entry", ".", "id", ")", "assert", "actions", "==", "expected_actions" ]
[ 38, 0 ]
[ 68, 38 ]
python
en
['en', 'en', 'en']
True
test_action
(hass, calls)
Test for turn_on and turn_off actions.
Test for turn_on and turn_off actions.
async def test_action(hass, calls): """Test for turn_on and turn_off actions.""" platform = getattr(hass.components, f"test.{DOMAIN}") platform.init() assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) await hass.async_block_till_done() ent1, ent2, ent3 = platform.ENTITIES assert await async_setup_component( hass, automation.DOMAIN, { automation.DOMAIN: [ { "trigger": {"platform": "event", "event_type": "test_event1"}, "action": { "domain": DOMAIN, "device_id": "", "entity_id": ent1.entity_id, "type": "turn_off", }, }, { "trigger": {"platform": "event", "event_type": "test_event2"}, "action": { "domain": DOMAIN, "device_id": "", "entity_id": ent1.entity_id, "type": "turn_on", }, }, { "trigger": {"platform": "event", "event_type": "test_event3"}, "action": { "domain": DOMAIN, "device_id": "", "entity_id": ent1.entity_id, "type": "toggle", }, }, ] }, ) await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_ON assert len(calls) == 0 hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_OFF hass.bus.async_fire("test_event1") await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_OFF hass.bus.async_fire("test_event2") await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_ON hass.bus.async_fire("test_event2") await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_ON hass.bus.async_fire("test_event3") await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_OFF hass.bus.async_fire("test_event3") await hass.async_block_till_done() assert hass.states.get(ent1.entity_id).state == STATE_ON
[ "async", "def", "test_action", "(", "hass", ",", "calls", ")", ":", "platform", "=", "getattr", "(", "hass", ".", "components", ",", "f\"test.{DOMAIN}\"", ")", "platform", ".", "init", "(", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "CONF_PLATFORM", ":", "\"test\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "ent1", ",", "ent2", ",", "ent3", "=", "platform", ".", "ENTITIES", "assert", "await", "async_setup_component", "(", "hass", ",", "automation", ".", "DOMAIN", ",", "{", "automation", ".", "DOMAIN", ":", "[", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event1\"", "}", ",", "\"action\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent1", ".", "entity_id", ",", "\"type\"", ":", "\"turn_off\"", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event2\"", "}", ",", "\"action\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent1", ".", "entity_id", ",", "\"type\"", ":", "\"turn_on\"", ",", "}", ",", "}", ",", "{", "\"trigger\"", ":", "{", "\"platform\"", ":", "\"event\"", ",", "\"event_type\"", ":", "\"test_event3\"", "}", ",", "\"action\"", ":", "{", "\"domain\"", ":", "DOMAIN", ",", "\"device_id\"", ":", "\"\"", ",", "\"entity_id\"", ":", "ent1", ".", "entity_id", ",", "\"type\"", ":", "\"toggle\"", ",", "}", ",", "}", ",", "]", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "ent1", ".", "entity_id", ")", ".", "state", "==", "STATE_ON", "assert", "len", "(", "calls", ")", "==", "0", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "ent1", ".", "entity_id", ")", ".", "state", "==", "STATE_OFF", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event1\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "ent1", ".", "entity_id", ")", ".", "state", "==", "STATE_OFF", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event2\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "ent1", ".", "entity_id", ")", ".", "state", "==", "STATE_ON", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event2\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "ent1", ".", "entity_id", ")", ".", "state", "==", "STATE_ON", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event3\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "ent1", ".", "entity_id", ")", ".", "state", "==", "STATE_OFF", "hass", ".", "bus", ".", "async_fire", "(", "\"test_event3\"", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "ent1", ".", "entity_id", ")", ".", "state", "==", "STATE_ON" ]
[ 71, 0 ]
[ 142, 60 ]
python
en
['en', 'en', 'en']
True
validate_input
(hass: core.HomeAssistant, data)
Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user.
Validate the user input allows us to connect.
async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect. Data has the keys from DATA_SCHEMA with values provided by the user. """ state_file = hass.config.path(f"nexia_config_{data[CONF_USERNAME]}.conf") try: nexia_home = NexiaHome( username=data[CONF_USERNAME], password=data[CONF_PASSWORD], auto_login=False, auto_update=False, device_name=hass.config.location_name, state_file=state_file, ) await hass.async_add_executor_job(nexia_home.login) except ConnectTimeout as ex: _LOGGER.error("Unable to connect to Nexia service: %s", ex) raise CannotConnect from ex except HTTPError as http_ex: _LOGGER.error("HTTP error from Nexia service: %s", http_ex) if is_invalid_auth_code(http_ex.response.status_code): raise InvalidAuth from http_ex raise CannotConnect from http_ex if not nexia_home.get_name(): raise InvalidAuth info = {"title": nexia_home.get_name(), "house_id": nexia_home.house_id} _LOGGER.debug("Setup ok with info: %s", info) return info
[ "async", "def", "validate_input", "(", "hass", ":", "core", ".", "HomeAssistant", ",", "data", ")", ":", "state_file", "=", "hass", ".", "config", ".", "path", "(", "f\"nexia_config_{data[CONF_USERNAME]}.conf\"", ")", "try", ":", "nexia_home", "=", "NexiaHome", "(", "username", "=", "data", "[", "CONF_USERNAME", "]", ",", "password", "=", "data", "[", "CONF_PASSWORD", "]", ",", "auto_login", "=", "False", ",", "auto_update", "=", "False", ",", "device_name", "=", "hass", ".", "config", ".", "location_name", ",", "state_file", "=", "state_file", ",", ")", "await", "hass", ".", "async_add_executor_job", "(", "nexia_home", ".", "login", ")", "except", "ConnectTimeout", "as", "ex", ":", "_LOGGER", ".", "error", "(", "\"Unable to connect to Nexia service: %s\"", ",", "ex", ")", "raise", "CannotConnect", "from", "ex", "except", "HTTPError", "as", "http_ex", ":", "_LOGGER", ".", "error", "(", "\"HTTP error from Nexia service: %s\"", ",", "http_ex", ")", "if", "is_invalid_auth_code", "(", "http_ex", ".", "response", ".", "status_code", ")", ":", "raise", "InvalidAuth", "from", "http_ex", "raise", "CannotConnect", "from", "http_ex", "if", "not", "nexia_home", ".", "get_name", "(", ")", ":", "raise", "InvalidAuth", "info", "=", "{", "\"title\"", ":", "nexia_home", ".", "get_name", "(", ")", ",", "\"house_id\"", ":", "nexia_home", ".", "house_id", "}", "_LOGGER", ".", "debug", "(", "\"Setup ok with info: %s\"", ",", "info", ")", "return", "info" ]
[ 18, 0 ]
[ 49, 15 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_step_user
(self, user_input=None)
Handle the initial step.
Handle the initial step.
async def async_step_user(self, user_input=None): """Handle the initial step.""" errors = {} if user_input is not None: try: info = await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: # pylint: disable=broad-except _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if "base" not in errors: await self.async_set_unique_id(info["house_id"]) self._abort_if_unique_id_configured() return self.async_create_entry(title=info["title"], data=user_input) return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "try", ":", "info", "=", "await", "validate_input", "(", "self", ".", "hass", ",", "user_input", ")", "except", "CannotConnect", ":", "errors", "[", "\"base\"", "]", "=", "\"cannot_connect\"", "except", "InvalidAuth", ":", "errors", "[", "\"base\"", "]", "=", "\"invalid_auth\"", "except", "Exception", ":", "# pylint: disable=broad-except", "_LOGGER", ".", "exception", "(", "\"Unexpected exception\"", ")", "errors", "[", "\"base\"", "]", "=", "\"unknown\"", "if", "\"base\"", "not", "in", "errors", ":", "await", "self", ".", "async_set_unique_id", "(", "info", "[", "\"house_id\"", "]", ")", "self", ".", "_abort_if_unique_id_configured", "(", ")", "return", "self", ".", "async_create_entry", "(", "title", "=", "info", "[", "\"title\"", "]", ",", "data", "=", "user_input", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "DATA_SCHEMA", ",", "errors", "=", "errors", ")" ]
[ 58, 4 ]
[ 79, 9 ]
python
en
['en', 'en', 'en']
True
ConfigFlow.async_step_import
(self, user_input)
Handle import.
Handle import.
async def async_step_import(self, user_input): """Handle import.""" for entry in self._async_current_entries(): if entry.data[CONF_USERNAME] == user_input[CONF_USERNAME]: return self.async_abort(reason="already_configured") return await self.async_step_user(user_input)
[ "async", "def", "async_step_import", "(", "self", ",", "user_input", ")", ":", "for", "entry", "in", "self", ".", "_async_current_entries", "(", ")", ":", "if", "entry", ".", "data", "[", "CONF_USERNAME", "]", "==", "user_input", "[", "CONF_USERNAME", "]", ":", "return", "self", ".", "async_abort", "(", "reason", "=", "\"already_configured\"", ")", "return", "await", "self", ".", "async_step_user", "(", "user_input", ")" ]
[ 81, 4 ]
[ 86, 53 ]
python
en
['en', 'ja', 'en']
False
AutoCompressPruner.validate_config
(self, model, config_list)
Parameters ---------- model : torch.nn.Module Model to be pruned config_list : list List on pruning configs
Parameters ---------- model : torch.nn.Module Model to be pruned config_list : list List on pruning configs
def validate_config(self, model, config_list): """ Parameters ---------- model : torch.nn.Module Model to be pruned config_list : list List on pruning configs """ if self._base_algo == 'level': schema = CompressorSchema([{ 'sparsity': And(float, lambda n: 0 < n < 1), Optional('op_types'): [str], Optional('op_names'): [str], }], model, _logger) elif self._base_algo in ['l1', 'l2', 'fpgm']: schema = CompressorSchema([{ 'sparsity': And(float, lambda n: 0 < n < 1), 'op_types': ['Conv2d'], Optional('op_names'): [str] }], model, _logger) schema.validate(config_list)
[ "def", "validate_config", "(", "self", ",", "model", ",", "config_list", ")", ":", "if", "self", ".", "_base_algo", "==", "'level'", ":", "schema", "=", "CompressorSchema", "(", "[", "{", "'sparsity'", ":", "And", "(", "float", ",", "lambda", "n", ":", "0", "<", "n", "<", "1", ")", ",", "Optional", "(", "'op_types'", ")", ":", "[", "str", "]", ",", "Optional", "(", "'op_names'", ")", ":", "[", "str", "]", ",", "}", "]", ",", "model", ",", "_logger", ")", "elif", "self", ".", "_base_algo", "in", "[", "'l1'", ",", "'l2'", ",", "'fpgm'", "]", ":", "schema", "=", "CompressorSchema", "(", "[", "{", "'sparsity'", ":", "And", "(", "float", ",", "lambda", "n", ":", "0", "<", "n", "<", "1", ")", ",", "'op_types'", ":", "[", "'Conv2d'", "]", ",", "Optional", "(", "'op_names'", ")", ":", "[", "str", "]", "}", "]", ",", "model", ",", "_logger", ")", "schema", ".", "validate", "(", "config_list", ")" ]
[ 121, 4 ]
[ 144, 36 ]
python
en
['en', 'error', 'th']
False
AutoCompressPruner.compress
(self)
Compress the model with AutoCompress. Returns ------- torch.nn.Module model with specified modules compressed.
Compress the model with AutoCompress.
def compress(self): """ Compress the model with AutoCompress. Returns ------- torch.nn.Module model with specified modules compressed. """ _logger.info('Starting AutoCompress pruning...') sparsity_each_round = 1 - pow(1 - self._sparsity, 1 / self._num_iterations) for i in range(self._num_iterations): _logger.info('Pruning iteration: %d', i) _logger.info('Target sparsity this round: %s', 1 - pow(1 - sparsity_each_round, i + 1)) # SimulatedAnnealingPruner _logger.info( 'Generating sparsities with SimulatedAnnealingPruner...') SApruner = SimulatedAnnealingPruner( model=copy.deepcopy(self._model_to_prune), config_list=[ {"sparsity": sparsity_each_round, "op_types": ['Conv2d']}], evaluator=self._evaluator, optimize_mode=self._optimize_mode, base_algo=self._base_algo, start_temperature=self._start_temperature, stop_temperature=self._stop_temperature, cool_down_rate=self._cool_down_rate, perturbation_magnitude=self._perturbation_magnitude, experiment_data_dir=self._experiment_data_dir) config_list = SApruner.compress(return_config_list=True) _logger.info("Generated config_list : %s", config_list) # ADMMPruner _logger.info('Performing structured pruning with ADMMPruner...') ADMMpruner = ADMMPruner( model=copy.deepcopy(self._model_to_prune), config_list=config_list, criterion=self._criterion, trainer=self._trainer, num_iterations=self._admm_num_iterations, epochs_per_iteration=self._admm_epochs_per_iteration, row=self._row, base_algo=self._base_algo) ADMMpruner.compress() ADMMpruner.export_model(os.path.join(self._experiment_data_dir, 'model_admm_masked.pth'), os.path.join( self._experiment_data_dir, 'mask.pth')) # use speed up to prune the model before next iteration, # because SimulatedAnnealingPruner & ADMMPruner don't take masked models self._model_to_prune.load_state_dict(torch.load(os.path.join( self._experiment_data_dir, 'model_admm_masked.pth'))) masks_file = os.path.join(self._experiment_data_dir, 'mask.pth') device = next(self._model_to_prune.parameters()).device _logger.info('Speeding up models...') m_speedup = ModelSpeedup(self._model_to_prune, self._dummy_input, masks_file, device) m_speedup.speedup_model() evaluation_result = self._evaluator(self._model_to_prune) _logger.info('Evaluation result of the pruned model in iteration %d: %s', i, evaluation_result) _logger.info('----------Compression finished--------------') os.remove(os.path.join(self._experiment_data_dir, 'model_admm_masked.pth')) os.remove(os.path.join(self._experiment_data_dir, 'mask.pth')) return self._model_to_prune
[ "def", "compress", "(", "self", ")", ":", "_logger", ".", "info", "(", "'Starting AutoCompress pruning...'", ")", "sparsity_each_round", "=", "1", "-", "pow", "(", "1", "-", "self", ".", "_sparsity", ",", "1", "/", "self", ".", "_num_iterations", ")", "for", "i", "in", "range", "(", "self", ".", "_num_iterations", ")", ":", "_logger", ".", "info", "(", "'Pruning iteration: %d'", ",", "i", ")", "_logger", ".", "info", "(", "'Target sparsity this round: %s'", ",", "1", "-", "pow", "(", "1", "-", "sparsity_each_round", ",", "i", "+", "1", ")", ")", "# SimulatedAnnealingPruner", "_logger", ".", "info", "(", "'Generating sparsities with SimulatedAnnealingPruner...'", ")", "SApruner", "=", "SimulatedAnnealingPruner", "(", "model", "=", "copy", ".", "deepcopy", "(", "self", ".", "_model_to_prune", ")", ",", "config_list", "=", "[", "{", "\"sparsity\"", ":", "sparsity_each_round", ",", "\"op_types\"", ":", "[", "'Conv2d'", "]", "}", "]", ",", "evaluator", "=", "self", ".", "_evaluator", ",", "optimize_mode", "=", "self", ".", "_optimize_mode", ",", "base_algo", "=", "self", ".", "_base_algo", ",", "start_temperature", "=", "self", ".", "_start_temperature", ",", "stop_temperature", "=", "self", ".", "_stop_temperature", ",", "cool_down_rate", "=", "self", ".", "_cool_down_rate", ",", "perturbation_magnitude", "=", "self", ".", "_perturbation_magnitude", ",", "experiment_data_dir", "=", "self", ".", "_experiment_data_dir", ")", "config_list", "=", "SApruner", ".", "compress", "(", "return_config_list", "=", "True", ")", "_logger", ".", "info", "(", "\"Generated config_list : %s\"", ",", "config_list", ")", "# ADMMPruner", "_logger", ".", "info", "(", "'Performing structured pruning with ADMMPruner...'", ")", "ADMMpruner", "=", "ADMMPruner", "(", "model", "=", "copy", ".", "deepcopy", "(", "self", ".", "_model_to_prune", ")", ",", "config_list", "=", "config_list", ",", "criterion", "=", "self", ".", "_criterion", ",", "trainer", "=", "self", ".", "_trainer", ",", "num_iterations", "=", "self", ".", "_admm_num_iterations", ",", "epochs_per_iteration", "=", "self", ".", "_admm_epochs_per_iteration", ",", "row", "=", "self", ".", "_row", ",", "base_algo", "=", "self", ".", "_base_algo", ")", "ADMMpruner", ".", "compress", "(", ")", "ADMMpruner", ".", "export_model", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_experiment_data_dir", ",", "'model_admm_masked.pth'", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "_experiment_data_dir", ",", "'mask.pth'", ")", ")", "# use speed up to prune the model before next iteration,", "# because SimulatedAnnealingPruner & ADMMPruner don't take masked models", "self", ".", "_model_to_prune", ".", "load_state_dict", "(", "torch", ".", "load", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_experiment_data_dir", ",", "'model_admm_masked.pth'", ")", ")", ")", "masks_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_experiment_data_dir", ",", "'mask.pth'", ")", "device", "=", "next", "(", "self", ".", "_model_to_prune", ".", "parameters", "(", ")", ")", ".", "device", "_logger", ".", "info", "(", "'Speeding up models...'", ")", "m_speedup", "=", "ModelSpeedup", "(", "self", ".", "_model_to_prune", ",", "self", ".", "_dummy_input", ",", "masks_file", ",", "device", ")", "m_speedup", ".", "speedup_model", "(", ")", "evaluation_result", "=", "self", ".", "_evaluator", "(", "self", ".", "_model_to_prune", ")", "_logger", ".", "info", "(", "'Evaluation result of the pruned model in iteration %d: %s'", ",", "i", ",", "evaluation_result", ")", "_logger", ".", "info", "(", "'----------Compression finished--------------'", ")", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_experiment_data_dir", ",", "'model_admm_masked.pth'", ")", ")", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_experiment_data_dir", ",", "'mask.pth'", ")", ")", "return", "self", ".", "_model_to_prune" ]
[ 149, 4 ]
[ 221, 35 ]
python
en
['en', 'error', 'th']
False
test_controlling_state_via_mqtt
(hass, mqtt_mock, setup_tasmota)
Test state update via MQTT.
Test state update via MQTT.
async def test_controlling_state_via_mqtt(hass, mqtt_mock, setup_tasmota): """Test state update via MQTT.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() state = hass.states.get("switch.test") assert state.state == "unavailable" assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("switch.test") assert state.state == STATE_OFF assert not state.attributes.get(ATTR_ASSUMED_STATE) async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/STATE", '{"POWER":"ON"}') state = hass.states.get("switch.test") assert state.state == STATE_ON async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/STATE", '{"POWER":"OFF"}') state = hass.states.get("switch.test") assert state.state == STATE_OFF async_fire_mqtt_message(hass, "tasmota_49A3BC/stat/RESULT", '{"POWER":"ON"}') state = hass.states.get("switch.test") assert state.state == STATE_ON async_fire_mqtt_message(hass, "tasmota_49A3BC/stat/RESULT", '{"POWER":"OFF"}') state = hass.states.get("switch.test") assert state.state == STATE_OFF
[ "async", "def", "test_controlling_state_via_mqtt", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "\"unavailable\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_ASSUMED_STATE", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/STATE\"", ",", "'{\"POWER\":\"ON\"}'", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "STATE_ON", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/STATE\"", ",", "'{\"POWER\":\"OFF\"}'", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"POWER\":\"ON\"}'", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "STATE_ON", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/stat/RESULT\"", ",", "'{\"POWER\":\"OFF\"}'", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF" ]
[ 32, 0 ]
[ 72, 35 ]
python
en
['en', 'co', 'en']
True
test_sending_mqtt_commands
(hass, mqtt_mock, setup_tasmota)
Test the sending MQTT commands.
Test the sending MQTT commands.
async def test_sending_mqtt_commands(hass, mqtt_mock, setup_tasmota): """Test the sending MQTT commands.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online") state = hass.states.get("switch.test") assert state.state == STATE_OFF await hass.async_block_till_done() await hass.async_block_till_done() mqtt_mock.async_publish.reset_mock() # Turn the switch on and verify MQTT message is sent await common.async_turn_on(hass, "switch.test") mqtt_mock.async_publish.assert_called_once_with( "tasmota_49A3BC/cmnd/Power1", "ON", 0, False ) mqtt_mock.async_publish.reset_mock() # Tasmota is not optimistic, the state should still be off state = hass.states.get("switch.test") assert state.state == STATE_OFF # Turn the switch off and verify MQTT message is sent await common.async_turn_off(hass, "switch.test") mqtt_mock.async_publish.assert_called_once_with( "tasmota_49A3BC/cmnd/Power1", "OFF", 0, False ) state = hass.states.get("switch.test") assert state.state == STATE_OFF
[ "async", "def", "test_sending_mqtt_commands", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "async_fire_mqtt_message", "(", "hass", ",", "\"tasmota_49A3BC/tele/LWT\"", ",", "\"Online\"", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "mqtt_mock", ".", "async_publish", ".", "reset_mock", "(", ")", "# Turn the switch on and verify MQTT message is sent", "await", "common", ".", "async_turn_on", "(", "hass", ",", "\"switch.test\"", ")", "mqtt_mock", ".", "async_publish", ".", "assert_called_once_with", "(", "\"tasmota_49A3BC/cmnd/Power1\"", ",", "\"ON\"", ",", "0", ",", "False", ")", "mqtt_mock", ".", "async_publish", ".", "reset_mock", "(", ")", "# Tasmota is not optimistic, the state should still be off", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF", "# Turn the switch off and verify MQTT message is sent", "await", "common", ".", "async_turn_off", "(", "hass", ",", "\"switch.test\"", ")", "mqtt_mock", ".", "async_publish", ".", "assert_called_once_with", "(", "\"tasmota_49A3BC/cmnd/Power1\"", ",", "\"OFF\"", ",", "0", ",", "False", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF" ]
[ 75, 0 ]
[ 113, 35 ]
python
en
['en', 'lb', 'en']
True
test_relay_as_light
(hass, mqtt_mock, setup_tasmota)
Test relay does not show up as switch in light mode.
Test relay does not show up as switch in light mode.
async def test_relay_as_light(hass, mqtt_mock, setup_tasmota): """Test relay does not show up as switch in light mode.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 config["so"]["30"] = 1 # Enforce Home Assistant auto-discovery as light mac = config["mac"] async_fire_mqtt_message( hass, f"{DEFAULT_PREFIX}/{mac}/config", json.dumps(config), ) await hass.async_block_till_done() state = hass.states.get("switch.test") assert state is None state = hass.states.get("light.test") assert state is not None
[ "async", "def", "test_relay_as_light", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "config", "[", "\"so\"", "]", "[", "\"30\"", "]", "=", "1", "# Enforce Home Assistant auto-discovery as light", "mac", "=", "config", "[", "\"mac\"", "]", "async_fire_mqtt_message", "(", "hass", ",", "f\"{DEFAULT_PREFIX}/{mac}/config\"", ",", "json", ".", "dumps", "(", "config", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"switch.test\"", ")", "assert", "state", "is", "None", "state", "=", "hass", ".", "states", ".", "get", "(", "\"light.test\"", ")", "assert", "state", "is", "not", "None" ]
[ 116, 0 ]
[ 133, 28 ]
python
en
['en', 'en', 'en']
True
test_availability_when_connection_lost
( hass, mqtt_client_mock, mqtt_mock, setup_tasmota )
Test availability after MQTT disconnection.
Test availability after MQTT disconnection.
async def test_availability_when_connection_lost( hass, mqtt_client_mock, mqtt_mock, setup_tasmota ): """Test availability after MQTT disconnection.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 await help_test_availability_when_connection_lost( hass, mqtt_client_mock, mqtt_mock, switch.DOMAIN, config )
[ "async", "def", "test_availability_when_connection_lost", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "await", "help_test_availability_when_connection_lost", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "switch", ".", "DOMAIN", ",", "config", ")" ]
[ 136, 0 ]
[ 144, 5 ]
python
en
['en', 'en', 'en']
True
test_availability
(hass, mqtt_mock, setup_tasmota)
Test availability.
Test availability.
async def test_availability(hass, mqtt_mock, setup_tasmota): """Test availability.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 await help_test_availability(hass, mqtt_mock, switch.DOMAIN, config)
[ "async", "def", "test_availability", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "await", "help_test_availability", "(", "hass", ",", "mqtt_mock", ",", "switch", ".", "DOMAIN", ",", "config", ")" ]
[ 147, 0 ]
[ 151, 72 ]
python
en
['fr', 'ga', 'en']
False
test_availability_discovery_update
(hass, mqtt_mock, setup_tasmota)
Test availability discovery update.
Test availability discovery update.
async def test_availability_discovery_update(hass, mqtt_mock, setup_tasmota): """Test availability discovery update.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 await help_test_availability_discovery_update( hass, mqtt_mock, switch.DOMAIN, config )
[ "async", "def", "test_availability_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "await", "help_test_availability_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "switch", ".", "DOMAIN", ",", "config", ")" ]
[ 154, 0 ]
[ 160, 5 ]
python
en
['en', 'en', 'en']
True
test_availability_poll_state
( hass, mqtt_client_mock, mqtt_mock, setup_tasmota )
Test polling after MQTT connection (re)established.
Test polling after MQTT connection (re)established.
async def test_availability_poll_state( hass, mqtt_client_mock, mqtt_mock, setup_tasmota ): """Test polling after MQTT connection (re)established.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 poll_topic = "tasmota_49A3BC/cmnd/STATE" await help_test_availability_poll_state( hass, mqtt_client_mock, mqtt_mock, switch.DOMAIN, config, poll_topic, "" )
[ "async", "def", "test_availability_poll_state", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "poll_topic", "=", "\"tasmota_49A3BC/cmnd/STATE\"", "await", "help_test_availability_poll_state", "(", "hass", ",", "mqtt_client_mock", ",", "mqtt_mock", ",", "switch", ".", "DOMAIN", ",", "config", ",", "poll_topic", ",", "\"\"", ")" ]
[ 163, 0 ]
[ 172, 5 ]
python
da
['da', 'da', 'en']
True
test_discovery_removal_switch
(hass, mqtt_mock, caplog, setup_tasmota)
Test removal of discovered switch.
Test removal of discovered switch.
async def test_discovery_removal_switch(hass, mqtt_mock, caplog, setup_tasmota): """Test removal of discovered switch.""" config1 = copy.deepcopy(DEFAULT_CONFIG) config1["rl"][0] = 1 config2 = copy.deepcopy(DEFAULT_CONFIG) config2["rl"][0] = 0 await help_test_discovery_removal( hass, mqtt_mock, caplog, switch.DOMAIN, config1, config2 )
[ "async", "def", "test_discovery_removal_switch", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "setup_tasmota", ")", ":", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "config2", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config2", "[", "\"rl\"", "]", "[", "0", "]", "=", "0", "await", "help_test_discovery_removal", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "switch", ".", "DOMAIN", ",", "config1", ",", "config2", ")" ]
[ 175, 0 ]
[ 184, 5 ]
python
en
['en', 'en', 'en']
True
test_discovery_removal_relay_as_light
(hass, mqtt_mock, caplog, setup_tasmota)
Test removal of discovered relay as light.
Test removal of discovered relay as light.
async def test_discovery_removal_relay_as_light(hass, mqtt_mock, caplog, setup_tasmota): """Test removal of discovered relay as light.""" config1 = copy.deepcopy(DEFAULT_CONFIG) config1["rl"][0] = 1 config1["so"]["30"] = 0 # Disable Home Assistant auto-discovery as light config2 = copy.deepcopy(DEFAULT_CONFIG) config2["rl"][0] = 1 config2["so"]["30"] = 1 # Enforce Home Assistant auto-discovery as light await help_test_discovery_removal( hass, mqtt_mock, caplog, switch.DOMAIN, config1, config2 )
[ "async", "def", "test_discovery_removal_relay_as_light", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "setup_tasmota", ")", ":", "config1", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config1", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "config1", "[", "\"so\"", "]", "[", "\"30\"", "]", "=", "0", "# Disable Home Assistant auto-discovery as light", "config2", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config2", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "config2", "[", "\"so\"", "]", "[", "\"30\"", "]", "=", "1", "# Enforce Home Assistant auto-discovery as light", "await", "help_test_discovery_removal", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "switch", ".", "DOMAIN", ",", "config1", ",", "config2", ")" ]
[ 187, 0 ]
[ 198, 5 ]
python
en
['en', 'en', 'en']
True
test_discovery_update_unchanged_switch
( hass, mqtt_mock, caplog, setup_tasmota )
Test update of discovered switch.
Test update of discovered switch.
async def test_discovery_update_unchanged_switch( hass, mqtt_mock, caplog, setup_tasmota ): """Test update of discovered switch.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 with patch( "homeassistant.components.tasmota.switch.TasmotaSwitch.discovery_update" ) as discovery_update: await help_test_discovery_update_unchanged( hass, mqtt_mock, caplog, switch.DOMAIN, config, discovery_update )
[ "async", "def", "test_discovery_update_unchanged_switch", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "with", "patch", "(", "\"homeassistant.components.tasmota.switch.TasmotaSwitch.discovery_update\"", ")", "as", "discovery_update", ":", "await", "help_test_discovery_update_unchanged", "(", "hass", ",", "mqtt_mock", ",", "caplog", ",", "switch", ".", "DOMAIN", ",", "config", ",", "discovery_update", ")" ]
[ 201, 0 ]
[ 212, 9 ]
python
en
['en', 'en', 'en']
True
test_discovery_device_remove
(hass, mqtt_mock, setup_tasmota)
Test device registry remove.
Test device registry remove.
async def test_discovery_device_remove(hass, mqtt_mock, setup_tasmota): """Test device registry remove.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 unique_id = f"{DEFAULT_CONFIG['mac']}_switch_relay_0" await help_test_discovery_device_remove( hass, mqtt_mock, switch.DOMAIN, unique_id, config )
[ "async", "def", "test_discovery_device_remove", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "unique_id", "=", "f\"{DEFAULT_CONFIG['mac']}_switch_relay_0\"", "await", "help_test_discovery_device_remove", "(", "hass", ",", "mqtt_mock", ",", "switch", ".", "DOMAIN", ",", "unique_id", ",", "config", ")" ]
[ 215, 0 ]
[ 222, 5 ]
python
en
['fr', 'en', 'en']
True
test_entity_id_update_subscriptions
(hass, mqtt_mock, setup_tasmota)
Test MQTT subscriptions are managed when entity_id is updated.
Test MQTT subscriptions are managed when entity_id is updated.
async def test_entity_id_update_subscriptions(hass, mqtt_mock, setup_tasmota): """Test MQTT subscriptions are managed when entity_id is updated.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 topics = [ get_topic_stat_result(config), get_topic_tele_state(config), get_topic_tele_will(config), ] await help_test_entity_id_update_subscriptions( hass, mqtt_mock, switch.DOMAIN, config, topics )
[ "async", "def", "test_entity_id_update_subscriptions", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "topics", "=", "[", "get_topic_stat_result", "(", "config", ")", ",", "get_topic_tele_state", "(", "config", ")", ",", "get_topic_tele_will", "(", "config", ")", ",", "]", "await", "help_test_entity_id_update_subscriptions", "(", "hass", ",", "mqtt_mock", ",", "switch", ".", "DOMAIN", ",", "config", ",", "topics", ")" ]
[ 225, 0 ]
[ 236, 5 ]
python
en
['en', 'en', 'en']
True
test_entity_id_update_discovery_update
(hass, mqtt_mock, setup_tasmota)
Test MQTT discovery update when entity_id is updated.
Test MQTT discovery update when entity_id is updated.
async def test_entity_id_update_discovery_update(hass, mqtt_mock, setup_tasmota): """Test MQTT discovery update when entity_id is updated.""" config = copy.deepcopy(DEFAULT_CONFIG) config["rl"][0] = 1 await help_test_entity_id_update_discovery_update( hass, mqtt_mock, switch.DOMAIN, config )
[ "async", "def", "test_entity_id_update_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "setup_tasmota", ")", ":", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "config", "[", "\"rl\"", "]", "[", "0", "]", "=", "1", "await", "help_test_entity_id_update_discovery_update", "(", "hass", ",", "mqtt_mock", ",", "switch", ".", "DOMAIN", ",", "config", ")" ]
[ 239, 0 ]
[ 245, 5 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Create the Elk-M1 scene platform.
Create the Elk-M1 scene platform.
async def async_setup_entry(hass, config_entry, async_add_entities): """Create the Elk-M1 scene platform.""" elk_data = hass.data[DOMAIN][config_entry.entry_id] entities = [] elk = elk_data["elk"] create_elk_entities(elk_data, elk.tasks, "task", ElkTask, entities) async_add_entities(entities, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "elk_data", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "entities", "=", "[", "]", "elk", "=", "elk_data", "[", "\"elk\"", "]", "create_elk_entities", "(", "elk_data", ",", "elk", ".", "tasks", ",", "\"task\"", ",", "ElkTask", ",", "entities", ")", "async_add_entities", "(", "entities", ",", "True", ")" ]
[ 9, 0 ]
[ 15, 38 ]
python
en
['en', 'la', 'en']
True
ElkTask.async_activate
(self, **kwargs: Any)
Activate the task.
Activate the task.
async def async_activate(self, **kwargs: Any) -> None: """Activate the task.""" self._element.activate()
[ "async", "def", "async_activate", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "self", ".", "_element", ".", "activate", "(", ")" ]
[ 21, 4 ]
[ 23, 32 ]
python
en
['en', 'en', 'en']
True
BaseAutoCompressionEngine.trial_execute_compress
(cls)
Execute the compressing trial.
Execute the compressing trial.
def trial_execute_compress(cls): """ Execute the compressing trial. """ pass
[ "def", "trial_execute_compress", "(", "cls", ")", ":", "pass" ]
[ 13, 4 ]
[ 17, 12 ]
python
en
['en', 'error', 'th']
False
AbstractAutoCompressionModule.model
(cls)
Returns ------- torch.nn.Module Model to be compress.
Returns ------- torch.nn.Module Model to be compress.
def model(cls) -> Module: """ Returns ------- torch.nn.Module Model to be compress. """ pass
[ "def", "model", "(", "cls", ")", "->", "Module", ":", "pass" ]
[ 26, 4 ]
[ 33, 12 ]
python
en
['en', 'error', 'th']
False
AbstractAutoCompressionModule.evaluator
(cls)
Returns ------- function The function used to evaluate the compressed model, return a scalar.
Returns ------- function The function used to evaluate the compressed model, return a scalar.
def evaluator(cls) -> Callable[[Module], float]: """ Returns ------- function The function used to evaluate the compressed model, return a scalar. """ pass
[ "def", "evaluator", "(", "cls", ")", "->", "Callable", "[", "[", "Module", "]", ",", "float", "]", ":", "pass" ]
[ 37, 4 ]
[ 44, 12 ]
python
en
['en', 'error', 'th']
False
AbstractAutoCompressionModule.optimizer_factory
(cls)
Returns ------- Optional[Callable[[Iterable], Optimizer]] Optimizer factory function. Input is a iterable value, i.e. `model.parameters()`. Output is the `torch.optim.Optimizer` instance.
Returns ------- Optional[Callable[[Iterable], Optimizer]] Optimizer factory function. Input is a iterable value, i.e. `model.parameters()`. Output is the `torch.optim.Optimizer` instance.
def optimizer_factory(cls) -> Optional[Callable[[Iterable], Optimizer]]: """ Returns ------- Optional[Callable[[Iterable], Optimizer]] Optimizer factory function. Input is a iterable value, i.e. `model.parameters()`. Output is the `torch.optim.Optimizer` instance. """ pass
[ "def", "optimizer_factory", "(", "cls", ")", "->", "Optional", "[", "Callable", "[", "[", "Iterable", "]", ",", "Optimizer", "]", "]", ":", "pass" ]
[ 48, 4 ]
[ 56, 12 ]
python
en
['en', 'error', 'th']
False
AbstractAutoCompressionModule.criterion
(cls)
Returns ------- Optional[Callable] The criterion function used to train the model.
Returns ------- Optional[Callable] The criterion function used to train the model.
def criterion(cls) -> Optional[Callable]: """ Returns ------- Optional[Callable] The criterion function used to train the model. """ pass
[ "def", "criterion", "(", "cls", ")", "->", "Optional", "[", "Callable", "]", ":", "pass" ]
[ 60, 4 ]
[ 67, 12 ]
python
en
['en', 'error', 'th']
False
AbstractAutoCompressionModule.sparsifying_trainer
(cls, compress_algorithm_name: str)
The trainer is used in sparsifying process. Parameters ---------- compress_algorithm_name: str The name of pruner and quantizer, i.e. 'level', 'l1', 'qat'. Returns ------- Optional[Callable[[Module, Optimizer, Callable, int], None]] Used to train model in compress stage, include `model, optimizer, criterion, current_epoch` as function arguments.
The trainer is used in sparsifying process.
def sparsifying_trainer(cls, compress_algorithm_name: str) -> Optional[Callable[[Module, Optimizer, Callable, int], None]]: """ The trainer is used in sparsifying process. Parameters ---------- compress_algorithm_name: str The name of pruner and quantizer, i.e. 'level', 'l1', 'qat'. Returns ------- Optional[Callable[[Module, Optimizer, Callable, int], None]] Used to train model in compress stage, include `model, optimizer, criterion, current_epoch` as function arguments. """ pass
[ "def", "sparsifying_trainer", "(", "cls", ",", "compress_algorithm_name", ":", "str", ")", "->", "Optional", "[", "Callable", "[", "[", "Module", ",", "Optimizer", ",", "Callable", ",", "int", "]", ",", "None", "]", "]", ":", "pass" ]
[ 71, 4 ]
[ 85, 12 ]
python
en
['en', 'error', 'th']
False
AbstractAutoCompressionModule.post_compress_finetuning_trainer
(cls, compress_algorithm_name: str)
The trainer is used in post-compress finetuning process. Parameters ---------- compress_algorithm_name: str The name of pruner and quantizer, i.e. 'level', 'l1', 'qat'. Returns ------- Optional[Callable[[Module, Optimizer, Callable, int], None]] Used to train model in finetune stage, include `model, optimizer, criterion, current_epoch` as function arguments.
The trainer is used in post-compress finetuning process.
def post_compress_finetuning_trainer(cls, compress_algorithm_name: str) -> Optional[Callable[[Module, Optimizer, Callable, int], None]]: """ The trainer is used in post-compress finetuning process. Parameters ---------- compress_algorithm_name: str The name of pruner and quantizer, i.e. 'level', 'l1', 'qat'. Returns ------- Optional[Callable[[Module, Optimizer, Callable, int], None]] Used to train model in finetune stage, include `model, optimizer, criterion, current_epoch` as function arguments. """ pass
[ "def", "post_compress_finetuning_trainer", "(", "cls", ",", "compress_algorithm_name", ":", "str", ")", "->", "Optional", "[", "Callable", "[", "[", "Module", ",", "Optimizer", ",", "Callable", ",", "int", "]", ",", "None", "]", "]", ":", "pass" ]
[ 89, 4 ]
[ 103, 12 ]
python
en
['en', 'error', 'th']
False