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
ZwaveDimmer.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" return self._supported_features
[ "def", "supported_features", "(", "self", ")", ":", "return", "self", ".", "_supported_features" ]
[ 196, 4 ]
[ 198, 39 ]
python
en
['da', 'en', 'en']
True
ZwaveDimmer._set_duration
(self, **kwargs)
Set the transition time for the brightness value. Zwave Dimming Duration values: 0x00 = instant 0x01-0x7F = 1 second to 127 seconds 0x80-0xFE = 1 minute to 127 minutes 0xFF = factory default
Set the transition time for the brightness value.
def _set_duration(self, **kwargs): """Set the transition time for the brightness value. Zwave Dimming Duration values: 0x00 = instant 0x01-0x7F = 1 second to 127 seconds 0x80-0xFE = 1 minute to 127 minutes 0xFF = factory default """ if self.values.dimming_duration is None: if ATTR_TRANSITION in kwargs: _LOGGER.debug("Dimming not supported by %s", self.entity_id) return if ATTR_TRANSITION not in kwargs: self.values.dimming_duration.data = 0xFF return transition = kwargs[ATTR_TRANSITION] if transition <= 127: self.values.dimming_duration.data = int(transition) elif transition > 7620: self.values.dimming_duration.data = 0xFE _LOGGER.warning("Transition clipped to 127 minutes for %s", self.entity_id) else: minutes = int(transition / 60) _LOGGER.debug( "Transition rounded to %d minutes for %s", minutes, self.entity_id ) self.values.dimming_duration.data = minutes + 0x7F
[ "def", "_set_duration", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "values", ".", "dimming_duration", "is", "None", ":", "if", "ATTR_TRANSITION", "in", "kwargs", ":", "_LOGGER", ".", "debug", "(", "\"Dimming not supported by %s\"", ",", "self", ".", "entity_id", ")", "return", "if", "ATTR_TRANSITION", "not", "in", "kwargs", ":", "self", ".", "values", ".", "dimming_duration", ".", "data", "=", "0xFF", "return", "transition", "=", "kwargs", "[", "ATTR_TRANSITION", "]", "if", "transition", "<=", "127", ":", "self", ".", "values", ".", "dimming_duration", ".", "data", "=", "int", "(", "transition", ")", "elif", "transition", ">", "7620", ":", "self", ".", "values", ".", "dimming_duration", ".", "data", "=", "0xFE", "_LOGGER", ".", "warning", "(", "\"Transition clipped to 127 minutes for %s\"", ",", "self", ".", "entity_id", ")", "else", ":", "minutes", "=", "int", "(", "transition", "/", "60", ")", "_LOGGER", ".", "debug", "(", "\"Transition rounded to %d minutes for %s\"", ",", "minutes", ",", "self", ".", "entity_id", ")", "self", ".", "values", ".", "dimming_duration", ".", "data", "=", "minutes", "+", "0x7F" ]
[ 200, 4 ]
[ 229, 62 ]
python
en
['en', 'en', 'en']
True
ZwaveDimmer.turn_on
(self, **kwargs)
Turn the device on.
Turn the device on.
def turn_on(self, **kwargs): """Turn the device on.""" self._set_duration(**kwargs) # Zwave multilevel switches use a range of [0, 99] to control # brightness. Level 255 means to set it to previous value. if ATTR_BRIGHTNESS in kwargs: self._brightness = kwargs[ATTR_BRIGHTNESS] brightness = byte_to_zwave_brightness(self._brightness) else: brightness = 255 if self.node.set_dimmer(self.values.primary.value_id, brightness): self._state = STATE_ON
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_set_duration", "(", "*", "*", "kwargs", ")", "# Zwave multilevel switches use a range of [0, 99] to control", "# brightness. Level 255 means to set it to previous value.", "if", "ATTR_BRIGHTNESS", "in", "kwargs", ":", "self", ".", "_brightness", "=", "kwargs", "[", "ATTR_BRIGHTNESS", "]", "brightness", "=", "byte_to_zwave_brightness", "(", "self", ".", "_brightness", ")", "else", ":", "brightness", "=", "255", "if", "self", ".", "node", ".", "set_dimmer", "(", "self", ".", "values", ".", "primary", ".", "value_id", ",", "brightness", ")", ":", "self", ".", "_state", "=", "STATE_ON" ]
[ 231, 4 ]
[ 244, 34 ]
python
en
['en', 'en', 'en']
True
ZwaveDimmer.turn_off
(self, **kwargs)
Turn the device off.
Turn the device off.
def turn_off(self, **kwargs): """Turn the device off.""" self._set_duration(**kwargs) if self.node.set_dimmer(self.values.primary.value_id, 0): self._state = STATE_OFF
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_set_duration", "(", "*", "*", "kwargs", ")", "if", "self", ".", "node", ".", "set_dimmer", "(", "self", ".", "values", ".", "primary", ".", "value_id", ",", "0", ")", ":", "self", ".", "_state", "=", "STATE_OFF" ]
[ 246, 4 ]
[ 251, 35 ]
python
en
['en', 'en', 'en']
True
ZwaveColorLight.__init__
(self, values, refresh, delay)
Initialize the light.
Initialize the light.
def __init__(self, values, refresh, delay): """Initialize the light.""" self._color_channels = None self._hs = None self._ct = None self._white = None super().__init__(values, refresh, delay)
[ "def", "__init__", "(", "self", ",", "values", ",", "refresh", ",", "delay", ")", ":", "self", ".", "_color_channels", "=", "None", "self", ".", "_hs", "=", "None", "self", ".", "_ct", "=", "None", "self", ".", "_white", "=", "None", "super", "(", ")", ".", "__init__", "(", "values", ",", "refresh", ",", "delay", ")" ]
[ 257, 4 ]
[ 264, 48 ]
python
en
['en', 'en', 'en']
True
ZwaveColorLight.value_added
(self)
Call when a new value is added to this entity.
Call when a new value is added to this entity.
def value_added(self): """Call when a new value is added to this entity.""" super().value_added() self._supported_features |= SUPPORT_COLOR if self._zw098: self._supported_features |= SUPPORT_COLOR_TEMP elif self._color_channels is not None and self._color_channels & ( COLOR_CHANNEL_WARM_WHITE | COLOR_CHANNEL_COLD_WHITE ): self._supported_features |= SUPPORT_WHITE_VALUE
[ "def", "value_added", "(", "self", ")", ":", "super", "(", ")", ".", "value_added", "(", ")", "self", ".", "_supported_features", "|=", "SUPPORT_COLOR", "if", "self", ".", "_zw098", ":", "self", ".", "_supported_features", "|=", "SUPPORT_COLOR_TEMP", "elif", "self", ".", "_color_channels", "is", "not", "None", "and", "self", ".", "_color_channels", "&", "(", "COLOR_CHANNEL_WARM_WHITE", "|", "COLOR_CHANNEL_COLD_WHITE", ")", ":", "self", ".", "_supported_features", "|=", "SUPPORT_WHITE_VALUE" ]
[ 266, 4 ]
[ 276, 59 ]
python
en
['en', 'en', 'en']
True
ZwaveColorLight.update_properties
(self)
Update internal properties based on zwave values.
Update internal properties based on zwave values.
def update_properties(self): """Update internal properties based on zwave values.""" super().update_properties() if self.values.color is None: return if self.values.color_channels is None: return # Color Channels self._color_channels = self.values.color_channels.data # Color Data String data = self.values.color.data # RGB is always present in the openzwave color data string. rgb = [int(data[1:3], 16), int(data[3:5], 16), int(data[5:7], 16)] self._hs = color_util.color_RGB_to_hs(*rgb) # Parse remaining color channels. Openzwave appends white channels # that are present. index = 7 # Warm white if self._color_channels & COLOR_CHANNEL_WARM_WHITE: warm_white = int(data[index : index + 2], 16) index += 2 else: warm_white = 0 # Cold white if self._color_channels & COLOR_CHANNEL_COLD_WHITE: cold_white = int(data[index : index + 2], 16) index += 2 else: cold_white = 0 # Color temperature. With the AEOTEC ZW098 bulb, only two color # temperatures are supported. The warm and cold channel values # indicate brightness for warm/cold color temperature. if self._zw098: if warm_white > 0: self._ct = TEMP_WARM_HASS self._hs = ct_to_hs(self._ct) elif cold_white > 0: self._ct = TEMP_COLD_HASS self._hs = ct_to_hs(self._ct) else: # RGB color is being used. Just report midpoint. self._ct = TEMP_MID_HASS elif self._color_channels & COLOR_CHANNEL_WARM_WHITE: self._white = warm_white elif self._color_channels & COLOR_CHANNEL_COLD_WHITE: self._white = cold_white # If no rgb channels supported, report None. if not ( self._color_channels & COLOR_CHANNEL_RED or self._color_channels & COLOR_CHANNEL_GREEN or self._color_channels & COLOR_CHANNEL_BLUE ): self._hs = None
[ "def", "update_properties", "(", "self", ")", ":", "super", "(", ")", ".", "update_properties", "(", ")", "if", "self", ".", "values", ".", "color", "is", "None", ":", "return", "if", "self", ".", "values", ".", "color_channels", "is", "None", ":", "return", "# Color Channels", "self", ".", "_color_channels", "=", "self", ".", "values", ".", "color_channels", ".", "data", "# Color Data String", "data", "=", "self", ".", "values", ".", "color", ".", "data", "# RGB is always present in the openzwave color data string.", "rgb", "=", "[", "int", "(", "data", "[", "1", ":", "3", "]", ",", "16", ")", ",", "int", "(", "data", "[", "3", ":", "5", "]", ",", "16", ")", ",", "int", "(", "data", "[", "5", ":", "7", "]", ",", "16", ")", "]", "self", ".", "_hs", "=", "color_util", ".", "color_RGB_to_hs", "(", "*", "rgb", ")", "# Parse remaining color channels. Openzwave appends white channels", "# that are present.", "index", "=", "7", "# Warm white", "if", "self", ".", "_color_channels", "&", "COLOR_CHANNEL_WARM_WHITE", ":", "warm_white", "=", "int", "(", "data", "[", "index", ":", "index", "+", "2", "]", ",", "16", ")", "index", "+=", "2", "else", ":", "warm_white", "=", "0", "# Cold white", "if", "self", ".", "_color_channels", "&", "COLOR_CHANNEL_COLD_WHITE", ":", "cold_white", "=", "int", "(", "data", "[", "index", ":", "index", "+", "2", "]", ",", "16", ")", "index", "+=", "2", "else", ":", "cold_white", "=", "0", "# Color temperature. With the AEOTEC ZW098 bulb, only two color", "# temperatures are supported. The warm and cold channel values", "# indicate brightness for warm/cold color temperature.", "if", "self", ".", "_zw098", ":", "if", "warm_white", ">", "0", ":", "self", ".", "_ct", "=", "TEMP_WARM_HASS", "self", ".", "_hs", "=", "ct_to_hs", "(", "self", ".", "_ct", ")", "elif", "cold_white", ">", "0", ":", "self", ".", "_ct", "=", "TEMP_COLD_HASS", "self", ".", "_hs", "=", "ct_to_hs", "(", "self", ".", "_ct", ")", "else", ":", "# RGB color is being used. Just report midpoint.", "self", ".", "_ct", "=", "TEMP_MID_HASS", "elif", "self", ".", "_color_channels", "&", "COLOR_CHANNEL_WARM_WHITE", ":", "self", ".", "_white", "=", "warm_white", "elif", "self", ".", "_color_channels", "&", "COLOR_CHANNEL_COLD_WHITE", ":", "self", ".", "_white", "=", "cold_white", "# If no rgb channels supported, report None.", "if", "not", "(", "self", ".", "_color_channels", "&", "COLOR_CHANNEL_RED", "or", "self", ".", "_color_channels", "&", "COLOR_CHANNEL_GREEN", "or", "self", ".", "_color_channels", "&", "COLOR_CHANNEL_BLUE", ")", ":", "self", ".", "_hs", "=", "None" ]
[ 278, 4 ]
[ 341, 27 ]
python
en
['en', 'af', 'en']
True
ZwaveColorLight.hs_color
(self)
Return the hs color.
Return the hs color.
def hs_color(self): """Return the hs color.""" return self._hs
[ "def", "hs_color", "(", "self", ")", ":", "return", "self", ".", "_hs" ]
[ 344, 4 ]
[ 346, 23 ]
python
en
['en', 'fr', 'en']
True
ZwaveColorLight.white_value
(self)
Return the white value of this light between 0..255.
Return the white value of this light between 0..255.
def white_value(self): """Return the white value of this light between 0..255.""" return self._white
[ "def", "white_value", "(", "self", ")", ":", "return", "self", ".", "_white" ]
[ 349, 4 ]
[ 351, 26 ]
python
en
['en', 'en', 'en']
True
ZwaveColorLight.color_temp
(self)
Return the color temperature.
Return the color temperature.
def color_temp(self): """Return the color temperature.""" return self._ct
[ "def", "color_temp", "(", "self", ")", ":", "return", "self", ".", "_ct" ]
[ 354, 4 ]
[ 356, 23 ]
python
en
['en', 'la', 'en']
True
ZwaveColorLight.turn_on
(self, **kwargs)
Turn the device on.
Turn the device on.
def turn_on(self, **kwargs): """Turn the device on.""" rgbw = None if ATTR_WHITE_VALUE in kwargs: self._white = kwargs[ATTR_WHITE_VALUE] if ATTR_COLOR_TEMP in kwargs: # Color temperature. With the AEOTEC ZW098 bulb, only two color # temperatures are supported. The warm and cold channel values # indicate brightness for warm/cold color temperature. if self._zw098: if kwargs[ATTR_COLOR_TEMP] > TEMP_MID_HASS: self._ct = TEMP_WARM_HASS rgbw = "#000000ff00" else: self._ct = TEMP_COLD_HASS rgbw = "#00000000ff" elif ATTR_HS_COLOR in kwargs: self._hs = kwargs[ATTR_HS_COLOR] if ATTR_WHITE_VALUE not in kwargs: # white LED must be off in order for color to work self._white = 0 if ( ATTR_WHITE_VALUE in kwargs or ATTR_HS_COLOR in kwargs ) and self._hs is not None: rgbw = "#" for colorval in color_util.color_hs_to_RGB(*self._hs): rgbw += format(colorval, "02x") if self._white is not None: rgbw += format(self._white, "02x") + "00" else: rgbw += "0000" if rgbw and self.values.color: self.values.color.data = rgbw super().turn_on(**kwargs)
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "rgbw", "=", "None", "if", "ATTR_WHITE_VALUE", "in", "kwargs", ":", "self", ".", "_white", "=", "kwargs", "[", "ATTR_WHITE_VALUE", "]", "if", "ATTR_COLOR_TEMP", "in", "kwargs", ":", "# Color temperature. With the AEOTEC ZW098 bulb, only two color", "# temperatures are supported. The warm and cold channel values", "# indicate brightness for warm/cold color temperature.", "if", "self", ".", "_zw098", ":", "if", "kwargs", "[", "ATTR_COLOR_TEMP", "]", ">", "TEMP_MID_HASS", ":", "self", ".", "_ct", "=", "TEMP_WARM_HASS", "rgbw", "=", "\"#000000ff00\"", "else", ":", "self", ".", "_ct", "=", "TEMP_COLD_HASS", "rgbw", "=", "\"#00000000ff\"", "elif", "ATTR_HS_COLOR", "in", "kwargs", ":", "self", ".", "_hs", "=", "kwargs", "[", "ATTR_HS_COLOR", "]", "if", "ATTR_WHITE_VALUE", "not", "in", "kwargs", ":", "# white LED must be off in order for color to work", "self", ".", "_white", "=", "0", "if", "(", "ATTR_WHITE_VALUE", "in", "kwargs", "or", "ATTR_HS_COLOR", "in", "kwargs", ")", "and", "self", ".", "_hs", "is", "not", "None", ":", "rgbw", "=", "\"#\"", "for", "colorval", "in", "color_util", ".", "color_hs_to_RGB", "(", "*", "self", ".", "_hs", ")", ":", "rgbw", "+=", "format", "(", "colorval", ",", "\"02x\"", ")", "if", "self", ".", "_white", "is", "not", "None", ":", "rgbw", "+=", "format", "(", "self", ".", "_white", ",", "\"02x\"", ")", "+", "\"00\"", "else", ":", "rgbw", "+=", "\"0000\"", "if", "rgbw", "and", "self", ".", "values", ".", "color", ":", "self", ".", "values", ".", "color", ".", "data", "=", "rgbw", "super", "(", ")", ".", "turn_on", "(", "*", "*", "kwargs", ")" ]
[ 358, 4 ]
[ 396, 33 ]
python
en
['en', 'en', 'en']
True
_hass_domain_validator
(config)
Validate platform in config for homeassistant domain.
Validate platform in config for homeassistant domain.
def _hass_domain_validator(config): """Validate platform in config for homeassistant domain.""" if CONF_PLATFORM not in config: config = {CONF_PLATFORM: HA_DOMAIN, STATES: config} return config
[ "def", "_hass_domain_validator", "(", "config", ")", ":", "if", "CONF_PLATFORM", "not", "in", "config", ":", "config", "=", "{", "CONF_PLATFORM", ":", "HA_DOMAIN", ",", "STATES", ":", "config", "}", "return", "config" ]
[ 21, 0 ]
[ 26, 17 ]
python
en
['en', 'en', 'en']
True
_platform_validator
(config)
Validate it is a valid platform.
Validate it is a valid platform.
def _platform_validator(config): """Validate it is a valid platform.""" try: platform = importlib.import_module( ".{}".format(config[CONF_PLATFORM]), __name__ ) except ImportError: try: platform = importlib.import_module( "homeassistant.components.{}.scene".format(config[CONF_PLATFORM]) ) except ImportError: raise vol.Invalid("Invalid platform specified") from None if not hasattr(platform, "PLATFORM_SCHEMA"): return config return platform.PLATFORM_SCHEMA(config)
[ "def", "_platform_validator", "(", "config", ")", ":", "try", ":", "platform", "=", "importlib", ".", "import_module", "(", "\".{}\"", ".", "format", "(", "config", "[", "CONF_PLATFORM", "]", ")", ",", "__name__", ")", "except", "ImportError", ":", "try", ":", "platform", "=", "importlib", ".", "import_module", "(", "\"homeassistant.components.{}.scene\"", ".", "format", "(", "config", "[", "CONF_PLATFORM", "]", ")", ")", "except", "ImportError", ":", "raise", "vol", ".", "Invalid", "(", "\"Invalid platform specified\"", ")", "from", "None", "if", "not", "hasattr", "(", "platform", ",", "\"PLATFORM_SCHEMA\"", ")", ":", "return", "config", "return", "platform", ".", "PLATFORM_SCHEMA", "(", "config", ")" ]
[ 29, 0 ]
[ 46, 43 ]
python
en
['en', 'et', 'en']
True
async_setup
(hass, config)
Set up the scenes.
Set up the scenes.
async def async_setup(hass, config): """Set up the scenes.""" component = hass.data[DOMAIN] = EntityComponent( logging.getLogger(__name__), DOMAIN, hass ) await component.async_setup(config) # Ensure Home Assistant platform always loaded. await component.async_setup_platform(HA_DOMAIN, {"platform": HA_DOMAIN, STATES: []}) component.async_register_entity_service( SERVICE_TURN_ON, {ATTR_TRANSITION: vol.All(vol.Coerce(float), vol.Clamp(min=0, max=6553))}, "async_activate", ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "component", "=", "hass", ".", "data", "[", "DOMAIN", "]", "=", "EntityComponent", "(", "logging", ".", "getLogger", "(", "__name__", ")", ",", "DOMAIN", ",", "hass", ")", "await", "component", ".", "async_setup", "(", "config", ")", "# Ensure Home Assistant platform always loaded.", "await", "component", ".", "async_setup_platform", "(", "HA_DOMAIN", ",", "{", "\"platform\"", ":", "HA_DOMAIN", ",", "STATES", ":", "[", "]", "}", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_TURN_ON", ",", "{", "ATTR_TRANSITION", ":", "vol", ".", "All", "(", "vol", ".", "Coerce", "(", "float", ")", ",", "vol", ".", "Clamp", "(", "min", "=", "0", ",", "max", "=", "6553", ")", ")", "}", ",", "\"async_activate\"", ",", ")", "return", "True" ]
[ 59, 0 ]
[ 74, 15 ]
python
en
['en', 'sr', 'en']
True
async_setup_entry
(hass, entry)
Set up a config entry.
Set up a config entry.
async def async_setup_entry(hass, entry): """Set up a config entry.""" return await hass.data[DOMAIN].async_setup_entry(entry)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ")", ":", "return", "await", "hass", ".", "data", "[", "DOMAIN", "]", ".", "async_setup_entry", "(", "entry", ")" ]
[ 77, 0 ]
[ 79, 59 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass, entry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass, entry): """Unload a config entry.""" return await hass.data[DOMAIN].async_unload_entry(entry)
[ "async", "def", "async_unload_entry", "(", "hass", ",", "entry", ")", ":", "return", "await", "hass", ".", "data", "[", "DOMAIN", "]", ".", "async_unload_entry", "(", "entry", ")" ]
[ 82, 0 ]
[ 84, 60 ]
python
en
['en', 'es', 'en']
True
Scene.should_poll
(self)
No polling needed.
No polling needed.
def should_poll(self) -> bool: """No polling needed.""" return False
[ "def", "should_poll", "(", "self", ")", "->", "bool", ":", "return", "False" ]
[ 91, 4 ]
[ 93, 20 ]
python
en
['en', 'en', 'en']
True
Scene.state
(self)
Return the state of the scene.
Return the state of the scene.
def state(self) -> Optional[str]: """Return the state of the scene.""" return STATE
[ "def", "state", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "STATE" ]
[ 96, 4 ]
[ 98, 20 ]
python
en
['en', 'en', 'en']
True
Scene.activate
(self, **kwargs: Any)
Activate scene. Try to get entities into requested state.
Activate scene. Try to get entities into requested state.
def activate(self, **kwargs: Any) -> None: """Activate scene. Try to get entities into requested state.""" raise NotImplementedError()
[ "def", "activate", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "raise", "NotImplementedError", "(", ")" ]
[ 100, 4 ]
[ 102, 35 ]
python
en
['en', 'en', 'en']
True
Scene.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.""" assert self.hass task = self.hass.async_add_job(ft.partial(self.activate, **kwargs)) if task: await task
[ "async", "def", "async_activate", "(", "self", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "assert", "self", ".", "hass", "task", "=", "self", ".", "hass", ".", "async_add_job", "(", "ft", ".", "partial", "(", "self", ".", "activate", ",", "*", "*", "kwargs", ")", ")", "if", "task", ":", "await", "task" ]
[ 104, 4 ]
[ 109, 22 ]
python
en
['en', 'en', 'en']
True
test_reproducing_states
(hass, caplog)
Test reproducing Alert states.
Test reproducing Alert states.
async def test_reproducing_states(hass, caplog): """Test reproducing Alert states.""" hass.states.async_set("alert.entity_off", "off", {}) hass.states.async_set("alert.entity_on", "on", {}) turn_on_calls = async_mock_service(hass, "alert", "turn_on") turn_off_calls = async_mock_service(hass, "alert", "turn_off") # These calls should do nothing as entities already in desired state await hass.helpers.state.async_reproduce_state( [State("alert.entity_off", "off"), State("alert.entity_on", "on")] ) assert len(turn_on_calls) == 0 assert len(turn_off_calls) == 0 # Test invalid state is handled await hass.helpers.state.async_reproduce_state( [State("alert.entity_off", "not_supported")] ) assert "not_supported" in caplog.text assert len(turn_on_calls) == 0 assert len(turn_off_calls) == 0 # Make sure correct services are called await hass.helpers.state.async_reproduce_state( [ State("alert.entity_on", "off"), State("alert.entity_off", "on"), # Should not raise State("alert.non_existing", "on"), ] ) assert len(turn_on_calls) == 1 assert turn_on_calls[0].domain == "alert" assert turn_on_calls[0].data == { "entity_id": "alert.entity_off", } assert len(turn_off_calls) == 1 assert turn_off_calls[0].domain == "alert" assert turn_off_calls[0].data == {"entity_id": "alert.entity_on"}
[ "async", "def", "test_reproducing_states", "(", "hass", ",", "caplog", ")", ":", "hass", ".", "states", ".", "async_set", "(", "\"alert.entity_off\"", ",", "\"off\"", ",", "{", "}", ")", "hass", ".", "states", ".", "async_set", "(", "\"alert.entity_on\"", ",", "\"on\"", ",", "{", "}", ")", "turn_on_calls", "=", "async_mock_service", "(", "hass", ",", "\"alert\"", ",", "\"turn_on\"", ")", "turn_off_calls", "=", "async_mock_service", "(", "hass", ",", "\"alert\"", ",", "\"turn_off\"", ")", "# These calls should do nothing as entities already in desired state", "await", "hass", ".", "helpers", ".", "state", ".", "async_reproduce_state", "(", "[", "State", "(", "\"alert.entity_off\"", ",", "\"off\"", ")", ",", "State", "(", "\"alert.entity_on\"", ",", "\"on\"", ")", "]", ")", "assert", "len", "(", "turn_on_calls", ")", "==", "0", "assert", "len", "(", "turn_off_calls", ")", "==", "0", "# Test invalid state is handled", "await", "hass", ".", "helpers", ".", "state", ".", "async_reproduce_state", "(", "[", "State", "(", "\"alert.entity_off\"", ",", "\"not_supported\"", ")", "]", ")", "assert", "\"not_supported\"", "in", "caplog", ".", "text", "assert", "len", "(", "turn_on_calls", ")", "==", "0", "assert", "len", "(", "turn_off_calls", ")", "==", "0", "# Make sure correct services are called", "await", "hass", ".", "helpers", ".", "state", ".", "async_reproduce_state", "(", "[", "State", "(", "\"alert.entity_on\"", ",", "\"off\"", ")", ",", "State", "(", "\"alert.entity_off\"", ",", "\"on\"", ")", ",", "# Should not raise", "State", "(", "\"alert.non_existing\"", ",", "\"on\"", ")", ",", "]", ")", "assert", "len", "(", "turn_on_calls", ")", "==", "1", "assert", "turn_on_calls", "[", "0", "]", ".", "domain", "==", "\"alert\"", "assert", "turn_on_calls", "[", "0", "]", ".", "data", "==", "{", "\"entity_id\"", ":", "\"alert.entity_off\"", ",", "}", "assert", "len", "(", "turn_off_calls", ")", "==", "1", "assert", "turn_off_calls", "[", "0", "]", ".", "domain", "==", "\"alert\"", "assert", "turn_off_calls", "[", "0", "]", ".", "data", "==", "{", "\"entity_id\"", ":", "\"alert.entity_on\"", "}" ]
[ 6, 0 ]
[ 49, 69 ]
python
en
['en', 'en', 'en']
True
data_transforms_cifar10
(args)
data_transforms for cifar10 dataset
data_transforms for cifar10 dataset
def data_transforms_cifar10(args): """ data_transforms for cifar10 dataset """ cifar_mean = [0.49139968, 0.48215827, 0.44653124] cifar_std = [0.24703233, 0.24348505, 0.26158768] train_transform = transforms.Compose( [ transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(cifar_mean, cifar_std), ] ) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(cifar_mean, cifar_std)] ) return train_transform, valid_transform
[ "def", "data_transforms_cifar10", "(", "args", ")", ":", "cifar_mean", "=", "[", "0.49139968", ",", "0.48215827", ",", "0.44653124", "]", "cifar_std", "=", "[", "0.24703233", ",", "0.24348505", ",", "0.26158768", "]", "train_transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "RandomCrop", "(", "32", ",", "padding", "=", "4", ")", ",", "transforms", ".", "RandomHorizontalFlip", "(", ")", ",", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "cifar_mean", ",", "cifar_std", ")", ",", "]", ")", "if", "args", ".", "cutout", ":", "train_transform", ".", "transforms", ".", "append", "(", "Cutout", "(", "args", ".", "cutout_length", ")", ")", "valid_transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "cifar_mean", ",", "cifar_std", ")", "]", ")", "return", "train_transform", ",", "valid_transform" ]
[ 115, 0 ]
[ 136, 43 ]
python
en
['en', 'no', 'en']
True
data_transforms_mnist
(args, mnist_mean=None, mnist_std=None)
data_transforms for mnist dataset
data_transforms for mnist dataset
def data_transforms_mnist(args, mnist_mean=None, mnist_std=None): """ data_transforms for mnist dataset """ if mnist_mean is None: mnist_mean = [0.5] if mnist_std is None: mnist_std = [0.5] train_transform = transforms.Compose( [ transforms.RandomCrop(28, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mnist_mean, mnist_std), ] ) if args.cutout: train_transform.transforms.append(Cutout(args.cutout_length)) valid_transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize(mnist_mean, mnist_std)] ) return train_transform, valid_transform
[ "def", "data_transforms_mnist", "(", "args", ",", "mnist_mean", "=", "None", ",", "mnist_std", "=", "None", ")", ":", "if", "mnist_mean", "is", "None", ":", "mnist_mean", "=", "[", "0.5", "]", "if", "mnist_std", "is", "None", ":", "mnist_std", "=", "[", "0.5", "]", "train_transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "RandomCrop", "(", "28", ",", "padding", "=", "4", ")", ",", "transforms", ".", "RandomHorizontalFlip", "(", ")", ",", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "mnist_mean", ",", "mnist_std", ")", ",", "]", ")", "if", "args", ".", "cutout", ":", "train_transform", ".", "transforms", ".", "append", "(", "Cutout", "(", "args", ".", "cutout_length", ")", ")", "valid_transform", "=", "transforms", ".", "Compose", "(", "[", "transforms", ".", "ToTensor", "(", ")", ",", "transforms", ".", "Normalize", "(", "mnist_mean", ",", "mnist_std", ")", "]", ")", "return", "train_transform", ",", "valid_transform" ]
[ 139, 0 ]
[ 162, 43 ]
python
en
['en', 'no', 'en']
True
get_mean_and_std
(dataset)
Compute the mean and std value of dataset.
Compute the mean and std value of dataset.
def get_mean_and_std(dataset): """Compute the mean and std value of dataset.""" dataloader = torch.utils.data.DataLoader( dataset, batch_size=1, shuffle=True, num_workers=2 ) mean = torch.zeros(3) std = torch.zeros(3) print("==> Computing mean and std..") for inputs, _ in dataloader: for i in range(3): mean[i] += inputs[:, i, :, :].mean() std[i] += inputs[:, i, :, :].std() mean.div_(len(dataset)) std.div_(len(dataset)) return mean, std
[ "def", "get_mean_and_std", "(", "dataset", ")", ":", "dataloader", "=", "torch", ".", "utils", ".", "data", ".", "DataLoader", "(", "dataset", ",", "batch_size", "=", "1", ",", "shuffle", "=", "True", ",", "num_workers", "=", "2", ")", "mean", "=", "torch", ".", "zeros", "(", "3", ")", "std", "=", "torch", ".", "zeros", "(", "3", ")", "print", "(", "\"==> Computing mean and std..\"", ")", "for", "inputs", ",", "_", "in", "dataloader", ":", "for", "i", "in", "range", "(", "3", ")", ":", "mean", "[", "i", "]", "+=", "inputs", "[", ":", ",", "i", ",", ":", ",", ":", "]", ".", "mean", "(", ")", "std", "[", "i", "]", "+=", "inputs", "[", ":", ",", "i", ",", ":", ",", ":", "]", ".", "std", "(", ")", "mean", ".", "div_", "(", "len", "(", "dataset", ")", ")", "std", ".", "div_", "(", "len", "(", "dataset", ")", ")", "return", "mean", ",", "std" ]
[ 165, 0 ]
[ 179, 20 ]
python
en
['en', 'en', 'en']
True
init_params
(net)
Init layer parameters.
Init layer parameters.
def init_params(net): """Init layer parameters.""" for module in net.modules(): if isinstance(module, nn.Conv2d): init.kaiming_normal(module.weight, mode="fan_out") if module.bias: init.constant(module.bias, 0) elif isinstance(module, nn.BatchNorm2d): init.constant(module.weight, 1) init.constant(module.bias, 0) elif isinstance(module, nn.Linear): init.normal(module.weight, std=1e-3) if module.bias: init.constant(module.bias, 0)
[ "def", "init_params", "(", "net", ")", ":", "for", "module", "in", "net", ".", "modules", "(", ")", ":", "if", "isinstance", "(", "module", ",", "nn", ".", "Conv2d", ")", ":", "init", ".", "kaiming_normal", "(", "module", ".", "weight", ",", "mode", "=", "\"fan_out\"", ")", "if", "module", ".", "bias", ":", "init", ".", "constant", "(", "module", ".", "bias", ",", "0", ")", "elif", "isinstance", "(", "module", ",", "nn", ".", "BatchNorm2d", ")", ":", "init", ".", "constant", "(", "module", ".", "weight", ",", "1", ")", "init", ".", "constant", "(", "module", ".", "bias", ",", "0", ")", "elif", "isinstance", "(", "module", ",", "nn", ".", "Linear", ")", ":", "init", ".", "normal", "(", "module", ".", "weight", ",", "std", "=", "1e-3", ")", "if", "module", ".", "bias", ":", "init", ".", "constant", "(", "module", ".", "bias", ",", "0", ")" ]
[ 182, 0 ]
[ 195, 45 ]
python
en
['en', 'id', 'en']
True
EarlyStopping.step
(self, metrics)
EarlyStopping step on each epoch Arguments: metrics {float} -- metric value
EarlyStopping step on each epoch Arguments: metrics {float} -- metric value
def step(self, metrics): """ EarlyStopping step on each epoch Arguments: metrics {float} -- metric value """ if self.best is None: self.best = metrics return False if np.isnan(metrics): return True if self.is_better(metrics, self.best): self.num_bad_epochs = 0 self.best = metrics else: self.num_bad_epochs += 1 if self.num_bad_epochs >= self.patience: return True return False
[ "def", "step", "(", "self", ",", "metrics", ")", ":", "if", "self", ".", "best", "is", "None", ":", "self", ".", "best", "=", "metrics", "return", "False", "if", "np", ".", "isnan", "(", "metrics", ")", ":", "return", "True", "if", "self", ".", "is_better", "(", "metrics", ",", "self", ".", "best", ")", ":", "self", ".", "num_bad_epochs", "=", "0", "self", ".", "best", "=", "metrics", "else", ":", "self", ".", "num_bad_epochs", "+=", "1", "if", "self", ".", "num_bad_epochs", ">=", "self", ".", "patience", ":", "return", "True", "return", "False" ]
[ 42, 4 ]
[ 64, 20 ]
python
en
['en', 'en', 'en']
True
Cutout.__call__
(self, img)
Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image with n_holes of dimension length x length cut out of it.
Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image with n_holes of dimension length x length cut out of it.
def __call__(self, img): """ Args: img (Tensor): Tensor image of size (C, H, W). Returns: Tensor: Image with n_holes of dimension length x length cut out of it. """ h_img, w_img = img.size(1), img.size(2) mask = np.ones((h_img, w_img), np.float32) y_img = np.random.randint(h_img) x_img = np.random.randint(w_img) y1_img = np.clip(y_img - self.length // 2, 0, h_img) y2_img = np.clip(y_img + self.length // 2, 0, h_img) x1_img = np.clip(x_img - self.length // 2, 0, w_img) x2_img = np.clip(x_img + self.length // 2, 0, w_img) mask[y1_img:y2_img, x1_img:x2_img] = 0.0 mask = torch.from_numpy(mask) mask = mask.expand_as(img) img *= mask return img
[ "def", "__call__", "(", "self", ",", "img", ")", ":", "h_img", ",", "w_img", "=", "img", ".", "size", "(", "1", ")", ",", "img", ".", "size", "(", "2", ")", "mask", "=", "np", ".", "ones", "(", "(", "h_img", ",", "w_img", ")", ",", "np", ".", "float32", ")", "y_img", "=", "np", ".", "random", ".", "randint", "(", "h_img", ")", "x_img", "=", "np", ".", "random", ".", "randint", "(", "w_img", ")", "y1_img", "=", "np", ".", "clip", "(", "y_img", "-", "self", ".", "length", "//", "2", ",", "0", ",", "h_img", ")", "y2_img", "=", "np", ".", "clip", "(", "y_img", "+", "self", ".", "length", "//", "2", ",", "0", ",", "h_img", ")", "x1_img", "=", "np", ".", "clip", "(", "x_img", "-", "self", ".", "length", "//", "2", ",", "0", ",", "w_img", ")", "x2_img", "=", "np", ".", "clip", "(", "x_img", "+", "self", ".", "length", "//", "2", ",", "0", ",", "w_img", ")", "mask", "[", "y1_img", ":", "y2_img", ",", "x1_img", ":", "x2_img", "]", "=", "0.0", "mask", "=", "torch", ".", "from_numpy", "(", "mask", ")", "mask", "=", "mask", ".", "expand_as", "(", "img", ")", "img", "*=", "mask", "return", "img" ]
[ 91, 4 ]
[ 112, 18 ]
python
en
['en', 'error', 'th']
False
test_form
(hass, aioclient_mock)
Test that form shows up.
Test that form shows up.
async def test_form(hass, aioclient_mock): """Test that form shows up.""" aioclient_mock.get( TEST_SYSTEM_URL, text=TEST_SYSTEM_DATA, ) result1 = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result1["type"] == data_entry_flow.RESULT_TYPE_FORM assert result1["step_id"] == "user" assert result1["errors"] == {} with patch( "homeassistant.components.advantage_air.async_setup_entry", return_value=True, ) as mock_setup_entry: result2 = await hass.config_entries.flow.async_configure( result1["flow_id"], USER_INPUT, ) assert len(aioclient_mock.mock_calls) == 1 assert result2["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result2["title"] == "testname" assert result2["data"] == USER_INPUT await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1 # Test Duplicate Config Flow result3 = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) result4 = await hass.config_entries.flow.async_configure( result3["flow_id"], USER_INPUT, ) assert result4["type"] == data_entry_flow.RESULT_TYPE_ABORT
[ "async", "def", "test_form", "(", "hass", ",", "aioclient_mock", ")", ":", "aioclient_mock", ".", "get", "(", "TEST_SYSTEM_URL", ",", "text", "=", "TEST_SYSTEM_DATA", ",", ")", "result1", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "assert", "result1", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result1", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result1", "[", "\"errors\"", "]", "==", "{", "}", "with", "patch", "(", "\"homeassistant.components.advantage_air.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup_entry", ":", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result1", "[", "\"flow_id\"", "]", ",", "USER_INPUT", ",", ")", "assert", "len", "(", "aioclient_mock", ".", "mock_calls", ")", "==", "1", "assert", "result2", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result2", "[", "\"title\"", "]", "==", "\"testname\"", "assert", "result2", "[", "\"data\"", "]", "==", "USER_INPUT", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1", "# Test Duplicate Config Flow", "result3", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "result4", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result3", "[", "\"flow_id\"", "]", ",", "USER_INPUT", ",", ")", "assert", "result4", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_ABORT" ]
[ 9, 0 ]
[ 48, 63 ]
python
en
['en', 'en', 'en']
True
test_form_cannot_connect
(hass, aioclient_mock)
Test we handle cannot connect error.
Test we handle cannot connect error.
async def test_form_cannot_connect(hass, aioclient_mock): """Test we handle cannot connect error.""" aioclient_mock.get( TEST_SYSTEM_URL, exc=SyntaxError, ) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) result2 = await hass.config_entries.flow.async_configure( result["flow_id"], USER_INPUT, ) assert result2["type"] == data_entry_flow.RESULT_TYPE_FORM assert result2["step_id"] == "user" assert result2["errors"] == {"base": "cannot_connect"} assert len(aioclient_mock.mock_calls) == 1
[ "async", "def", "test_form_cannot_connect", "(", "hass", ",", "aioclient_mock", ")", ":", "aioclient_mock", ".", "get", "(", "TEST_SYSTEM_URL", ",", "exc", "=", "SyntaxError", ",", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "USER_INPUT", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result2", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result2", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}", "assert", "len", "(", "aioclient_mock", ".", "mock_calls", ")", "==", "1" ]
[ 51, 0 ]
[ 70, 46 ]
python
en
['en', 'en', 'en']
True
patch_cluster
(cluster)
Patch a cluster for testing.
Patch a cluster for testing.
def patch_cluster(cluster): """Patch a cluster for testing.""" cluster.PLUGGED_ATTR_READS = {} async def _read_attribute_raw(attributes, *args, **kwargs): result = [] for attr_id in attributes: value = cluster.PLUGGED_ATTR_READS.get(attr_id) if value is None: # try converting attr_id to attr_name and lookup the plugs again attr_name = cluster.attributes.get(attr_id) value = attr_name and cluster.PLUGGED_ATTR_READS.get(attr_name[0]) if value is not None: result.append( zcl_f.ReadAttributeRecord( attr_id, zcl_f.Status.SUCCESS, zcl_f.TypeValue(python_type=None, value=value), ) ) else: result.append(zcl_f.ReadAttributeRecord(attr_id, zcl_f.Status.FAILURE)) return (result,) cluster.bind = AsyncMock(return_value=[0]) cluster.configure_reporting = AsyncMock(return_value=[0]) cluster.deserialize = Mock() cluster.handle_cluster_request = Mock() cluster.read_attributes = AsyncMock(wraps=cluster.read_attributes) cluster.read_attributes_raw = AsyncMock(side_effect=_read_attribute_raw) cluster.unbind = AsyncMock(return_value=[0]) cluster.write_attributes = AsyncMock( return_value=[zcl_f.WriteAttributesResponse.deserialize(b"\x00")[0]] ) if cluster.cluster_id == 4: cluster.add = AsyncMock(return_value=[0])
[ "def", "patch_cluster", "(", "cluster", ")", ":", "cluster", ".", "PLUGGED_ATTR_READS", "=", "{", "}", "async", "def", "_read_attribute_raw", "(", "attributes", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "[", "]", "for", "attr_id", "in", "attributes", ":", "value", "=", "cluster", ".", "PLUGGED_ATTR_READS", ".", "get", "(", "attr_id", ")", "if", "value", "is", "None", ":", "# try converting attr_id to attr_name and lookup the plugs again", "attr_name", "=", "cluster", ".", "attributes", ".", "get", "(", "attr_id", ")", "value", "=", "attr_name", "and", "cluster", ".", "PLUGGED_ATTR_READS", ".", "get", "(", "attr_name", "[", "0", "]", ")", "if", "value", "is", "not", "None", ":", "result", ".", "append", "(", "zcl_f", ".", "ReadAttributeRecord", "(", "attr_id", ",", "zcl_f", ".", "Status", ".", "SUCCESS", ",", "zcl_f", ".", "TypeValue", "(", "python_type", "=", "None", ",", "value", "=", "value", ")", ",", ")", ")", "else", ":", "result", ".", "append", "(", "zcl_f", ".", "ReadAttributeRecord", "(", "attr_id", ",", "zcl_f", ".", "Status", ".", "FAILURE", ")", ")", "return", "(", "result", ",", ")", "cluster", ".", "bind", "=", "AsyncMock", "(", "return_value", "=", "[", "0", "]", ")", "cluster", ".", "configure_reporting", "=", "AsyncMock", "(", "return_value", "=", "[", "0", "]", ")", "cluster", ".", "deserialize", "=", "Mock", "(", ")", "cluster", ".", "handle_cluster_request", "=", "Mock", "(", ")", "cluster", ".", "read_attributes", "=", "AsyncMock", "(", "wraps", "=", "cluster", ".", "read_attributes", ")", "cluster", ".", "read_attributes_raw", "=", "AsyncMock", "(", "side_effect", "=", "_read_attribute_raw", ")", "cluster", ".", "unbind", "=", "AsyncMock", "(", "return_value", "=", "[", "0", "]", ")", "cluster", ".", "write_attributes", "=", "AsyncMock", "(", "return_value", "=", "[", "zcl_f", ".", "WriteAttributesResponse", ".", "deserialize", "(", "b\"\\x00\"", ")", "[", "0", "]", "]", ")", "if", "cluster", ".", "cluster_id", "==", "4", ":", "cluster", ".", "add", "=", "AsyncMock", "(", "return_value", "=", "[", "0", "]", ")" ]
[ 70, 0 ]
[ 105, 49 ]
python
en
['en', 'en', 'en']
True
get_zha_gateway
(hass)
Return ZHA gateway from hass.data.
Return ZHA gateway from hass.data.
def get_zha_gateway(hass): """Return ZHA gateway from hass.data.""" try: return hass.data[zha_const.DATA_ZHA][zha_const.DATA_ZHA_GATEWAY] except KeyError: return None
[ "def", "get_zha_gateway", "(", "hass", ")", ":", "try", ":", "return", "hass", ".", "data", "[", "zha_const", ".", "DATA_ZHA", "]", "[", "zha_const", ".", "DATA_ZHA_GATEWAY", "]", "except", "KeyError", ":", "return", "None" ]
[ 138, 0 ]
[ 143, 19 ]
python
en
['en', 'sn', 'en']
True
make_attribute
(attrid, value, status=0)
Make an attribute.
Make an attribute.
def make_attribute(attrid, value, status=0): """Make an attribute.""" attr = zcl_f.Attribute() attr.attrid = attrid attr.value = zcl_f.TypeValue() attr.value.value = value return attr
[ "def", "make_attribute", "(", "attrid", ",", "value", ",", "status", "=", "0", ")", ":", "attr", "=", "zcl_f", ".", "Attribute", "(", ")", "attr", ".", "attrid", "=", "attrid", "attr", ".", "value", "=", "zcl_f", ".", "TypeValue", "(", ")", "attr", ".", "value", ".", "value", "=", "value", "return", "attr" ]
[ 146, 0 ]
[ 152, 15 ]
python
en
['en', 'gd', 'en']
True
send_attribute_report
(hass, cluster, attrid, value)
Send a single attribute report.
Send a single attribute report.
def send_attribute_report(hass, cluster, attrid, value): """Send a single attribute report.""" return send_attributes_report(hass, cluster, {attrid: value})
[ "def", "send_attribute_report", "(", "hass", ",", "cluster", ",", "attrid", ",", "value", ")", ":", "return", "send_attributes_report", "(", "hass", ",", "cluster", ",", "{", "attrid", ":", "value", "}", ")" ]
[ 155, 0 ]
[ 157, 65 ]
python
en
['en', 'it', 'en']
True
send_attributes_report
(hass, cluster: int, attributes: dict)
Cause the sensor to receive an attribute report from the network. This is to simulate the normal device communication that happens when a device is paired to the zigbee network.
Cause the sensor to receive an attribute report from the network.
async def send_attributes_report(hass, cluster: int, attributes: dict): """Cause the sensor to receive an attribute report from the network. This is to simulate the normal device communication that happens when a device is paired to the zigbee network. """ attrs = [make_attribute(attrid, value) for attrid, value in attributes.items()] hdr = make_zcl_header(zcl_f.Command.Report_Attributes) hdr.frame_control.disable_default_response = True cluster.handle_message(hdr, [attrs]) await hass.async_block_till_done()
[ "async", "def", "send_attributes_report", "(", "hass", ",", "cluster", ":", "int", ",", "attributes", ":", "dict", ")", ":", "attrs", "=", "[", "make_attribute", "(", "attrid", ",", "value", ")", "for", "attrid", ",", "value", "in", "attributes", ".", "items", "(", ")", "]", "hdr", "=", "make_zcl_header", "(", "zcl_f", ".", "Command", ".", "Report_Attributes", ")", "hdr", ".", "frame_control", ".", "disable_default_response", "=", "True", "cluster", ".", "handle_message", "(", "hdr", ",", "[", "attrs", "]", ")", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 160, 0 ]
[ 170, 38 ]
python
en
['en', 'en', 'en']
True
find_entity_id
(domain, zha_device, hass)
Find the entity id under the testing. This is used to get the entity id in order to get the state from the state machine so that we can test state changes.
Find the entity id under the testing.
async def find_entity_id(domain, zha_device, hass): """Find the entity id under the testing. This is used to get the entity id in order to get the state from the state machine so that we can test state changes. """ ieeetail = "".join([f"{o:02x}" for o in zha_device.ieee[:4]]) head = f"{domain}.{slugify(f'{zha_device.name} {ieeetail}')}" enitiy_ids = hass.states.async_entity_ids(domain) await hass.async_block_till_done() for entity_id in enitiy_ids: if entity_id.startswith(head): return entity_id return None
[ "async", "def", "find_entity_id", "(", "domain", ",", "zha_device", ",", "hass", ")", ":", "ieeetail", "=", "\"\"", ".", "join", "(", "[", "f\"{o:02x}\"", "for", "o", "in", "zha_device", ".", "ieee", "[", ":", "4", "]", "]", ")", "head", "=", "f\"{domain}.{slugify(f'{zha_device.name} {ieeetail}')}\"", "enitiy_ids", "=", "hass", ".", "states", ".", "async_entity_ids", "(", "domain", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "for", "entity_id", "in", "enitiy_ids", ":", "if", "entity_id", ".", "startswith", "(", "head", ")", ":", "return", "entity_id", "return", "None" ]
[ 173, 0 ]
[ 188, 15 ]
python
en
['en', 'en', 'en']
True
async_find_group_entity_id
(hass, domain, group)
Find the group entity id under test.
Find the group entity id under test.
def async_find_group_entity_id(hass, domain, group): """Find the group entity id under test.""" entity_id = f"{domain}.{group.name.lower().replace(' ','_')}_zha_group_0x{group.group_id:04x}" entity_ids = hass.states.async_entity_ids(domain) if entity_id in entity_ids: return entity_id return None
[ "def", "async_find_group_entity_id", "(", "hass", ",", "domain", ",", "group", ")", ":", "entity_id", "=", "f\"{domain}.{group.name.lower().replace(' ','_')}_zha_group_0x{group.group_id:04x}\"", "entity_ids", "=", "hass", ".", "states", ".", "async_entity_ids", "(", "domain", ")", "if", "entity_id", "in", "entity_ids", ":", "return", "entity_id", "return", "None" ]
[ 191, 0 ]
[ 199, 15 ]
python
en
['en', 'en', 'en']
True
async_enable_traffic
(hass, zha_devices, enabled=True)
Allow traffic to flow through the gateway and the zha device.
Allow traffic to flow through the gateway and the zha device.
async def async_enable_traffic(hass, zha_devices, enabled=True): """Allow traffic to flow through the gateway and the zha device.""" for zha_device in zha_devices: zha_device.update_available(enabled) await hass.async_block_till_done()
[ "async", "def", "async_enable_traffic", "(", "hass", ",", "zha_devices", ",", "enabled", "=", "True", ")", ":", "for", "zha_device", "in", "zha_devices", ":", "zha_device", ".", "update_available", "(", "enabled", ")", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 202, 0 ]
[ 206, 38 ]
python
en
['en', 'en', 'en']
True
make_zcl_header
( command_id: int, global_command: bool = True, tsn: int = 1 )
Cluster.handle_message() ZCL Header helper.
Cluster.handle_message() ZCL Header helper.
def make_zcl_header( command_id: int, global_command: bool = True, tsn: int = 1 ) -> zcl_f.ZCLHeader: """Cluster.handle_message() ZCL Header helper.""" if global_command: frc = zcl_f.FrameControl(zcl_f.FrameType.GLOBAL_COMMAND) else: frc = zcl_f.FrameControl(zcl_f.FrameType.CLUSTER_COMMAND) return zcl_f.ZCLHeader(frc, tsn=tsn, command_id=command_id)
[ "def", "make_zcl_header", "(", "command_id", ":", "int", ",", "global_command", ":", "bool", "=", "True", ",", "tsn", ":", "int", "=", "1", ")", "->", "zcl_f", ".", "ZCLHeader", ":", "if", "global_command", ":", "frc", "=", "zcl_f", ".", "FrameControl", "(", "zcl_f", ".", "FrameType", ".", "GLOBAL_COMMAND", ")", "else", ":", "frc", "=", "zcl_f", ".", "FrameControl", "(", "zcl_f", ".", "FrameType", ".", "CLUSTER_COMMAND", ")", "return", "zcl_f", ".", "ZCLHeader", "(", "frc", ",", "tsn", "=", "tsn", ",", "command_id", "=", "command_id", ")" ]
[ 209, 0 ]
[ 217, 63 ]
python
en
['en', 'nl', 'en']
True
reset_clusters
(clusters)
Reset mocks on cluster.
Reset mocks on cluster.
def reset_clusters(clusters): """Reset mocks on cluster.""" for cluster in clusters: cluster.bind.reset_mock() cluster.configure_reporting.reset_mock() cluster.write_attributes.reset_mock()
[ "def", "reset_clusters", "(", "clusters", ")", ":", "for", "cluster", "in", "clusters", ":", "cluster", ".", "bind", ".", "reset_mock", "(", ")", "cluster", ".", "configure_reporting", ".", "reset_mock", "(", ")", "cluster", ".", "write_attributes", ".", "reset_mock", "(", ")" ]
[ 220, 0 ]
[ 225, 45 ]
python
da
['et', 'da', 'en']
False
async_test_rejoin
(hass, zigpy_device, clusters, report_counts, ep_id=1)
Test device rejoins.
Test device rejoins.
async def async_test_rejoin(hass, zigpy_device, clusters, report_counts, ep_id=1): """Test device rejoins.""" reset_clusters(clusters) zha_gateway = get_zha_gateway(hass) await zha_gateway.async_device_initialized(zigpy_device) await hass.async_block_till_done() for cluster, reports in zip(clusters, report_counts): assert cluster.bind.call_count == 1 assert cluster.bind.await_count == 1 assert cluster.configure_reporting.call_count == reports assert cluster.configure_reporting.await_count == reports
[ "async", "def", "async_test_rejoin", "(", "hass", ",", "zigpy_device", ",", "clusters", ",", "report_counts", ",", "ep_id", "=", "1", ")", ":", "reset_clusters", "(", "clusters", ")", "zha_gateway", "=", "get_zha_gateway", "(", "hass", ")", "await", "zha_gateway", ".", "async_device_initialized", "(", "zigpy_device", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "for", "cluster", ",", "reports", "in", "zip", "(", "clusters", ",", "report_counts", ")", ":", "assert", "cluster", ".", "bind", ".", "call_count", "==", "1", "assert", "cluster", ".", "bind", ".", "await_count", "==", "1", "assert", "cluster", ".", "configure_reporting", ".", "call_count", "==", "reports", "assert", "cluster", ".", "configure_reporting", ".", "await_count", "==", "reports" ]
[ 228, 0 ]
[ 239, 65 ]
python
da
['fr', 'da', 'en']
False
FakeEndpoint.__init__
(self, manufacturer, model, epid=1)
Init fake endpoint.
Init fake endpoint.
def __init__(self, manufacturer, model, epid=1): """Init fake endpoint.""" self.device = None self.endpoint_id = epid self.in_clusters = {} self.out_clusters = {} self._cluster_attr = {} self.member_of = {} self.status = 1 self.manufacturer = manufacturer self.model = model self.profile_id = zigpy.profiles.zha.PROFILE_ID self.device_type = None self.request = AsyncMock(return_value=[0])
[ "def", "__init__", "(", "self", ",", "manufacturer", ",", "model", ",", "epid", "=", "1", ")", ":", "self", ".", "device", "=", "None", "self", ".", "endpoint_id", "=", "epid", "self", ".", "in_clusters", "=", "{", "}", "self", ".", "out_clusters", "=", "{", "}", "self", ".", "_cluster_attr", "=", "{", "}", "self", ".", "member_of", "=", "{", "}", "self", ".", "status", "=", "1", "self", ".", "manufacturer", "=", "manufacturer", "self", ".", "model", "=", "model", "self", ".", "profile_id", "=", "zigpy", ".", "profiles", ".", "zha", ".", "PROFILE_ID", "self", ".", "device_type", "=", "None", "self", ".", "request", "=", "AsyncMock", "(", "return_value", "=", "[", "0", "]", ")" ]
[ 21, 4 ]
[ 34, 50 ]
python
en
['en', 'en', 'en']
True
FakeEndpoint.add_input_cluster
(self, cluster_id, _patch_cluster=True)
Add an input cluster.
Add an input cluster.
def add_input_cluster(self, cluster_id, _patch_cluster=True): """Add an input cluster.""" cluster = zigpy.zcl.Cluster.from_id(self, cluster_id, is_server=True) if _patch_cluster: patch_cluster(cluster) self.in_clusters[cluster_id] = cluster if hasattr(cluster, "ep_attribute"): setattr(self, cluster.ep_attribute, cluster)
[ "def", "add_input_cluster", "(", "self", ",", "cluster_id", ",", "_patch_cluster", "=", "True", ")", ":", "cluster", "=", "zigpy", ".", "zcl", ".", "Cluster", ".", "from_id", "(", "self", ",", "cluster_id", ",", "is_server", "=", "True", ")", "if", "_patch_cluster", ":", "patch_cluster", "(", "cluster", ")", "self", ".", "in_clusters", "[", "cluster_id", "]", "=", "cluster", "if", "hasattr", "(", "cluster", ",", "\"ep_attribute\"", ")", ":", "setattr", "(", "self", ",", "cluster", ".", "ep_attribute", ",", "cluster", ")" ]
[ 36, 4 ]
[ 43, 56 ]
python
en
['en', 'lb', 'en']
True
FakeEndpoint.add_output_cluster
(self, cluster_id, _patch_cluster=True)
Add an output cluster.
Add an output cluster.
def add_output_cluster(self, cluster_id, _patch_cluster=True): """Add an output cluster.""" cluster = zigpy.zcl.Cluster.from_id(self, cluster_id, is_server=False) if _patch_cluster: patch_cluster(cluster) self.out_clusters[cluster_id] = cluster
[ "def", "add_output_cluster", "(", "self", ",", "cluster_id", ",", "_patch_cluster", "=", "True", ")", ":", "cluster", "=", "zigpy", ".", "zcl", ".", "Cluster", ".", "from_id", "(", "self", ",", "cluster_id", ",", "is_server", "=", "False", ")", "if", "_patch_cluster", ":", "patch_cluster", "(", "cluster", ")", "self", ".", "out_clusters", "[", "cluster_id", "]", "=", "cluster" ]
[ 45, 4 ]
[ 50, 47 ]
python
en
['en', 'en', 'en']
True
FakeEndpoint.__class__
(self)
Fake being Zigpy endpoint.
Fake being Zigpy endpoint.
def __class__(self): """Fake being Zigpy endpoint.""" return zigpy_ep
[ "def", "__class__", "(", "self", ")", ":", "return", "zigpy_ep" ]
[ 56, 4 ]
[ 58, 23 ]
python
en
['de', 'en', 'en']
True
FakeEndpoint.unique_id
(self)
Return the unique id for the endpoint.
Return the unique id for the endpoint.
def unique_id(self): """Return the unique id for the endpoint.""" return self.device.ieee, self.endpoint_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "device", ".", "ieee", ",", "self", ".", "endpoint_id" ]
[ 61, 4 ]
[ 63, 49 ]
python
en
['en', 'en', 'en']
True
FakeDevice.__init__
(self, app, ieee, manufacturer, model, node_desc=None, nwk=0xB79C)
Init fake device.
Init fake device.
def __init__(self, app, ieee, manufacturer, model, node_desc=None, nwk=0xB79C): """Init fake device.""" self._application = app self.application = app self.ieee = zigpy.types.EUI64.convert(ieee) self.nwk = nwk self.zdo = Mock() self.endpoints = {0: self.zdo} self.lqi = 255 self.rssi = 8 self.last_seen = time.time() self.status = 2 self.initializing = False self.skip_configuration = False self.manufacturer = manufacturer self.model = model self.node_desc = zigpy.zdo.types.NodeDescriptor() self.remove_from_group = AsyncMock() if node_desc is None: node_desc = b"\x02@\x807\x10\x7fd\x00\x00*d\x00\x00" self.node_desc = zigpy.zdo.types.NodeDescriptor.deserialize(node_desc)[0] self.neighbors = []
[ "def", "__init__", "(", "self", ",", "app", ",", "ieee", ",", "manufacturer", ",", "model", ",", "node_desc", "=", "None", ",", "nwk", "=", "0xB79C", ")", ":", "self", ".", "_application", "=", "app", "self", ".", "application", "=", "app", "self", ".", "ieee", "=", "zigpy", ".", "types", ".", "EUI64", ".", "convert", "(", "ieee", ")", "self", ".", "nwk", "=", "nwk", "self", ".", "zdo", "=", "Mock", "(", ")", "self", ".", "endpoints", "=", "{", "0", ":", "self", ".", "zdo", "}", "self", ".", "lqi", "=", "255", "self", ".", "rssi", "=", "8", "self", ".", "last_seen", "=", "time", ".", "time", "(", ")", "self", ".", "status", "=", "2", "self", ".", "initializing", "=", "False", "self", ".", "skip_configuration", "=", "False", "self", ".", "manufacturer", "=", "manufacturer", "self", ".", "model", "=", "model", "self", ".", "node_desc", "=", "zigpy", ".", "zdo", ".", "types", ".", "NodeDescriptor", "(", ")", "self", ".", "remove_from_group", "=", "AsyncMock", "(", ")", "if", "node_desc", "is", "None", ":", "node_desc", "=", "b\"\\x02@\\x807\\x10\\x7fd\\x00\\x00*d\\x00\\x00\"", "self", ".", "node_desc", "=", "zigpy", ".", "zdo", ".", "types", ".", "NodeDescriptor", ".", "deserialize", "(", "node_desc", ")", "[", "0", "]", "self", ".", "neighbors", "=", "[", "]" ]
[ 111, 4 ]
[ 132, 27 ]
python
en
['fr', 'en', 'en']
True
test_show_form
(hass)
Test that the form is served with no input.
Test that the form is served with no input.
async def test_show_form(hass): """Test that the form is served with no input.""" flow = config_flow.GiosFlowHandler() flow.hass = hass result = await flow.async_step_user(user_input=None) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user"
[ "async", "def", "test_show_form", "(", "hass", ")", ":", "flow", "=", "config_flow", ".", "GiosFlowHandler", "(", ")", "flow", ".", "hass", "=", "hass", "result", "=", "await", "flow", ".", "async_step_user", "(", "user_input", "=", "None", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"" ]
[ 20, 0 ]
[ 28, 38 ]
python
en
['en', 'en', 'en']
True
test_invalid_station_id
(hass)
Test that errors are shown when measuring station ID is invalid.
Test that errors are shown when measuring station ID is invalid.
async def test_invalid_station_id(hass): """Test that errors are shown when measuring station ID is invalid.""" with patch( "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS ): flow = config_flow.GiosFlowHandler() flow.hass = hass flow.context = {} result = await flow.async_step_user( user_input={CONF_NAME: "Foo", CONF_STATION_ID: 0} ) assert result["errors"] == {CONF_STATION_ID: "wrong_station_id"}
[ "async", "def", "test_invalid_station_id", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.gios.Gios._get_stations\"", ",", "return_value", "=", "STATIONS", ")", ":", "flow", "=", "config_flow", ".", "GiosFlowHandler", "(", ")", "flow", ".", "hass", "=", "hass", "flow", ".", "context", "=", "{", "}", "result", "=", "await", "flow", ".", "async_step_user", "(", "user_input", "=", "{", "CONF_NAME", ":", "\"Foo\"", ",", "CONF_STATION_ID", ":", "0", "}", ")", "assert", "result", "[", "\"errors\"", "]", "==", "{", "CONF_STATION_ID", ":", "\"wrong_station_id\"", "}" ]
[ 31, 0 ]
[ 44, 72 ]
python
en
['en', 'en', 'en']
True
test_invalid_sensor_data
(hass)
Test that errors are shown when sensor data is invalid.
Test that errors are shown when sensor data is invalid.
async def test_invalid_sensor_data(hass): """Test that errors are shown when sensor data is invalid.""" with patch( "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS ), patch( "homeassistant.components.gios.Gios._get_station", return_value=json.loads(load_fixture("gios/station.json")), ), patch( "homeassistant.components.gios.Gios._get_sensor", return_value={} ): flow = config_flow.GiosFlowHandler() flow.hass = hass flow.context = {} result = await flow.async_step_user(user_input=CONFIG) assert result["errors"] == {CONF_STATION_ID: "invalid_sensors_data"}
[ "async", "def", "test_invalid_sensor_data", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.gios.Gios._get_stations\"", ",", "return_value", "=", "STATIONS", ")", ",", "patch", "(", "\"homeassistant.components.gios.Gios._get_station\"", ",", "return_value", "=", "json", ".", "loads", "(", "load_fixture", "(", "\"gios/station.json\"", ")", ")", ",", ")", ",", "patch", "(", "\"homeassistant.components.gios.Gios._get_sensor\"", ",", "return_value", "=", "{", "}", ")", ":", "flow", "=", "config_flow", ".", "GiosFlowHandler", "(", ")", "flow", ".", "hass", "=", "hass", "flow", ".", "context", "=", "{", "}", "result", "=", "await", "flow", ".", "async_step_user", "(", "user_input", "=", "CONFIG", ")", "assert", "result", "[", "\"errors\"", "]", "==", "{", "CONF_STATION_ID", ":", "\"invalid_sensors_data\"", "}" ]
[ 47, 0 ]
[ 63, 76 ]
python
en
['en', 'en', 'en']
True
test_cannot_connect
(hass)
Test that errors are shown when cannot connect to GIOS server.
Test that errors are shown when cannot connect to GIOS server.
async def test_cannot_connect(hass): """Test that errors are shown when cannot connect to GIOS server.""" with patch( "homeassistant.components.gios.Gios._async_get", side_effect=ApiError("error") ): flow = config_flow.GiosFlowHandler() flow.hass = hass flow.context = {} result = await flow.async_step_user(user_input=CONFIG) assert result["errors"] == {"base": "cannot_connect"}
[ "async", "def", "test_cannot_connect", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.gios.Gios._async_get\"", ",", "side_effect", "=", "ApiError", "(", "\"error\"", ")", ")", ":", "flow", "=", "config_flow", ".", "GiosFlowHandler", "(", ")", "flow", ".", "hass", "=", "hass", "flow", ".", "context", "=", "{", "}", "result", "=", "await", "flow", ".", "async_step_user", "(", "user_input", "=", "CONFIG", ")", "assert", "result", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}" ]
[ 66, 0 ]
[ 77, 61 ]
python
en
['en', 'en', 'en']
True
test_create_entry
(hass)
Test that the user step works.
Test that the user step works.
async def test_create_entry(hass): """Test that the user step works.""" with patch( "homeassistant.components.gios.Gios._get_stations", return_value=STATIONS ), patch( "homeassistant.components.gios.Gios._get_station", return_value=json.loads(load_fixture("gios/station.json")), ), patch( "homeassistant.components.gios.Gios._get_all_sensors", return_value=json.loads(load_fixture("gios/sensors.json")), ), patch( "homeassistant.components.gios.Gios._get_indexes", return_value=json.loads(load_fixture("gios/indexes.json")), ): flow = config_flow.GiosFlowHandler() flow.hass = hass flow.context = {} result = await flow.async_step_user(user_input=CONFIG) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["title"] == CONFIG[CONF_STATION_ID] assert result["data"][CONF_STATION_ID] == CONFIG[CONF_STATION_ID] assert flow.context["unique_id"] == CONFIG[CONF_STATION_ID]
[ "async", "def", "test_create_entry", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.gios.Gios._get_stations\"", ",", "return_value", "=", "STATIONS", ")", ",", "patch", "(", "\"homeassistant.components.gios.Gios._get_station\"", ",", "return_value", "=", "json", ".", "loads", "(", "load_fixture", "(", "\"gios/station.json\"", ")", ")", ",", ")", ",", "patch", "(", "\"homeassistant.components.gios.Gios._get_all_sensors\"", ",", "return_value", "=", "json", ".", "loads", "(", "load_fixture", "(", "\"gios/sensors.json\"", ")", ")", ",", ")", ",", "patch", "(", "\"homeassistant.components.gios.Gios._get_indexes\"", ",", "return_value", "=", "json", ".", "loads", "(", "load_fixture", "(", "\"gios/indexes.json\"", ")", ")", ",", ")", ":", "flow", "=", "config_flow", ".", "GiosFlowHandler", "(", ")", "flow", ".", "hass", "=", "hass", "flow", ".", "context", "=", "{", "}", "result", "=", "await", "flow", ".", "async_step_user", "(", "user_input", "=", "CONFIG", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"title\"", "]", "==", "CONFIG", "[", "CONF_STATION_ID", "]", "assert", "result", "[", "\"data\"", "]", "[", "CONF_STATION_ID", "]", "==", "CONFIG", "[", "CONF_STATION_ID", "]", "assert", "flow", ".", "context", "[", "\"unique_id\"", "]", "==", "CONFIG", "[", "CONF_STATION_ID", "]" ]
[ 80, 0 ]
[ 104, 67 ]
python
en
['en', 'en', 'en']
True
test_creating_entry_sets_up_media_player
(hass)
Test setting up Cast loads the media player.
Test setting up Cast loads the media player.
async def test_creating_entry_sets_up_media_player(hass): """Test setting up Cast loads the media player.""" with patch( "homeassistant.components.cast.media_player.async_setup_entry", return_value=True, ) as mock_setup, patch( "pychromecast.discovery.discover_chromecasts", return_value=(True, None) ), patch( "pychromecast.discovery.stop_discovery" ): result = await hass.config_entries.flow.async_init( cast.DOMAIN, context={"source": config_entries.SOURCE_USER} ) # Confirmation form assert result["type"] == data_entry_flow.RESULT_TYPE_FORM result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1
[ "async", "def", "test_creating_entry_sets_up_media_player", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.cast.media_player.async_setup_entry\"", ",", "return_value", "=", "True", ",", ")", "as", "mock_setup", ",", "patch", "(", "\"pychromecast.discovery.discover_chromecasts\"", ",", "return_value", "=", "(", "True", ",", "None", ")", ")", ",", "patch", "(", "\"pychromecast.discovery.stop_discovery\"", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "cast", ".", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "# Confirmation form", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1" ]
[ 9, 0 ]
[ 31, 42 ]
python
en
['en', 'en', 'en']
True
test_configuring_cast_creates_entry
(hass)
Test that specifying config will create an entry.
Test that specifying config will create an entry.
async def test_configuring_cast_creates_entry(hass): """Test that specifying config will create an entry.""" with patch( "homeassistant.components.cast.async_setup_entry", return_value=True ) as mock_setup: await async_setup_component( hass, cast.DOMAIN, {"cast": {"some_config": "to_trigger_import"}} ) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 1
[ "async", "def", "test_configuring_cast_creates_entry", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.cast.async_setup_entry\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ":", "await", "async_setup_component", "(", "hass", ",", "cast", ".", "DOMAIN", ",", "{", "\"cast\"", ":", "{", "\"some_config\"", ":", "\"to_trigger_import\"", "}", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1" ]
[ 34, 0 ]
[ 44, 42 ]
python
en
['en', 'en', 'en']
True
test_not_configuring_cast_not_creates_entry
(hass)
Test that no config will not create an entry.
Test that no config will not create an entry.
async def test_not_configuring_cast_not_creates_entry(hass): """Test that no config will not create an entry.""" with patch( "homeassistant.components.cast.async_setup_entry", return_value=True ) as mock_setup: await async_setup_component(hass, cast.DOMAIN, {}) await hass.async_block_till_done() assert len(mock_setup.mock_calls) == 0
[ "async", "def", "test_not_configuring_cast_not_creates_entry", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.cast.async_setup_entry\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ":", "await", "async_setup_component", "(", "hass", ",", "cast", ".", "DOMAIN", ",", "{", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "0" ]
[ 47, 0 ]
[ 55, 42 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up an Utility Meter.
Set up an Utility Meter.
async def async_setup(hass, config): """Set up an Utility Meter.""" component = EntityComponent(_LOGGER, DOMAIN, hass) hass.data[DATA_UTILITY] = {} register_services = False for meter, conf in config.get(DOMAIN).items(): _LOGGER.debug("Setup %s.%s", DOMAIN, meter) hass.data[DATA_UTILITY][meter] = conf if not conf[CONF_TARIFFS]: # only one entity is required hass.async_create_task( discovery.async_load_platform( hass, SENSOR_DOMAIN, DOMAIN, [{CONF_METER: meter, CONF_NAME: meter}], config, ) ) else: # create tariff selection await component.async_add_entities( [TariffSelect(meter, list(conf[CONF_TARIFFS]))] ) hass.data[DATA_UTILITY][meter][CONF_TARIFF_ENTITY] = "{}.{}".format( DOMAIN, meter ) # add one meter for each tariff tariff_confs = [] for tariff in conf[CONF_TARIFFS]: tariff_confs.append( { CONF_METER: meter, CONF_NAME: f"{meter} {tariff}", CONF_TARIFF: tariff, } ) hass.async_create_task( discovery.async_load_platform( hass, SENSOR_DOMAIN, DOMAIN, tariff_confs, config ) ) register_services = True if register_services: component.async_register_entity_service(SERVICE_RESET, {}, "async_reset_meters") component.async_register_entity_service( SERVICE_SELECT_TARIFF, {vol.Required(ATTR_TARIFF): cv.string}, "async_select_tariff", ) component.async_register_entity_service( SERVICE_SELECT_NEXT_TARIFF, {}, "async_next_tariff" ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "component", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ")", "hass", ".", "data", "[", "DATA_UTILITY", "]", "=", "{", "}", "register_services", "=", "False", "for", "meter", ",", "conf", "in", "config", ".", "get", "(", "DOMAIN", ")", ".", "items", "(", ")", ":", "_LOGGER", ".", "debug", "(", "\"Setup %s.%s\"", ",", "DOMAIN", ",", "meter", ")", "hass", ".", "data", "[", "DATA_UTILITY", "]", "[", "meter", "]", "=", "conf", "if", "not", "conf", "[", "CONF_TARIFFS", "]", ":", "# only one entity is required", "hass", ".", "async_create_task", "(", "discovery", ".", "async_load_platform", "(", "hass", ",", "SENSOR_DOMAIN", ",", "DOMAIN", ",", "[", "{", "CONF_METER", ":", "meter", ",", "CONF_NAME", ":", "meter", "}", "]", ",", "config", ",", ")", ")", "else", ":", "# create tariff selection", "await", "component", ".", "async_add_entities", "(", "[", "TariffSelect", "(", "meter", ",", "list", "(", "conf", "[", "CONF_TARIFFS", "]", ")", ")", "]", ")", "hass", ".", "data", "[", "DATA_UTILITY", "]", "[", "meter", "]", "[", "CONF_TARIFF_ENTITY", "]", "=", "\"{}.{}\"", ".", "format", "(", "DOMAIN", ",", "meter", ")", "# add one meter for each tariff", "tariff_confs", "=", "[", "]", "for", "tariff", "in", "conf", "[", "CONF_TARIFFS", "]", ":", "tariff_confs", ".", "append", "(", "{", "CONF_METER", ":", "meter", ",", "CONF_NAME", ":", "f\"{meter} {tariff}\"", ",", "CONF_TARIFF", ":", "tariff", ",", "}", ")", "hass", ".", "async_create_task", "(", "discovery", ".", "async_load_platform", "(", "hass", ",", "SENSOR_DOMAIN", ",", "DOMAIN", ",", "tariff_confs", ",", "config", ")", ")", "register_services", "=", "True", "if", "register_services", ":", "component", ".", "async_register_entity_service", "(", "SERVICE_RESET", ",", "{", "}", ",", "\"async_reset_meters\"", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_SELECT_TARIFF", ",", "{", "vol", ".", "Required", "(", "ATTR_TARIFF", ")", ":", "cv", ".", "string", "}", ",", "\"async_select_tariff\"", ",", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_SELECT_NEXT_TARIFF", ",", "{", "}", ",", "\"async_next_tariff\"", ")", "return", "True" ]
[ 60, 0 ]
[ 121, 15 ]
python
en
['en', 'en', 'en']
True
TariffSelect.__init__
(self, name, tariffs)
Initialize a tariff selector.
Initialize a tariff selector.
def __init__(self, name, tariffs): """Initialize a tariff selector.""" self._name = name self._current_tariff = None self._tariffs = tariffs self._icon = TARIFF_ICON
[ "def", "__init__", "(", "self", ",", "name", ",", "tariffs", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_current_tariff", "=", "None", "self", ".", "_tariffs", "=", "tariffs", "self", ".", "_icon", "=", "TARIFF_ICON" ]
[ 127, 4 ]
[ 132, 32 ]
python
en
['en', 'en', 'it']
True
TariffSelect.async_added_to_hass
(self)
Run when entity about to be added.
Run when entity about to be added.
async def async_added_to_hass(self): """Run when entity about to be added.""" await super().async_added_to_hass() if self._current_tariff is not None: return state = await self.async_get_last_state() if not state or state.state not in self._tariffs: self._current_tariff = self._tariffs[0] else: self._current_tariff = state.state
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_added_to_hass", "(", ")", "if", "self", ".", "_current_tariff", "is", "not", "None", ":", "return", "state", "=", "await", "self", ".", "async_get_last_state", "(", ")", "if", "not", "state", "or", "state", ".", "state", "not", "in", "self", ".", "_tariffs", ":", "self", ".", "_current_tariff", "=", "self", ".", "_tariffs", "[", "0", "]", "else", ":", "self", ".", "_current_tariff", "=", "state", ".", "state" ]
[ 134, 4 ]
[ 144, 46 ]
python
en
['en', 'en', 'en']
True
TariffSelect.should_poll
(self)
If entity should be polled.
If entity should be polled.
def should_poll(self): """If entity should be polled.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 147, 4 ]
[ 149, 20 ]
python
en
['en', 'en', 'en']
True
TariffSelect.name
(self)
Return the name of the select input.
Return the name of the select input.
def name(self): """Return the name of the select input.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 152, 4 ]
[ 154, 25 ]
python
en
['en', 'en', 'en']
True
TariffSelect.icon
(self)
Return the icon to be used for this entity.
Return the icon to be used for this entity.
def icon(self): """Return the icon to be used for this entity.""" return self._icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "_icon" ]
[ 157, 4 ]
[ 159, 25 ]
python
en
['en', 'en', 'en']
True
TariffSelect.state
(self)
Return the state of the component.
Return the state of the component.
def state(self): """Return the state of the component.""" return self._current_tariff
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_current_tariff" ]
[ 162, 4 ]
[ 164, 35 ]
python
en
['en', 'en', 'en']
True
TariffSelect.state_attributes
(self)
Return the state attributes.
Return the state attributes.
def state_attributes(self): """Return the state attributes.""" return {ATTR_TARIFFS: self._tariffs}
[ "def", "state_attributes", "(", "self", ")", ":", "return", "{", "ATTR_TARIFFS", ":", "self", ".", "_tariffs", "}" ]
[ 167, 4 ]
[ 169, 44 ]
python
en
['en', 'en', 'en']
True
TariffSelect.async_reset_meters
(self)
Reset all sensors of this meter.
Reset all sensors of this meter.
async def async_reset_meters(self): """Reset all sensors of this meter.""" _LOGGER.debug("reset meter %s", self.entity_id) async_dispatcher_send(self.hass, SIGNAL_RESET_METER, self.entity_id)
[ "async", "def", "async_reset_meters", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"reset meter %s\"", ",", "self", ".", "entity_id", ")", "async_dispatcher_send", "(", "self", ".", "hass", ",", "SIGNAL_RESET_METER", ",", "self", ".", "entity_id", ")" ]
[ 171, 4 ]
[ 174, 76 ]
python
en
['en', 'id', 'en']
True
TariffSelect.async_select_tariff
(self, tariff)
Select new option.
Select new option.
async def async_select_tariff(self, tariff): """Select new option.""" if tariff not in self._tariffs: _LOGGER.warning( "Invalid tariff: %s (possible tariffs: %s)", tariff, ", ".join(self._tariffs), ) return self._current_tariff = tariff self.async_write_ha_state()
[ "async", "def", "async_select_tariff", "(", "self", ",", "tariff", ")", ":", "if", "tariff", "not", "in", "self", ".", "_tariffs", ":", "_LOGGER", ".", "warning", "(", "\"Invalid tariff: %s (possible tariffs: %s)\"", ",", "tariff", ",", "\", \"", ".", "join", "(", "self", ".", "_tariffs", ")", ",", ")", "return", "self", ".", "_current_tariff", "=", "tariff", "self", ".", "async_write_ha_state", "(", ")" ]
[ 176, 4 ]
[ 186, 35 ]
python
en
['en', 'ceb', 'en']
True
TariffSelect.async_next_tariff
(self)
Offset current index.
Offset current index.
async def async_next_tariff(self): """Offset current index.""" current_index = self._tariffs.index(self._current_tariff) new_index = (current_index + 1) % len(self._tariffs) self._current_tariff = self._tariffs[new_index] self.async_write_ha_state()
[ "async", "def", "async_next_tariff", "(", "self", ")", ":", "current_index", "=", "self", ".", "_tariffs", ".", "index", "(", "self", ".", "_current_tariff", ")", "new_index", "=", "(", "current_index", "+", "1", ")", "%", "len", "(", "self", ".", "_tariffs", ")", "self", ".", "_current_tariff", "=", "self", ".", "_tariffs", "[", "new_index", "]", "self", ".", "async_write_ha_state", "(", ")" ]
[ 188, 4 ]
[ 193, 35 ]
python
en
['en', 'da', 'en']
True
async_subscribe_topics
( hass: HomeAssistantType, new_state: Optional[Dict[str, EntitySubscription]], topics: Dict[str, Any], )
(Re)Subscribe to a set of MQTT topics. State is kept in sub_state and a dictionary mapping from the subscription key to the subscription state. Please note that the sub state must not be shared between multiple sets of topics. Every call to async_subscribe_topics must always contain _all_ the topics the subscription state should manage.
(Re)Subscribe to a set of MQTT topics.
async def async_subscribe_topics( hass: HomeAssistantType, new_state: Optional[Dict[str, EntitySubscription]], topics: Dict[str, Any], ): """(Re)Subscribe to a set of MQTT topics. State is kept in sub_state and a dictionary mapping from the subscription key to the subscription state. Please note that the sub state must not be shared between multiple sets of topics. Every call to async_subscribe_topics must always contain _all_ the topics the subscription state should manage. """ current_subscriptions = new_state if new_state is not None else {} new_state = {} for key, value in topics.items(): # Extract the new requested subscription requested = EntitySubscription( topic=value.get("topic", None), message_callback=value.get("msg_callback", None), unsubscribe_callback=None, qos=value.get("qos", DEFAULT_QOS), encoding=value.get("encoding", "utf-8"), hass=hass, ) # Get the current subscription state current = current_subscriptions.pop(key, None) await requested.resubscribe_if_necessary(hass, current) new_state[key] = requested # Go through all remaining subscriptions and unsubscribe them for remaining in current_subscriptions.values(): if remaining.unsubscribe_callback is not None: remaining.unsubscribe_callback() # Clear debug data if it exists debug_info.remove_subscription( hass, remaining.message_callback, remaining.topic ) return new_state
[ "async", "def", "async_subscribe_topics", "(", "hass", ":", "HomeAssistantType", ",", "new_state", ":", "Optional", "[", "Dict", "[", "str", ",", "EntitySubscription", "]", "]", ",", "topics", ":", "Dict", "[", "str", ",", "Any", "]", ",", ")", ":", "current_subscriptions", "=", "new_state", "if", "new_state", "is", "not", "None", "else", "{", "}", "new_state", "=", "{", "}", "for", "key", ",", "value", "in", "topics", ".", "items", "(", ")", ":", "# Extract the new requested subscription", "requested", "=", "EntitySubscription", "(", "topic", "=", "value", ".", "get", "(", "\"topic\"", ",", "None", ")", ",", "message_callback", "=", "value", ".", "get", "(", "\"msg_callback\"", ",", "None", ")", ",", "unsubscribe_callback", "=", "None", ",", "qos", "=", "value", ".", "get", "(", "\"qos\"", ",", "DEFAULT_QOS", ")", ",", "encoding", "=", "value", ".", "get", "(", "\"encoding\"", ",", "\"utf-8\"", ")", ",", "hass", "=", "hass", ",", ")", "# Get the current subscription state", "current", "=", "current_subscriptions", ".", "pop", "(", "key", ",", "None", ")", "await", "requested", ".", "resubscribe_if_necessary", "(", "hass", ",", "current", ")", "new_state", "[", "key", "]", "=", "requested", "# Go through all remaining subscriptions and unsubscribe them", "for", "remaining", "in", "current_subscriptions", ".", "values", "(", ")", ":", "if", "remaining", ".", "unsubscribe_callback", "is", "not", "None", ":", "remaining", ".", "unsubscribe_callback", "(", ")", "# Clear debug data if it exists", "debug_info", ".", "remove_subscription", "(", "hass", ",", "remaining", ".", "message_callback", ",", "remaining", ".", "topic", ")", "return", "new_state" ]
[ 65, 0 ]
[ 105, 20 ]
python
en
['en', 'en', 'en']
True
async_unsubscribe_topics
(hass: HomeAssistantType, sub_state: dict)
Unsubscribe from all MQTT topics managed by async_subscribe_topics.
Unsubscribe from all MQTT topics managed by async_subscribe_topics.
async def async_unsubscribe_topics(hass: HomeAssistantType, sub_state: dict): """Unsubscribe from all MQTT topics managed by async_subscribe_topics.""" return await async_subscribe_topics(hass, sub_state, {})
[ "async", "def", "async_unsubscribe_topics", "(", "hass", ":", "HomeAssistantType", ",", "sub_state", ":", "dict", ")", ":", "return", "await", "async_subscribe_topics", "(", "hass", ",", "sub_state", ",", "{", "}", ")" ]
[ 109, 0 ]
[ 111, 60 ]
python
en
['en', 'en', 'en']
True
format_unique_id
(app_id: str, location_id: str)
Format the unique id for a config entry.
Format the unique id for a config entry.
def format_unique_id(app_id: str, location_id: str) -> str: """Format the unique id for a config entry.""" return f"{app_id}_{location_id}"
[ "def", "format_unique_id", "(", "app_id", ":", "str", ",", "location_id", ":", "str", ")", "->", "str", ":", "return", "f\"{app_id}_{location_id}\"" ]
[ 57, 0 ]
[ 59, 36 ]
python
en
['en', 'en', 'en']
True
find_app
(hass: HomeAssistantType, api)
Find an existing SmartApp for this installation of hass.
Find an existing SmartApp for this installation of hass.
async def find_app(hass: HomeAssistantType, api): """Find an existing SmartApp for this installation of hass.""" apps = await api.apps() for app in [app for app in apps if app.app_name.startswith(APP_NAME_PREFIX)]: # Load settings to compare instance id settings = await app.settings() if ( settings.settings.get(SETTINGS_INSTANCE_ID) == hass.data[DOMAIN][CONF_INSTANCE_ID] ): return app
[ "async", "def", "find_app", "(", "hass", ":", "HomeAssistantType", ",", "api", ")", ":", "apps", "=", "await", "api", ".", "apps", "(", ")", "for", "app", "in", "[", "app", "for", "app", "in", "apps", "if", "app", ".", "app_name", ".", "startswith", "(", "APP_NAME_PREFIX", ")", "]", ":", "# Load settings to compare instance id", "settings", "=", "await", "app", ".", "settings", "(", ")", "if", "(", "settings", ".", "settings", ".", "get", "(", "SETTINGS_INSTANCE_ID", ")", "==", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_INSTANCE_ID", "]", ")", ":", "return", "app" ]
[ 62, 0 ]
[ 72, 22 ]
python
en
['en', 'en', 'en']
True
validate_installed_app
(api, installed_app_id: str)
Ensure the specified installed SmartApp is valid and functioning. Query the API for the installed SmartApp and validate that it is tied to the specified app_id and is in an authorized state.
Ensure the specified installed SmartApp is valid and functioning.
async def validate_installed_app(api, installed_app_id: str): """ Ensure the specified installed SmartApp is valid and functioning. Query the API for the installed SmartApp and validate that it is tied to the specified app_id and is in an authorized state. """ installed_app = await api.installed_app(installed_app_id) if installed_app.installed_app_status != InstalledAppStatus.AUTHORIZED: raise RuntimeWarning( "Installed SmartApp instance '{}' ({}) is not AUTHORIZED but instead {}".format( installed_app.display_name, installed_app.installed_app_id, installed_app.installed_app_status, ) ) return installed_app
[ "async", "def", "validate_installed_app", "(", "api", ",", "installed_app_id", ":", "str", ")", ":", "installed_app", "=", "await", "api", ".", "installed_app", "(", "installed_app_id", ")", "if", "installed_app", ".", "installed_app_status", "!=", "InstalledAppStatus", ".", "AUTHORIZED", ":", "raise", "RuntimeWarning", "(", "\"Installed SmartApp instance '{}' ({}) is not AUTHORIZED but instead {}\"", ".", "format", "(", "installed_app", ".", "display_name", ",", "installed_app", ".", "installed_app_id", ",", "installed_app", ".", "installed_app_status", ",", ")", ")", "return", "installed_app" ]
[ 75, 0 ]
[ 91, 24 ]
python
en
['en', 'error', 'th']
False
validate_webhook_requirements
(hass: HomeAssistantType)
Ensure Home Assistant is setup properly to receive webhooks.
Ensure Home Assistant is setup properly to receive webhooks.
def validate_webhook_requirements(hass: HomeAssistantType) -> bool: """Ensure Home Assistant is setup properly to receive webhooks.""" if hass.components.cloud.async_active_subscription(): return True if hass.data[DOMAIN][CONF_CLOUDHOOK_URL] is not None: return True return get_webhook_url(hass).lower().startswith("https://")
[ "def", "validate_webhook_requirements", "(", "hass", ":", "HomeAssistantType", ")", "->", "bool", ":", "if", "hass", ".", "components", ".", "cloud", ".", "async_active_subscription", "(", ")", ":", "return", "True", "if", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_CLOUDHOOK_URL", "]", "is", "not", "None", ":", "return", "True", "return", "get_webhook_url", "(", "hass", ")", ".", "lower", "(", ")", ".", "startswith", "(", "\"https://\"", ")" ]
[ 94, 0 ]
[ 100, 63 ]
python
en
['en', 'en', 'en']
True
get_webhook_url
(hass: HomeAssistantType)
Get the URL of the webhook. Return the cloudhook if available, otherwise local webhook.
Get the URL of the webhook.
def get_webhook_url(hass: HomeAssistantType) -> str: """ Get the URL of the webhook. Return the cloudhook if available, otherwise local webhook. """ cloudhook_url = hass.data[DOMAIN][CONF_CLOUDHOOK_URL] if hass.components.cloud.async_active_subscription() and cloudhook_url is not None: return cloudhook_url return webhook.async_generate_url(hass, hass.data[DOMAIN][CONF_WEBHOOK_ID])
[ "def", "get_webhook_url", "(", "hass", ":", "HomeAssistantType", ")", "->", "str", ":", "cloudhook_url", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_CLOUDHOOK_URL", "]", "if", "hass", ".", "components", ".", "cloud", ".", "async_active_subscription", "(", ")", "and", "cloudhook_url", "is", "not", "None", ":", "return", "cloudhook_url", "return", "webhook", ".", "async_generate_url", "(", "hass", ",", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_WEBHOOK_ID", "]", ")" ]
[ 103, 0 ]
[ 112, 79 ]
python
en
['en', 'error', 'th']
False
create_app
(hass: HomeAssistantType, api)
Create a SmartApp for this instance of hass.
Create a SmartApp for this instance of hass.
async def create_app(hass: HomeAssistantType, api): """Create a SmartApp for this instance of hass.""" # Create app from template attributes template = _get_app_template(hass) app = App() for key, value in template.items(): setattr(app, key, value) app, client = await api.create_app(app) _LOGGER.debug("Created SmartApp '%s' (%s)", app.app_name, app.app_id) # Set unique hass id in settings settings = AppSettings(app.app_id) settings.settings[SETTINGS_APP_ID] = app.app_id settings.settings[SETTINGS_INSTANCE_ID] = hass.data[DOMAIN][CONF_INSTANCE_ID] await api.update_app_settings(settings) _LOGGER.debug( "Updated App Settings for SmartApp '%s' (%s)", app.app_name, app.app_id ) # Set oauth scopes oauth = AppOAuth(app.app_id) oauth.client_name = APP_OAUTH_CLIENT_NAME oauth.scope.extend(APP_OAUTH_SCOPES) await api.update_app_oauth(oauth) _LOGGER.debug("Updated App OAuth for SmartApp '%s' (%s)", app.app_name, app.app_id) return app, client
[ "async", "def", "create_app", "(", "hass", ":", "HomeAssistantType", ",", "api", ")", ":", "# Create app from template attributes", "template", "=", "_get_app_template", "(", "hass", ")", "app", "=", "App", "(", ")", "for", "key", ",", "value", "in", "template", ".", "items", "(", ")", ":", "setattr", "(", "app", ",", "key", ",", "value", ")", "app", ",", "client", "=", "await", "api", ".", "create_app", "(", "app", ")", "_LOGGER", ".", "debug", "(", "\"Created SmartApp '%s' (%s)\"", ",", "app", ".", "app_name", ",", "app", ".", "app_id", ")", "# Set unique hass id in settings", "settings", "=", "AppSettings", "(", "app", ".", "app_id", ")", "settings", ".", "settings", "[", "SETTINGS_APP_ID", "]", "=", "app", ".", "app_id", "settings", ".", "settings", "[", "SETTINGS_INSTANCE_ID", "]", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_INSTANCE_ID", "]", "await", "api", ".", "update_app_settings", "(", "settings", ")", "_LOGGER", ".", "debug", "(", "\"Updated App Settings for SmartApp '%s' (%s)\"", ",", "app", ".", "app_name", ",", "app", ".", "app_id", ")", "# Set oauth scopes", "oauth", "=", "AppOAuth", "(", "app", ".", "app_id", ")", "oauth", ".", "client_name", "=", "APP_OAUTH_CLIENT_NAME", "oauth", ".", "scope", ".", "extend", "(", "APP_OAUTH_SCOPES", ")", "await", "api", ".", "update_app_oauth", "(", "oauth", ")", "_LOGGER", ".", "debug", "(", "\"Updated App OAuth for SmartApp '%s' (%s)\"", ",", "app", ".", "app_name", ",", "app", ".", "app_id", ")", "return", "app", ",", "client" ]
[ 137, 0 ]
[ 162, 22 ]
python
en
['en', 'en', 'en']
True
update_app
(hass: HomeAssistantType, app)
Ensure the SmartApp is up-to-date and update if necessary.
Ensure the SmartApp is up-to-date and update if necessary.
async def update_app(hass: HomeAssistantType, app): """Ensure the SmartApp is up-to-date and update if necessary.""" template = _get_app_template(hass) template.pop("app_name") # don't update this update_required = False for key, value in template.items(): if getattr(app, key) != value: update_required = True setattr(app, key, value) if update_required: await app.save() _LOGGER.debug( "SmartApp '%s' (%s) updated with latest settings", app.app_name, app.app_id )
[ "async", "def", "update_app", "(", "hass", ":", "HomeAssistantType", ",", "app", ")", ":", "template", "=", "_get_app_template", "(", "hass", ")", "template", ".", "pop", "(", "\"app_name\"", ")", "# don't update this", "update_required", "=", "False", "for", "key", ",", "value", "in", "template", ".", "items", "(", ")", ":", "if", "getattr", "(", "app", ",", "key", ")", "!=", "value", ":", "update_required", "=", "True", "setattr", "(", "app", ",", "key", ",", "value", ")", "if", "update_required", ":", "await", "app", ".", "save", "(", ")", "_LOGGER", ".", "debug", "(", "\"SmartApp '%s' (%s) updated with latest settings\"", ",", "app", ".", "app_name", ",", "app", ".", "app_id", ")" ]
[ 165, 0 ]
[ 178, 9 ]
python
en
['en', 'en', 'en']
True
setup_smartapp
(hass, app)
Configure an individual SmartApp in hass. Register the SmartApp with the SmartAppManager so that hass will service lifecycle events (install, event, etc...). A unique SmartApp is created for each SmartThings account that is configured in hass.
Configure an individual SmartApp in hass.
def setup_smartapp(hass, app): """ Configure an individual SmartApp in hass. Register the SmartApp with the SmartAppManager so that hass will service lifecycle events (install, event, etc...). A unique SmartApp is created for each SmartThings account that is configured in hass. """ manager = hass.data[DOMAIN][DATA_MANAGER] smartapp = manager.smartapps.get(app.app_id) if smartapp: # already setup return smartapp smartapp = manager.register(app.app_id, app.webhook_public_key) smartapp.name = app.display_name smartapp.description = app.description smartapp.permissions.extend(APP_OAUTH_SCOPES) return smartapp
[ "def", "setup_smartapp", "(", "hass", ",", "app", ")", ":", "manager", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_MANAGER", "]", "smartapp", "=", "manager", ".", "smartapps", ".", "get", "(", "app", ".", "app_id", ")", "if", "smartapp", ":", "# already setup", "return", "smartapp", "smartapp", "=", "manager", ".", "register", "(", "app", ".", "app_id", ",", "app", ".", "webhook_public_key", ")", "smartapp", ".", "name", "=", "app", ".", "display_name", "smartapp", ".", "description", "=", "app", ".", "description", "smartapp", ".", "permissions", ".", "extend", "(", "APP_OAUTH_SCOPES", ")", "return", "smartapp" ]
[ 181, 0 ]
[ 198, 19 ]
python
en
['en', 'error', 'th']
False
setup_smartapp_endpoint
(hass: HomeAssistantType)
Configure the SmartApp webhook in hass. SmartApps are an extension point within the SmartThings ecosystem and is used to receive push updates (i.e. device updates) from the cloud.
Configure the SmartApp webhook in hass.
async def setup_smartapp_endpoint(hass: HomeAssistantType): """ Configure the SmartApp webhook in hass. SmartApps are an extension point within the SmartThings ecosystem and is used to receive push updates (i.e. device updates) from the cloud. """ data = hass.data.get(DOMAIN) if data: # already setup return # Get/create config to store a unique id for this hass instance. store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY) config = await store.async_load() if not config: # Create config config = { CONF_INSTANCE_ID: str(uuid4()), CONF_WEBHOOK_ID: secrets.token_hex(), CONF_CLOUDHOOK_URL: None, } await store.async_save(config) # Register webhook webhook.async_register( hass, DOMAIN, "SmartApp", config[CONF_WEBHOOK_ID], smartapp_webhook ) # Create webhook if eligible cloudhook_url = config.get(CONF_CLOUDHOOK_URL) if ( cloudhook_url is None and hass.components.cloud.async_active_subscription() and not hass.config_entries.async_entries(DOMAIN) ): cloudhook_url = await hass.components.cloud.async_create_cloudhook( config[CONF_WEBHOOK_ID] ) config[CONF_CLOUDHOOK_URL] = cloudhook_url await store.async_save(config) _LOGGER.debug("Created cloudhook '%s'", cloudhook_url) # SmartAppManager uses a dispatcher to invoke callbacks when push events # occur. Use hass' implementation instead of the built-in one. dispatcher = Dispatcher( signal_prefix=SIGNAL_SMARTAPP_PREFIX, connect=functools.partial(async_dispatcher_connect, hass), send=functools.partial(async_dispatcher_send, hass), ) # Path is used in digital signature validation path = ( urlparse(cloudhook_url).path if cloudhook_url else webhook.async_generate_path(config[CONF_WEBHOOK_ID]) ) manager = SmartAppManager(path, dispatcher=dispatcher) manager.connect_install(functools.partial(smartapp_install, hass)) manager.connect_update(functools.partial(smartapp_update, hass)) manager.connect_uninstall(functools.partial(smartapp_uninstall, hass)) hass.data[DOMAIN] = { DATA_MANAGER: manager, CONF_INSTANCE_ID: config[CONF_INSTANCE_ID], DATA_BROKERS: {}, CONF_WEBHOOK_ID: config[CONF_WEBHOOK_ID], # Will not be present if not enabled CONF_CLOUDHOOK_URL: config.get(CONF_CLOUDHOOK_URL), } _LOGGER.debug( "Setup endpoint for %s", cloudhook_url if cloudhook_url else webhook.async_generate_url(hass, config[CONF_WEBHOOK_ID]), )
[ "async", "def", "setup_smartapp_endpoint", "(", "hass", ":", "HomeAssistantType", ")", ":", "data", "=", "hass", ".", "data", ".", "get", "(", "DOMAIN", ")", "if", "data", ":", "# already setup", "return", "# Get/create config to store a unique id for this hass instance.", "store", "=", "hass", ".", "helpers", ".", "storage", ".", "Store", "(", "STORAGE_VERSION", ",", "STORAGE_KEY", ")", "config", "=", "await", "store", ".", "async_load", "(", ")", "if", "not", "config", ":", "# Create config", "config", "=", "{", "CONF_INSTANCE_ID", ":", "str", "(", "uuid4", "(", ")", ")", ",", "CONF_WEBHOOK_ID", ":", "secrets", ".", "token_hex", "(", ")", ",", "CONF_CLOUDHOOK_URL", ":", "None", ",", "}", "await", "store", ".", "async_save", "(", "config", ")", "# Register webhook", "webhook", ".", "async_register", "(", "hass", ",", "DOMAIN", ",", "\"SmartApp\"", ",", "config", "[", "CONF_WEBHOOK_ID", "]", ",", "smartapp_webhook", ")", "# Create webhook if eligible", "cloudhook_url", "=", "config", ".", "get", "(", "CONF_CLOUDHOOK_URL", ")", "if", "(", "cloudhook_url", "is", "None", "and", "hass", ".", "components", ".", "cloud", ".", "async_active_subscription", "(", ")", "and", "not", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", ")", ":", "cloudhook_url", "=", "await", "hass", ".", "components", ".", "cloud", ".", "async_create_cloudhook", "(", "config", "[", "CONF_WEBHOOK_ID", "]", ")", "config", "[", "CONF_CLOUDHOOK_URL", "]", "=", "cloudhook_url", "await", "store", ".", "async_save", "(", "config", ")", "_LOGGER", ".", "debug", "(", "\"Created cloudhook '%s'\"", ",", "cloudhook_url", ")", "# SmartAppManager uses a dispatcher to invoke callbacks when push events", "# occur. Use hass' implementation instead of the built-in one.", "dispatcher", "=", "Dispatcher", "(", "signal_prefix", "=", "SIGNAL_SMARTAPP_PREFIX", ",", "connect", "=", "functools", ".", "partial", "(", "async_dispatcher_connect", ",", "hass", ")", ",", "send", "=", "functools", ".", "partial", "(", "async_dispatcher_send", ",", "hass", ")", ",", ")", "# Path is used in digital signature validation", "path", "=", "(", "urlparse", "(", "cloudhook_url", ")", ".", "path", "if", "cloudhook_url", "else", "webhook", ".", "async_generate_path", "(", "config", "[", "CONF_WEBHOOK_ID", "]", ")", ")", "manager", "=", "SmartAppManager", "(", "path", ",", "dispatcher", "=", "dispatcher", ")", "manager", ".", "connect_install", "(", "functools", ".", "partial", "(", "smartapp_install", ",", "hass", ")", ")", "manager", ".", "connect_update", "(", "functools", ".", "partial", "(", "smartapp_update", ",", "hass", ")", ")", "manager", ".", "connect_uninstall", "(", "functools", ".", "partial", "(", "smartapp_uninstall", ",", "hass", ")", ")", "hass", ".", "data", "[", "DOMAIN", "]", "=", "{", "DATA_MANAGER", ":", "manager", ",", "CONF_INSTANCE_ID", ":", "config", "[", "CONF_INSTANCE_ID", "]", ",", "DATA_BROKERS", ":", "{", "}", ",", "CONF_WEBHOOK_ID", ":", "config", "[", "CONF_WEBHOOK_ID", "]", ",", "# Will not be present if not enabled", "CONF_CLOUDHOOK_URL", ":", "config", ".", "get", "(", "CONF_CLOUDHOOK_URL", ")", ",", "}", "_LOGGER", ".", "debug", "(", "\"Setup endpoint for %s\"", ",", "cloudhook_url", "if", "cloudhook_url", "else", "webhook", ".", "async_generate_url", "(", "hass", ",", "config", "[", "CONF_WEBHOOK_ID", "]", ")", ",", ")" ]
[ 201, 0 ]
[ 275, 5 ]
python
en
['en', 'error', 'th']
False
unload_smartapp_endpoint
(hass: HomeAssistantType)
Tear down the component configuration.
Tear down the component configuration.
async def unload_smartapp_endpoint(hass: HomeAssistantType): """Tear down the component configuration.""" if DOMAIN not in hass.data: return # Remove the cloudhook if it was created cloudhook_url = hass.data[DOMAIN][CONF_CLOUDHOOK_URL] if cloudhook_url and hass.components.cloud.async_is_logged_in(): await hass.components.cloud.async_delete_cloudhook( hass.data[DOMAIN][CONF_WEBHOOK_ID] ) # Remove cloudhook from storage store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY) await store.async_save( { CONF_INSTANCE_ID: hass.data[DOMAIN][CONF_INSTANCE_ID], CONF_WEBHOOK_ID: hass.data[DOMAIN][CONF_WEBHOOK_ID], CONF_CLOUDHOOK_URL: None, } ) _LOGGER.debug("Cloudhook '%s' was removed", cloudhook_url) # Remove the webhook webhook.async_unregister(hass, hass.data[DOMAIN][CONF_WEBHOOK_ID]) # Disconnect all brokers for broker in hass.data[DOMAIN][DATA_BROKERS].values(): broker.disconnect() # Remove all handlers from manager hass.data[DOMAIN][DATA_MANAGER].dispatcher.disconnect_all() # Remove the component data hass.data.pop(DOMAIN)
[ "async", "def", "unload_smartapp_endpoint", "(", "hass", ":", "HomeAssistantType", ")", ":", "if", "DOMAIN", "not", "in", "hass", ".", "data", ":", "return", "# Remove the cloudhook if it was created", "cloudhook_url", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_CLOUDHOOK_URL", "]", "if", "cloudhook_url", "and", "hass", ".", "components", ".", "cloud", ".", "async_is_logged_in", "(", ")", ":", "await", "hass", ".", "components", ".", "cloud", ".", "async_delete_cloudhook", "(", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_WEBHOOK_ID", "]", ")", "# Remove cloudhook from storage", "store", "=", "hass", ".", "helpers", ".", "storage", ".", "Store", "(", "STORAGE_VERSION", ",", "STORAGE_KEY", ")", "await", "store", ".", "async_save", "(", "{", "CONF_INSTANCE_ID", ":", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_INSTANCE_ID", "]", ",", "CONF_WEBHOOK_ID", ":", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_WEBHOOK_ID", "]", ",", "CONF_CLOUDHOOK_URL", ":", "None", ",", "}", ")", "_LOGGER", ".", "debug", "(", "\"Cloudhook '%s' was removed\"", ",", "cloudhook_url", ")", "# Remove the webhook", "webhook", ".", "async_unregister", "(", "hass", ",", "hass", ".", "data", "[", "DOMAIN", "]", "[", "CONF_WEBHOOK_ID", "]", ")", "# Disconnect all brokers", "for", "broker", "in", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_BROKERS", "]", ".", "values", "(", ")", ":", "broker", ".", "disconnect", "(", ")", "# Remove all handlers from manager", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_MANAGER", "]", ".", "dispatcher", ".", "disconnect_all", "(", ")", "# Remove the component data", "hass", ".", "data", ".", "pop", "(", "DOMAIN", ")" ]
[ 278, 0 ]
[ 306, 25 ]
python
en
['en', 'en', 'en']
True
smartapp_sync_subscriptions
( hass: HomeAssistantType, auth_token: str, location_id: str, installed_app_id: str, devices, )
Synchronize subscriptions of an installed up.
Synchronize subscriptions of an installed up.
async def smartapp_sync_subscriptions( hass: HomeAssistantType, auth_token: str, location_id: str, installed_app_id: str, devices, ): """Synchronize subscriptions of an installed up.""" api = SmartThings(async_get_clientsession(hass), auth_token) tasks = [] async def create_subscription(target: str): sub = Subscription() sub.installed_app_id = installed_app_id sub.location_id = location_id sub.source_type = SourceType.CAPABILITY sub.capability = target try: await api.create_subscription(sub) _LOGGER.debug( "Created subscription for '%s' under app '%s'", target, installed_app_id ) except Exception as error: # pylint:disable=broad-except _LOGGER.error( "Failed to create subscription for '%s' under app '%s': %s", target, installed_app_id, error, ) async def delete_subscription(sub: SubscriptionEntity): try: await api.delete_subscription(installed_app_id, sub.subscription_id) _LOGGER.debug( "Removed subscription for '%s' under app '%s' because it was no longer needed", sub.capability, installed_app_id, ) except Exception as error: # pylint:disable=broad-except _LOGGER.error( "Failed to remove subscription for '%s' under app '%s': %s", sub.capability, installed_app_id, error, ) # Build set of capabilities and prune unsupported ones capabilities = set() for device in devices: capabilities.update(device.capabilities) # Remove items not defined in the library capabilities.intersection_update(CAPABILITIES) # Remove unused capabilities capabilities.difference_update(IGNORED_CAPABILITIES) capability_count = len(capabilities) if capability_count > SUBSCRIPTION_WARNING_LIMIT: _LOGGER.warning( "Some device attributes may not receive push updates and there may be subscription " "creation failures under app '%s' because %s subscriptions are required but " "there is a limit of %s per app", installed_app_id, capability_count, SUBSCRIPTION_WARNING_LIMIT, ) _LOGGER.debug( "Synchronizing subscriptions for %s capabilities under app '%s': %s", capability_count, installed_app_id, capabilities, ) # Get current subscriptions and find differences subscriptions = await api.subscriptions(installed_app_id) for subscription in subscriptions: if subscription.capability in capabilities: capabilities.remove(subscription.capability) else: # Delete the subscription tasks.append(delete_subscription(subscription)) # Remaining capabilities need subscriptions created tasks.extend([create_subscription(c) for c in capabilities]) if tasks: await asyncio.gather(*tasks) else: _LOGGER.debug("Subscriptions for app '%s' are up-to-date", installed_app_id)
[ "async", "def", "smartapp_sync_subscriptions", "(", "hass", ":", "HomeAssistantType", ",", "auth_token", ":", "str", ",", "location_id", ":", "str", ",", "installed_app_id", ":", "str", ",", "devices", ",", ")", ":", "api", "=", "SmartThings", "(", "async_get_clientsession", "(", "hass", ")", ",", "auth_token", ")", "tasks", "=", "[", "]", "async", "def", "create_subscription", "(", "target", ":", "str", ")", ":", "sub", "=", "Subscription", "(", ")", "sub", ".", "installed_app_id", "=", "installed_app_id", "sub", ".", "location_id", "=", "location_id", "sub", ".", "source_type", "=", "SourceType", ".", "CAPABILITY", "sub", ".", "capability", "=", "target", "try", ":", "await", "api", ".", "create_subscription", "(", "sub", ")", "_LOGGER", ".", "debug", "(", "\"Created subscription for '%s' under app '%s'\"", ",", "target", ",", "installed_app_id", ")", "except", "Exception", "as", "error", ":", "# pylint:disable=broad-except", "_LOGGER", ".", "error", "(", "\"Failed to create subscription for '%s' under app '%s': %s\"", ",", "target", ",", "installed_app_id", ",", "error", ",", ")", "async", "def", "delete_subscription", "(", "sub", ":", "SubscriptionEntity", ")", ":", "try", ":", "await", "api", ".", "delete_subscription", "(", "installed_app_id", ",", "sub", ".", "subscription_id", ")", "_LOGGER", ".", "debug", "(", "\"Removed subscription for '%s' under app '%s' because it was no longer needed\"", ",", "sub", ".", "capability", ",", "installed_app_id", ",", ")", "except", "Exception", "as", "error", ":", "# pylint:disable=broad-except", "_LOGGER", ".", "error", "(", "\"Failed to remove subscription for '%s' under app '%s': %s\"", ",", "sub", ".", "capability", ",", "installed_app_id", ",", "error", ",", ")", "# Build set of capabilities and prune unsupported ones", "capabilities", "=", "set", "(", ")", "for", "device", "in", "devices", ":", "capabilities", ".", "update", "(", "device", ".", "capabilities", ")", "# Remove items not defined in the library", "capabilities", ".", "intersection_update", "(", "CAPABILITIES", ")", "# Remove unused capabilities", "capabilities", ".", "difference_update", "(", "IGNORED_CAPABILITIES", ")", "capability_count", "=", "len", "(", "capabilities", ")", "if", "capability_count", ">", "SUBSCRIPTION_WARNING_LIMIT", ":", "_LOGGER", ".", "warning", "(", "\"Some device attributes may not receive push updates and there may be subscription \"", "\"creation failures under app '%s' because %s subscriptions are required but \"", "\"there is a limit of %s per app\"", ",", "installed_app_id", ",", "capability_count", ",", "SUBSCRIPTION_WARNING_LIMIT", ",", ")", "_LOGGER", ".", "debug", "(", "\"Synchronizing subscriptions for %s capabilities under app '%s': %s\"", ",", "capability_count", ",", "installed_app_id", ",", "capabilities", ",", ")", "# Get current subscriptions and find differences", "subscriptions", "=", "await", "api", ".", "subscriptions", "(", "installed_app_id", ")", "for", "subscription", "in", "subscriptions", ":", "if", "subscription", ".", "capability", "in", "capabilities", ":", "capabilities", ".", "remove", "(", "subscription", ".", "capability", ")", "else", ":", "# Delete the subscription", "tasks", ".", "append", "(", "delete_subscription", "(", "subscription", ")", ")", "# Remaining capabilities need subscriptions created", "tasks", ".", "extend", "(", "[", "create_subscription", "(", "c", ")", "for", "c", "in", "capabilities", "]", ")", "if", "tasks", ":", "await", "asyncio", ".", "gather", "(", "*", "tasks", ")", "else", ":", "_LOGGER", ".", "debug", "(", "\"Subscriptions for app '%s' are up-to-date\"", ",", "installed_app_id", ")" ]
[ 309, 0 ]
[ 395, 84 ]
python
en
['en', 'en', 'en']
True
_continue_flow
( hass: HomeAssistantType, app_id: str, location_id: str, installed_app_id: str, refresh_token: str, )
Continue a config flow if one is in progress for the specific installed app.
Continue a config flow if one is in progress for the specific installed app.
async def _continue_flow( hass: HomeAssistantType, app_id: str, location_id: str, installed_app_id: str, refresh_token: str, ): """Continue a config flow if one is in progress for the specific installed app.""" unique_id = format_unique_id(app_id, location_id) flow = next( ( flow for flow in hass.config_entries.flow.async_progress() if flow["handler"] == DOMAIN and flow["context"]["unique_id"] == unique_id ), None, ) if flow is not None: await hass.config_entries.flow.async_configure( flow["flow_id"], { CONF_INSTALLED_APP_ID: installed_app_id, CONF_REFRESH_TOKEN: refresh_token, }, ) _LOGGER.debug( "Continued config flow '%s' for SmartApp '%s' under parent app '%s'", flow["flow_id"], installed_app_id, app_id, )
[ "async", "def", "_continue_flow", "(", "hass", ":", "HomeAssistantType", ",", "app_id", ":", "str", ",", "location_id", ":", "str", ",", "installed_app_id", ":", "str", ",", "refresh_token", ":", "str", ",", ")", ":", "unique_id", "=", "format_unique_id", "(", "app_id", ",", "location_id", ")", "flow", "=", "next", "(", "(", "flow", "for", "flow", "in", "hass", ".", "config_entries", ".", "flow", ".", "async_progress", "(", ")", "if", "flow", "[", "\"handler\"", "]", "==", "DOMAIN", "and", "flow", "[", "\"context\"", "]", "[", "\"unique_id\"", "]", "==", "unique_id", ")", ",", "None", ",", ")", "if", "flow", "is", "not", "None", ":", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "flow", "[", "\"flow_id\"", "]", ",", "{", "CONF_INSTALLED_APP_ID", ":", "installed_app_id", ",", "CONF_REFRESH_TOKEN", ":", "refresh_token", ",", "}", ",", ")", "_LOGGER", ".", "debug", "(", "\"Continued config flow '%s' for SmartApp '%s' under parent app '%s'\"", ",", "flow", "[", "\"flow_id\"", "]", ",", "installed_app_id", ",", "app_id", ",", ")" ]
[ 398, 0 ]
[ 428, 9 ]
python
en
['en', 'en', 'en']
True
smartapp_install
(hass: HomeAssistantType, req, resp, app)
Handle a SmartApp installation and continue the config flow.
Handle a SmartApp installation and continue the config flow.
async def smartapp_install(hass: HomeAssistantType, req, resp, app): """Handle a SmartApp installation and continue the config flow.""" await _continue_flow( hass, app.app_id, req.location_id, req.installed_app_id, req.refresh_token ) _LOGGER.debug( "Installed SmartApp '%s' under parent app '%s'", req.installed_app_id, app.app_id, )
[ "async", "def", "smartapp_install", "(", "hass", ":", "HomeAssistantType", ",", "req", ",", "resp", ",", "app", ")", ":", "await", "_continue_flow", "(", "hass", ",", "app", ".", "app_id", ",", "req", ".", "location_id", ",", "req", ".", "installed_app_id", ",", "req", ".", "refresh_token", ")", "_LOGGER", ".", "debug", "(", "\"Installed SmartApp '%s' under parent app '%s'\"", ",", "req", ".", "installed_app_id", ",", "app", ".", "app_id", ",", ")" ]
[ 431, 0 ]
[ 440, 5 ]
python
en
['en', 'en', 'en']
True
smartapp_update
(hass: HomeAssistantType, req, resp, app)
Handle a SmartApp update and either update the entry or continue the flow.
Handle a SmartApp update and either update the entry or continue the flow.
async def smartapp_update(hass: HomeAssistantType, req, resp, app): """Handle a SmartApp update and either update the entry or continue the flow.""" entry = next( ( entry for entry in hass.config_entries.async_entries(DOMAIN) if entry.data.get(CONF_INSTALLED_APP_ID) == req.installed_app_id ), None, ) if entry: hass.config_entries.async_update_entry( entry, data={**entry.data, CONF_REFRESH_TOKEN: req.refresh_token} ) _LOGGER.debug( "Updated config entry '%s' for SmartApp '%s' under parent app '%s'", entry.entry_id, req.installed_app_id, app.app_id, ) await _continue_flow( hass, app.app_id, req.location_id, req.installed_app_id, req.refresh_token ) _LOGGER.debug( "Updated SmartApp '%s' under parent app '%s'", req.installed_app_id, app.app_id )
[ "async", "def", "smartapp_update", "(", "hass", ":", "HomeAssistantType", ",", "req", ",", "resp", ",", "app", ")", ":", "entry", "=", "next", "(", "(", "entry", "for", "entry", "in", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", "if", "entry", ".", "data", ".", "get", "(", "CONF_INSTALLED_APP_ID", ")", "==", "req", ".", "installed_app_id", ")", ",", "None", ",", ")", "if", "entry", ":", "hass", ".", "config_entries", ".", "async_update_entry", "(", "entry", ",", "data", "=", "{", "*", "*", "entry", ".", "data", ",", "CONF_REFRESH_TOKEN", ":", "req", ".", "refresh_token", "}", ")", "_LOGGER", ".", "debug", "(", "\"Updated config entry '%s' for SmartApp '%s' under parent app '%s'\"", ",", "entry", ".", "entry_id", ",", "req", ".", "installed_app_id", ",", "app", ".", "app_id", ",", ")", "await", "_continue_flow", "(", "hass", ",", "app", ".", "app_id", ",", "req", ".", "location_id", ",", "req", ".", "installed_app_id", ",", "req", ".", "refresh_token", ")", "_LOGGER", ".", "debug", "(", "\"Updated SmartApp '%s' under parent app '%s'\"", ",", "req", ".", "installed_app_id", ",", "app", ".", "app_id", ")" ]
[ 443, 0 ]
[ 469, 5 ]
python
en
['en', 'en', 'en']
True
smartapp_uninstall
(hass: HomeAssistantType, req, resp, app)
Handle when a SmartApp is removed from a location by the user. Find and delete the config entry representing the integration.
Handle when a SmartApp is removed from a location by the user.
async def smartapp_uninstall(hass: HomeAssistantType, req, resp, app): """ Handle when a SmartApp is removed from a location by the user. Find and delete the config entry representing the integration. """ entry = next( ( entry for entry in hass.config_entries.async_entries(DOMAIN) if entry.data.get(CONF_INSTALLED_APP_ID) == req.installed_app_id ), None, ) if entry: # Add as job not needed because the current coroutine was invoked # from the dispatcher and is not being awaited. await hass.config_entries.async_remove(entry.entry_id) _LOGGER.debug( "Uninstalled SmartApp '%s' under parent app '%s'", req.installed_app_id, app.app_id, )
[ "async", "def", "smartapp_uninstall", "(", "hass", ":", "HomeAssistantType", ",", "req", ",", "resp", ",", "app", ")", ":", "entry", "=", "next", "(", "(", "entry", "for", "entry", "in", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", "if", "entry", ".", "data", ".", "get", "(", "CONF_INSTALLED_APP_ID", ")", "==", "req", ".", "installed_app_id", ")", ",", "None", ",", ")", "if", "entry", ":", "# Add as job not needed because the current coroutine was invoked", "# from the dispatcher and is not being awaited.", "await", "hass", ".", "config_entries", ".", "async_remove", "(", "entry", ".", "entry_id", ")", "_LOGGER", ".", "debug", "(", "\"Uninstalled SmartApp '%s' under parent app '%s'\"", ",", "req", ".", "installed_app_id", ",", "app", ".", "app_id", ",", ")" ]
[ 472, 0 ]
[ 495, 5 ]
python
en
['en', 'error', 'th']
False
smartapp_webhook
(hass: HomeAssistantType, webhook_id: str, request)
Handle a smartapp lifecycle event callback from SmartThings. Requests from SmartThings are digitally signed and the SmartAppManager validates the signature for authenticity.
Handle a smartapp lifecycle event callback from SmartThings.
async def smartapp_webhook(hass: HomeAssistantType, webhook_id: str, request): """ Handle a smartapp lifecycle event callback from SmartThings. Requests from SmartThings are digitally signed and the SmartAppManager validates the signature for authenticity. """ manager = hass.data[DOMAIN][DATA_MANAGER] data = await request.json() result = await manager.handle_request(data, request.headers) return web.json_response(result)
[ "async", "def", "smartapp_webhook", "(", "hass", ":", "HomeAssistantType", ",", "webhook_id", ":", "str", ",", "request", ")", ":", "manager", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_MANAGER", "]", "data", "=", "await", "request", ".", "json", "(", ")", "result", "=", "await", "manager", ".", "handle_request", "(", "data", ",", "request", ".", "headers", ")", "return", "web", ".", "json_response", "(", "result", ")" ]
[ 498, 0 ]
[ 508, 36 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.__init__
(self, root, fileids=PKL_PATTERN, **kwargs)
Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor.
Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor.
def __init__(self, root, fileids=PKL_PATTERN, **kwargs): """ Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``) are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the ``CorpusReader`` constructor. """ # Add the default category pattern if not passed into the class. if not any(key.startswith('cat_') for key in kwargs.keys()): kwargs['cat_pattern'] = CAT_PATTERN CategorizedCorpusReader.__init__(self, kwargs) CorpusReader.__init__(self, root, fileids) self._word_tokenizer = WordPunctTokenizer() self._sent_tokenizer = nltk.data.LazyLoader( 'tokenizers/punkt/english.pickle')
[ "def", "__init__", "(", "self", ",", "root", ",", "fileids", "=", "PKL_PATTERN", ",", "*", "*", "kwargs", ")", ":", "# Add the default category pattern if not passed into the class.", "if", "not", "any", "(", "key", ".", "startswith", "(", "'cat_'", ")", "for", "key", "in", "kwargs", ".", "keys", "(", ")", ")", ":", "kwargs", "[", "'cat_pattern'", "]", "=", "CAT_PATTERN", "CategorizedCorpusReader", ".", "__init__", "(", "self", ",", "kwargs", ")", "CorpusReader", ".", "__init__", "(", "self", ",", "root", ",", "fileids", ")", "self", ".", "_word_tokenizer", "=", "WordPunctTokenizer", "(", ")", "self", ".", "_sent_tokenizer", "=", "nltk", ".", "data", ".", "LazyLoader", "(", "'tokenizers/punkt/english.pickle'", ")" ]
[ 18, 4 ]
[ 34, 46 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader._resolve
(self, fileids, categories)
Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. This primarily bubbles up to the high level ``docs`` method, but is implemented here similar to the nltk ``CategorizedPlaintextCorpusReader``.
Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. This primarily bubbles up to the high level ``docs`` method, but is implemented here similar to the nltk ``CategorizedPlaintextCorpusReader``.
def _resolve(self, fileids, categories): """ Returns a list of fileids or categories depending on what is passed to each internal corpus reader function. This primarily bubbles up to the high level ``docs`` method, but is implemented here similar to the nltk ``CategorizedPlaintextCorpusReader``. """ if fileids is not None and categories is not None: raise ValueError("Specify fileids or categories, not both") if categories is not None: return self.fileids(categories) return fileids
[ "def", "_resolve", "(", "self", ",", "fileids", ",", "categories", ")", ":", "if", "fileids", "is", "not", "None", "and", "categories", "is", "not", "None", ":", "raise", "ValueError", "(", "\"Specify fileids or categories, not both\"", ")", "if", "categories", "is", "not", "None", ":", "return", "self", ".", "fileids", "(", "categories", ")", "return", "fileids" ]
[ 36, 4 ]
[ 48, 22 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.docs
(self, fileids=None, categories=None)
Returns the document loaded from a pickled object for every file in the corpus. Similar to the BaleenCorpusReader, this uses a generator to acheive memory safe iteration.
Returns the document loaded from a pickled object for every file in the corpus. Similar to the BaleenCorpusReader, this uses a generator to acheive memory safe iteration.
def docs(self, fileids=None, categories=None): """ Returns the document loaded from a pickled object for every file in the corpus. Similar to the BaleenCorpusReader, this uses a generator to acheive memory safe iteration. """ # Resolve the fileids and the categories fileids = self._resolve(fileids, categories) # Create a generator, loading one document into memory at a time. for path, enc, fileid in self.abspaths(fileids, True, True): with open(path, 'rb') as f: yield pickle.load(f)
[ "def", "docs", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "# Resolve the fileids and the categories", "fileids", "=", "self", ".", "_resolve", "(", "fileids", ",", "categories", ")", "# Create a generator, loading one document into memory at a time.", "for", "path", ",", "enc", ",", "fileid", "in", "self", ".", "abspaths", "(", "fileids", ",", "True", ",", "True", ")", ":", "with", "open", "(", "path", ",", "'rb'", ")", "as", "f", ":", "yield", "pickle", ".", "load", "(", "f", ")" ]
[ 54, 4 ]
[ 66, 36 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.paras
(self, fileids=None, categories=None)
Returns a generator of paragraphs where each paragraph is a list of sentences, which is in turn a list of (token, tag) tuples.
Returns a generator of paragraphs where each paragraph is a list of sentences, which is in turn a list of (token, tag) tuples.
def paras(self, fileids=None, categories=None): """ Returns a generator of paragraphs where each paragraph is a list of sentences, which is in turn a list of (token, tag) tuples. """ for doc in self.docs(fileids, categories): for paragraph in doc: yield paragraph
[ "def", "paras", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "doc", "in", "self", ".", "docs", "(", "fileids", ",", "categories", ")", ":", "for", "paragraph", "in", "doc", ":", "yield", "paragraph" ]
[ 68, 4 ]
[ 75, 31 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.sents
(self, fileids=None, categories=None)
Returns a generator of sentences where each sentence is a list of (token, tag) tuples.
Returns a generator of sentences where each sentence is a list of (token, tag) tuples.
def sents(self, fileids=None, categories=None): """ Returns a generator of sentences where each sentence is a list of (token, tag) tuples. """ for paragraph in self.paras(fileids, categories): for sentence in paragraph: yield sentence
[ "def", "sents", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "paragraph", "in", "self", ".", "paras", "(", "fileids", ",", "categories", ")", ":", "for", "sentence", "in", "paragraph", ":", "yield", "sentence" ]
[ 77, 4 ]
[ 84, 30 ]
python
en
['en', 'error', 'th']
False
PickledCorpusReader.words
(self, fileids=None, categories=None)
Returns a generator of (token, tag) tuples.
Returns a generator of (token, tag) tuples.
def words(self, fileids=None, categories=None): """ Returns a generator of (token, tag) tuples. """ for token in self.tagged(fileids, categories): yield token[0]
[ "def", "words", "(", "self", ",", "fileids", "=", "None", ",", "categories", "=", "None", ")", ":", "for", "token", "in", "self", ".", "tagged", "(", "fileids", ",", "categories", ")", ":", "yield", "token", "[", "0", "]" ]
[ 91, 4 ]
[ 96, 26 ]
python
en
['en', 'error', 'th']
False
test_show_user_form
(hass: HomeAssistant)
Test that the user set up form is served.
Test that the user set up form is served.
async def test_show_user_form(hass: HomeAssistant) -> None: """Test that the user set up form is served.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, ) assert result["step_id"] == "user" assert result["type"] == RESULT_TYPE_FORM
[ "async", "def", "test_show_user_form", "(", "hass", ":", "HomeAssistant", ")", "->", "None", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", ")", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM" ]
[ 23, 0 ]
[ 31, 45 ]
python
en
['en', 'en', 'en']
True
test_show_zeroconf_form
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test that the zeroconf confirmation form is served.
Test that the zeroconf confirmation form is served.
async def test_show_zeroconf_form( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test that the zeroconf confirmation form is served.""" mock_connection(aioclient_mock) discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info, ) assert result["step_id"] == "zeroconf_confirm" assert result["type"] == RESULT_TYPE_FORM assert result["description_placeholders"] == {CONF_NAME: "EPSON XP-6000 Series"}
[ "async", "def", "test_show_zeroconf_form", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ")", "discovery_info", "=", "MOCK_ZEROCONF_IPP_SERVICE_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_ZEROCONF", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"step_id\"", "]", "==", "\"zeroconf_confirm\"", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM", "assert", "result", "[", "\"description_placeholders\"", "]", "==", "{", "CONF_NAME", ":", "\"EPSON XP-6000 Series\"", "}" ]
[ 34, 0 ]
[ 49, 84 ]
python
en
['en', 'en', 'en']
True
test_connection_error
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we show user form on IPP connection error.
Test we show user form on IPP connection error.
async def test_connection_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we show user form on IPP connection error.""" mock_connection(aioclient_mock, conn_error=True) user_input = MOCK_USER_INPUT.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=user_input, ) assert result["step_id"] == "user" assert result["type"] == RESULT_TYPE_FORM assert result["errors"] == {"base": "cannot_connect"}
[ "async", "def", "test_connection_error", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "conn_error", "=", "True", ")", "user_input", "=", "MOCK_USER_INPUT", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", "data", "=", "user_input", ",", ")", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM", "assert", "result", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"cannot_connect\"", "}" ]
[ 52, 0 ]
[ 67, 57 ]
python
en
['en', 'en', 'en']
True
test_zeroconf_connection_error
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we abort zeroconf flow on IPP connection error.
Test we abort zeroconf flow on IPP connection error.
async def test_zeroconf_connection_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort zeroconf flow on IPP connection error.""" mock_connection(aioclient_mock, conn_error=True) discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "cannot_connect"
[ "async", "def", "test_zeroconf_connection_error", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "conn_error", "=", "True", ")", "discovery_info", "=", "MOCK_ZEROCONF_IPP_SERVICE_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_ZEROCONF", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"cannot_connect\"" ]
[ 70, 0 ]
[ 84, 47 ]
python
en
['en', 'de', 'en']
True
test_zeroconf_confirm_connection_error
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we abort zeroconf flow on IPP connection error.
Test we abort zeroconf flow on IPP connection error.
async def test_zeroconf_confirm_connection_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort zeroconf flow on IPP connection error.""" mock_connection(aioclient_mock, conn_error=True) discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "cannot_connect"
[ "async", "def", "test_zeroconf_confirm_connection_error", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "conn_error", "=", "True", ")", "discovery_info", "=", "MOCK_ZEROCONF_IPP_SERVICE_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_ZEROCONF", "}", ",", "data", "=", "discovery_info", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"cannot_connect\"" ]
[ 87, 0 ]
[ 99, 47 ]
python
en
['en', 'de', 'en']
True
test_user_connection_upgrade_required
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we show the user form if connection upgrade required by server.
Test we show the user form if connection upgrade required by server.
async def test_user_connection_upgrade_required( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we show the user form if connection upgrade required by server.""" mock_connection(aioclient_mock, conn_upgrade_error=True) user_input = MOCK_USER_INPUT.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=user_input, ) assert result["step_id"] == "user" assert result["type"] == RESULT_TYPE_FORM assert result["errors"] == {"base": "connection_upgrade"}
[ "async", "def", "test_user_connection_upgrade_required", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "conn_upgrade_error", "=", "True", ")", "user_input", "=", "MOCK_USER_INPUT", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", "data", "=", "user_input", ",", ")", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_FORM", "assert", "result", "[", "\"errors\"", "]", "==", "{", "\"base\"", ":", "\"connection_upgrade\"", "}" ]
[ 102, 0 ]
[ 117, 61 ]
python
en
['en', 'en', 'en']
True
test_zeroconf_connection_upgrade_required
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we abort zeroconf flow on IPP connection error.
Test we abort zeroconf flow on IPP connection error.
async def test_zeroconf_connection_upgrade_required( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort zeroconf flow on IPP connection error.""" mock_connection(aioclient_mock, conn_upgrade_error=True) discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "connection_upgrade"
[ "async", "def", "test_zeroconf_connection_upgrade_required", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "conn_upgrade_error", "=", "True", ")", "discovery_info", "=", "MOCK_ZEROCONF_IPP_SERVICE_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_ZEROCONF", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"connection_upgrade\"" ]
[ 120, 0 ]
[ 134, 51 ]
python
en
['en', 'de', 'en']
True
test_user_parse_error
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we abort user flow on IPP parse error.
Test we abort user flow on IPP parse error.
async def test_user_parse_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort user flow on IPP parse error.""" mock_connection(aioclient_mock, parse_error=True) user_input = MOCK_USER_INPUT.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=user_input, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "parse_error"
[ "async", "def", "test_user_parse_error", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "parse_error", "=", "True", ")", "user_input", "=", "MOCK_USER_INPUT", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", "data", "=", "user_input", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"parse_error\"" ]
[ 137, 0 ]
[ 151, 44 ]
python
en
['en', 'de', 'en']
True
test_zeroconf_parse_error
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we abort zeroconf flow on IPP parse error.
Test we abort zeroconf flow on IPP parse error.
async def test_zeroconf_parse_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort zeroconf flow on IPP parse error.""" mock_connection(aioclient_mock, parse_error=True) discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "parse_error"
[ "async", "def", "test_zeroconf_parse_error", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "parse_error", "=", "True", ")", "discovery_info", "=", "MOCK_ZEROCONF_IPP_SERVICE_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_ZEROCONF", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"parse_error\"" ]
[ 154, 0 ]
[ 168, 44 ]
python
de
['de', 'de', 'en']
True
test_user_ipp_error
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we abort the user flow on IPP error.
Test we abort the user flow on IPP error.
async def test_user_ipp_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort the user flow on IPP error.""" mock_connection(aioclient_mock, ipp_error=True) user_input = MOCK_USER_INPUT.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=user_input, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "ipp_error"
[ "async", "def", "test_user_ipp_error", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "ipp_error", "=", "True", ")", "user_input", "=", "MOCK_USER_INPUT", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ",", "data", "=", "user_input", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"ipp_error\"" ]
[ 171, 0 ]
[ 185, 42 ]
python
en
['en', 'nl', 'en']
True
test_zeroconf_ipp_error
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker )
Test we abort zeroconf flow on IPP error.
Test we abort zeroconf flow on IPP error.
async def test_zeroconf_ipp_error( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker ) -> None: """Test we abort zeroconf flow on IPP error.""" mock_connection(aioclient_mock, ipp_error=True) discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info, ) assert result["type"] == RESULT_TYPE_ABORT assert result["reason"] == "ipp_error"
[ "async", "def", "test_zeroconf_ipp_error", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ")", "->", "None", ":", "mock_connection", "(", "aioclient_mock", ",", "ipp_error", "=", "True", ")", "discovery_info", "=", "MOCK_ZEROCONF_IPP_SERVICE_INFO", ".", "copy", "(", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_ZEROCONF", "}", ",", "data", "=", "discovery_info", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "RESULT_TYPE_ABORT", "assert", "result", "[", "\"reason\"", "]", "==", "\"ipp_error\"" ]
[ 188, 0 ]
[ 202, 42 ]
python
en
['en', 'nl', 'en']
True