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
is_speaking
()
Determine if Text to Speech is occurring Returns: bool: True while still speaking
Determine if Text to Speech is occurring
def is_speaking(): """Determine if Text to Speech is occurring Returns: bool: True while still speaking """ return check_for_signal("isSpeaking", -1, CONFIG)
[ "def", "is_speaking", "(", ")", ":", "return", "check_for_signal", "(", "\"isSpeaking\"", ",", "-", "1", ",", "CONFIG", ")" ]
[ 30, 0 ]
[ 36, 53 ]
python
en
['en', 'en', 'en']
True
wait_while_speaking
()
Pause as long as Text to Speech is still happening Pause while Text to Speech is still happening. This always pauses briefly to ensure that any preceeding request to speak has time to begin.
Pause as long as Text to Speech is still happening
def wait_while_speaking(): """Pause as long as Text to Speech is still happening Pause while Text to Speech is still happening. This always pauses briefly to ensure that any preceeding request to speak has time to begin. """ # TODO: Better method using messages or signals here DM time.sleep(0.3) # Wait briefly in for any queued speech to begin while is_speaking(): time.sleep(0.1)
[ "def", "wait_while_speaking", "(", ")", ":", "# TODO: Better method using messages or signals here DM", "time", ".", "sleep", "(", "0.3", ")", "# Wait briefly in for any queued speech to begin", "while", "is_speaking", "(", ")", ":", "time", ".", "sleep", "(", "0.1", ")" ]
[ 39, 0 ]
[ 49, 23 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Social Blade sensor.
Set up the Social Blade sensor.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Social Blade sensor.""" social_blade = SocialBladeSensor(config[CHANNEL_ID], config[CONF_NAME]) social_blade.update() if social_blade.valid_channel_id is False: return add_entities([social_blade])
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "social_blade", "=", "SocialBladeSensor", "(", "config", "[", "CHANNEL_ID", "]", ",", "config", "[", "CONF_NAME", "]", ")", "social_blade", ".", "update", "(", ")", "if", "social_blade", ".", "valid_channel_id", "is", "False", ":", "return", "add_entities", "(", "[", "social_blade", "]", ")" ]
[ 33, 0 ]
[ 41, 32 ]
python
en
['en', 'pt', 'en']
True
SocialBladeSensor.__init__
(self, case, name)
Initialize the Social Blade sensor.
Initialize the Social Blade sensor.
def __init__(self, case, name): """Initialize the Social Blade sensor.""" self._state = None self.channel_id = case self._attributes = None self.valid_channel_id = None self._name = name
[ "def", "__init__", "(", "self", ",", "case", ",", "name", ")", ":", "self", ".", "_state", "=", "None", "self", ".", "channel_id", "=", "case", "self", ".", "_attributes", "=", "None", "self", ".", "valid_channel_id", "=", "None", "self", ".", "_name", "=", "name" ]
[ 47, 4 ]
[ 53, 25 ]
python
en
['en', 'pt', 'en']
True
SocialBladeSensor.name
(self)
Return the name.
Return the name.
def name(self): """Return the name.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 56, 4 ]
[ 58, 25 ]
python
en
['en', 'ig', 'en']
True
SocialBladeSensor.state
(self)
Return the state.
Return the state.
def state(self): """Return the state.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 61, 4 ]
[ 63, 26 ]
python
en
['en', 'en', 'en']
True
SocialBladeSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" if self._attributes: return self._attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "if", "self", ".", "_attributes", ":", "return", "self", ".", "_attributes" ]
[ 66, 4 ]
[ 69, 35 ]
python
en
['en', 'en', 'en']
True
SocialBladeSensor.update
(self)
Get the latest data from Social Blade.
Get the latest data from Social Blade.
def update(self): """Get the latest data from Social Blade.""" try: data = socialbladeclient.get_data(self.channel_id) self._attributes = {TOTAL_VIEWS: data[TOTAL_VIEWS]} self._state = data[SUBSCRIBERS] self.valid_channel_id = True except (ValueError, IndexError): _LOGGER.error("Unable to find valid channel ID") self.valid_channel_id = False self._attributes = None
[ "def", "update", "(", "self", ")", ":", "try", ":", "data", "=", "socialbladeclient", ".", "get_data", "(", "self", ".", "channel_id", ")", "self", ".", "_attributes", "=", "{", "TOTAL_VIEWS", ":", "data", "[", "TOTAL_VIEWS", "]", "}", "self", ".", "_state", "=", "data", "[", "SUBSCRIBERS", "]", "self", ".", "valid_channel_id", "=", "True", "except", "(", "ValueError", ",", "IndexError", ")", ":", "_LOGGER", ".", "error", "(", "\"Unable to find valid channel ID\"", ")", "self", ".", "valid_channel_id", "=", "False", "self", ".", "_attributes", "=", "None" ]
[ 72, 4 ]
[ 84, 35 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, entry, async_add_entities)
Set up the GeoNet NZ Volcano Feed platform.
Set up the GeoNet NZ Volcano Feed platform.
async def async_setup_entry(hass, entry, async_add_entities): """Set up the GeoNet NZ Volcano Feed platform.""" manager = hass.data[DOMAIN][FEED][entry.entry_id] @callback def async_add_sensor(feed_manager, external_id, unit_system): """Add sensor entity from feed.""" new_entity = GeonetnzVolcanoSensor( entry.entry_id, feed_manager, external_id, unit_system ) _LOGGER.debug("Adding sensor %s", new_entity) async_add_entities([new_entity], True) manager.listeners.append( async_dispatcher_connect( hass, manager.async_event_new_entity(), async_add_sensor ) ) hass.async_create_task(manager.async_update()) _LOGGER.debug("Sensor setup done")
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ",", "async_add_entities", ")", ":", "manager", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "FEED", "]", "[", "entry", ".", "entry_id", "]", "@", "callback", "def", "async_add_sensor", "(", "feed_manager", ",", "external_id", ",", "unit_system", ")", ":", "\"\"\"Add sensor entity from feed.\"\"\"", "new_entity", "=", "GeonetnzVolcanoSensor", "(", "entry", ".", "entry_id", ",", "feed_manager", ",", "external_id", ",", "unit_system", ")", "_LOGGER", ".", "debug", "(", "\"Adding sensor %s\"", ",", "new_entity", ")", "async_add_entities", "(", "[", "new_entity", "]", ",", "True", ")", "manager", ".", "listeners", ".", "append", "(", "async_dispatcher_connect", "(", "hass", ",", "manager", ".", "async_event_new_entity", "(", ")", ",", "async_add_sensor", ")", ")", "hass", ".", "async_create_task", "(", "manager", ".", "async_update", "(", ")", ")", "_LOGGER", ".", "debug", "(", "\"Sensor setup done\"", ")" ]
[ 33, 0 ]
[ 52, 38 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor.__init__
(self, config_entry_id, feed_manager, external_id, unit_system)
Initialize entity with data from feed entry.
Initialize entity with data from feed entry.
def __init__(self, config_entry_id, feed_manager, external_id, unit_system): """Initialize entity with data from feed entry.""" self._config_entry_id = config_entry_id self._feed_manager = feed_manager self._external_id = external_id self._unit_system = unit_system self._title = None self._distance = None self._latitude = None self._longitude = None self._attribution = None self._alert_level = None self._activity = None self._hazards = None self._feed_last_update = None self._feed_last_update_successful = None self._remove_signal_update = None
[ "def", "__init__", "(", "self", ",", "config_entry_id", ",", "feed_manager", ",", "external_id", ",", "unit_system", ")", ":", "self", ".", "_config_entry_id", "=", "config_entry_id", "self", ".", "_feed_manager", "=", "feed_manager", "self", ".", "_external_id", "=", "external_id", "self", ".", "_unit_system", "=", "unit_system", "self", ".", "_title", "=", "None", "self", ".", "_distance", "=", "None", "self", ".", "_latitude", "=", "None", "self", ".", "_longitude", "=", "None", "self", ".", "_attribution", "=", "None", "self", ".", "_alert_level", "=", "None", "self", ".", "_activity", "=", "None", "self", ".", "_hazards", "=", "None", "self", ".", "_feed_last_update", "=", "None", "self", ".", "_feed_last_update_successful", "=", "None", "self", ".", "_remove_signal_update", "=", "None" ]
[ 58, 4 ]
[ 74, 41 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor.async_added_to_hass
(self)
Call when entity is added to hass.
Call when entity is added to hass.
async def async_added_to_hass(self): """Call when entity is added to hass.""" self._remove_signal_update = async_dispatcher_connect( self.hass, f"geonetnz_volcano_update_{self._external_id}", self._update_callback, )
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "self", ".", "_remove_signal_update", "=", "async_dispatcher_connect", "(", "self", ".", "hass", ",", "f\"geonetnz_volcano_update_{self._external_id}\"", ",", "self", ".", "_update_callback", ",", ")" ]
[ 76, 4 ]
[ 82, 9 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor.async_will_remove_from_hass
(self)
Call when entity will be removed from hass.
Call when entity will be removed from hass.
async def async_will_remove_from_hass(self) -> None: """Call when entity will be removed from hass.""" if self._remove_signal_update: self._remove_signal_update()
[ "async", "def", "async_will_remove_from_hass", "(", "self", ")", "->", "None", ":", "if", "self", ".", "_remove_signal_update", ":", "self", ".", "_remove_signal_update", "(", ")" ]
[ 84, 4 ]
[ 87, 40 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor._update_callback
(self)
Call update method.
Call update method.
def _update_callback(self): """Call update method.""" self.async_schedule_update_ha_state(True)
[ "def", "_update_callback", "(", "self", ")", ":", "self", ".", "async_schedule_update_ha_state", "(", "True", ")" ]
[ 90, 4 ]
[ 92, 49 ]
python
en
['en', 'sn', 'en']
True
GeonetnzVolcanoSensor.should_poll
(self)
No polling needed for GeoNet NZ Volcano feed location events.
No polling needed for GeoNet NZ Volcano feed location events.
def should_poll(self): """No polling needed for GeoNet NZ Volcano feed location events.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 95, 4 ]
[ 97, 20 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor.async_update
(self)
Update this entity from the data held in the feed manager.
Update this entity from the data held in the feed manager.
async def async_update(self): """Update this entity from the data held in the feed manager.""" _LOGGER.debug("Updating %s", self._external_id) feed_entry = self._feed_manager.get_entry(self._external_id) last_update = self._feed_manager.last_update() last_update_successful = self._feed_manager.last_update_successful() if feed_entry: self._update_from_feed(feed_entry, last_update, last_update_successful)
[ "async", "def", "async_update", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Updating %s\"", ",", "self", ".", "_external_id", ")", "feed_entry", "=", "self", ".", "_feed_manager", ".", "get_entry", "(", "self", ".", "_external_id", ")", "last_update", "=", "self", ".", "_feed_manager", ".", "last_update", "(", ")", "last_update_successful", "=", "self", ".", "_feed_manager", ".", "last_update_successful", "(", ")", "if", "feed_entry", ":", "self", ".", "_update_from_feed", "(", "feed_entry", ",", "last_update", ",", "last_update_successful", ")" ]
[ 99, 4 ]
[ 106, 83 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor._update_from_feed
(self, feed_entry, last_update, last_update_successful)
Update the internal state from the provided feed entry.
Update the internal state from the provided feed entry.
def _update_from_feed(self, feed_entry, last_update, last_update_successful): """Update the internal state from the provided feed entry.""" self._title = feed_entry.title # Convert distance if not metric system. if self._unit_system == CONF_UNIT_SYSTEM_IMPERIAL: self._distance = round( IMPERIAL_SYSTEM.length(feed_entry.distance_to_home, LENGTH_KILOMETERS), 1, ) else: self._distance = round(feed_entry.distance_to_home, 1) self._latitude = round(feed_entry.coordinates[0], 5) self._longitude = round(feed_entry.coordinates[1], 5) self._attribution = feed_entry.attribution self._alert_level = feed_entry.alert_level self._activity = feed_entry.activity self._hazards = feed_entry.hazards self._feed_last_update = dt.as_utc(last_update) if last_update else None self._feed_last_update_successful = ( dt.as_utc(last_update_successful) if last_update_successful else None )
[ "def", "_update_from_feed", "(", "self", ",", "feed_entry", ",", "last_update", ",", "last_update_successful", ")", ":", "self", ".", "_title", "=", "feed_entry", ".", "title", "# Convert distance if not metric system.", "if", "self", ".", "_unit_system", "==", "CONF_UNIT_SYSTEM_IMPERIAL", ":", "self", ".", "_distance", "=", "round", "(", "IMPERIAL_SYSTEM", ".", "length", "(", "feed_entry", ".", "distance_to_home", ",", "LENGTH_KILOMETERS", ")", ",", "1", ",", ")", "else", ":", "self", ".", "_distance", "=", "round", "(", "feed_entry", ".", "distance_to_home", ",", "1", ")", "self", ".", "_latitude", "=", "round", "(", "feed_entry", ".", "coordinates", "[", "0", "]", ",", "5", ")", "self", ".", "_longitude", "=", "round", "(", "feed_entry", ".", "coordinates", "[", "1", "]", ",", "5", ")", "self", ".", "_attribution", "=", "feed_entry", ".", "attribution", "self", ".", "_alert_level", "=", "feed_entry", ".", "alert_level", "self", ".", "_activity", "=", "feed_entry", ".", "activity", "self", ".", "_hazards", "=", "feed_entry", ".", "hazards", "self", ".", "_feed_last_update", "=", "dt", ".", "as_utc", "(", "last_update", ")", "if", "last_update", "else", "None", "self", ".", "_feed_last_update_successful", "=", "(", "dt", ".", "as_utc", "(", "last_update_successful", ")", "if", "last_update_successful", "else", "None", ")" ]
[ 108, 4 ]
[ 128, 9 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._alert_level
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_alert_level" ]
[ 131, 4 ]
[ 133, 32 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor.icon
(self)
Return the icon to use in the frontend, if any.
Return the icon to use in the frontend, if any.
def icon(self): """Return the icon to use in the frontend, if any.""" return DEFAULT_ICON
[ "def", "icon", "(", "self", ")", ":", "return", "DEFAULT_ICON" ]
[ 136, 4 ]
[ 138, 27 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor.name
(self)
Return the name of the entity.
Return the name of the entity.
def name(self) -> Optional[str]: """Return the name of the entity.""" return f"Volcano {self._title}"
[ "def", "name", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "return", "f\"Volcano {self._title}\"" ]
[ 141, 4 ]
[ 143, 39 ]
python
en
['en', 'en', 'en']
True
GeonetnzVolcanoSensor.unit_of_measurement
(self)
Return the unit of measurement.
Return the unit of measurement.
def unit_of_measurement(self): """Return the unit of measurement.""" return "alert level"
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "\"alert level\"" ]
[ 146, 4 ]
[ 148, 28 ]
python
en
['en', 'la', 'en']
True
GeonetnzVolcanoSensor.device_state_attributes
(self)
Return the device state attributes.
Return the device state attributes.
def device_state_attributes(self): """Return the device state attributes.""" attributes = {} for key, value in ( (ATTR_EXTERNAL_ID, self._external_id), (ATTR_ATTRIBUTION, self._attribution), (ATTR_ACTIVITY, self._activity), (ATTR_HAZARDS, self._hazards), (ATTR_LONGITUDE, self._longitude), (ATTR_LATITUDE, self._latitude), (ATTR_DISTANCE, self._distance), (ATTR_LAST_UPDATE, self._feed_last_update), (ATTR_LAST_UPDATE_SUCCESSFUL, self._feed_last_update_successful), ): if value or isinstance(value, bool): attributes[key] = value return attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "attributes", "=", "{", "}", "for", "key", ",", "value", "in", "(", "(", "ATTR_EXTERNAL_ID", ",", "self", ".", "_external_id", ")", ",", "(", "ATTR_ATTRIBUTION", ",", "self", ".", "_attribution", ")", ",", "(", "ATTR_ACTIVITY", ",", "self", ".", "_activity", ")", ",", "(", "ATTR_HAZARDS", ",", "self", ".", "_hazards", ")", ",", "(", "ATTR_LONGITUDE", ",", "self", ".", "_longitude", ")", ",", "(", "ATTR_LATITUDE", ",", "self", ".", "_latitude", ")", ",", "(", "ATTR_DISTANCE", ",", "self", ".", "_distance", ")", ",", "(", "ATTR_LAST_UPDATE", ",", "self", ".", "_feed_last_update", ")", ",", "(", "ATTR_LAST_UPDATE_SUCCESSFUL", ",", "self", ".", "_feed_last_update_successful", ")", ",", ")", ":", "if", "value", "or", "isinstance", "(", "value", ",", "bool", ")", ":", "attributes", "[", "key", "]", "=", "value", "return", "attributes" ]
[ 151, 4 ]
[ 167, 25 ]
python
en
['en', 'en', 'en']
True
run_sensor_test
( hass: HomeAssistant, vera_component_factory: ComponentFactory, category: int, class_property: str, assert_states: Tuple[Tuple[Any, Any]], assert_unit_of_measurement: str = None, setup_callback: Callable[[pv.VeraController], None] = None, )
Test generic sensor.
Test generic sensor.
async def run_sensor_test( hass: HomeAssistant, vera_component_factory: ComponentFactory, category: int, class_property: str, assert_states: Tuple[Tuple[Any, Any]], assert_unit_of_measurement: str = None, setup_callback: Callable[[pv.VeraController], None] = None, ) -> None: """Test generic sensor.""" vera_device = MagicMock(spec=pv.VeraSensor) # type: pv.VeraSensor vera_device.device_id = 1 vera_device.vera_device_id = vera_device.device_id vera_device.name = "dev1" vera_device.category = category setattr(vera_device, class_property, "33") entity_id = "sensor.dev1_1" component_data = await vera_component_factory.configure_component( hass=hass, controller_config=new_simple_controller_config( devices=(vera_device,), setup_callback=setup_callback ), ) update_callback = component_data.controller_data[0].update_callback for (initial_value, state_value) in assert_states: setattr(vera_device, class_property, initial_value) update_callback(vera_device) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state.state == state_value if assert_unit_of_measurement: assert ( state.attributes[ATTR_UNIT_OF_MEASUREMENT] == assert_unit_of_measurement )
[ "async", "def", "run_sensor_test", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ",", "category", ":", "int", ",", "class_property", ":", "str", ",", "assert_states", ":", "Tuple", "[", "Tuple", "[", "Any", ",", "Any", "]", "]", ",", "assert_unit_of_measurement", ":", "str", "=", "None", ",", "setup_callback", ":", "Callable", "[", "[", "pv", ".", "VeraController", "]", ",", "None", "]", "=", "None", ",", ")", "->", "None", ":", "vera_device", "=", "MagicMock", "(", "spec", "=", "pv", ".", "VeraSensor", ")", "# type: pv.VeraSensor", "vera_device", ".", "device_id", "=", "1", "vera_device", ".", "vera_device_id", "=", "vera_device", ".", "device_id", "vera_device", ".", "name", "=", "\"dev1\"", "vera_device", ".", "category", "=", "category", "setattr", "(", "vera_device", ",", "class_property", ",", "\"33\"", ")", "entity_id", "=", "\"sensor.dev1_1\"", "component_data", "=", "await", "vera_component_factory", ".", "configure_component", "(", "hass", "=", "hass", ",", "controller_config", "=", "new_simple_controller_config", "(", "devices", "=", "(", "vera_device", ",", ")", ",", "setup_callback", "=", "setup_callback", ")", ",", ")", "update_callback", "=", "component_data", ".", "controller_data", "[", "0", "]", ".", "update_callback", "for", "(", "initial_value", ",", "state_value", ")", "in", "assert_states", ":", "setattr", "(", "vera_device", ",", "class_property", ",", "initial_value", ")", "update_callback", "(", "vera_device", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "entity_id", ")", "assert", "state", ".", "state", "==", "state_value", "if", "assert_unit_of_measurement", ":", "assert", "(", "state", ".", "attributes", "[", "ATTR_UNIT_OF_MEASUREMENT", "]", "==", "assert_unit_of_measurement", ")" ]
[ 13, 0 ]
[ 48, 13 ]
python
en
['nl', 'id', 'en']
False
test_temperature_sensor_f
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_temperature_sensor_f( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" def setup_callback(controller: pv.VeraController) -> None: controller.temperature_units = "F" await run_sensor_test( hass=hass, vera_component_factory=vera_component_factory, category=pv.CATEGORY_TEMPERATURE_SENSOR, class_property="temperature", assert_states=(("33", "1"), ("44", "7")), setup_callback=setup_callback, )
[ "async", "def", "test_temperature_sensor_f", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "def", "setup_callback", "(", "controller", ":", "pv", ".", "VeraController", ")", "->", "None", ":", "controller", ".", "temperature_units", "=", "\"F\"", "await", "run_sensor_test", "(", "hass", "=", "hass", ",", "vera_component_factory", "=", "vera_component_factory", ",", "category", "=", "pv", ".", "CATEGORY_TEMPERATURE_SENSOR", ",", "class_property", "=", "\"temperature\"", ",", "assert_states", "=", "(", "(", "\"33\"", ",", "\"1\"", ")", ",", "(", "\"44\"", ",", "\"7\"", ")", ")", ",", "setup_callback", "=", "setup_callback", ",", ")" ]
[ 51, 0 ]
[ 66, 5 ]
python
en
['en', 'en', 'en']
False
test_temperature_sensor_c
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_temperature_sensor_c( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" await run_sensor_test( hass=hass, vera_component_factory=vera_component_factory, category=pv.CATEGORY_TEMPERATURE_SENSOR, class_property="temperature", assert_states=(("33", "33"), ("44", "44")), )
[ "async", "def", "test_temperature_sensor_c", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "await", "run_sensor_test", "(", "hass", "=", "hass", ",", "vera_component_factory", "=", "vera_component_factory", ",", "category", "=", "pv", ".", "CATEGORY_TEMPERATURE_SENSOR", ",", "class_property", "=", "\"temperature\"", ",", "assert_states", "=", "(", "(", "\"33\"", ",", "\"33\"", ")", ",", "(", "\"44\"", ",", "\"44\"", ")", ")", ",", ")" ]
[ 69, 0 ]
[ 79, 5 ]
python
en
['en', 'en', 'en']
False
test_light_sensor
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_light_sensor( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" await run_sensor_test( hass=hass, vera_component_factory=vera_component_factory, category=pv.CATEGORY_LIGHT_SENSOR, class_property="light", assert_states=(("12", "12"), ("13", "13")), assert_unit_of_measurement=LIGHT_LUX, )
[ "async", "def", "test_light_sensor", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "await", "run_sensor_test", "(", "hass", "=", "hass", ",", "vera_component_factory", "=", "vera_component_factory", ",", "category", "=", "pv", ".", "CATEGORY_LIGHT_SENSOR", ",", "class_property", "=", "\"light\"", ",", "assert_states", "=", "(", "(", "\"12\"", ",", "\"12\"", ")", ",", "(", "\"13\"", ",", "\"13\"", ")", ")", ",", "assert_unit_of_measurement", "=", "LIGHT_LUX", ",", ")" ]
[ 82, 0 ]
[ 93, 5 ]
python
en
['en', 'en', 'en']
False
test_uv_sensor
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_uv_sensor( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" await run_sensor_test( hass=hass, vera_component_factory=vera_component_factory, category=pv.CATEGORY_UV_SENSOR, class_property="light", assert_states=(("12", "12"), ("13", "13")), assert_unit_of_measurement="level", )
[ "async", "def", "test_uv_sensor", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "await", "run_sensor_test", "(", "hass", "=", "hass", ",", "vera_component_factory", "=", "vera_component_factory", ",", "category", "=", "pv", ".", "CATEGORY_UV_SENSOR", ",", "class_property", "=", "\"light\"", ",", "assert_states", "=", "(", "(", "\"12\"", ",", "\"12\"", ")", ",", "(", "\"13\"", ",", "\"13\"", ")", ")", ",", "assert_unit_of_measurement", "=", "\"level\"", ",", ")" ]
[ 96, 0 ]
[ 107, 5 ]
python
en
['en', 'en', 'en']
False
test_humidity_sensor
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_humidity_sensor( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" await run_sensor_test( hass=hass, vera_component_factory=vera_component_factory, category=pv.CATEGORY_HUMIDITY_SENSOR, class_property="humidity", assert_states=(("12", "12"), ("13", "13")), assert_unit_of_measurement=PERCENTAGE, )
[ "async", "def", "test_humidity_sensor", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "await", "run_sensor_test", "(", "hass", "=", "hass", ",", "vera_component_factory", "=", "vera_component_factory", ",", "category", "=", "pv", ".", "CATEGORY_HUMIDITY_SENSOR", ",", "class_property", "=", "\"humidity\"", ",", "assert_states", "=", "(", "(", "\"12\"", ",", "\"12\"", ")", ",", "(", "\"13\"", ",", "\"13\"", ")", ")", ",", "assert_unit_of_measurement", "=", "PERCENTAGE", ",", ")" ]
[ 110, 0 ]
[ 121, 5 ]
python
en
['en', 'en', 'en']
False
test_power_meter_sensor
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_power_meter_sensor( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" await run_sensor_test( hass=hass, vera_component_factory=vera_component_factory, category=pv.CATEGORY_POWER_METER, class_property="power", assert_states=(("12", "12"), ("13", "13")), assert_unit_of_measurement="watts", )
[ "async", "def", "test_power_meter_sensor", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "await", "run_sensor_test", "(", "hass", "=", "hass", ",", "vera_component_factory", "=", "vera_component_factory", ",", "category", "=", "pv", ".", "CATEGORY_POWER_METER", ",", "class_property", "=", "\"power\"", ",", "assert_states", "=", "(", "(", "\"12\"", ",", "\"12\"", ")", ",", "(", "\"13\"", ",", "\"13\"", ")", ")", ",", "assert_unit_of_measurement", "=", "\"watts\"", ",", ")" ]
[ 124, 0 ]
[ 135, 5 ]
python
en
['en', 'en', 'en']
False
test_trippable_sensor
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_trippable_sensor( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" def setup_callback(controller: pv.VeraController) -> None: controller.get_devices()[0].is_trippable = True await run_sensor_test( hass=hass, vera_component_factory=vera_component_factory, category=999, class_property="is_tripped", assert_states=((True, "Tripped"), (False, "Not Tripped"), (True, "Tripped")), setup_callback=setup_callback, )
[ "async", "def", "test_trippable_sensor", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "def", "setup_callback", "(", "controller", ":", "pv", ".", "VeraController", ")", "->", "None", ":", "controller", ".", "get_devices", "(", ")", "[", "0", "]", ".", "is_trippable", "=", "True", "await", "run_sensor_test", "(", "hass", "=", "hass", ",", "vera_component_factory", "=", "vera_component_factory", ",", "category", "=", "999", ",", "class_property", "=", "\"is_tripped\"", ",", "assert_states", "=", "(", "(", "True", ",", "\"Tripped\"", ")", ",", "(", "False", ",", "\"Not Tripped\"", ")", ",", "(", "True", ",", "\"Tripped\"", ")", ")", ",", "setup_callback", "=", "setup_callback", ",", ")" ]
[ 138, 0 ]
[ 153, 5 ]
python
en
['en', 'en', 'en']
False
test_unknown_sensor
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_unknown_sensor( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" def setup_callback(controller: pv.VeraController) -> None: controller.get_devices()[0].is_trippable = False await run_sensor_test( hass=hass, vera_component_factory=vera_component_factory, category=999, class_property="is_tripped", assert_states=((True, "Unknown"), (False, "Unknown"), (True, "Unknown")), setup_callback=setup_callback, )
[ "async", "def", "test_unknown_sensor", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "def", "setup_callback", "(", "controller", ":", "pv", ".", "VeraController", ")", "->", "None", ":", "controller", ".", "get_devices", "(", ")", "[", "0", "]", ".", "is_trippable", "=", "False", "await", "run_sensor_test", "(", "hass", "=", "hass", ",", "vera_component_factory", "=", "vera_component_factory", ",", "category", "=", "999", ",", "class_property", "=", "\"is_tripped\"", ",", "assert_states", "=", "(", "(", "True", ",", "\"Unknown\"", ")", ",", "(", "False", ",", "\"Unknown\"", ")", ",", "(", "True", ",", "\"Unknown\"", ")", ")", ",", "setup_callback", "=", "setup_callback", ",", ")" ]
[ 156, 0 ]
[ 171, 5 ]
python
en
['en', 'en', 'en']
False
test_scene_controller_sensor
( hass: HomeAssistant, vera_component_factory: ComponentFactory )
Test function.
Test function.
async def test_scene_controller_sensor( hass: HomeAssistant, vera_component_factory: ComponentFactory ) -> None: """Test function.""" vera_device = MagicMock(spec=pv.VeraSensor) # type: pv.VeraSensor vera_device.device_id = 1 vera_device.vera_device_id = vera_device.device_id vera_device.name = "dev1" vera_device.category = pv.CATEGORY_SCENE_CONTROLLER vera_device.get_last_scene_id = MagicMock(return_value="id0") vera_device.get_last_scene_time = MagicMock(return_value="0000") entity_id = "sensor.dev1_1" component_data = await vera_component_factory.configure_component( hass=hass, controller_config=new_simple_controller_config(devices=(vera_device,)), ) update_callback = component_data.controller_data[0].update_callback vera_device.get_last_scene_time.return_value = "1111" update_callback(vera_device) await hass.async_block_till_done() assert hass.states.get(entity_id).state == "id0"
[ "async", "def", "test_scene_controller_sensor", "(", "hass", ":", "HomeAssistant", ",", "vera_component_factory", ":", "ComponentFactory", ")", "->", "None", ":", "vera_device", "=", "MagicMock", "(", "spec", "=", "pv", ".", "VeraSensor", ")", "# type: pv.VeraSensor", "vera_device", ".", "device_id", "=", "1", "vera_device", ".", "vera_device_id", "=", "vera_device", ".", "device_id", "vera_device", ".", "name", "=", "\"dev1\"", "vera_device", ".", "category", "=", "pv", ".", "CATEGORY_SCENE_CONTROLLER", "vera_device", ".", "get_last_scene_id", "=", "MagicMock", "(", "return_value", "=", "\"id0\"", ")", "vera_device", ".", "get_last_scene_time", "=", "MagicMock", "(", "return_value", "=", "\"0000\"", ")", "entity_id", "=", "\"sensor.dev1_1\"", "component_data", "=", "await", "vera_component_factory", ".", "configure_component", "(", "hass", "=", "hass", ",", "controller_config", "=", "new_simple_controller_config", "(", "devices", "=", "(", "vera_device", ",", ")", ")", ",", ")", "update_callback", "=", "component_data", ".", "controller_data", "[", "0", "]", ".", "update_callback", "vera_device", ".", "get_last_scene_time", ".", "return_value", "=", "\"1111\"", "update_callback", "(", "vera_device", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "states", ".", "get", "(", "entity_id", ")", ".", "state", "==", "\"id0\"" ]
[ 174, 0 ]
[ 196, 52 ]
python
en
['en', 'en', 'en']
False
find_code_in_transformers
(object_name)
Find and return the code source code of `object_name`.
Find and return the code source code of `object_name`.
def find_code_in_transformers(object_name): """ Find and return the code source code of `object_name`.""" parts = object_name.split(".") i = 0 # First let's find the module where our object lives. module = parts[i] while i < len(parts) and not os.path.isfile(os.path.join(TRANSFORMERS_PATH, f"{module}.py")): i += 1 if i < len(parts): module = os.path.join(module, parts[i]) if i >= len(parts): raise ValueError( f"`object_name` should begin with the name of a module of transformers but got {object_name}." ) with open(os.path.join(TRANSFORMERS_PATH, f"{module}.py"), "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Now let's find the class / func in the code! indent = "" line_index = 0 for name in parts[i + 1 :]: while ( line_index < len(lines) and re.search(fr"^{indent}(class|def)\s+{name}(\(|\:)", lines[line_index]) is None ): line_index += 1 indent += " " line_index += 1 if line_index >= len(lines): raise ValueError(f" {object_name} does not match any function or class in {module}.") # We found the beginning of the class / func, now let's find the end (when the indent diminishes). start_index = line_index while line_index < len(lines) and _should_continue(lines[line_index], indent): line_index += 1 # Clean up empty lines at the end (if any). while len(lines[line_index - 1]) <= 1: line_index -= 1 code_lines = lines[start_index:line_index] return "".join(code_lines)
[ "def", "find_code_in_transformers", "(", "object_name", ")", ":", "parts", "=", "object_name", ".", "split", "(", "\".\"", ")", "i", "=", "0", "# First let's find the module where our object lives.", "module", "=", "parts", "[", "i", "]", "while", "i", "<", "len", "(", "parts", ")", "and", "not", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "TRANSFORMERS_PATH", ",", "f\"{module}.py\"", ")", ")", ":", "i", "+=", "1", "if", "i", "<", "len", "(", "parts", ")", ":", "module", "=", "os", ".", "path", ".", "join", "(", "module", ",", "parts", "[", "i", "]", ")", "if", "i", ">=", "len", "(", "parts", ")", ":", "raise", "ValueError", "(", "f\"`object_name` should begin with the name of a module of transformers but got {object_name}.\"", ")", "with", "open", "(", "os", ".", "path", ".", "join", "(", "TRANSFORMERS_PATH", ",", "f\"{module}.py\"", ")", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ",", "newline", "=", "\"\\n\"", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "# Now let's find the class / func in the code!", "indent", "=", "\"\"", "line_index", "=", "0", "for", "name", "in", "parts", "[", "i", "+", "1", ":", "]", ":", "while", "(", "line_index", "<", "len", "(", "lines", ")", "and", "re", ".", "search", "(", "fr\"^{indent}(class|def)\\s+{name}(\\(|\\:)\"", ",", "lines", "[", "line_index", "]", ")", "is", "None", ")", ":", "line_index", "+=", "1", "indent", "+=", "\" \"", "line_index", "+=", "1", "if", "line_index", ">=", "len", "(", "lines", ")", ":", "raise", "ValueError", "(", "f\" {object_name} does not match any function or class in {module}.\"", ")", "# We found the beginning of the class / func, now let's find the end (when the indent diminishes).", "start_index", "=", "line_index", "while", "line_index", "<", "len", "(", "lines", ")", "and", "_should_continue", "(", "lines", "[", "line_index", "]", ",", "indent", ")", ":", "line_index", "+=", "1", "# Clean up empty lines at the end (if any).", "while", "len", "(", "lines", "[", "line_index", "-", "1", "]", ")", "<=", "1", ":", "line_index", "-=", "1", "code_lines", "=", "lines", "[", "start_index", ":", "line_index", "]", "return", "\"\"", ".", "join", "(", "code_lines", ")" ]
[ 34, 0 ]
[ 76, 30 ]
python
en
['en', 'en', 'en']
True
blackify
(code)
Applies the black part of our `make style` command to `code`.
Applies the black part of our `make style` command to `code`.
def blackify(code): """ Applies the black part of our `make style` command to `code`. """ has_indent = len(get_indent(code)) > 0 if has_indent: code = f"class Bla:\n{code}" result = black.format_str(code, mode=black.FileMode([black.TargetVersion.PY35], line_length=119)) return result[len("class Bla:\n") :] if has_indent else result
[ "def", "blackify", "(", "code", ")", ":", "has_indent", "=", "len", "(", "get_indent", "(", "code", ")", ")", ">", "0", "if", "has_indent", ":", "code", "=", "f\"class Bla:\\n{code}\"", "result", "=", "black", ".", "format_str", "(", "code", ",", "mode", "=", "black", ".", "FileMode", "(", "[", "black", ".", "TargetVersion", ".", "PY35", "]", ",", "line_length", "=", "119", ")", ")", "return", "result", "[", "len", "(", "\"class Bla:\\n\"", ")", ":", "]", "if", "has_indent", "else", "result" ]
[ 93, 0 ]
[ 101, 66 ]
python
en
['en', 'error', 'th']
False
is_copy_consistent
(filename, overwrite=False)
Check if the code commented as a copy in `filename` matches the original. Return the differences or overwrites the content depending on `overwrite`.
Check if the code commented as a copy in `filename` matches the original.
def is_copy_consistent(filename, overwrite=False): """ Check if the code commented as a copy in `filename` matches the original. Return the differences or overwrites the content depending on `overwrite`. """ with open(filename, "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() diffs = [] line_index = 0 # Not a for loop cause `lines` is going to change (if `overwrite=True`). while line_index < len(lines): search = _re_copy_warning.search(lines[line_index]) if search is None: line_index += 1 continue # There is some copied code here, let's retrieve the original. indent, object_name, replace_pattern = search.groups() theoretical_code = find_code_in_transformers(object_name) theoretical_indent = get_indent(theoretical_code) start_index = line_index + 1 if indent == theoretical_indent else line_index + 2 indent = theoretical_indent line_index = start_index # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. should_continue = True while line_index < len(lines) and should_continue: line_index += 1 if line_index >= len(lines): break line = lines[line_index] should_continue = _should_continue(line, indent) and re.search(f"^{indent}# End copy", line) is None # Clean up empty lines at the end (if any). while len(lines[line_index - 1]) <= 1: line_index -= 1 observed_code_lines = lines[start_index:line_index] observed_code = "".join(observed_code_lines) # Before comparing, use the `replace_pattern` on the original code. if len(replace_pattern) > 0: patterns = replace_pattern.replace("with", "").split(",") patterns = [_re_replace_pattern.search(p) for p in patterns] for pattern in patterns: if pattern is None: continue obj1, obj2, option = pattern.groups() theoretical_code = re.sub(obj1, obj2, theoretical_code) if option.strip() == "all-casing": theoretical_code = re.sub(obj1.lower(), obj2.lower(), theoretical_code) theoretical_code = re.sub(obj1.upper(), obj2.upper(), theoretical_code) # Blackify after replacement. To be able to do that, we need the header (class or function definition) # from the previous line theoretical_code = blackify(lines[start_index - 1] + theoretical_code) theoretical_code = theoretical_code[len(lines[start_index - 1]) :] # Test for a diff and act accordingly. if observed_code != theoretical_code: diffs.append([object_name, start_index]) if overwrite: lines = lines[:start_index] + [theoretical_code] + lines[line_index:] line_index = start_index + 1 if overwrite and len(diffs) > 0: # Warn the user a file has been modified. print(f"Detected changes, rewriting {filename}.") with open(filename, "w", encoding="utf-8", newline="\n") as f: f.writelines(lines) return diffs
[ "def", "is_copy_consistent", "(", "filename", ",", "overwrite", "=", "False", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ",", "newline", "=", "\"\\n\"", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "diffs", "=", "[", "]", "line_index", "=", "0", "# Not a for loop cause `lines` is going to change (if `overwrite=True`).", "while", "line_index", "<", "len", "(", "lines", ")", ":", "search", "=", "_re_copy_warning", ".", "search", "(", "lines", "[", "line_index", "]", ")", "if", "search", "is", "None", ":", "line_index", "+=", "1", "continue", "# There is some copied code here, let's retrieve the original.", "indent", ",", "object_name", ",", "replace_pattern", "=", "search", ".", "groups", "(", ")", "theoretical_code", "=", "find_code_in_transformers", "(", "object_name", ")", "theoretical_indent", "=", "get_indent", "(", "theoretical_code", ")", "start_index", "=", "line_index", "+", "1", "if", "indent", "==", "theoretical_indent", "else", "line_index", "+", "2", "indent", "=", "theoretical_indent", "line_index", "=", "start_index", "# Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment.", "should_continue", "=", "True", "while", "line_index", "<", "len", "(", "lines", ")", "and", "should_continue", ":", "line_index", "+=", "1", "if", "line_index", ">=", "len", "(", "lines", ")", ":", "break", "line", "=", "lines", "[", "line_index", "]", "should_continue", "=", "_should_continue", "(", "line", ",", "indent", ")", "and", "re", ".", "search", "(", "f\"^{indent}# End copy\"", ",", "line", ")", "is", "None", "# Clean up empty lines at the end (if any).", "while", "len", "(", "lines", "[", "line_index", "-", "1", "]", ")", "<=", "1", ":", "line_index", "-=", "1", "observed_code_lines", "=", "lines", "[", "start_index", ":", "line_index", "]", "observed_code", "=", "\"\"", ".", "join", "(", "observed_code_lines", ")", "# Before comparing, use the `replace_pattern` on the original code.", "if", "len", "(", "replace_pattern", ")", ">", "0", ":", "patterns", "=", "replace_pattern", ".", "replace", "(", "\"with\"", ",", "\"\"", ")", ".", "split", "(", "\",\"", ")", "patterns", "=", "[", "_re_replace_pattern", ".", "search", "(", "p", ")", "for", "p", "in", "patterns", "]", "for", "pattern", "in", "patterns", ":", "if", "pattern", "is", "None", ":", "continue", "obj1", ",", "obj2", ",", "option", "=", "pattern", ".", "groups", "(", ")", "theoretical_code", "=", "re", ".", "sub", "(", "obj1", ",", "obj2", ",", "theoretical_code", ")", "if", "option", ".", "strip", "(", ")", "==", "\"all-casing\"", ":", "theoretical_code", "=", "re", ".", "sub", "(", "obj1", ".", "lower", "(", ")", ",", "obj2", ".", "lower", "(", ")", ",", "theoretical_code", ")", "theoretical_code", "=", "re", ".", "sub", "(", "obj1", ".", "upper", "(", ")", ",", "obj2", ".", "upper", "(", ")", ",", "theoretical_code", ")", "# Blackify after replacement. To be able to do that, we need the header (class or function definition)", "# from the previous line", "theoretical_code", "=", "blackify", "(", "lines", "[", "start_index", "-", "1", "]", "+", "theoretical_code", ")", "theoretical_code", "=", "theoretical_code", "[", "len", "(", "lines", "[", "start_index", "-", "1", "]", ")", ":", "]", "# Test for a diff and act accordingly.", "if", "observed_code", "!=", "theoretical_code", ":", "diffs", ".", "append", "(", "[", "object_name", ",", "start_index", "]", ")", "if", "overwrite", ":", "lines", "=", "lines", "[", ":", "start_index", "]", "+", "[", "theoretical_code", "]", "+", "lines", "[", "line_index", ":", "]", "line_index", "=", "start_index", "+", "1", "if", "overwrite", "and", "len", "(", "diffs", ")", ">", "0", ":", "# Warn the user a file has been modified.", "print", "(", "f\"Detected changes, rewriting {filename}.\"", ")", "with", "open", "(", "filename", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ",", "newline", "=", "\"\\n\"", ")", "as", "f", ":", "f", ".", "writelines", "(", "lines", ")", "return", "diffs" ]
[ 104, 0 ]
[ 175, 16 ]
python
en
['en', 'error', 'th']
False
get_model_list
()
Extracts the model list from the README.
Extracts the model list from the README.
def get_model_list(): """ Extracts the model list from the README. """ # If the introduction or the conclusion of the list change, the prompts may need to be updated. _start_prompt = "🤗 Transformers currently provides the following architectures" _end_prompt = "1. Want to contribute a new model?" with open(os.path.join(REPO_PATH, "README.md"), "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Find the start of the list. start_index = 0 while not lines[start_index].startswith(_start_prompt): start_index += 1 start_index += 1 result = [] current_line = "" end_index = start_index while not lines[end_index].startswith(_end_prompt): if lines[end_index].startswith("1."): if len(current_line) > 1: result.append(current_line) current_line = lines[end_index] elif len(lines[end_index]) > 1: current_line = f"{current_line[:-1]} {lines[end_index].lstrip()}" end_index += 1 if len(current_line) > 1: result.append(current_line) return "".join(result)
[ "def", "get_model_list", "(", ")", ":", "# If the introduction or the conclusion of the list change, the prompts may need to be updated.", "_start_prompt", "=", "\"🤗 Transformers currently provides the following architectures\"", "_end_prompt", "=", "\"1. Want to contribute a new model?\"", "with", "open", "(", "os", ".", "path", ".", "join", "(", "REPO_PATH", ",", "\"README.md\"", ")", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ",", "newline", "=", "\"\\n\"", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "# Find the start of the list.", "start_index", "=", "0", "while", "not", "lines", "[", "start_index", "]", ".", "startswith", "(", "_start_prompt", ")", ":", "start_index", "+=", "1", "start_index", "+=", "1", "result", "=", "[", "]", "current_line", "=", "\"\"", "end_index", "=", "start_index", "while", "not", "lines", "[", "end_index", "]", ".", "startswith", "(", "_end_prompt", ")", ":", "if", "lines", "[", "end_index", "]", ".", "startswith", "(", "\"1.\"", ")", ":", "if", "len", "(", "current_line", ")", ">", "1", ":", "result", ".", "append", "(", "current_line", ")", "current_line", "=", "lines", "[", "end_index", "]", "elif", "len", "(", "lines", "[", "end_index", "]", ")", ">", "1", ":", "current_line", "=", "f\"{current_line[:-1]} {lines[end_index].lstrip()}\"", "end_index", "+=", "1", "if", "len", "(", "current_line", ")", ">", "1", ":", "result", ".", "append", "(", "current_line", ")", "return", "\"\"", ".", "join", "(", "result", ")" ]
[ 194, 0 ]
[ 222, 26 ]
python
en
['en', 'en', 'en']
True
split_long_line_with_indent
(line, max_per_line, indent)
Split the `line` so that it doesn't go over `max_per_line` and adds `indent` to new lines.
Split the `line` so that it doesn't go over `max_per_line` and adds `indent` to new lines.
def split_long_line_with_indent(line, max_per_line, indent): """ Split the `line` so that it doesn't go over `max_per_line` and adds `indent` to new lines. """ words = line.split(" ") lines = [] current_line = words[0] for word in words[1:]: if len(f"{current_line} {word}") > max_per_line: lines.append(current_line) current_line = " " * indent + word else: current_line = f"{current_line} {word}" lines.append(current_line) return "\n".join(lines)
[ "def", "split_long_line_with_indent", "(", "line", ",", "max_per_line", ",", "indent", ")", ":", "words", "=", "line", ".", "split", "(", "\" \"", ")", "lines", "=", "[", "]", "current_line", "=", "words", "[", "0", "]", "for", "word", "in", "words", "[", "1", ":", "]", ":", "if", "len", "(", "f\"{current_line} {word}\"", ")", ">", "max_per_line", ":", "lines", ".", "append", "(", "current_line", ")", "current_line", "=", "\" \"", "*", "indent", "+", "word", "else", ":", "current_line", "=", "f\"{current_line} {word}\"", "lines", ".", "append", "(", "current_line", ")", "return", "\"\\n\"", ".", "join", "(", "lines", ")" ]
[ 225, 0 ]
[ 237, 27 ]
python
en
['en', 'en', 'en']
True
convert_to_rst
(model_list, max_per_line=None)
Convert `model_list` to rst format.
Convert `model_list` to rst format.
def convert_to_rst(model_list, max_per_line=None): """ Convert `model_list` to rst format. """ # Convert **[description](link)** to `description <link>`__ def _rep_link(match): title, link = match.groups() # Keep hard links for the models not released yet if "master" in link or not link.startswith("https://huggingface.co/transformers"): return f"`{title} <{link}>`__" # Convert links to relative links otherwise else: link = link[len("https://huggingface.co/transformers/") : -len(".html")] return f":doc:`{title} <{link}>`" model_list = re.sub(r"\*\*\[([^\]]*)\]\(([^\)]*)\)\*\*", _rep_link, model_list) # Convert [description](link) to `description <link>`__ model_list = re.sub(r"\[([^\]]*)\]\(([^\)]*)\)", r"`\1 <\2>`__", model_list) # Enumerate the lines properly lines = model_list.split("\n") result = [] for i, line in enumerate(lines): line = re.sub(r"^\s*(\d+)\.", f"{i+1}.", line) # Split the lines that are too long if max_per_line is not None and len(line) > max_per_line: prompt = re.search(r"^(\s*\d+\.\s+)\S", line) indent = len(prompt.groups()[0]) if prompt is not None else 0 line = split_long_line_with_indent(line, max_per_line, indent) result.append(line) return "\n".join(result)
[ "def", "convert_to_rst", "(", "model_list", ",", "max_per_line", "=", "None", ")", ":", "# Convert **[description](link)** to `description <link>`__", "def", "_rep_link", "(", "match", ")", ":", "title", ",", "link", "=", "match", ".", "groups", "(", ")", "# Keep hard links for the models not released yet", "if", "\"master\"", "in", "link", "or", "not", "link", ".", "startswith", "(", "\"https://huggingface.co/transformers\"", ")", ":", "return", "f\"`{title} <{link}>`__\"", "# Convert links to relative links otherwise", "else", ":", "link", "=", "link", "[", "len", "(", "\"https://huggingface.co/transformers/\"", ")", ":", "-", "len", "(", "\".html\"", ")", "]", "return", "f\":doc:`{title} <{link}>`\"", "model_list", "=", "re", ".", "sub", "(", "r\"\\*\\*\\[([^\\]]*)\\]\\(([^\\)]*)\\)\\*\\*\"", ",", "_rep_link", ",", "model_list", ")", "# Convert [description](link) to `description <link>`__", "model_list", "=", "re", ".", "sub", "(", "r\"\\[([^\\]]*)\\]\\(([^\\)]*)\\)\"", ",", "r\"`\\1 <\\2>`__\"", ",", "model_list", ")", "# Enumerate the lines properly", "lines", "=", "model_list", ".", "split", "(", "\"\\n\"", ")", "result", "=", "[", "]", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "line", "=", "re", ".", "sub", "(", "r\"^\\s*(\\d+)\\.\"", ",", "f\"{i+1}.\"", ",", "line", ")", "# Split the lines that are too long", "if", "max_per_line", "is", "not", "None", "and", "len", "(", "line", ")", ">", "max_per_line", ":", "prompt", "=", "re", ".", "search", "(", "r\"^(\\s*\\d+\\.\\s+)\\S\"", ",", "line", ")", "indent", "=", "len", "(", "prompt", ".", "groups", "(", ")", "[", "0", "]", ")", "if", "prompt", "is", "not", "None", "else", "0", "line", "=", "split_long_line_with_indent", "(", "line", ",", "max_per_line", ",", "indent", ")", "result", ".", "append", "(", "line", ")", "return", "\"\\n\"", ".", "join", "(", "result", ")" ]
[ 240, 0 ]
[ 270, 28 ]
python
en
['en', 'en', 'en']
True
_find_text_in_file
(filename, start_prompt, end_prompt)
Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty lines.
Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty lines.
def _find_text_in_file(filename, start_prompt, end_prompt): """ Find the text in `filename` between a line beginning with `start_prompt` and before `end_prompt`, removing empty lines. """ with open(filename, "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Find the start prompt. start_index = 0 while not lines[start_index].startswith(start_prompt): start_index += 1 start_index += 1 end_index = start_index while not lines[end_index].startswith(end_prompt): end_index += 1 end_index -= 1 while len(lines[start_index]) <= 1: start_index += 1 while len(lines[end_index]) <= 1: end_index -= 1 end_index += 1 return "".join(lines[start_index:end_index]), start_index, end_index, lines
[ "def", "_find_text_in_file", "(", "filename", ",", "start_prompt", ",", "end_prompt", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ",", "newline", "=", "\"\\n\"", ")", "as", "f", ":", "lines", "=", "f", ".", "readlines", "(", ")", "# Find the start prompt.", "start_index", "=", "0", "while", "not", "lines", "[", "start_index", "]", ".", "startswith", "(", "start_prompt", ")", ":", "start_index", "+=", "1", "start_index", "+=", "1", "end_index", "=", "start_index", "while", "not", "lines", "[", "end_index", "]", ".", "startswith", "(", "end_prompt", ")", ":", "end_index", "+=", "1", "end_index", "-=", "1", "while", "len", "(", "lines", "[", "start_index", "]", ")", "<=", "1", ":", "start_index", "+=", "1", "while", "len", "(", "lines", "[", "end_index", "]", ")", "<=", "1", ":", "end_index", "-=", "1", "end_index", "+=", "1", "return", "\"\"", ".", "join", "(", "lines", "[", "start_index", ":", "end_index", "]", ")", ",", "start_index", ",", "end_index", ",", "lines" ]
[ 273, 0 ]
[ 296, 79 ]
python
en
['en', 'error', 'th']
False
check_model_list_copy
(overwrite=False, max_per_line=119)
Check the model lists in the README and index.rst are consistent and maybe `overwrite`.
Check the model lists in the README and index.rst are consistent and maybe `overwrite`.
def check_model_list_copy(overwrite=False, max_per_line=119): """ Check the model lists in the README and index.rst are consistent and maybe `overwrite`. """ rst_list, start_index, end_index, lines = _find_text_in_file( filename=os.path.join(PATH_TO_DOCS, "index.rst"), start_prompt=" This list is updated automatically from the README", end_prompt=".. _bigtable:", ) md_list = get_model_list() converted_list = convert_to_rst(md_list, max_per_line=max_per_line) if converted_list != rst_list: if overwrite: with open(os.path.join(PATH_TO_DOCS, "index.rst"), "w", encoding="utf-8", newline="\n") as f: f.writelines(lines[:start_index] + [converted_list] + lines[end_index:]) else: raise ValueError( "The model list in the README changed and the list in `index.rst` has not been updated. Run " "`make fix-copies` to fix this." )
[ "def", "check_model_list_copy", "(", "overwrite", "=", "False", ",", "max_per_line", "=", "119", ")", ":", "rst_list", ",", "start_index", ",", "end_index", ",", "lines", "=", "_find_text_in_file", "(", "filename", "=", "os", ".", "path", ".", "join", "(", "PATH_TO_DOCS", ",", "\"index.rst\"", ")", ",", "start_prompt", "=", "\" This list is updated automatically from the README\"", ",", "end_prompt", "=", "\".. _bigtable:\"", ",", ")", "md_list", "=", "get_model_list", "(", ")", "converted_list", "=", "convert_to_rst", "(", "md_list", ",", "max_per_line", "=", "max_per_line", ")", "if", "converted_list", "!=", "rst_list", ":", "if", "overwrite", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "PATH_TO_DOCS", ",", "\"index.rst\"", ")", ",", "\"w\"", ",", "encoding", "=", "\"utf-8\"", ",", "newline", "=", "\"\\n\"", ")", "as", "f", ":", "f", ".", "writelines", "(", "lines", "[", ":", "start_index", "]", "+", "[", "converted_list", "]", "+", "lines", "[", "end_index", ":", "]", ")", "else", ":", "raise", "ValueError", "(", "\"The model list in the README changed and the list in `index.rst` has not been updated. Run \"", "\"`make fix-copies` to fix this.\"", ")" ]
[ 299, 0 ]
[ 317, 13 ]
python
en
['en', 'en', 'en']
True
test_login_new_user_and_trying_refresh_token
(hass, aiohttp_client)
Test logging in with new user and refreshing tokens.
Test logging in with new user and refreshing tokens.
async def test_login_new_user_and_trying_refresh_token(hass, aiohttp_client): """Test logging in with new user and refreshing tokens.""" client = await async_setup_auth(hass, aiohttp_client, setup_api=True) resp = await client.post( "/auth/login_flow", json={ "client_id": CLIENT_ID, "handler": ["insecure_example", None], "redirect_uri": CLIENT_REDIRECT_URI, }, ) assert resp.status == 200 step = await resp.json() resp = await client.post( f"/auth/login_flow/{step['flow_id']}", json={"client_id": CLIENT_ID, "username": "test-user", "password": "test-pass"}, ) assert resp.status == 200 step = await resp.json() code = step["result"] # Exchange code for tokens resp = await client.post( "/auth/token", data={"client_id": CLIENT_ID, "grant_type": "authorization_code", "code": code}, ) assert resp.status == 200 tokens = await resp.json() assert ( await hass.auth.async_validate_access_token(tokens["access_token"]) is not None ) # Use refresh token to get more tokens. resp = await client.post( "/auth/token", data={ "client_id": CLIENT_ID, "grant_type": "refresh_token", "refresh_token": tokens["refresh_token"], }, ) assert resp.status == 200 tokens = await resp.json() assert "refresh_token" not in tokens assert ( await hass.auth.async_validate_access_token(tokens["access_token"]) is not None ) # Test using access token to hit API. resp = await client.get("/api/") assert resp.status == 401 resp = await client.get( "/api/", headers={"authorization": f"Bearer {tokens['access_token']}"} ) assert resp.status == 200
[ "async", "def", "test_login_new_user_and_trying_refresh_token", "(", "hass", ",", "aiohttp_client", ")", ":", "client", "=", "await", "async_setup_auth", "(", "hass", ",", "aiohttp_client", ",", "setup_api", "=", "True", ")", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/login_flow\"", ",", "json", "=", "{", "\"client_id\"", ":", "CLIENT_ID", ",", "\"handler\"", ":", "[", "\"insecure_example\"", ",", "None", "]", ",", "\"redirect_uri\"", ":", "CLIENT_REDIRECT_URI", ",", "}", ",", ")", "assert", "resp", ".", "status", "==", "200", "step", "=", "await", "resp", ".", "json", "(", ")", "resp", "=", "await", "client", ".", "post", "(", "f\"/auth/login_flow/{step['flow_id']}\"", ",", "json", "=", "{", "\"client_id\"", ":", "CLIENT_ID", ",", "\"username\"", ":", "\"test-user\"", ",", "\"password\"", ":", "\"test-pass\"", "}", ",", ")", "assert", "resp", ".", "status", "==", "200", "step", "=", "await", "resp", ".", "json", "(", ")", "code", "=", "step", "[", "\"result\"", "]", "# Exchange code for tokens", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"client_id\"", ":", "CLIENT_ID", ",", "\"grant_type\"", ":", "\"authorization_code\"", ",", "\"code\"", ":", "code", "}", ",", ")", "assert", "resp", ".", "status", "==", "200", "tokens", "=", "await", "resp", ".", "json", "(", ")", "assert", "(", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "tokens", "[", "\"access_token\"", "]", ")", "is", "not", "None", ")", "# Use refresh token to get more tokens.", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"client_id\"", ":", "CLIENT_ID", ",", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "tokens", "[", "\"refresh_token\"", "]", ",", "}", ",", ")", "assert", "resp", ".", "status", "==", "200", "tokens", "=", "await", "resp", ".", "json", "(", ")", "assert", "\"refresh_token\"", "not", "in", "tokens", "assert", "(", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "tokens", "[", "\"access_token\"", "]", ")", "is", "not", "None", ")", "# Test using access token to hit API.", "resp", "=", "await", "client", ".", "get", "(", "\"/api/\"", ")", "assert", "resp", ".", "status", "==", "401", "resp", "=", "await", "client", ".", "get", "(", "\"/api/\"", ",", "headers", "=", "{", "\"authorization\"", ":", "f\"Bearer {tokens['access_token']}\"", "}", ")", "assert", "resp", ".", "status", "==", "200" ]
[ 15, 0 ]
[ 75, 29 ]
python
en
['en', 'en', 'en']
True
test_auth_code_store_expiration
()
Test that the auth code store will not return expired tokens.
Test that the auth code store will not return expired tokens.
def test_auth_code_store_expiration(): """Test that the auth code store will not return expired tokens.""" store, retrieve = auth._create_auth_code_store() client_id = "bla" user = MockUser(id="mock_user") now = utcnow() with patch("homeassistant.util.dt.utcnow", return_value=now): code = store(client_id, user) with patch( "homeassistant.util.dt.utcnow", return_value=now + timedelta(minutes=10) ): assert retrieve(client_id, RESULT_TYPE_USER, code) is None with patch("homeassistant.util.dt.utcnow", return_value=now): code = store(client_id, user) with patch( "homeassistant.util.dt.utcnow", return_value=now + timedelta(minutes=9, seconds=59), ): assert retrieve(client_id, RESULT_TYPE_USER, code) == user
[ "def", "test_auth_code_store_expiration", "(", ")", ":", "store", ",", "retrieve", "=", "auth", ".", "_create_auth_code_store", "(", ")", "client_id", "=", "\"bla\"", "user", "=", "MockUser", "(", "id", "=", "\"mock_user\"", ")", "now", "=", "utcnow", "(", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ",", "return_value", "=", "now", ")", ":", "code", "=", "store", "(", "client_id", ",", "user", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ",", "return_value", "=", "now", "+", "timedelta", "(", "minutes", "=", "10", ")", ")", ":", "assert", "retrieve", "(", "client_id", ",", "RESULT_TYPE_USER", ",", "code", ")", "is", "None", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ",", "return_value", "=", "now", ")", ":", "code", "=", "store", "(", "client_id", ",", "user", ")", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ",", "return_value", "=", "now", "+", "timedelta", "(", "minutes", "=", "9", ",", "seconds", "=", "59", ")", ",", ")", ":", "assert", "retrieve", "(", "client_id", ",", "RESULT_TYPE_USER", ",", "code", ")", "==", "user" ]
[ 78, 0 ]
[ 100, 66 ]
python
en
['en', 'en', 'en']
True
test_ws_current_user
(hass, hass_ws_client, hass_access_token)
Test the current user command with Home Assistant creds.
Test the current user command with Home Assistant creds.
async def test_ws_current_user(hass, hass_ws_client, hass_access_token): """Test the current user command with Home Assistant creds.""" assert await async_setup_component(hass, "auth", {}) refresh_token = await hass.auth.async_validate_access_token(hass_access_token) user = refresh_token.user credential = Credentials( auth_provider_type="homeassistant", auth_provider_id=None, data={}, id="test-id" ) user.credentials.append(credential) assert len(user.credentials) == 1 client = await hass_ws_client(hass, hass_access_token) await client.send_json({"id": 5, "type": auth.WS_TYPE_CURRENT_USER}) result = await client.receive_json() assert result["success"], result user_dict = result["result"] assert user_dict["name"] == user.name assert user_dict["id"] == user.id assert user_dict["is_owner"] == user.is_owner assert len(user_dict["credentials"]) == 1 hass_cred = user_dict["credentials"][0] assert hass_cred["auth_provider_type"] == "homeassistant" assert hass_cred["auth_provider_id"] is None assert "data" not in hass_cred
[ "async", "def", "test_ws_current_user", "(", "hass", ",", "hass_ws_client", ",", "hass_access_token", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"auth\"", ",", "{", "}", ")", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "hass_access_token", ")", "user", "=", "refresh_token", ".", "user", "credential", "=", "Credentials", "(", "auth_provider_type", "=", "\"homeassistant\"", ",", "auth_provider_id", "=", "None", ",", "data", "=", "{", "}", ",", "id", "=", "\"test-id\"", ")", "user", ".", "credentials", ".", "append", "(", "credential", ")", "assert", "len", "(", "user", ".", "credentials", ")", "==", "1", "client", "=", "await", "hass_ws_client", "(", "hass", ",", "hass_access_token", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "auth", ".", "WS_TYPE_CURRENT_USER", "}", ")", "result", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "result", "[", "\"success\"", "]", ",", "result", "user_dict", "=", "result", "[", "\"result\"", "]", "assert", "user_dict", "[", "\"name\"", "]", "==", "user", ".", "name", "assert", "user_dict", "[", "\"id\"", "]", "==", "user", ".", "id", "assert", "user_dict", "[", "\"is_owner\"", "]", "==", "user", ".", "is_owner", "assert", "len", "(", "user_dict", "[", "\"credentials\"", "]", ")", "==", "1", "hass_cred", "=", "user_dict", "[", "\"credentials\"", "]", "[", "0", "]", "assert", "hass_cred", "[", "\"auth_provider_type\"", "]", "==", "\"homeassistant\"", "assert", "hass_cred", "[", "\"auth_provider_id\"", "]", "is", "None", "assert", "\"data\"", "not", "in", "hass_cred" ]
[ 103, 0 ]
[ 132, 34 ]
python
en
['en', 'en', 'en']
True
test_cors_on_token
(hass, aiohttp_client)
Test logging in with new user and refreshing tokens.
Test logging in with new user and refreshing tokens.
async def test_cors_on_token(hass, aiohttp_client): """Test logging in with new user and refreshing tokens.""" client = await async_setup_auth(hass, aiohttp_client) resp = await client.options( "/auth/token", headers={ "origin": "http://example.com", "Access-Control-Request-Method": "POST", }, ) assert resp.headers["Access-Control-Allow-Origin"] == "http://example.com" assert resp.headers["Access-Control-Allow-Methods"] == "POST" resp = await client.post("/auth/token", headers={"origin": "http://example.com"}) assert resp.headers["Access-Control-Allow-Origin"] == "http://example.com"
[ "async", "def", "test_cors_on_token", "(", "hass", ",", "aiohttp_client", ")", ":", "client", "=", "await", "async_setup_auth", "(", "hass", ",", "aiohttp_client", ")", "resp", "=", "await", "client", ".", "options", "(", "\"/auth/token\"", ",", "headers", "=", "{", "\"origin\"", ":", "\"http://example.com\"", ",", "\"Access-Control-Request-Method\"", ":", "\"POST\"", ",", "}", ",", ")", "assert", "resp", ".", "headers", "[", "\"Access-Control-Allow-Origin\"", "]", "==", "\"http://example.com\"", "assert", "resp", ".", "headers", "[", "\"Access-Control-Allow-Methods\"", "]", "==", "\"POST\"", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "headers", "=", "{", "\"origin\"", ":", "\"http://example.com\"", "}", ")", "assert", "resp", ".", "headers", "[", "\"Access-Control-Allow-Origin\"", "]", "==", "\"http://example.com\"" ]
[ 135, 0 ]
[ 150, 78 ]
python
en
['en', 'en', 'en']
True
test_refresh_token_system_generated
(hass, aiohttp_client)
Test that we can get access tokens for system generated user.
Test that we can get access tokens for system generated user.
async def test_refresh_token_system_generated(hass, aiohttp_client): """Test that we can get access tokens for system generated user.""" client = await async_setup_auth(hass, aiohttp_client) user = await hass.auth.async_create_system_user("Test System") refresh_token = await hass.auth.async_create_refresh_token(user, None) resp = await client.post( "/auth/token", data={ "client_id": "https://this-is-not-allowed-for-system-users.com/", "grant_type": "refresh_token", "refresh_token": refresh_token.token, }, ) assert resp.status == 400 result = await resp.json() assert result["error"] == "invalid_request" resp = await client.post( "/auth/token", data={"grant_type": "refresh_token", "refresh_token": refresh_token.token}, ) assert resp.status == 200 tokens = await resp.json() assert ( await hass.auth.async_validate_access_token(tokens["access_token"]) is not None )
[ "async", "def", "test_refresh_token_system_generated", "(", "hass", ",", "aiohttp_client", ")", ":", "client", "=", "await", "async_setup_auth", "(", "hass", ",", "aiohttp_client", ")", "user", "=", "await", "hass", ".", "auth", ".", "async_create_system_user", "(", "\"Test System\"", ")", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_create_refresh_token", "(", "user", ",", "None", ")", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"client_id\"", ":", "\"https://this-is-not-allowed-for-system-users.com/\"", ",", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "refresh_token", ".", "token", ",", "}", ",", ")", "assert", "resp", ".", "status", "==", "400", "result", "=", "await", "resp", ".", "json", "(", ")", "assert", "result", "[", "\"error\"", "]", "==", "\"invalid_request\"", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "refresh_token", ".", "token", "}", ",", ")", "assert", "resp", ".", "status", "==", "200", "tokens", "=", "await", "resp", ".", "json", "(", ")", "assert", "(", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "tokens", "[", "\"access_token\"", "]", ")", "is", "not", "None", ")" ]
[ 153, 0 ]
[ 181, 5 ]
python
en
['en', 'en', 'en']
True
test_refresh_token_different_client_id
(hass, aiohttp_client)
Test that we verify client ID.
Test that we verify client ID.
async def test_refresh_token_different_client_id(hass, aiohttp_client): """Test that we verify client ID.""" client = await async_setup_auth(hass, aiohttp_client) user = await hass.auth.async_create_user("Test User") refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID) # No client ID resp = await client.post( "/auth/token", data={"grant_type": "refresh_token", "refresh_token": refresh_token.token}, ) assert resp.status == 400 result = await resp.json() assert result["error"] == "invalid_request" # Different client ID resp = await client.post( "/auth/token", data={ "client_id": "http://example-different.com", "grant_type": "refresh_token", "refresh_token": refresh_token.token, }, ) assert resp.status == 400 result = await resp.json() assert result["error"] == "invalid_request" # Correct resp = await client.post( "/auth/token", data={ "client_id": CLIENT_ID, "grant_type": "refresh_token", "refresh_token": refresh_token.token, }, ) assert resp.status == 200 tokens = await resp.json() assert ( await hass.auth.async_validate_access_token(tokens["access_token"]) is not None )
[ "async", "def", "test_refresh_token_different_client_id", "(", "hass", ",", "aiohttp_client", ")", ":", "client", "=", "await", "async_setup_auth", "(", "hass", ",", "aiohttp_client", ")", "user", "=", "await", "hass", ".", "auth", ".", "async_create_user", "(", "\"Test User\"", ")", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_create_refresh_token", "(", "user", ",", "CLIENT_ID", ")", "# No client ID", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "refresh_token", ".", "token", "}", ",", ")", "assert", "resp", ".", "status", "==", "400", "result", "=", "await", "resp", ".", "json", "(", ")", "assert", "result", "[", "\"error\"", "]", "==", "\"invalid_request\"", "# Different client ID", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"client_id\"", ":", "\"http://example-different.com\"", ",", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "refresh_token", ".", "token", ",", "}", ",", ")", "assert", "resp", ".", "status", "==", "400", "result", "=", "await", "resp", ".", "json", "(", ")", "assert", "result", "[", "\"error\"", "]", "==", "\"invalid_request\"", "# Correct", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"client_id\"", ":", "CLIENT_ID", ",", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "refresh_token", ".", "token", ",", "}", ",", ")", "assert", "resp", ".", "status", "==", "200", "tokens", "=", "await", "resp", ".", "json", "(", ")", "assert", "(", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "tokens", "[", "\"access_token\"", "]", ")", "is", "not", "None", ")" ]
[ 184, 0 ]
[ 228, 5 ]
python
en
['en', 'fr', 'en']
True
test_revoking_refresh_token
(hass, aiohttp_client)
Test that we can revoke refresh tokens.
Test that we can revoke refresh tokens.
async def test_revoking_refresh_token(hass, aiohttp_client): """Test that we can revoke refresh tokens.""" client = await async_setup_auth(hass, aiohttp_client) user = await hass.auth.async_create_user("Test User") refresh_token = await hass.auth.async_create_refresh_token(user, CLIENT_ID) # Test that we can create an access token resp = await client.post( "/auth/token", data={ "client_id": CLIENT_ID, "grant_type": "refresh_token", "refresh_token": refresh_token.token, }, ) assert resp.status == 200 tokens = await resp.json() assert ( await hass.auth.async_validate_access_token(tokens["access_token"]) is not None ) # Revoke refresh token resp = await client.post( "/auth/token", data={"token": refresh_token.token, "action": "revoke"} ) assert resp.status == 200 # Old access token should be no longer valid assert await hass.auth.async_validate_access_token(tokens["access_token"]) is None # Test that we no longer can create an access token resp = await client.post( "/auth/token", data={ "client_id": CLIENT_ID, "grant_type": "refresh_token", "refresh_token": refresh_token.token, }, ) assert resp.status == 400
[ "async", "def", "test_revoking_refresh_token", "(", "hass", ",", "aiohttp_client", ")", ":", "client", "=", "await", "async_setup_auth", "(", "hass", ",", "aiohttp_client", ")", "user", "=", "await", "hass", ".", "auth", ".", "async_create_user", "(", "\"Test User\"", ")", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_create_refresh_token", "(", "user", ",", "CLIENT_ID", ")", "# Test that we can create an access token", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"client_id\"", ":", "CLIENT_ID", ",", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "refresh_token", ".", "token", ",", "}", ",", ")", "assert", "resp", ".", "status", "==", "200", "tokens", "=", "await", "resp", ".", "json", "(", ")", "assert", "(", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "tokens", "[", "\"access_token\"", "]", ")", "is", "not", "None", ")", "# Revoke refresh token", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"token\"", ":", "refresh_token", ".", "token", ",", "\"action\"", ":", "\"revoke\"", "}", ")", "assert", "resp", ".", "status", "==", "200", "# Old access token should be no longer valid", "assert", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "tokens", "[", "\"access_token\"", "]", ")", "is", "None", "# Test that we no longer can create an access token", "resp", "=", "await", "client", ".", "post", "(", "\"/auth/token\"", ",", "data", "=", "{", "\"client_id\"", ":", "CLIENT_ID", ",", "\"grant_type\"", ":", "\"refresh_token\"", ",", "\"refresh_token\"", ":", "refresh_token", ".", "token", ",", "}", ",", ")", "assert", "resp", ".", "status", "==", "400" ]
[ 231, 0 ]
[ 272, 29 ]
python
en
['en', 'en', 'en']
True
test_ws_long_lived_access_token
(hass, hass_ws_client, hass_access_token)
Test generate long-lived access token.
Test generate long-lived access token.
async def test_ws_long_lived_access_token(hass, hass_ws_client, hass_access_token): """Test generate long-lived access token.""" assert await async_setup_component(hass, "auth", {"http": {}}) ws_client = await hass_ws_client(hass, hass_access_token) # verify create long-lived access token await ws_client.send_json( { "id": 5, "type": auth.WS_TYPE_LONG_LIVED_ACCESS_TOKEN, "client_name": "GPS Logger", "lifespan": 365, } ) result = await ws_client.receive_json() assert result["success"], result long_lived_access_token = result["result"] assert long_lived_access_token is not None refresh_token = await hass.auth.async_validate_access_token(long_lived_access_token) assert refresh_token.client_id is None assert refresh_token.client_name == "GPS Logger" assert refresh_token.client_icon is None
[ "async", "def", "test_ws_long_lived_access_token", "(", "hass", ",", "hass_ws_client", ",", "hass_access_token", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"auth\"", ",", "{", "\"http\"", ":", "{", "}", "}", ")", "ws_client", "=", "await", "hass_ws_client", "(", "hass", ",", "hass_access_token", ")", "# verify create long-lived access token", "await", "ws_client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "auth", ".", "WS_TYPE_LONG_LIVED_ACCESS_TOKEN", ",", "\"client_name\"", ":", "\"GPS Logger\"", ",", "\"lifespan\"", ":", "365", ",", "}", ")", "result", "=", "await", "ws_client", ".", "receive_json", "(", ")", "assert", "result", "[", "\"success\"", "]", ",", "result", "long_lived_access_token", "=", "result", "[", "\"result\"", "]", "assert", "long_lived_access_token", "is", "not", "None", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "long_lived_access_token", ")", "assert", "refresh_token", ".", "client_id", "is", "None", "assert", "refresh_token", ".", "client_name", "==", "\"GPS Logger\"", "assert", "refresh_token", ".", "client_icon", "is", "None" ]
[ 275, 0 ]
[ 300, 44 ]
python
en
['en', 'en', 'en']
True
test_ws_refresh_tokens
(hass, hass_ws_client, hass_access_token)
Test fetching refresh token metadata.
Test fetching refresh token metadata.
async def test_ws_refresh_tokens(hass, hass_ws_client, hass_access_token): """Test fetching refresh token metadata.""" assert await async_setup_component(hass, "auth", {"http": {}}) ws_client = await hass_ws_client(hass, hass_access_token) await ws_client.send_json({"id": 5, "type": auth.WS_TYPE_REFRESH_TOKENS}) result = await ws_client.receive_json() assert result["success"], result assert len(result["result"]) == 1 token = result["result"][0] refresh_token = await hass.auth.async_validate_access_token(hass_access_token) assert token["id"] == refresh_token.id assert token["type"] == refresh_token.token_type assert token["client_id"] == refresh_token.client_id assert token["client_name"] == refresh_token.client_name assert token["client_icon"] == refresh_token.client_icon assert token["created_at"] == refresh_token.created_at.isoformat() assert token["is_current"] is True assert token["last_used_at"] == refresh_token.last_used_at.isoformat() assert token["last_used_ip"] == refresh_token.last_used_ip
[ "async", "def", "test_ws_refresh_tokens", "(", "hass", ",", "hass_ws_client", ",", "hass_access_token", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"auth\"", ",", "{", "\"http\"", ":", "{", "}", "}", ")", "ws_client", "=", "await", "hass_ws_client", "(", "hass", ",", "hass_access_token", ")", "await", "ws_client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "auth", ".", "WS_TYPE_REFRESH_TOKENS", "}", ")", "result", "=", "await", "ws_client", ".", "receive_json", "(", ")", "assert", "result", "[", "\"success\"", "]", ",", "result", "assert", "len", "(", "result", "[", "\"result\"", "]", ")", "==", "1", "token", "=", "result", "[", "\"result\"", "]", "[", "0", "]", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "hass_access_token", ")", "assert", "token", "[", "\"id\"", "]", "==", "refresh_token", ".", "id", "assert", "token", "[", "\"type\"", "]", "==", "refresh_token", ".", "token_type", "assert", "token", "[", "\"client_id\"", "]", "==", "refresh_token", ".", "client_id", "assert", "token", "[", "\"client_name\"", "]", "==", "refresh_token", ".", "client_name", "assert", "token", "[", "\"client_icon\"", "]", "==", "refresh_token", ".", "client_icon", "assert", "token", "[", "\"created_at\"", "]", "==", "refresh_token", ".", "created_at", ".", "isoformat", "(", ")", "assert", "token", "[", "\"is_current\"", "]", "is", "True", "assert", "token", "[", "\"last_used_at\"", "]", "==", "refresh_token", ".", "last_used_at", ".", "isoformat", "(", ")", "assert", "token", "[", "\"last_used_ip\"", "]", "==", "refresh_token", ".", "last_used_ip" ]
[ 303, 0 ]
[ 324, 62 ]
python
en
['en', 'jv', 'pt']
False
test_ws_delete_refresh_token
(hass, hass_ws_client, hass_access_token)
Test deleting a refresh token.
Test deleting a refresh token.
async def test_ws_delete_refresh_token(hass, hass_ws_client, hass_access_token): """Test deleting a refresh token.""" assert await async_setup_component(hass, "auth", {"http": {}}) refresh_token = await hass.auth.async_validate_access_token(hass_access_token) ws_client = await hass_ws_client(hass, hass_access_token) # verify create long-lived access token await ws_client.send_json( { "id": 5, "type": auth.WS_TYPE_DELETE_REFRESH_TOKEN, "refresh_token_id": refresh_token.id, } ) result = await ws_client.receive_json() assert result["success"], result refresh_token = await hass.auth.async_validate_access_token(hass_access_token) assert refresh_token is None
[ "async", "def", "test_ws_delete_refresh_token", "(", "hass", ",", "hass_ws_client", ",", "hass_access_token", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"auth\"", ",", "{", "\"http\"", ":", "{", "}", "}", ")", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "hass_access_token", ")", "ws_client", "=", "await", "hass_ws_client", "(", "hass", ",", "hass_access_token", ")", "# verify create long-lived access token", "await", "ws_client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "auth", ".", "WS_TYPE_DELETE_REFRESH_TOKEN", ",", "\"refresh_token_id\"", ":", "refresh_token", ".", "id", ",", "}", ")", "result", "=", "await", "ws_client", ".", "receive_json", "(", ")", "assert", "result", "[", "\"success\"", "]", ",", "result", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "hass_access_token", ")", "assert", "refresh_token", "is", "None" ]
[ 327, 0 ]
[ 347, 32 ]
python
en
['en', 'en', 'pt']
True
test_ws_sign_path
(hass, hass_ws_client, hass_access_token)
Test signing a path.
Test signing a path.
async def test_ws_sign_path(hass, hass_ws_client, hass_access_token): """Test signing a path.""" assert await async_setup_component(hass, "auth", {"http": {}}) ws_client = await hass_ws_client(hass, hass_access_token) refresh_token = await hass.auth.async_validate_access_token(hass_access_token) with patch( "homeassistant.components.auth.async_sign_path", return_value="hello_world" ) as mock_sign: await ws_client.send_json( { "id": 5, "type": auth.WS_TYPE_SIGN_PATH, "path": "/api/hello", "expires": 20, } ) result = await ws_client.receive_json() assert result["success"], result assert result["result"] == {"path": "hello_world"} assert len(mock_sign.mock_calls) == 1 hass, p_refresh_token, path, expires = mock_sign.mock_calls[0][1] assert p_refresh_token == refresh_token.id assert path == "/api/hello" assert expires.total_seconds() == 20
[ "async", "def", "test_ws_sign_path", "(", "hass", ",", "hass_ws_client", ",", "hass_access_token", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"auth\"", ",", "{", "\"http\"", ":", "{", "}", "}", ")", "ws_client", "=", "await", "hass_ws_client", "(", "hass", ",", "hass_access_token", ")", "refresh_token", "=", "await", "hass", ".", "auth", ".", "async_validate_access_token", "(", "hass_access_token", ")", "with", "patch", "(", "\"homeassistant.components.auth.async_sign_path\"", ",", "return_value", "=", "\"hello_world\"", ")", "as", "mock_sign", ":", "await", "ws_client", ".", "send_json", "(", "{", "\"id\"", ":", "5", ",", "\"type\"", ":", "auth", ".", "WS_TYPE_SIGN_PATH", ",", "\"path\"", ":", "\"/api/hello\"", ",", "\"expires\"", ":", "20", ",", "}", ")", "result", "=", "await", "ws_client", ".", "receive_json", "(", ")", "assert", "result", "[", "\"success\"", "]", ",", "result", "assert", "result", "[", "\"result\"", "]", "==", "{", "\"path\"", ":", "\"hello_world\"", "}", "assert", "len", "(", "mock_sign", ".", "mock_calls", ")", "==", "1", "hass", ",", "p_refresh_token", ",", "path", ",", "expires", "=", "mock_sign", ".", "mock_calls", "[", "0", "]", "[", "1", "]", "assert", "p_refresh_token", "==", "refresh_token", ".", "id", "assert", "path", "==", "\"/api/hello\"", "assert", "expires", ".", "total_seconds", "(", ")", "==", "20" ]
[ 350, 0 ]
[ 376, 40 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the updater component.
Set up the updater component.
async def async_setup(hass, config): """Set up the updater component.""" if "dev" in current_version: # This component only makes sense in release versions _LOGGER.info("Running on 'dev', only analytics will be submitted") conf = config.get(DOMAIN, {}) if conf.get(CONF_REPORTING): huuid = await hass.helpers.instance_id.async_get() else: huuid = None include_components = conf.get(CONF_COMPONENT_REPORTING) async def check_new_version() -> Updater: """Check if a new version is available and report if one is.""" newest, release_notes = await get_newest_version( hass, huuid, include_components ) _LOGGER.debug("Fetched version %s: %s", newest, release_notes) # Skip on dev if "dev" in current_version: return Updater(False, "", "") # Load data from Supervisor if hass.components.hassio.is_hassio(): core_info = hass.components.hassio.get_core_info() newest = core_info["version_latest"] # Validate version update_available = False if StrictVersion(newest) > StrictVersion(current_version): _LOGGER.debug( "The latest available version of Home Assistant is %s", newest ) update_available = True elif StrictVersion(newest) == StrictVersion(current_version): _LOGGER.debug( "You are on the latest version (%s) of Home Assistant", newest ) elif StrictVersion(newest) < StrictVersion(current_version): _LOGGER.debug("Local version is newer than the latest version (%s)", newest) _LOGGER.debug("Update available: %s", update_available) return Updater(update_available, newest, release_notes) coordinator = hass.data[DOMAIN] = update_coordinator.DataUpdateCoordinator[Updater]( hass, _LOGGER, name="Home Assistant update", update_method=check_new_version, update_interval=timedelta(days=1), ) # This can take up to 15s which can delay startup asyncio.create_task(coordinator.async_refresh()) hass.async_create_task( discovery.async_load_platform(hass, "binary_sensor", DOMAIN, {}, config) ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "if", "\"dev\"", "in", "current_version", ":", "# This component only makes sense in release versions", "_LOGGER", ".", "info", "(", "\"Running on 'dev', only analytics will be submitted\"", ")", "conf", "=", "config", ".", "get", "(", "DOMAIN", ",", "{", "}", ")", "if", "conf", ".", "get", "(", "CONF_REPORTING", ")", ":", "huuid", "=", "await", "hass", ".", "helpers", ".", "instance_id", ".", "async_get", "(", ")", "else", ":", "huuid", "=", "None", "include_components", "=", "conf", ".", "get", "(", "CONF_COMPONENT_REPORTING", ")", "async", "def", "check_new_version", "(", ")", "->", "Updater", ":", "\"\"\"Check if a new version is available and report if one is.\"\"\"", "newest", ",", "release_notes", "=", "await", "get_newest_version", "(", "hass", ",", "huuid", ",", "include_components", ")", "_LOGGER", ".", "debug", "(", "\"Fetched version %s: %s\"", ",", "newest", ",", "release_notes", ")", "# Skip on dev", "if", "\"dev\"", "in", "current_version", ":", "return", "Updater", "(", "False", ",", "\"\"", ",", "\"\"", ")", "# Load data from Supervisor", "if", "hass", ".", "components", ".", "hassio", ".", "is_hassio", "(", ")", ":", "core_info", "=", "hass", ".", "components", ".", "hassio", ".", "get_core_info", "(", ")", "newest", "=", "core_info", "[", "\"version_latest\"", "]", "# Validate version", "update_available", "=", "False", "if", "StrictVersion", "(", "newest", ")", ">", "StrictVersion", "(", "current_version", ")", ":", "_LOGGER", ".", "debug", "(", "\"The latest available version of Home Assistant is %s\"", ",", "newest", ")", "update_available", "=", "True", "elif", "StrictVersion", "(", "newest", ")", "==", "StrictVersion", "(", "current_version", ")", ":", "_LOGGER", ".", "debug", "(", "\"You are on the latest version (%s) of Home Assistant\"", ",", "newest", ")", "elif", "StrictVersion", "(", "newest", ")", "<", "StrictVersion", "(", "current_version", ")", ":", "_LOGGER", ".", "debug", "(", "\"Local version is newer than the latest version (%s)\"", ",", "newest", ")", "_LOGGER", ".", "debug", "(", "\"Update available: %s\"", ",", "update_available", ")", "return", "Updater", "(", "update_available", ",", "newest", ",", "release_notes", ")", "coordinator", "=", "hass", ".", "data", "[", "DOMAIN", "]", "=", "update_coordinator", ".", "DataUpdateCoordinator", "[", "Updater", "]", "(", "hass", ",", "_LOGGER", ",", "name", "=", "\"Home Assistant update\"", ",", "update_method", "=", "check_new_version", ",", "update_interval", "=", "timedelta", "(", "days", "=", "1", ")", ",", ")", "# This can take up to 15s which can delay startup", "asyncio", ".", "create_task", "(", "coordinator", ".", "async_refresh", "(", ")", ")", "hass", ".", "async_create_task", "(", "discovery", ".", "async_load_platform", "(", "hass", ",", "\"binary_sensor\"", ",", "DOMAIN", ",", "{", "}", ",", "config", ")", ")", "return", "True" ]
[ 52, 0 ]
[ 116, 15 ]
python
en
['en', 'en', 'en']
True
get_newest_version
(hass, huuid, include_components)
Get the newest Home Assistant version.
Get the newest Home Assistant version.
async def get_newest_version(hass, huuid, include_components): """Get the newest Home Assistant version.""" if huuid: info_object = await hass.helpers.system_info.async_get_system_info() if include_components: info_object["components"] = list(hass.config.components) linux_dist = await hass.async_add_executor_job(linux_distribution, False) info_object["distribution"] = linux_dist[0] info_object["os_version"] = linux_dist[1] info_object["huuid"] = huuid else: info_object = {} session = async_get_clientsession(hass) with async_timeout.timeout(30): req = await session.post(UPDATER_URL, json=info_object) _LOGGER.info( ( "Submitted analytics to Home Assistant servers. " "Information submitted includes %s" ), info_object, ) try: res = await req.json() except ValueError as err: raise update_coordinator.UpdateFailed( "Received invalid JSON from Home Assistant Update" ) from err try: res = RESPONSE_SCHEMA(res) return res["version"], res["release-notes"] except vol.Invalid as err: raise update_coordinator.UpdateFailed( f"Got unexpected response: {err}" ) from err
[ "async", "def", "get_newest_version", "(", "hass", ",", "huuid", ",", "include_components", ")", ":", "if", "huuid", ":", "info_object", "=", "await", "hass", ".", "helpers", ".", "system_info", ".", "async_get_system_info", "(", ")", "if", "include_components", ":", "info_object", "[", "\"components\"", "]", "=", "list", "(", "hass", ".", "config", ".", "components", ")", "linux_dist", "=", "await", "hass", ".", "async_add_executor_job", "(", "linux_distribution", ",", "False", ")", "info_object", "[", "\"distribution\"", "]", "=", "linux_dist", "[", "0", "]", "info_object", "[", "\"os_version\"", "]", "=", "linux_dist", "[", "1", "]", "info_object", "[", "\"huuid\"", "]", "=", "huuid", "else", ":", "info_object", "=", "{", "}", "session", "=", "async_get_clientsession", "(", "hass", ")", "with", "async_timeout", ".", "timeout", "(", "30", ")", ":", "req", "=", "await", "session", ".", "post", "(", "UPDATER_URL", ",", "json", "=", "info_object", ")", "_LOGGER", ".", "info", "(", "(", "\"Submitted analytics to Home Assistant servers. \"", "\"Information submitted includes %s\"", ")", ",", "info_object", ",", ")", "try", ":", "res", "=", "await", "req", ".", "json", "(", ")", "except", "ValueError", "as", "err", ":", "raise", "update_coordinator", ".", "UpdateFailed", "(", "\"Received invalid JSON from Home Assistant Update\"", ")", "from", "err", "try", ":", "res", "=", "RESPONSE_SCHEMA", "(", "res", ")", "return", "res", "[", "\"version\"", "]", ",", "res", "[", "\"release-notes\"", "]", "except", "vol", ".", "Invalid", "as", "err", ":", "raise", "update_coordinator", ".", "UpdateFailed", "(", "f\"Got unexpected response: {err}\"", ")", "from", "err" ]
[ 119, 0 ]
[ 161, 18 ]
python
en
['en', 'en', 'en']
True
Updater.__init__
(self, update_available: bool, newest_version: str, release_notes: str)
Initialize attributes.
Initialize attributes.
def __init__(self, update_available: bool, newest_version: str, release_notes: str): """Initialize attributes.""" self.update_available = update_available self.release_notes = release_notes self.newest_version = newest_version
[ "def", "__init__", "(", "self", ",", "update_available", ":", "bool", ",", "newest_version", ":", "str", ",", "release_notes", ":", "str", ")", ":", "self", ".", "update_available", "=", "update_available", "self", ".", "release_notes", "=", "release_notes", "self", ".", "newest_version", "=", "newest_version" ]
[ 45, 4 ]
[ 49, 44 ]
python
en
['en', 'en', 'it']
False
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the Transmission switch.
Set up the Transmission switch.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Transmission switch.""" tm_client = hass.data[DOMAIN][config_entry.entry_id] name = config_entry.data[CONF_NAME] dev = [] for switch_type, switch_name in SWITCH_TYPES.items(): dev.append(TransmissionSwitch(switch_type, switch_name, tm_client, name)) async_add_entities(dev, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "tm_client", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "name", "=", "config_entry", ".", "data", "[", "CONF_NAME", "]", "dev", "=", "[", "]", "for", "switch_type", ",", "switch_name", "in", "SWITCH_TYPES", ".", "items", "(", ")", ":", "dev", ".", "append", "(", "TransmissionSwitch", "(", "switch_type", ",", "switch_name", ",", "tm_client", ",", "name", ")", ")", "async_add_entities", "(", "dev", ",", "True", ")" ]
[ 13, 0 ]
[ 23, 33 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.__init__
(self, switch_type, switch_name, tm_client, name)
Initialize the Transmission switch.
Initialize the Transmission switch.
def __init__(self, switch_type, switch_name, tm_client, name): """Initialize the Transmission switch.""" self._name = switch_name self.client_name = name self.type = switch_type self._tm_client = tm_client self._state = STATE_OFF self._data = None self.unsub_update = None
[ "def", "__init__", "(", "self", ",", "switch_type", ",", "switch_name", ",", "tm_client", ",", "name", ")", ":", "self", ".", "_name", "=", "switch_name", "self", ".", "client_name", "=", "name", "self", ".", "type", "=", "switch_type", "self", ".", "_tm_client", "=", "tm_client", "self", ".", "_state", "=", "STATE_OFF", "self", ".", "_data", "=", "None", "self", ".", "unsub_update", "=", "None" ]
[ 29, 4 ]
[ 37, 32 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.name
(self)
Return the name of the switch.
Return the name of the switch.
def name(self): """Return the name of the switch.""" return f"{self.client_name} {self._name}"
[ "def", "name", "(", "self", ")", ":", "return", "f\"{self.client_name} {self._name}\"" ]
[ 40, 4 ]
[ 42, 49 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.unique_id
(self)
Return the unique id of the entity.
Return the unique id of the entity.
def unique_id(self): """Return the unique id of the entity.""" return f"{self._tm_client.api.host}-{self.name}"
[ "def", "unique_id", "(", "self", ")", ":", "return", "f\"{self._tm_client.api.host}-{self.name}\"" ]
[ 45, 4 ]
[ 47, 56 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.state
(self)
Return the state of the device.
Return the state of the device.
def state(self): """Return the state of the device.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 50, 4 ]
[ 52, 26 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.should_poll
(self)
Poll for status regularly.
Poll for status regularly.
def should_poll(self): """Poll for status regularly.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 55, 4 ]
[ 57, 20 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.is_on
(self)
Return true if device is on.
Return true if device is on.
def is_on(self): """Return true if device is on.""" return self._state == STATE_ON
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state", "==", "STATE_ON" ]
[ 60, 4 ]
[ 62, 38 ]
python
en
['en', 'fy', 'en']
True
TransmissionSwitch.available
(self)
Could the device be accessed during the last update call.
Could the device be accessed during the last update call.
def available(self): """Could the device be accessed during the last update call.""" return self._tm_client.api.available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_tm_client", ".", "api", ".", "available" ]
[ 65, 4 ]
[ 67, 44 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.turn_on
(self, **kwargs)
Turn the device on.
Turn the device on.
def turn_on(self, **kwargs): """Turn the device on.""" if self.type == "on_off": _LOGGING.debug("Starting all torrents") self._tm_client.api.start_torrents() elif self.type == "turtle_mode": _LOGGING.debug("Turning Turtle Mode of Transmission on") self._tm_client.api.set_alt_speed_enabled(True) self._tm_client.api.update()
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "type", "==", "\"on_off\"", ":", "_LOGGING", ".", "debug", "(", "\"Starting all torrents\"", ")", "self", ".", "_tm_client", ".", "api", ".", "start_torrents", "(", ")", "elif", "self", ".", "type", "==", "\"turtle_mode\"", ":", "_LOGGING", ".", "debug", "(", "\"Turning Turtle Mode of Transmission on\"", ")", "self", ".", "_tm_client", ".", "api", ".", "set_alt_speed_enabled", "(", "True", ")", "self", ".", "_tm_client", ".", "api", ".", "update", "(", ")" ]
[ 69, 4 ]
[ 77, 36 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.turn_off
(self, **kwargs)
Turn the device off.
Turn the device off.
def turn_off(self, **kwargs): """Turn the device off.""" if self.type == "on_off": _LOGGING.debug("Stopping all torrents") self._tm_client.api.stop_torrents() if self.type == "turtle_mode": _LOGGING.debug("Turning Turtle Mode of Transmission off") self._tm_client.api.set_alt_speed_enabled(False) self._tm_client.api.update()
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "type", "==", "\"on_off\"", ":", "_LOGGING", ".", "debug", "(", "\"Stopping all torrents\"", ")", "self", ".", "_tm_client", ".", "api", ".", "stop_torrents", "(", ")", "if", "self", ".", "type", "==", "\"turtle_mode\"", ":", "_LOGGING", ".", "debug", "(", "\"Turning Turtle Mode of Transmission off\"", ")", "self", ".", "_tm_client", ".", "api", ".", "set_alt_speed_enabled", "(", "False", ")", "self", ".", "_tm_client", ".", "api", ".", "update", "(", ")" ]
[ 79, 4 ]
[ 87, 36 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.async_added_to_hass
(self)
Handle entity which will be added.
Handle entity which will be added.
async def async_added_to_hass(self): """Handle entity which will be added.""" self.unsub_update = async_dispatcher_connect( self.hass, self._tm_client.api.signal_update, self._schedule_immediate_update, )
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "self", ".", "unsub_update", "=", "async_dispatcher_connect", "(", "self", ".", "hass", ",", "self", ".", "_tm_client", ".", "api", ".", "signal_update", ",", "self", ".", "_schedule_immediate_update", ",", ")" ]
[ 89, 4 ]
[ 95, 9 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.will_remove_from_hass
(self)
Unsubscribe from update dispatcher.
Unsubscribe from update dispatcher.
async def will_remove_from_hass(self): """Unsubscribe from update dispatcher.""" if self.unsub_update: self.unsub_update() self.unsub_update = None
[ "async", "def", "will_remove_from_hass", "(", "self", ")", ":", "if", "self", ".", "unsub_update", ":", "self", ".", "unsub_update", "(", ")", "self", ".", "unsub_update", "=", "None" ]
[ 101, 4 ]
[ 105, 36 ]
python
en
['en', 'en', 'en']
True
TransmissionSwitch.update
(self)
Get the latest data from Transmission and updates the state.
Get the latest data from Transmission and updates the state.
def update(self): """Get the latest data from Transmission and updates the state.""" active = None if self.type == "on_off": self._data = self._tm_client.api.data if self._data: active = self._data.activeTorrentCount > 0 elif self.type == "turtle_mode": active = self._tm_client.api.get_alt_speed_enabled() if active is None: return self._state = STATE_ON if active else STATE_OFF
[ "def", "update", "(", "self", ")", ":", "active", "=", "None", "if", "self", ".", "type", "==", "\"on_off\"", ":", "self", ".", "_data", "=", "self", ".", "_tm_client", ".", "api", ".", "data", "if", "self", ".", "_data", ":", "active", "=", "self", ".", "_data", ".", "activeTorrentCount", ">", "0", "elif", "self", ".", "type", "==", "\"turtle_mode\"", ":", "active", "=", "self", ".", "_tm_client", ".", "api", ".", "get_alt_speed_enabled", "(", ")", "if", "active", "is", "None", ":", "return", "self", ".", "_state", "=", "STATE_ON", "if", "active", "else", "STATE_OFF" ]
[ 107, 4 ]
[ 121, 55 ]
python
en
['en', 'en', 'en']
True
PathConvertor.build_path_without_trailing_slash
(path: str)
Build source path without trailing '/'. Args: path (str): Original path. Returns: str: Reformatted path.
Build source path without trailing '/'.
def build_path_without_trailing_slash(path: str) -> str: """Build source path without trailing '/'. Args: path (str): Original path. Returns: str: Reformatted path. """ if path.endswith("/"): path = path[:-1] return path
[ "def", "build_path_without_trailing_slash", "(", "path", ":", "str", ")", "->", "str", ":", "if", "path", ".", "endswith", "(", "\"/\"", ")", ":", "path", "=", "path", "[", ":", "-", "1", "]", "return", "path" ]
[ 6, 4 ]
[ 17, 19 ]
python
en
['en', 'en', 'en']
True
PathConvertor.build_path_with_trailing_slash
(path: str)
Build reformatted target dir with trailing '/'. Args: path: (str): Original path. Returns: str: Reformatted path.
Build reformatted target dir with trailing '/'.
def build_path_with_trailing_slash(path: str) -> str: """Build reformatted target dir with trailing '/'. Args: path: (str): Original path. Returns: str: Reformatted path. """ if not path.endswith("/"): path = path + "/" return path
[ "def", "build_path_with_trailing_slash", "(", "path", ":", "str", ")", "->", "str", ":", "if", "not", "path", ".", "endswith", "(", "\"/\"", ")", ":", "path", "=", "path", "+", "\"/\"", "return", "path" ]
[ 20, 4 ]
[ 31, 19 ]
python
en
['en', 'en', 'en']
True
extract_placeholders
(obj: Any)
Extract placeholders from a structure.
Extract placeholders from a structure.
def extract_placeholders(obj: Any) -> Set[str]: """Extract placeholders from a structure.""" found: Set[str] = set() _extract_placeholders(obj, found) return found
[ "def", "extract_placeholders", "(", "obj", ":", "Any", ")", "->", "Set", "[", "str", "]", ":", "found", ":", "Set", "[", "str", "]", "=", "set", "(", ")", "_extract_placeholders", "(", "obj", ",", "found", ")", "return", "found" ]
[ 15, 0 ]
[ 19, 16 ]
python
en
['en', 'en', 'en']
True
_extract_placeholders
(obj: Any, found: Set[str])
Extract placeholders from a structure.
Extract placeholders from a structure.
def _extract_placeholders(obj: Any, found: Set[str]) -> None: """Extract placeholders from a structure.""" if isinstance(obj, Placeholder): found.add(obj.name) return if isinstance(obj, list): for val in obj: _extract_placeholders(val, found) return if isinstance(obj, dict): for val in obj.values(): _extract_placeholders(val, found) return
[ "def", "_extract_placeholders", "(", "obj", ":", "Any", ",", "found", ":", "Set", "[", "str", "]", ")", "->", "None", ":", "if", "isinstance", "(", "obj", ",", "Placeholder", ")", ":", "found", ".", "add", "(", "obj", ".", "name", ")", "return", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "val", "in", "obj", ":", "_extract_placeholders", "(", "val", ",", "found", ")", "return", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "for", "val", "in", "obj", ".", "values", "(", ")", ":", "_extract_placeholders", "(", "val", ",", "found", ")", "return" ]
[ 22, 0 ]
[ 36, 14 ]
python
en
['en', 'en', 'en']
True
substitute
(obj: Any, substitutions: Dict[str, Any])
Substitute values.
Substitute values.
def substitute(obj: Any, substitutions: Dict[str, Any]) -> Any: """Substitute values.""" if isinstance(obj, Placeholder): if obj.name not in substitutions: raise UndefinedSubstitution(obj.name) return substitutions[obj.name] if isinstance(obj, list): return [substitute(val, substitutions) for val in obj] if isinstance(obj, dict): return {key: substitute(val, substitutions) for key, val in obj.items()} return obj
[ "def", "substitute", "(", "obj", ":", "Any", ",", "substitutions", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Any", ":", "if", "isinstance", "(", "obj", ",", "Placeholder", ")", ":", "if", "obj", ".", "name", "not", "in", "substitutions", ":", "raise", "UndefinedSubstitution", "(", "obj", ".", "name", ")", "return", "substitutions", "[", "obj", ".", "name", "]", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "return", "[", "substitute", "(", "val", ",", "substitutions", ")", "for", "val", "in", "obj", "]", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "{", "key", ":", "substitute", "(", "val", ",", "substitutions", ")", "for", "key", ",", "val", "in", "obj", ".", "items", "(", ")", "}", "return", "obj" ]
[ 39, 0 ]
[ 52, 14 ]
python
en
['en', 'la', 'en']
False
UndefinedSubstitution.__init__
(self, placeholder: str)
Initialize the undefined substitution exception.
Initialize the undefined substitution exception.
def __init__(self, placeholder: str) -> None: """Initialize the undefined substitution exception.""" super().__init__(f"No substitution found for placeholder {placeholder}") self.placeholder = placeholder
[ "def", "__init__", "(", "self", ",", "placeholder", ":", "str", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "f\"No substitution found for placeholder {placeholder}\"", ")", "self", ".", "placeholder", "=", "placeholder" ]
[ 9, 4 ]
[ 12, 38 ]
python
en
['en', 'en', 'en']
True
test_async_setup_no_domain_config
(hass: HomeAssistant)
Test setup without configuration is noop.
Test setup without configuration is noop.
async def test_async_setup_no_domain_config(hass: HomeAssistant): """Test setup without configuration is noop.""" result = await async_setup_component(hass, DOMAIN, {}) assert result is True
[ "async", "def", "test_async_setup_no_domain_config", "(", "hass", ":", "HomeAssistant", ")", ":", "result", "=", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "}", ")", "assert", "result", "is", "True" ]
[ 19, 0 ]
[ 23, 25 ]
python
en
['en', 'en', 'en']
True
test_async_setup_raises_entry_not_ready
(hass: HomeAssistant)
Test that it throws ConfigEntryNotReady when exception occurs during setup.
Test that it throws ConfigEntryNotReady when exception occurs during setup.
async def test_async_setup_raises_entry_not_ready(hass: HomeAssistant): """Test that it throws ConfigEntryNotReady when exception occurs during setup.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"}, ) config_entry.add_to_hass(hass) with patch_bond_version(side_effect=ClientConnectionError()): await hass.config_entries.async_setup(config_entry.entry_id) assert config_entry.state == ENTRY_STATE_SETUP_RETRY
[ "async", "def", "test_async_setup_raises_entry_not_ready", "(", "hass", ":", "HomeAssistant", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "CONF_HOST", ":", "\"some host\"", ",", "CONF_ACCESS_TOKEN", ":", "\"test-token\"", "}", ",", ")", "config_entry", ".", "add_to_hass", "(", "hass", ")", "with", "patch_bond_version", "(", "side_effect", "=", "ClientConnectionError", "(", ")", ")", ":", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "config_entry", ".", "entry_id", ")", "assert", "config_entry", ".", "state", "==", "ENTRY_STATE_SETUP_RETRY" ]
[ 26, 0 ]
[ 36, 56 ]
python
en
['en', 'en', 'en']
True
test_async_setup_entry_sets_up_hub_and_supported_domains
(hass: HomeAssistant)
Test that configuring entry sets up cover domain.
Test that configuring entry sets up cover domain.
async def test_async_setup_entry_sets_up_hub_and_supported_domains(hass: HomeAssistant): """Test that configuring entry sets up cover domain.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"}, ) with patch_bond_version( return_value={ "bondid": "test-bond-id", "target": "test-model", "fw_ver": "test-version", } ): with patch_setup_entry( "cover" ) as mock_cover_async_setup_entry, patch_setup_entry( "fan" ) as mock_fan_async_setup_entry, patch_setup_entry( "light" ) as mock_light_async_setup_entry, patch_setup_entry( "switch" ) as mock_switch_async_setup_entry: result = await setup_bond_entity(hass, config_entry, patch_device_ids=True) assert result is True await hass.async_block_till_done() assert config_entry.entry_id in hass.data[DOMAIN] assert config_entry.state == ENTRY_STATE_LOADED assert config_entry.unique_id == "test-bond-id" # verify hub device is registered correctly device_registry = await dr.async_get_registry(hass) hub = device_registry.async_get_device( identifiers={(DOMAIN, "test-bond-id")}, connections=set() ) assert hub.name == "test-bond-id" assert hub.manufacturer == "Olibra" assert hub.model == "test-model" assert hub.sw_version == "test-version" # verify supported domains are setup assert len(mock_cover_async_setup_entry.mock_calls) == 1 assert len(mock_fan_async_setup_entry.mock_calls) == 1 assert len(mock_light_async_setup_entry.mock_calls) == 1 assert len(mock_switch_async_setup_entry.mock_calls) == 1
[ "async", "def", "test_async_setup_entry_sets_up_hub_and_supported_domains", "(", "hass", ":", "HomeAssistant", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "CONF_HOST", ":", "\"some host\"", ",", "CONF_ACCESS_TOKEN", ":", "\"test-token\"", "}", ",", ")", "with", "patch_bond_version", "(", "return_value", "=", "{", "\"bondid\"", ":", "\"test-bond-id\"", ",", "\"target\"", ":", "\"test-model\"", ",", "\"fw_ver\"", ":", "\"test-version\"", ",", "}", ")", ":", "with", "patch_setup_entry", "(", "\"cover\"", ")", "as", "mock_cover_async_setup_entry", ",", "patch_setup_entry", "(", "\"fan\"", ")", "as", "mock_fan_async_setup_entry", ",", "patch_setup_entry", "(", "\"light\"", ")", "as", "mock_light_async_setup_entry", ",", "patch_setup_entry", "(", "\"switch\"", ")", "as", "mock_switch_async_setup_entry", ":", "result", "=", "await", "setup_bond_entity", "(", "hass", ",", "config_entry", ",", "patch_device_ids", "=", "True", ")", "assert", "result", "is", "True", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "config_entry", ".", "entry_id", "in", "hass", ".", "data", "[", "DOMAIN", "]", "assert", "config_entry", ".", "state", "==", "ENTRY_STATE_LOADED", "assert", "config_entry", ".", "unique_id", "==", "\"test-bond-id\"", "# verify hub device is registered correctly", "device_registry", "=", "await", "dr", ".", "async_get_registry", "(", "hass", ")", "hub", "=", "device_registry", ".", "async_get_device", "(", "identifiers", "=", "{", "(", "DOMAIN", ",", "\"test-bond-id\"", ")", "}", ",", "connections", "=", "set", "(", ")", ")", "assert", "hub", ".", "name", "==", "\"test-bond-id\"", "assert", "hub", ".", "manufacturer", "==", "\"Olibra\"", "assert", "hub", ".", "model", "==", "\"test-model\"", "assert", "hub", ".", "sw_version", "==", "\"test-version\"", "# verify supported domains are setup", "assert", "len", "(", "mock_cover_async_setup_entry", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_fan_async_setup_entry", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_light_async_setup_entry", ".", "mock_calls", ")", "==", "1", "assert", "len", "(", "mock_switch_async_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 39, 0 ]
[ 84, 61 ]
python
en
['en', 'en', 'en']
True
test_unload_config_entry
(hass: HomeAssistant)
Test that configuration entry supports unloading.
Test that configuration entry supports unloading.
async def test_unload_config_entry(hass: HomeAssistant): """Test that configuration entry supports unloading.""" config_entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: "some host", CONF_ACCESS_TOKEN: "test-token"}, ) result = await setup_bond_entity( hass, config_entry, patch_version=True, patch_device_ids=True, patch_platforms=True, ) assert result is True await hass.async_block_till_done() await hass.config_entries.async_unload(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.entry_id not in hass.data[DOMAIN] assert config_entry.state == ENTRY_STATE_NOT_LOADED
[ "async", "def", "test_unload_config_entry", "(", "hass", ":", "HomeAssistant", ")", ":", "config_entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "CONF_HOST", ":", "\"some host\"", ",", "CONF_ACCESS_TOKEN", ":", "\"test-token\"", "}", ",", ")", "result", "=", "await", "setup_bond_entity", "(", "hass", ",", "config_entry", ",", "patch_version", "=", "True", ",", "patch_device_ids", "=", "True", ",", "patch_platforms", "=", "True", ",", ")", "assert", "result", "is", "True", "await", "hass", ".", "async_block_till_done", "(", ")", "await", "hass", ".", "config_entries", ".", "async_unload", "(", "config_entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "config_entry", ".", "entry_id", "not", "in", "hass", ".", "data", "[", "DOMAIN", "]", "assert", "config_entry", ".", "state", "==", "ENTRY_STATE_NOT_LOADED" ]
[ 87, 0 ]
[ 108, 55 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass, config)
Set up the KNX component.
Set up the KNX component.
async def async_setup(hass, config): """Set up the KNX component.""" try: hass.data[DOMAIN] = KNXModule(hass, config) hass.data[DOMAIN].async_create_exposures() await hass.data[DOMAIN].start() except XKNXException as ex: _LOGGER.warning("Could not connect to KNX interface: %s", ex) hass.components.persistent_notification.async_create( f"Could not connect to KNX interface: <br><b>{ex}</b>", title="KNX" ) for platform in SupportedPlatforms: if platform.value in config[DOMAIN]: for device_config in config[DOMAIN][platform.value]: create_knx_device(platform, hass.data[DOMAIN].xknx, device_config) # We need to wait until all entities are loaded into the device list since they could also be created from other platforms for platform in SupportedPlatforms: hass.async_create_task( discovery.async_load_platform(hass, platform.value, DOMAIN, {}, config) ) if not hass.data[DOMAIN].xknx.devices: _LOGGER.warning( "No KNX devices are configured. Please read " "https://www.home-assistant.io/blog/2020/09/17/release-115/#breaking-changes" ) hass.services.async_register( DOMAIN, SERVICE_KNX_SEND, hass.data[DOMAIN].service_send_to_knx_bus, schema=SERVICE_KNX_SEND_SCHEMA, ) async def reload_service_handler(service_call: ServiceCallType) -> None: """Remove all KNX components and load new ones from config.""" # First check for config file. If for some reason it is no longer there # or knx is no longer mentioned, stop the reload. config = await async_integration_yaml_config(hass, DOMAIN) if not config or DOMAIN not in config: return await hass.data[DOMAIN].xknx.stop() await asyncio.gather( *[platform.async_reset() for platform in async_get_platforms(hass, DOMAIN)] ) await async_setup(hass, config) async_register_admin_service( hass, DOMAIN, SERVICE_RELOAD, reload_service_handler, schema=vol.Schema({}) ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "try", ":", "hass", ".", "data", "[", "DOMAIN", "]", "=", "KNXModule", "(", "hass", ",", "config", ")", "hass", ".", "data", "[", "DOMAIN", "]", ".", "async_create_exposures", "(", ")", "await", "hass", ".", "data", "[", "DOMAIN", "]", ".", "start", "(", ")", "except", "XKNXException", "as", "ex", ":", "_LOGGER", ".", "warning", "(", "\"Could not connect to KNX interface: %s\"", ",", "ex", ")", "hass", ".", "components", ".", "persistent_notification", ".", "async_create", "(", "f\"Could not connect to KNX interface: <br><b>{ex}</b>\"", ",", "title", "=", "\"KNX\"", ")", "for", "platform", "in", "SupportedPlatforms", ":", "if", "platform", ".", "value", "in", "config", "[", "DOMAIN", "]", ":", "for", "device_config", "in", "config", "[", "DOMAIN", "]", "[", "platform", ".", "value", "]", ":", "create_knx_device", "(", "platform", ",", "hass", ".", "data", "[", "DOMAIN", "]", ".", "xknx", ",", "device_config", ")", "# We need to wait until all entities are loaded into the device list since they could also be created from other platforms", "for", "platform", "in", "SupportedPlatforms", ":", "hass", ".", "async_create_task", "(", "discovery", ".", "async_load_platform", "(", "hass", ",", "platform", ".", "value", ",", "DOMAIN", ",", "{", "}", ",", "config", ")", ")", "if", "not", "hass", ".", "data", "[", "DOMAIN", "]", ".", "xknx", ".", "devices", ":", "_LOGGER", ".", "warning", "(", "\"No KNX devices are configured. Please read \"", "\"https://www.home-assistant.io/blog/2020/09/17/release-115/#breaking-changes\"", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_KNX_SEND", ",", "hass", ".", "data", "[", "DOMAIN", "]", ".", "service_send_to_knx_bus", ",", "schema", "=", "SERVICE_KNX_SEND_SCHEMA", ",", ")", "async", "def", "reload_service_handler", "(", "service_call", ":", "ServiceCallType", ")", "->", "None", ":", "\"\"\"Remove all KNX components and load new ones from config.\"\"\"", "# First check for config file. If for some reason it is no longer there", "# or knx is no longer mentioned, stop the reload.", "config", "=", "await", "async_integration_yaml_config", "(", "hass", ",", "DOMAIN", ")", "if", "not", "config", "or", "DOMAIN", "not", "in", "config", ":", "return", "await", "hass", ".", "data", "[", "DOMAIN", "]", ".", "xknx", ".", "stop", "(", ")", "await", "asyncio", ".", "gather", "(", "*", "[", "platform", ".", "async_reset", "(", ")", "for", "platform", "in", "async_get_platforms", "(", "hass", ",", "DOMAIN", ")", "]", ")", "await", "async_setup", "(", "hass", ",", "config", ")", "async_register_admin_service", "(", "hass", ",", "DOMAIN", ",", "SERVICE_RELOAD", ",", "reload_service_handler", ",", "schema", "=", "vol", ".", "Schema", "(", "{", "}", ")", ")", "return", "True" ]
[ 144, 0 ]
[ 202, 15 ]
python
en
['en', 'en', 'en']
True
KNXModule.__init__
(self, hass, config)
Initialize of KNX module.
Initialize of KNX module.
def __init__(self, hass, config): """Initialize of KNX module.""" self.hass = hass self.config = config self.connected = False self.init_xknx() self.register_callbacks() self.exposures = []
[ "def", "__init__", "(", "self", ",", "hass", ",", "config", ")", ":", "self", ".", "hass", "=", "hass", "self", ".", "config", "=", "config", "self", ".", "connected", "=", "False", "self", ".", "init_xknx", "(", ")", "self", ".", "register_callbacks", "(", ")", "self", ".", "exposures", "=", "[", "]" ]
[ 208, 4 ]
[ 215, 27 ]
python
en
['en', 'en', 'en']
True
KNXModule.init_xknx
(self)
Initialize of KNX object.
Initialize of KNX object.
def init_xknx(self): """Initialize of KNX object.""" self.xknx = XKNX( config=self.config_file(), own_address=self.config[DOMAIN][CONF_KNX_INDIVIDUAL_ADDRESS], rate_limit=self.config[DOMAIN][CONF_KNX_RATE_LIMIT], multicast_group=self.config[DOMAIN][CONF_KNX_MCAST_GRP], multicast_port=self.config[DOMAIN][CONF_KNX_MCAST_PORT], connection_config=self.connection_config(), state_updater=self.config[DOMAIN][CONF_KNX_STATE_UPDATER], )
[ "def", "init_xknx", "(", "self", ")", ":", "self", ".", "xknx", "=", "XKNX", "(", "config", "=", "self", ".", "config_file", "(", ")", ",", "own_address", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_INDIVIDUAL_ADDRESS", "]", ",", "rate_limit", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_RATE_LIMIT", "]", ",", "multicast_group", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_MCAST_GRP", "]", ",", "multicast_port", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_MCAST_PORT", "]", ",", "connection_config", "=", "self", ".", "connection_config", "(", ")", ",", "state_updater", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_STATE_UPDATER", "]", ",", ")" ]
[ 217, 4 ]
[ 227, 9 ]
python
en
['en', 'en', 'en']
True
KNXModule.start
(self)
Start KNX object. Connect to tunneling or Routing device.
Start KNX object. Connect to tunneling or Routing device.
async def start(self): """Start KNX object. Connect to tunneling or Routing device.""" await self.xknx.start() self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop) self.connected = True
[ "async", "def", "start", "(", "self", ")", ":", "await", "self", ".", "xknx", ".", "start", "(", ")", "self", ".", "hass", ".", "bus", ".", "async_listen_once", "(", "EVENT_HOMEASSISTANT_STOP", ",", "self", ".", "stop", ")", "self", ".", "connected", "=", "True" ]
[ 229, 4 ]
[ 233, 29 ]
python
en
['en', 'en', 'en']
True
KNXModule.stop
(self, event)
Stop KNX object. Disconnect from tunneling or Routing device.
Stop KNX object. Disconnect from tunneling or Routing device.
async def stop(self, event): """Stop KNX object. Disconnect from tunneling or Routing device.""" await self.xknx.stop()
[ "async", "def", "stop", "(", "self", ",", "event", ")", ":", "await", "self", ".", "xknx", ".", "stop", "(", ")" ]
[ 235, 4 ]
[ 237, 30 ]
python
en
['en', 'en', 'en']
True
KNXModule.config_file
(self)
Resolve and return the full path of xknx.yaml if configured.
Resolve and return the full path of xknx.yaml if configured.
def config_file(self): """Resolve and return the full path of xknx.yaml if configured.""" config_file = self.config[DOMAIN].get(CONF_KNX_CONFIG) if not config_file: return None if not config_file.startswith("/"): return self.hass.config.path(config_file) return config_file
[ "def", "config_file", "(", "self", ")", ":", "config_file", "=", "self", ".", "config", "[", "DOMAIN", "]", ".", "get", "(", "CONF_KNX_CONFIG", ")", "if", "not", "config_file", ":", "return", "None", "if", "not", "config_file", ".", "startswith", "(", "\"/\"", ")", ":", "return", "self", ".", "hass", ".", "config", ".", "path", "(", "config_file", ")", "return", "config_file" ]
[ 239, 4 ]
[ 246, 26 ]
python
en
['en', 'en', 'en']
True
KNXModule.connection_config
(self)
Return the connection_config.
Return the connection_config.
def connection_config(self): """Return the connection_config.""" if CONF_KNX_TUNNELING in self.config[DOMAIN]: return self.connection_config_tunneling() if CONF_KNX_ROUTING in self.config[DOMAIN]: return self.connection_config_routing() # config from xknx.yaml always has priority later on return ConnectionConfig()
[ "def", "connection_config", "(", "self", ")", ":", "if", "CONF_KNX_TUNNELING", "in", "self", ".", "config", "[", "DOMAIN", "]", ":", "return", "self", ".", "connection_config_tunneling", "(", ")", "if", "CONF_KNX_ROUTING", "in", "self", ".", "config", "[", "DOMAIN", "]", ":", "return", "self", ".", "connection_config_routing", "(", ")", "# config from xknx.yaml always has priority later on", "return", "ConnectionConfig", "(", ")" ]
[ 248, 4 ]
[ 255, 33 ]
python
en
['en', 'en', 'en']
True
KNXModule.connection_config_routing
(self)
Return the connection_config if routing is configured.
Return the connection_config if routing is configured.
def connection_config_routing(self): """Return the connection_config if routing is configured.""" local_ip = self.config[DOMAIN][CONF_KNX_ROUTING].get( ConnectionSchema.CONF_KNX_LOCAL_IP ) return ConnectionConfig( connection_type=ConnectionType.ROUTING, local_ip=local_ip )
[ "def", "connection_config_routing", "(", "self", ")", ":", "local_ip", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_ROUTING", "]", ".", "get", "(", "ConnectionSchema", ".", "CONF_KNX_LOCAL_IP", ")", "return", "ConnectionConfig", "(", "connection_type", "=", "ConnectionType", ".", "ROUTING", ",", "local_ip", "=", "local_ip", ")" ]
[ 257, 4 ]
[ 264, 9 ]
python
en
['en', 'en', 'en']
True
KNXModule.connection_config_tunneling
(self)
Return the connection_config if tunneling is configured.
Return the connection_config if tunneling is configured.
def connection_config_tunneling(self): """Return the connection_config if tunneling is configured.""" gateway_ip = self.config[DOMAIN][CONF_KNX_TUNNELING][CONF_HOST] gateway_port = self.config[DOMAIN][CONF_KNX_TUNNELING][CONF_PORT] local_ip = self.config[DOMAIN][CONF_KNX_TUNNELING].get( ConnectionSchema.CONF_KNX_LOCAL_IP ) return ConnectionConfig( connection_type=ConnectionType.TUNNELING, gateway_ip=gateway_ip, gateway_port=gateway_port, local_ip=local_ip, auto_reconnect=True, )
[ "def", "connection_config_tunneling", "(", "self", ")", ":", "gateway_ip", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_TUNNELING", "]", "[", "CONF_HOST", "]", "gateway_port", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_TUNNELING", "]", "[", "CONF_PORT", "]", "local_ip", "=", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_TUNNELING", "]", ".", "get", "(", "ConnectionSchema", ".", "CONF_KNX_LOCAL_IP", ")", "return", "ConnectionConfig", "(", "connection_type", "=", "ConnectionType", ".", "TUNNELING", ",", "gateway_ip", "=", "gateway_ip", ",", "gateway_port", "=", "gateway_port", ",", "local_ip", "=", "local_ip", ",", "auto_reconnect", "=", "True", ",", ")" ]
[ 266, 4 ]
[ 279, 9 ]
python
en
['en', 'en', 'en']
True
KNXModule.register_callbacks
(self)
Register callbacks within XKNX object.
Register callbacks within XKNX object.
def register_callbacks(self): """Register callbacks within XKNX object.""" if ( CONF_KNX_FIRE_EVENT in self.config[DOMAIN] and self.config[DOMAIN][CONF_KNX_FIRE_EVENT] ): address_filters = list( map(AddressFilter, self.config[DOMAIN][CONF_KNX_FIRE_EVENT_FILTER]) ) self.xknx.telegram_queue.register_telegram_received_cb( self.telegram_received_cb, address_filters )
[ "def", "register_callbacks", "(", "self", ")", ":", "if", "(", "CONF_KNX_FIRE_EVENT", "in", "self", ".", "config", "[", "DOMAIN", "]", "and", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_FIRE_EVENT", "]", ")", ":", "address_filters", "=", "list", "(", "map", "(", "AddressFilter", ",", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_FIRE_EVENT_FILTER", "]", ")", ")", "self", ".", "xknx", ".", "telegram_queue", ".", "register_telegram_received_cb", "(", "self", ".", "telegram_received_cb", ",", "address_filters", ")" ]
[ 281, 4 ]
[ 292, 13 ]
python
en
['en', 'en', 'en']
True
KNXModule.async_create_exposures
(self)
Create exposures.
Create exposures.
def async_create_exposures(self): """Create exposures.""" if CONF_KNX_EXPOSE not in self.config[DOMAIN]: return for to_expose in self.config[DOMAIN][CONF_KNX_EXPOSE]: expose_type = to_expose.get(ExposeSchema.CONF_KNX_EXPOSE_TYPE) entity_id = to_expose.get(CONF_ENTITY_ID) attribute = to_expose.get(ExposeSchema.CONF_KNX_EXPOSE_ATTRIBUTE) default = to_expose.get(ExposeSchema.CONF_KNX_EXPOSE_DEFAULT) address = to_expose.get(ExposeSchema.CONF_KNX_EXPOSE_ADDRESS) if expose_type.lower() in ["time", "date", "datetime"]: exposure = KNXExposeTime(self.xknx, expose_type, address) exposure.async_register() self.exposures.append(exposure) else: exposure = KNXExposeSensor( self.hass, self.xknx, expose_type, entity_id, attribute, default, address, ) exposure.async_register() self.exposures.append(exposure)
[ "def", "async_create_exposures", "(", "self", ")", ":", "if", "CONF_KNX_EXPOSE", "not", "in", "self", ".", "config", "[", "DOMAIN", "]", ":", "return", "for", "to_expose", "in", "self", ".", "config", "[", "DOMAIN", "]", "[", "CONF_KNX_EXPOSE", "]", ":", "expose_type", "=", "to_expose", ".", "get", "(", "ExposeSchema", ".", "CONF_KNX_EXPOSE_TYPE", ")", "entity_id", "=", "to_expose", ".", "get", "(", "CONF_ENTITY_ID", ")", "attribute", "=", "to_expose", ".", "get", "(", "ExposeSchema", ".", "CONF_KNX_EXPOSE_ATTRIBUTE", ")", "default", "=", "to_expose", ".", "get", "(", "ExposeSchema", ".", "CONF_KNX_EXPOSE_DEFAULT", ")", "address", "=", "to_expose", ".", "get", "(", "ExposeSchema", ".", "CONF_KNX_EXPOSE_ADDRESS", ")", "if", "expose_type", ".", "lower", "(", ")", "in", "[", "\"time\"", ",", "\"date\"", ",", "\"datetime\"", "]", ":", "exposure", "=", "KNXExposeTime", "(", "self", ".", "xknx", ",", "expose_type", ",", "address", ")", "exposure", ".", "async_register", "(", ")", "self", ".", "exposures", ".", "append", "(", "exposure", ")", "else", ":", "exposure", "=", "KNXExposeSensor", "(", "self", ".", "hass", ",", "self", ".", "xknx", ",", "expose_type", ",", "entity_id", ",", "attribute", ",", "default", ",", "address", ",", ")", "exposure", ".", "async_register", "(", ")", "self", ".", "exposures", ".", "append", "(", "exposure", ")" ]
[ 295, 4 ]
[ 320, 47 ]
python
en
['es', 'la', 'en']
False
KNXModule.telegram_received_cb
(self, telegram)
Call invoked after a KNX telegram was received.
Call invoked after a KNX telegram was received.
async def telegram_received_cb(self, telegram): """Call invoked after a KNX telegram was received.""" self.hass.bus.async_fire( "knx_event", {"address": str(telegram.group_address), "data": telegram.payload.value}, ) # False signals XKNX to proceed with processing telegrams. return False
[ "async", "def", "telegram_received_cb", "(", "self", ",", "telegram", ")", ":", "self", ".", "hass", ".", "bus", ".", "async_fire", "(", "\"knx_event\"", ",", "{", "\"address\"", ":", "str", "(", "telegram", ".", "group_address", ")", ",", "\"data\"", ":", "telegram", ".", "payload", ".", "value", "}", ",", ")", "# False signals XKNX to proceed with processing telegrams.", "return", "False" ]
[ 322, 4 ]
[ 329, 20 ]
python
en
['en', 'en', 'en']
True
KNXModule.service_send_to_knx_bus
(self, call)
Service for sending an arbitrary KNX message to the KNX bus.
Service for sending an arbitrary KNX message to the KNX bus.
async def service_send_to_knx_bus(self, call): """Service for sending an arbitrary KNX message to the KNX bus.""" attr_payload = call.data.get(SERVICE_KNX_ATTR_PAYLOAD) attr_address = call.data.get(SERVICE_KNX_ATTR_ADDRESS) attr_type = call.data.get(SERVICE_KNX_ATTR_TYPE) def calculate_payload(attr_payload): """Calculate payload depending on type of attribute.""" if attr_type is not None: transcoder = DPTBase.parse_transcoder(attr_type) if transcoder is None: raise ValueError(f"Invalid type for knx.send service: {attr_type}") return DPTArray(transcoder.to_knx(attr_payload)) if isinstance(attr_payload, int): return DPTBinary(attr_payload) return DPTArray(attr_payload) payload = calculate_payload(attr_payload) address = GroupAddress(attr_address) telegram = Telegram(group_address=address, payload=payload) await self.xknx.telegrams.put(telegram)
[ "async", "def", "service_send_to_knx_bus", "(", "self", ",", "call", ")", ":", "attr_payload", "=", "call", ".", "data", ".", "get", "(", "SERVICE_KNX_ATTR_PAYLOAD", ")", "attr_address", "=", "call", ".", "data", ".", "get", "(", "SERVICE_KNX_ATTR_ADDRESS", ")", "attr_type", "=", "call", ".", "data", ".", "get", "(", "SERVICE_KNX_ATTR_TYPE", ")", "def", "calculate_payload", "(", "attr_payload", ")", ":", "\"\"\"Calculate payload depending on type of attribute.\"\"\"", "if", "attr_type", "is", "not", "None", ":", "transcoder", "=", "DPTBase", ".", "parse_transcoder", "(", "attr_type", ")", "if", "transcoder", "is", "None", ":", "raise", "ValueError", "(", "f\"Invalid type for knx.send service: {attr_type}\"", ")", "return", "DPTArray", "(", "transcoder", ".", "to_knx", "(", "attr_payload", ")", ")", "if", "isinstance", "(", "attr_payload", ",", "int", ")", ":", "return", "DPTBinary", "(", "attr_payload", ")", "return", "DPTArray", "(", "attr_payload", ")", "payload", "=", "calculate_payload", "(", "attr_payload", ")", "address", "=", "GroupAddress", "(", "attr_address", ")", "telegram", "=", "Telegram", "(", "group_address", "=", "address", ",", "payload", "=", "payload", ")", "await", "self", ".", "xknx", ".", "telegrams", ".", "put", "(", "telegram", ")" ]
[ 331, 4 ]
[ 352, 47 ]
python
en
['en', 'en', 'en']
True
KNXExposeTime.__init__
(self, xknx: XKNX, expose_type: str, address: str)
Initialize of Expose class.
Initialize of Expose class.
def __init__(self, xknx: XKNX, expose_type: str, address: str): """Initialize of Expose class.""" self.xknx = xknx self.expose_type = expose_type self.address = address self.device = None
[ "def", "__init__", "(", "self", ",", "xknx", ":", "XKNX", ",", "expose_type", ":", "str", ",", "address", ":", "str", ")", ":", "self", ".", "xknx", "=", "xknx", "self", ".", "expose_type", "=", "expose_type", "self", ".", "address", "=", "address", "self", ".", "device", "=", "None" ]
[ 358, 4 ]
[ 363, 26 ]
python
en
['en', 'en', 'en']
True
KNXExposeTime.async_register
(self)
Register listener.
Register listener.
def async_register(self): """Register listener.""" self.device = DateTime( self.xknx, name=self.expose_type.capitalize(), broadcast_type=self.expose_type.upper(), localtime=True, group_address=self.address, )
[ "def", "async_register", "(", "self", ")", ":", "self", ".", "device", "=", "DateTime", "(", "self", ".", "xknx", ",", "name", "=", "self", ".", "expose_type", ".", "capitalize", "(", ")", ",", "broadcast_type", "=", "self", ".", "expose_type", ".", "upper", "(", ")", ",", "localtime", "=", "True", ",", "group_address", "=", "self", ".", "address", ",", ")" ]
[ 366, 4 ]
[ 374, 9 ]
python
en
['fr', 'no', 'en']
False
KNXExposeSensor.__init__
(self, hass, xknx, expose_type, entity_id, attribute, default, address)
Initialize of Expose class.
Initialize of Expose class.
def __init__(self, hass, xknx, expose_type, entity_id, attribute, default, address): """Initialize of Expose class.""" self.hass = hass self.xknx = xknx self.type = expose_type self.entity_id = entity_id self.expose_attribute = attribute self.expose_default = default self.address = address self.device = None
[ "def", "__init__", "(", "self", ",", "hass", ",", "xknx", ",", "expose_type", ",", "entity_id", ",", "attribute", ",", "default", ",", "address", ")", ":", "self", ".", "hass", "=", "hass", "self", ".", "xknx", "=", "xknx", "self", ".", "type", "=", "expose_type", "self", ".", "entity_id", "=", "entity_id", "self", ".", "expose_attribute", "=", "attribute", "self", ".", "expose_default", "=", "default", "self", ".", "address", "=", "address", "self", ".", "device", "=", "None" ]
[ 380, 4 ]
[ 389, 26 ]
python
en
['en', 'en', 'en']
True
KNXExposeSensor.async_register
(self)
Register listener.
Register listener.
def async_register(self): """Register listener.""" if self.expose_attribute is not None: _name = self.entity_id + "__" + self.expose_attribute else: _name = self.entity_id self.device = ExposeSensor( self.xknx, name=_name, group_address=self.address, value_type=self.type, ) async_track_state_change_event( self.hass, [self.entity_id], self._async_entity_changed )
[ "def", "async_register", "(", "self", ")", ":", "if", "self", ".", "expose_attribute", "is", "not", "None", ":", "_name", "=", "self", ".", "entity_id", "+", "\"__\"", "+", "self", ".", "expose_attribute", "else", ":", "_name", "=", "self", ".", "entity_id", "self", ".", "device", "=", "ExposeSensor", "(", "self", ".", "xknx", ",", "name", "=", "_name", ",", "group_address", "=", "self", ".", "address", ",", "value_type", "=", "self", ".", "type", ",", ")", "async_track_state_change_event", "(", "self", ".", "hass", ",", "[", "self", ".", "entity_id", "]", ",", "self", ".", "_async_entity_changed", ")" ]
[ 392, 4 ]
[ 406, 9 ]
python
en
['fr', 'no', 'en']
False
KNXExposeSensor._async_entity_changed
(self, event)
Handle entity change.
Handle entity change.
async def _async_entity_changed(self, event): """Handle entity change.""" new_state = event.data.get("new_state") if new_state is None: return if new_state.state in (STATE_UNKNOWN, STATE_UNAVAILABLE): return if self.expose_attribute is not None: new_attribute = new_state.attributes.get(self.expose_attribute) old_state = event.data.get("old_state") if old_state is not None: old_attribute = old_state.attributes.get(self.expose_attribute) if old_attribute == new_attribute: # don't send same value sequentially return await self._async_set_knx_value(new_attribute) else: await self._async_set_knx_value(new_state.state)
[ "async", "def", "_async_entity_changed", "(", "self", ",", "event", ")", ":", "new_state", "=", "event", ".", "data", ".", "get", "(", "\"new_state\"", ")", "if", "new_state", "is", "None", ":", "return", "if", "new_state", ".", "state", "in", "(", "STATE_UNKNOWN", ",", "STATE_UNAVAILABLE", ")", ":", "return", "if", "self", ".", "expose_attribute", "is", "not", "None", ":", "new_attribute", "=", "new_state", ".", "attributes", ".", "get", "(", "self", ".", "expose_attribute", ")", "old_state", "=", "event", ".", "data", ".", "get", "(", "\"old_state\"", ")", "if", "old_state", "is", "not", "None", ":", "old_attribute", "=", "old_state", ".", "attributes", ".", "get", "(", "self", ".", "expose_attribute", ")", "if", "old_attribute", "==", "new_attribute", ":", "# don't send same value sequentially", "return", "await", "self", ".", "_async_set_knx_value", "(", "new_attribute", ")", "else", ":", "await", "self", ".", "_async_set_knx_value", "(", "new_state", ".", "state", ")" ]
[ 408, 4 ]
[ 427, 60 ]
python
en
['en', 'xh', 'en']
True
KNXExposeSensor._async_set_knx_value
(self, value)
Set new value on xknx ExposeSensor.
Set new value on xknx ExposeSensor.
async def _async_set_knx_value(self, value): """Set new value on xknx ExposeSensor.""" if value is None: if self.expose_default is None: return value = self.expose_default if self.type == "binary": if value == STATE_ON: value = True elif value == STATE_OFF: value = False await self.device.set(value)
[ "async", "def", "_async_set_knx_value", "(", "self", ",", "value", ")", ":", "if", "value", "is", "None", ":", "if", "self", ".", "expose_default", "is", "None", ":", "return", "value", "=", "self", ".", "expose_default", "if", "self", ".", "type", "==", "\"binary\"", ":", "if", "value", "==", "STATE_ON", ":", "value", "=", "True", "elif", "value", "==", "STATE_OFF", ":", "value", "=", "False", "await", "self", ".", "device", ".", "set", "(", "value", ")" ]
[ 429, 4 ]
[ 442, 36 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Perform the setup for Switchbot devices.
Perform the setup for Switchbot devices.
def setup_platform(hass, config, add_entities, discovery_info=None): """Perform the setup for Switchbot devices.""" name = config.get(CONF_NAME) mac_addr = config[CONF_MAC] password = config.get(CONF_PASSWORD) add_entities([SwitchBot(mac_addr, name, password)])
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "mac_addr", "=", "config", "[", "CONF_MAC", "]", "password", "=", "config", ".", "get", "(", "CONF_PASSWORD", ")", "add_entities", "(", "[", "SwitchBot", "(", "mac_addr", ",", "name", ",", "password", ")", "]", ")" ]
[ 23, 0 ]
[ 28, 55 ]
python
en
['en', 'en', 'en']
True
SwitchBot.__init__
(self, mac, name, password)
Initialize the Switchbot.
Initialize the Switchbot.
def __init__(self, mac, name, password) -> None: """Initialize the Switchbot.""" self._state = None self._last_run_success = None self._name = name self._mac = mac self._device = switchbot.Switchbot(mac=mac, password=password)
[ "def", "__init__", "(", "self", ",", "mac", ",", "name", ",", "password", ")", "->", "None", ":", "self", ".", "_state", "=", "None", "self", ".", "_last_run_success", "=", "None", "self", ".", "_name", "=", "name", "self", ".", "_mac", "=", "mac", "self", ".", "_device", "=", "switchbot", ".", "Switchbot", "(", "mac", "=", "mac", ",", "password", "=", "password", ")" ]
[ 34, 4 ]
[ 41, 70 ]
python
en
['en', 'en', 'en']
True
SwitchBot.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() state = await self.async_get_last_state() if not state: return self._state = state.state == "on"
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "await", "super", "(", ")", ".", "async_added_to_hass", "(", ")", "state", "=", "await", "self", ".", "async_get_last_state", "(", ")", "if", "not", "state", ":", "return", "self", ".", "_state", "=", "state", ".", "state", "==", "\"on\"" ]
[ 43, 4 ]
[ 49, 41 ]
python
en
['en', 'en', 'en']
True
SwitchBot.turn_on
(self, **kwargs)
Turn device on.
Turn device on.
def turn_on(self, **kwargs) -> None: """Turn device on.""" if self._device.turn_on(): self._state = True self._last_run_success = True else: self._last_run_success = False
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "self", ".", "_device", ".", "turn_on", "(", ")", ":", "self", ".", "_state", "=", "True", "self", ".", "_last_run_success", "=", "True", "else", ":", "self", ".", "_last_run_success", "=", "False" ]
[ 51, 4 ]
[ 57, 42 ]
python
en
['es', 'en', 'en']
True
SwitchBot.turn_off
(self, **kwargs)
Turn device off.
Turn device off.
def turn_off(self, **kwargs) -> None: """Turn device off.""" if self._device.turn_off(): self._state = False self._last_run_success = True else: self._last_run_success = False
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "if", "self", ".", "_device", ".", "turn_off", "(", ")", ":", "self", ".", "_state", "=", "False", "self", ".", "_last_run_success", "=", "True", "else", ":", "self", ".", "_last_run_success", "=", "False" ]
[ 59, 4 ]
[ 65, 42 ]
python
en
['en', 'en', 'en']
True