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
RainMachineFlowHandler.__init__
(self)
Initialize the config flow.
Initialize the config flow.
def __init__(self): """Initialize the config flow.""" self.data_schema = vol.Schema( { vol.Required(CONF_IP_ADDRESS): str, vol.Required(CONF_PASSWORD): str, vol.Optional(CONF_PORT, default=DEFAULT_PORT): int, } )
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Required", "(", "CONF_IP_ADDRESS", ")", ":", "str", ",", "vol", ".", "Required", "(", "CONF_PASSWORD", ")", ":", "str", ",", "vol", ".", "Optional", "(", "CONF_PORT", ",", "default", "=", "DEFAULT_PORT", ")", ":", "int", ",", "}", ")" ]
[ 24, 4 ]
[ 32, 9 ]
python
en
['en', 'en', 'en']
True
RainMachineFlowHandler._show_form
(self, errors=None)
Show the form to the user.
Show the form to the user.
async def _show_form(self, errors=None): """Show the form to the user.""" return self.async_show_form( step_id="user", data_schema=self.data_schema, errors=errors if errors else {}, )
[ "async", "def", "_show_form", "(", "self", ",", "errors", "=", "None", ")", ":", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "self", ".", "data_schema", ",", "errors", "=", "errors", "if", "errors", "else", "{", "}", ",", ")" ]
[ 34, 4 ]
[ 40, 9 ]
python
en
['en', 'en', 'en']
True
RainMachineFlowHandler.async_get_options_flow
(config_entry)
Define the config flow to handle options.
Define the config flow to handle options.
def async_get_options_flow(config_entry): """Define the config flow to handle options.""" return RainMachineOptionsFlowHandler(config_entry)
[ "def", "async_get_options_flow", "(", "config_entry", ")", ":", "return", "RainMachineOptionsFlowHandler", "(", "config_entry", ")" ]
[ 44, 4 ]
[ 46, 58 ]
python
en
['en', 'en', 'en']
True
RainMachineFlowHandler.async_step_user
(self, user_input=None)
Handle the start of the config flow.
Handle the start of the config flow.
async def async_step_user(self, user_input=None): """Handle the start of the config flow.""" if not user_input: return await self._show_form() await self.async_set_unique_id(user_input[CONF_IP_ADDRESS]) self._abort_if_unique_id_configured() websession = aiohttp_client.async_get_clientsession(self.hass) client = Client(session=websession) try: await client.load_local( user_input[CONF_IP_ADDRESS], user_input[CONF_PASSWORD], port=user_input[CONF_PORT], ssl=user_input.get(CONF_SSL, True), ) except RainMachineError: return await self._show_form({CONF_PASSWORD: "invalid_auth"}) # Unfortunately, RainMachine doesn't provide a way to refresh the # access token without using the IP address and password, so we have to # store it: return self.async_create_entry( title=user_input[CONF_IP_ADDRESS], data={ CONF_IP_ADDRESS: user_input[CONF_IP_ADDRESS], CONF_PASSWORD: user_input[CONF_PASSWORD], CONF_PORT: user_input[CONF_PORT], CONF_SSL: user_input.get(CONF_SSL, True), CONF_ZONE_RUN_TIME: user_input.get( CONF_ZONE_RUN_TIME, DEFAULT_ZONE_RUN ), }, )
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "not", "user_input", ":", "return", "await", "self", ".", "_show_form", "(", ")", "await", "self", ".", "async_set_unique_id", "(", "user_input", "[", "CONF_IP_ADDRESS", "]", ")", "self", ".", "_abort_if_unique_id_configured", "(", ")", "websession", "=", "aiohttp_client", ".", "async_get_clientsession", "(", "self", ".", "hass", ")", "client", "=", "Client", "(", "session", "=", "websession", ")", "try", ":", "await", "client", ".", "load_local", "(", "user_input", "[", "CONF_IP_ADDRESS", "]", ",", "user_input", "[", "CONF_PASSWORD", "]", ",", "port", "=", "user_input", "[", "CONF_PORT", "]", ",", "ssl", "=", "user_input", ".", "get", "(", "CONF_SSL", ",", "True", ")", ",", ")", "except", "RainMachineError", ":", "return", "await", "self", ".", "_show_form", "(", "{", "CONF_PASSWORD", ":", "\"invalid_auth\"", "}", ")", "# Unfortunately, RainMachine doesn't provide a way to refresh the", "# access token without using the IP address and password, so we have to", "# store it:", "return", "self", ".", "async_create_entry", "(", "title", "=", "user_input", "[", "CONF_IP_ADDRESS", "]", ",", "data", "=", "{", "CONF_IP_ADDRESS", ":", "user_input", "[", "CONF_IP_ADDRESS", "]", ",", "CONF_PASSWORD", ":", "user_input", "[", "CONF_PASSWORD", "]", ",", "CONF_PORT", ":", "user_input", "[", "CONF_PORT", "]", ",", "CONF_SSL", ":", "user_input", ".", "get", "(", "CONF_SSL", ",", "True", ")", ",", "CONF_ZONE_RUN_TIME", ":", "user_input", ".", "get", "(", "CONF_ZONE_RUN_TIME", ",", "DEFAULT_ZONE_RUN", ")", ",", "}", ",", ")" ]
[ 48, 4 ]
[ 83, 9 ]
python
en
['en', 'en', 'en']
True
RainMachineOptionsFlowHandler.__init__
(self, config_entry)
Initialize.
Initialize.
def __init__(self, config_entry): """Initialize.""" self.config_entry = config_entry
[ "def", "__init__", "(", "self", ",", "config_entry", ")", ":", "self", ".", "config_entry", "=", "config_entry" ]
[ 89, 4 ]
[ 91, 40 ]
python
en
['en', 'en', 'it']
False
RainMachineOptionsFlowHandler.async_step_init
(self, user_input=None)
Manage the options.
Manage the options.
async def async_step_init(self, user_input=None): """Manage the options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Optional( CONF_ZONE_RUN_TIME, default=self.config_entry.options.get(CONF_ZONE_RUN_TIME), ): cv.positive_int } ), )
[ "async", "def", "async_step_init", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "user_input", "is", "not", "None", ":", "return", "self", ".", "async_create_entry", "(", "title", "=", "\"\"", ",", "data", "=", "user_input", ")", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"init\"", ",", "data_schema", "=", "vol", ".", "Schema", "(", "{", "vol", ".", "Optional", "(", "CONF_ZONE_RUN_TIME", ",", "default", "=", "self", ".", "config_entry", ".", "options", ".", "get", "(", "CONF_ZONE_RUN_TIME", ")", ",", ")", ":", "cv", ".", "positive_int", "}", ")", ",", ")" ]
[ 93, 4 ]
[ 108, 9 ]
python
en
['en', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Open Sky platform.
Set up the Open Sky platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Open Sky platform.""" latitude = config.get(CONF_LATITUDE, hass.config.latitude) longitude = config.get(CONF_LONGITUDE, hass.config.longitude) add_entities( [ OpenSkySensor( hass, config.get(CONF_NAME, DOMAIN), latitude, longitude, config.get(CONF_RADIUS), config.get(CONF_ALTITUDE), ) ], True, )
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "latitude", "=", "config", ".", "get", "(", "CONF_LATITUDE", ",", "hass", ".", "config", ".", "latitude", ")", "longitude", "=", "config", ".", "get", "(", "CONF_LONGITUDE", ",", "hass", ".", "config", ".", "longitude", ")", "add_entities", "(", "[", "OpenSkySensor", "(", "hass", ",", "config", ".", "get", "(", "CONF_NAME", ",", "DOMAIN", ")", ",", "latitude", ",", "longitude", ",", "config", ".", "get", "(", "CONF_RADIUS", ")", ",", "config", ".", "get", "(", "CONF_ALTITUDE", ")", ",", ")", "]", ",", "True", ",", ")" ]
[ 70, 0 ]
[ 86, 5 ]
python
en
['en', 'cs', 'en']
True
OpenSkySensor.__init__
(self, hass, name, latitude, longitude, radius, altitude)
Initialize the sensor.
Initialize the sensor.
def __init__(self, hass, name, latitude, longitude, radius, altitude): """Initialize the sensor.""" self._session = requests.Session() self._latitude = latitude self._longitude = longitude self._radius = util_distance.convert(radius, LENGTH_KILOMETERS, LENGTH_METERS) self._altitude = altitude self._state = 0 self._hass = hass self._name = name self._previously_tracked = None
[ "def", "__init__", "(", "self", ",", "hass", ",", "name", ",", "latitude", ",", "longitude", ",", "radius", ",", "altitude", ")", ":", "self", ".", "_session", "=", "requests", ".", "Session", "(", ")", "self", ".", "_latitude", "=", "latitude", "self", ".", "_longitude", "=", "longitude", "self", ".", "_radius", "=", "util_distance", ".", "convert", "(", "radius", ",", "LENGTH_KILOMETERS", ",", "LENGTH_METERS", ")", "self", ".", "_altitude", "=", "altitude", "self", ".", "_state", "=", "0", "self", ".", "_hass", "=", "hass", "self", ".", "_name", "=", "name", "self", ".", "_previously_tracked", "=", "None" ]
[ 92, 4 ]
[ 102, 39 ]
python
en
['en', 'en', 'en']
True
OpenSkySensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 105, 4 ]
[ 107, 25 ]
python
en
['en', 'mi', 'en']
True
OpenSkySensor.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._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 110, 4 ]
[ 112, 26 ]
python
en
['en', 'en', 'en']
True
OpenSkySensor._handle_boundary
(self, flights, event, metadata)
Handle flights crossing region boundary.
Handle flights crossing region boundary.
def _handle_boundary(self, flights, event, metadata): """Handle flights crossing region boundary.""" for flight in flights: if flight in metadata: altitude = metadata[flight].get(ATTR_ALTITUDE) else: # Assume Flight has landed if missing. altitude = 0 data = { ATTR_CALLSIGN: flight, ATTR_ALTITUDE: altitude, ATTR_SENSOR: self._name, } self._hass.bus.fire(event, data)
[ "def", "_handle_boundary", "(", "self", ",", "flights", ",", "event", ",", "metadata", ")", ":", "for", "flight", "in", "flights", ":", "if", "flight", "in", "metadata", ":", "altitude", "=", "metadata", "[", "flight", "]", ".", "get", "(", "ATTR_ALTITUDE", ")", "else", ":", "# Assume Flight has landed if missing.", "altitude", "=", "0", "data", "=", "{", "ATTR_CALLSIGN", ":", "flight", ",", "ATTR_ALTITUDE", ":", "altitude", ",", "ATTR_SENSOR", ":", "self", ".", "_name", ",", "}", "self", ".", "_hass", ".", "bus", ".", "fire", "(", "event", ",", "data", ")" ]
[ 114, 4 ]
[ 128, 44 ]
python
en
['en', 'sv', 'en']
True
OpenSkySensor.update
(self)
Update device state.
Update device state.
def update(self): """Update device state.""" currently_tracked = set() flight_metadata = {} states = self._session.get(OPENSKY_API_URL).json().get(ATTR_STATES) for state in states: flight = dict(zip(OPENSKY_API_FIELDS, state)) callsign = flight[ATTR_CALLSIGN].strip() if callsign != "": flight_metadata[callsign] = flight else: continue missing_location = ( flight.get(ATTR_LONGITUDE) is None or flight.get(ATTR_LATITUDE) is None ) if missing_location: continue if flight.get(ATTR_ON_GROUND): continue distance = util_location.distance( self._latitude, self._longitude, flight.get(ATTR_LATITUDE), flight.get(ATTR_LONGITUDE), ) if distance is None or distance > self._radius: continue altitude = flight.get(ATTR_ALTITUDE) if altitude > self._altitude and self._altitude != 0: continue currently_tracked.add(callsign) if self._previously_tracked is not None: entries = currently_tracked - self._previously_tracked exits = self._previously_tracked - currently_tracked self._handle_boundary(entries, EVENT_OPENSKY_ENTRY, flight_metadata) self._handle_boundary(exits, EVENT_OPENSKY_EXIT, flight_metadata) self._state = len(currently_tracked) self._previously_tracked = currently_tracked
[ "def", "update", "(", "self", ")", ":", "currently_tracked", "=", "set", "(", ")", "flight_metadata", "=", "{", "}", "states", "=", "self", ".", "_session", ".", "get", "(", "OPENSKY_API_URL", ")", ".", "json", "(", ")", ".", "get", "(", "ATTR_STATES", ")", "for", "state", "in", "states", ":", "flight", "=", "dict", "(", "zip", "(", "OPENSKY_API_FIELDS", ",", "state", ")", ")", "callsign", "=", "flight", "[", "ATTR_CALLSIGN", "]", ".", "strip", "(", ")", "if", "callsign", "!=", "\"\"", ":", "flight_metadata", "[", "callsign", "]", "=", "flight", "else", ":", "continue", "missing_location", "=", "(", "flight", ".", "get", "(", "ATTR_LONGITUDE", ")", "is", "None", "or", "flight", ".", "get", "(", "ATTR_LATITUDE", ")", "is", "None", ")", "if", "missing_location", ":", "continue", "if", "flight", ".", "get", "(", "ATTR_ON_GROUND", ")", ":", "continue", "distance", "=", "util_location", ".", "distance", "(", "self", ".", "_latitude", ",", "self", ".", "_longitude", ",", "flight", ".", "get", "(", "ATTR_LATITUDE", ")", ",", "flight", ".", "get", "(", "ATTR_LONGITUDE", ")", ",", ")", "if", "distance", "is", "None", "or", "distance", ">", "self", ".", "_radius", ":", "continue", "altitude", "=", "flight", ".", "get", "(", "ATTR_ALTITUDE", ")", "if", "altitude", ">", "self", ".", "_altitude", "and", "self", ".", "_altitude", "!=", "0", ":", "continue", "currently_tracked", ".", "add", "(", "callsign", ")", "if", "self", ".", "_previously_tracked", "is", "not", "None", ":", "entries", "=", "currently_tracked", "-", "self", ".", "_previously_tracked", "exits", "=", "self", ".", "_previously_tracked", "-", "currently_tracked", "self", ".", "_handle_boundary", "(", "entries", ",", "EVENT_OPENSKY_ENTRY", ",", "flight_metadata", ")", "self", ".", "_handle_boundary", "(", "exits", ",", "EVENT_OPENSKY_EXIT", ",", "flight_metadata", ")", "self", ".", "_state", "=", "len", "(", "currently_tracked", ")", "self", ".", "_previously_tracked", "=", "currently_tracked" ]
[ 130, 4 ]
[ 167, 52 ]
python
en
['fr', 'en', 'en']
True
OpenSkySensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return {ATTR_ATTRIBUTION: OPENSKY_ATTRIBUTION}
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "ATTR_ATTRIBUTION", ":", "OPENSKY_ATTRIBUTION", "}" ]
[ 170, 4 ]
[ 172, 54 ]
python
en
['en', 'en', 'en']
True
OpenSkySensor.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 "flights"
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "\"flights\"" ]
[ 175, 4 ]
[ 177, 24 ]
python
en
['en', 'la', 'en']
True
OpenSkySensor.icon
(self)
Return the icon.
Return the icon.
def icon(self): """Return the icon.""" return "mdi:airplane"
[ "def", "icon", "(", "self", ")", ":", "return", "\"mdi:airplane\"" ]
[ 180, 4 ]
[ 182, 29 ]
python
en
['en', 'sr', 'en']
True
test_reload_notify
(hass)
Verify we can reload the notify service.
Verify we can reload the notify service.
async def test_reload_notify(hass): """Verify we can reload the notify service.""" assert await async_setup_component( hass, notify.DOMAIN, { notify.DOMAIN: [ { "name": DOMAIN, "platform": DOMAIN, "resource": "http://127.0.0.1/off", }, ] }, ) await hass.async_block_till_done() assert hass.services.has_service(notify.DOMAIN, DOMAIN) yaml_path = path.join( _get_fixtures_base_path(), "fixtures", "rest/configuration.yaml", ) with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, {}, blocking=True, ) await hass.async_block_till_done() assert not hass.services.has_service(notify.DOMAIN, DOMAIN) assert hass.services.has_service(notify.DOMAIN, "rest_reloaded")
[ "async", "def", "test_reload_notify", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "notify", ".", "DOMAIN", ",", "{", "notify", ".", "DOMAIN", ":", "[", "{", "\"name\"", ":", "DOMAIN", ",", "\"platform\"", ":", "DOMAIN", ",", "\"resource\"", ":", "\"http://127.0.0.1/off\"", ",", "}", ",", "]", "}", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "hass", ".", "services", ".", "has_service", "(", "notify", ".", "DOMAIN", ",", "DOMAIN", ")", "yaml_path", "=", "path", ".", "join", "(", "_get_fixtures_base_path", "(", ")", ",", "\"fixtures\"", ",", "\"rest/configuration.yaml\"", ",", ")", "with", "patch", ".", "object", "(", "hass_config", ",", "\"YAML_CONFIG_FILE\"", ",", "yaml_path", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_RELOAD", ",", "{", "}", ",", "blocking", "=", "True", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "hass", ".", "services", ".", "has_service", "(", "notify", ".", "DOMAIN", ",", "DOMAIN", ")", "assert", "hass", ".", "services", ".", "has_service", "(", "notify", ".", "DOMAIN", ",", "\"rest_reloaded\"", ")" ]
[ 12, 0 ]
[ 47, 68 ]
python
en
['en', 'en', 'en']
True
async_setup_camera
(hass, traits={}, auth=None)
Set up the platform and prerequisites.
Set up the platform and prerequisites.
async def async_setup_camera(hass, traits={}, auth=None): """Set up the platform and prerequisites.""" devices = {} if traits: devices[DEVICE_ID] = Device.MakeDevice( { "name": DEVICE_ID, "type": CAMERA_DEVICE_TYPE, "traits": traits, }, auth=auth, ) return await async_setup_sdm_platform(hass, PLATFORM, devices)
[ "async", "def", "async_setup_camera", "(", "hass", ",", "traits", "=", "{", "}", ",", "auth", "=", "None", ")", ":", "devices", "=", "{", "}", "if", "traits", ":", "devices", "[", "DEVICE_ID", "]", "=", "Device", ".", "MakeDevice", "(", "{", "\"name\"", ":", "DEVICE_ID", ",", "\"type\"", ":", "CAMERA_DEVICE_TYPE", ",", "\"traits\"", ":", "traits", ",", "}", ",", "auth", "=", "auth", ",", ")", "return", "await", "async_setup_sdm_platform", "(", "hass", ",", "PLATFORM", ",", "devices", ")" ]
[ 41, 0 ]
[ 53, 66 ]
python
en
['en', 'en', 'en']
True
fire_alarm
(hass, point_in_time)
Fire an alarm and wait for callbacks to run.
Fire an alarm and wait for callbacks to run.
async def fire_alarm(hass, point_in_time): """Fire an alarm and wait for callbacks to run.""" with patch("homeassistant.util.dt.utcnow", return_value=point_in_time): async_fire_time_changed(hass, point_in_time) await hass.async_block_till_done()
[ "async", "def", "fire_alarm", "(", "hass", ",", "point_in_time", ")", ":", "with", "patch", "(", "\"homeassistant.util.dt.utcnow\"", ",", "return_value", "=", "point_in_time", ")", ":", "async_fire_time_changed", "(", "hass", ",", "point_in_time", ")", "await", "hass", ".", "async_block_till_done", "(", ")" ]
[ 56, 0 ]
[ 60, 42 ]
python
en
['en', 'en', 'en']
True
test_no_devices
(hass)
Test configuration that returns no devices.
Test configuration that returns no devices.
async def test_no_devices(hass): """Test configuration that returns no devices.""" await async_setup_camera(hass) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_no_devices", "(", "hass", ")", ":", "await", "async_setup_camera", "(", "hass", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 63, 0 ]
[ 66, 44 ]
python
en
['en', 'fr', 'en']
True
test_ineligible_device
(hass)
Test configuration with devices that do not support cameras.
Test configuration with devices that do not support cameras.
async def test_ineligible_device(hass): """Test configuration with devices that do not support cameras.""" await async_setup_camera( hass, { "sdm.devices.traits.Info": { "customName": "My Camera", }, }, ) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_ineligible_device", "(", "hass", ")", ":", "await", "async_setup_camera", "(", "hass", ",", "{", "\"sdm.devices.traits.Info\"", ":", "{", "\"customName\"", ":", "\"My Camera\"", ",", "}", ",", "}", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 69, 0 ]
[ 79, 44 ]
python
en
['en', 'en', 'en']
True
test_camera_device
(hass)
Test a basic camera with a live stream.
Test a basic camera with a live stream.
async def test_camera_device(hass): """Test a basic camera with a live stream.""" await async_setup_camera(hass, DEVICE_TRAITS) assert len(hass.states.async_all()) == 1 camera = hass.states.get("camera.my_camera") assert camera is not None assert camera.state == STATE_IDLE registry = await hass.helpers.entity_registry.async_get_registry() entry = registry.async_get("camera.my_camera") assert entry.unique_id == "some-device-id-camera" assert entry.original_name == "My Camera" assert entry.domain == "camera" device_registry = await hass.helpers.device_registry.async_get_registry() device = device_registry.async_get(entry.device_id) assert device.name == "My Camera" assert device.model == "Camera" assert device.identifiers == {("nest", DEVICE_ID)}
[ "async", "def", "test_camera_device", "(", "hass", ")", ":", "await", "async_setup_camera", "(", "hass", ",", "DEVICE_TRAITS", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "camera", "=", "hass", ".", "states", ".", "get", "(", "\"camera.my_camera\"", ")", "assert", "camera", "is", "not", "None", "assert", "camera", ".", "state", "==", "STATE_IDLE", "registry", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "entry", "=", "registry", ".", "async_get", "(", "\"camera.my_camera\"", ")", "assert", "entry", ".", "unique_id", "==", "\"some-device-id-camera\"", "assert", "entry", ".", "original_name", "==", "\"My Camera\"", "assert", "entry", ".", "domain", "==", "\"camera\"", "device_registry", "=", "await", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", "device", "=", "device_registry", ".", "async_get", "(", "entry", ".", "device_id", ")", "assert", "device", ".", "name", "==", "\"My Camera\"", "assert", "device", ".", "model", "==", "\"Camera\"", "assert", "device", ".", "identifiers", "==", "{", "(", "\"nest\"", ",", "DEVICE_ID", ")", "}" ]
[ 82, 0 ]
[ 101, 54 ]
python
en
['en', 'en', 'en']
True
test_camera_stream
(hass, auth)
Test a basic camera and fetch its live stream.
Test a basic camera and fetch its live stream.
async def test_camera_stream(hass, auth): """Test a basic camera and fetch its live stream.""" now = utcnow() expiration = now + datetime.timedelta(seconds=100) auth.responses = [ aiohttp.web.json_response( { "results": { "streamUrls": { "rtspUrl": "rtsp://some/url?auth=g.0.streamingToken" }, "streamExtensionToken": "g.1.extensionToken", "streamToken": "g.0.streamingToken", "expiresAt": expiration.isoformat(timespec="seconds"), }, } ) ] await async_setup_camera(hass, DEVICE_TRAITS, auth=auth) assert len(hass.states.async_all()) == 1 cam = hass.states.get("camera.my_camera") assert cam is not None assert cam.state == STATE_IDLE stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.0.streamingToken" with patch( "homeassistant.components.ffmpeg.ImageFrame.get_image", autopatch=True, return_value=b"image bytes", ): image = await camera.async_get_image(hass, "camera.my_camera") assert image.content == b"image bytes"
[ "async", "def", "test_camera_stream", "(", "hass", ",", "auth", ")", ":", "now", "=", "utcnow", "(", ")", "expiration", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "100", ")", "auth", ".", "responses", "=", "[", "aiohttp", ".", "web", ".", "json_response", "(", "{", "\"results\"", ":", "{", "\"streamUrls\"", ":", "{", "\"rtspUrl\"", ":", "\"rtsp://some/url?auth=g.0.streamingToken\"", "}", ",", "\"streamExtensionToken\"", ":", "\"g.1.extensionToken\"", ",", "\"streamToken\"", ":", "\"g.0.streamingToken\"", ",", "\"expiresAt\"", ":", "expiration", ".", "isoformat", "(", "timespec", "=", "\"seconds\"", ")", ",", "}", ",", "}", ")", "]", "await", "async_setup_camera", "(", "hass", ",", "DEVICE_TRAITS", ",", "auth", "=", "auth", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "cam", "=", "hass", ".", "states", ".", "get", "(", "\"camera.my_camera\"", ")", "assert", "cam", "is", "not", "None", "assert", "cam", ".", "state", "==", "STATE_IDLE", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.0.streamingToken\"", "with", "patch", "(", "\"homeassistant.components.ffmpeg.ImageFrame.get_image\"", ",", "autopatch", "=", "True", ",", "return_value", "=", "b\"image bytes\"", ",", ")", ":", "image", "=", "await", "camera", ".", "async_get_image", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "image", ".", "content", "==", "b\"image bytes\"" ]
[ 104, 0 ]
[ 139, 42 ]
python
en
['en', 'en', 'en']
True
test_refresh_expired_stream_token
(hass, auth)
Test a camera stream expiration and refresh.
Test a camera stream expiration and refresh.
async def test_refresh_expired_stream_token(hass, auth): """Test a camera stream expiration and refresh.""" now = utcnow() stream_1_expiration = now + datetime.timedelta(seconds=90) stream_2_expiration = now + datetime.timedelta(seconds=180) stream_3_expiration = now + datetime.timedelta(seconds=360) auth.responses = [ # Stream URL #1 aiohttp.web.json_response( { "results": { "streamUrls": { "rtspUrl": "rtsp://some/url?auth=g.1.streamingToken" }, "streamExtensionToken": "g.1.extensionToken", "streamToken": "g.1.streamingToken", "expiresAt": stream_1_expiration.isoformat(timespec="seconds"), }, } ), # Stream URL #2 aiohttp.web.json_response( { "results": { "streamExtensionToken": "g.2.extensionToken", "streamToken": "g.2.streamingToken", "expiresAt": stream_2_expiration.isoformat(timespec="seconds"), }, } ), # Stream URL #3 aiohttp.web.json_response( { "results": { "streamExtensionToken": "g.3.extensionToken", "streamToken": "g.3.streamingToken", "expiresAt": stream_3_expiration.isoformat(timespec="seconds"), }, } ), ] await async_setup_camera( hass, DEVICE_TRAITS, auth=auth, ) assert len(hass.states.async_all()) == 1 cam = hass.states.get("camera.my_camera") assert cam is not None assert cam.state == STATE_IDLE stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.1.streamingToken" # Fire alarm before stream_1_expiration. The stream url is not refreshed next_update = now + datetime.timedelta(seconds=25) await fire_alarm(hass, next_update) stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.1.streamingToken" # Alarm is near stream_1_expiration which causes the stream extension next_update = now + datetime.timedelta(seconds=65) await fire_alarm(hass, next_update) stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.2.streamingToken" # Next alarm is well before stream_2_expiration, no change next_update = now + datetime.timedelta(seconds=100) await fire_alarm(hass, next_update) stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.2.streamingToken" # Alarm is near stream_2_expiration, causing it to be extended next_update = now + datetime.timedelta(seconds=155) await fire_alarm(hass, next_update) stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.3.streamingToken"
[ "async", "def", "test_refresh_expired_stream_token", "(", "hass", ",", "auth", ")", ":", "now", "=", "utcnow", "(", ")", "stream_1_expiration", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "90", ")", "stream_2_expiration", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "180", ")", "stream_3_expiration", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "360", ")", "auth", ".", "responses", "=", "[", "# Stream URL #1", "aiohttp", ".", "web", ".", "json_response", "(", "{", "\"results\"", ":", "{", "\"streamUrls\"", ":", "{", "\"rtspUrl\"", ":", "\"rtsp://some/url?auth=g.1.streamingToken\"", "}", ",", "\"streamExtensionToken\"", ":", "\"g.1.extensionToken\"", ",", "\"streamToken\"", ":", "\"g.1.streamingToken\"", ",", "\"expiresAt\"", ":", "stream_1_expiration", ".", "isoformat", "(", "timespec", "=", "\"seconds\"", ")", ",", "}", ",", "}", ")", ",", "# Stream URL #2", "aiohttp", ".", "web", ".", "json_response", "(", "{", "\"results\"", ":", "{", "\"streamExtensionToken\"", ":", "\"g.2.extensionToken\"", ",", "\"streamToken\"", ":", "\"g.2.streamingToken\"", ",", "\"expiresAt\"", ":", "stream_2_expiration", ".", "isoformat", "(", "timespec", "=", "\"seconds\"", ")", ",", "}", ",", "}", ")", ",", "# Stream URL #3", "aiohttp", ".", "web", ".", "json_response", "(", "{", "\"results\"", ":", "{", "\"streamExtensionToken\"", ":", "\"g.3.extensionToken\"", ",", "\"streamToken\"", ":", "\"g.3.streamingToken\"", ",", "\"expiresAt\"", ":", "stream_3_expiration", ".", "isoformat", "(", "timespec", "=", "\"seconds\"", ")", ",", "}", ",", "}", ")", ",", "]", "await", "async_setup_camera", "(", "hass", ",", "DEVICE_TRAITS", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "cam", "=", "hass", ".", "states", ".", "get", "(", "\"camera.my_camera\"", ")", "assert", "cam", "is", "not", "None", "assert", "cam", ".", "state", "==", "STATE_IDLE", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.1.streamingToken\"", "# Fire alarm before stream_1_expiration. The stream url is not refreshed", "next_update", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "25", ")", "await", "fire_alarm", "(", "hass", ",", "next_update", ")", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.1.streamingToken\"", "# Alarm is near stream_1_expiration which causes the stream extension", "next_update", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "65", ")", "await", "fire_alarm", "(", "hass", ",", "next_update", ")", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.2.streamingToken\"", "# Next alarm is well before stream_2_expiration, no change", "next_update", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "100", ")", "await", "fire_alarm", "(", "hass", ",", "next_update", ")", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.2.streamingToken\"", "# Alarm is near stream_2_expiration, causing it to be extended", "next_update", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "155", ")", "await", "fire_alarm", "(", "hass", ",", "next_update", ")", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.3.streamingToken\"" ]
[ 142, 0 ]
[ 219, 69 ]
python
en
['en', 'pt', 'en']
True
test_camera_removed
(hass, auth)
Test case where entities are removed and stream tokens expired.
Test case where entities are removed and stream tokens expired.
async def test_camera_removed(hass, auth): """Test case where entities are removed and stream tokens expired.""" now = utcnow() expiration = now + datetime.timedelta(seconds=100) auth.responses = [ aiohttp.web.json_response( { "results": { "streamUrls": { "rtspUrl": "rtsp://some/url?auth=g.0.streamingToken" }, "streamExtensionToken": "g.1.extensionToken", "streamToken": "g.0.streamingToken", "expiresAt": expiration.isoformat(timespec="seconds"), }, } ), aiohttp.web.json_response({"results": {}}), ] await async_setup_camera( hass, DEVICE_TRAITS, auth=auth, ) assert len(hass.states.async_all()) == 1 cam = hass.states.get("camera.my_camera") assert cam is not None assert cam.state == STATE_IDLE stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.0.streamingToken" for config_entry in hass.config_entries.async_entries(DOMAIN): await hass.config_entries.async_remove(config_entry.entry_id) assert len(hass.states.async_all()) == 0
[ "async", "def", "test_camera_removed", "(", "hass", ",", "auth", ")", ":", "now", "=", "utcnow", "(", ")", "expiration", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "100", ")", "auth", ".", "responses", "=", "[", "aiohttp", ".", "web", ".", "json_response", "(", "{", "\"results\"", ":", "{", "\"streamUrls\"", ":", "{", "\"rtspUrl\"", ":", "\"rtsp://some/url?auth=g.0.streamingToken\"", "}", ",", "\"streamExtensionToken\"", ":", "\"g.1.extensionToken\"", ",", "\"streamToken\"", ":", "\"g.0.streamingToken\"", ",", "\"expiresAt\"", ":", "expiration", ".", "isoformat", "(", "timespec", "=", "\"seconds\"", ")", ",", "}", ",", "}", ")", ",", "aiohttp", ".", "web", ".", "json_response", "(", "{", "\"results\"", ":", "{", "}", "}", ")", ",", "]", "await", "async_setup_camera", "(", "hass", ",", "DEVICE_TRAITS", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "cam", "=", "hass", ".", "states", ".", "get", "(", "\"camera.my_camera\"", ")", "assert", "cam", "is", "not", "None", "assert", "cam", ".", "state", "==", "STATE_IDLE", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.0.streamingToken\"", "for", "config_entry", "in", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", ":", "await", "hass", ".", "config_entries", ".", "async_remove", "(", "config_entry", ".", "entry_id", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "0" ]
[ 222, 0 ]
[ 257, 44 ]
python
en
['en', 'en', 'en']
True
test_refresh_expired_stream_failure
(hass, auth)
Tests a failure when refreshing the stream.
Tests a failure when refreshing the stream.
async def test_refresh_expired_stream_failure(hass, auth): """Tests a failure when refreshing the stream.""" now = utcnow() stream_1_expiration = now + datetime.timedelta(seconds=90) stream_2_expiration = now + datetime.timedelta(seconds=180) auth.responses = [ aiohttp.web.json_response( { "results": { "streamUrls": { "rtspUrl": "rtsp://some/url?auth=g.1.streamingToken" }, "streamExtensionToken": "g.1.extensionToken", "streamToken": "g.1.streamingToken", "expiresAt": stream_1_expiration.isoformat(timespec="seconds"), }, } ), # Extending the stream fails with arbitrary error aiohttp.web.Response(status=500), # Next attempt to get a stream fetches a new url aiohttp.web.json_response( { "results": { "streamUrls": { "rtspUrl": "rtsp://some/url?auth=g.2.streamingToken" }, "streamExtensionToken": "g.2.extensionToken", "streamToken": "g.2.streamingToken", "expiresAt": stream_2_expiration.isoformat(timespec="seconds"), }, } ), ] await async_setup_camera( hass, DEVICE_TRAITS, auth=auth, ) assert len(hass.states.async_all()) == 1 cam = hass.states.get("camera.my_camera") assert cam is not None assert cam.state == STATE_IDLE stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.1.streamingToken" # Fire alarm when stream is nearing expiration, causing it to be extended. # The stream expires. next_update = now + datetime.timedelta(seconds=65) await fire_alarm(hass, next_update) # The stream is entirely refreshed stream_source = await camera.async_get_stream_source(hass, "camera.my_camera") assert stream_source == "rtsp://some/url?auth=g.2.streamingToken"
[ "async", "def", "test_refresh_expired_stream_failure", "(", "hass", ",", "auth", ")", ":", "now", "=", "utcnow", "(", ")", "stream_1_expiration", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "90", ")", "stream_2_expiration", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "180", ")", "auth", ".", "responses", "=", "[", "aiohttp", ".", "web", ".", "json_response", "(", "{", "\"results\"", ":", "{", "\"streamUrls\"", ":", "{", "\"rtspUrl\"", ":", "\"rtsp://some/url?auth=g.1.streamingToken\"", "}", ",", "\"streamExtensionToken\"", ":", "\"g.1.extensionToken\"", ",", "\"streamToken\"", ":", "\"g.1.streamingToken\"", ",", "\"expiresAt\"", ":", "stream_1_expiration", ".", "isoformat", "(", "timespec", "=", "\"seconds\"", ")", ",", "}", ",", "}", ")", ",", "# Extending the stream fails with arbitrary error", "aiohttp", ".", "web", ".", "Response", "(", "status", "=", "500", ")", ",", "# Next attempt to get a stream fetches a new url", "aiohttp", ".", "web", ".", "json_response", "(", "{", "\"results\"", ":", "{", "\"streamUrls\"", ":", "{", "\"rtspUrl\"", ":", "\"rtsp://some/url?auth=g.2.streamingToken\"", "}", ",", "\"streamExtensionToken\"", ":", "\"g.2.extensionToken\"", ",", "\"streamToken\"", ":", "\"g.2.streamingToken\"", ",", "\"expiresAt\"", ":", "stream_2_expiration", ".", "isoformat", "(", "timespec", "=", "\"seconds\"", ")", ",", "}", ",", "}", ")", ",", "]", "await", "async_setup_camera", "(", "hass", ",", "DEVICE_TRAITS", ",", "auth", "=", "auth", ",", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "1", "cam", "=", "hass", ".", "states", ".", "get", "(", "\"camera.my_camera\"", ")", "assert", "cam", "is", "not", "None", "assert", "cam", ".", "state", "==", "STATE_IDLE", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.1.streamingToken\"", "# Fire alarm when stream is nearing expiration, causing it to be extended.", "# The stream expires.", "next_update", "=", "now", "+", "datetime", ".", "timedelta", "(", "seconds", "=", "65", ")", "await", "fire_alarm", "(", "hass", ",", "next_update", ")", "# The stream is entirely refreshed", "stream_source", "=", "await", "camera", ".", "async_get_stream_source", "(", "hass", ",", "\"camera.my_camera\"", ")", "assert", "stream_source", "==", "\"rtsp://some/url?auth=g.2.streamingToken\"" ]
[ 260, 0 ]
[ 315, 69 ]
python
en
['en', 'en', 'en']
True
BlueprintException.__init__
(self, domain: str, msg: str)
Initialize a blueprint exception.
Initialize a blueprint exception.
def __init__(self, domain: str, msg: str) -> None: """Initialize a blueprint exception.""" super().__init__(msg) self.domain = domain
[ "def", "__init__", "(", "self", ",", "domain", ":", "str", ",", "msg", ":", "str", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "msg", ")", "self", ".", "domain", "=", "domain" ]
[ 12, 4 ]
[ 15, 28 ]
python
fr
['fr', 'fr', 'en']
True
BlueprintWithNameException.__init__
(self, domain: str, blueprint_name: str, msg: str)
Initialize blueprint exception.
Initialize blueprint exception.
def __init__(self, domain: str, blueprint_name: str, msg: str) -> None: """Initialize blueprint exception.""" super().__init__(domain, msg) self.blueprint_name = blueprint_name
[ "def", "__init__", "(", "self", ",", "domain", ":", "str", ",", "blueprint_name", ":", "str", ",", "msg", ":", "str", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "domain", ",", "msg", ")", "self", ".", "blueprint_name", "=", "blueprint_name" ]
[ 21, 4 ]
[ 24, 44 ]
python
fr
['fr', 'fr', 'en']
True
FailedToLoad.__init__
(self, domain: str, blueprint_name: str, exc: Exception)
Initialize blueprint exception.
Initialize blueprint exception.
def __init__(self, domain: str, blueprint_name: str, exc: Exception) -> None: """Initialize blueprint exception.""" super().__init__(domain, blueprint_name, f"Failed to load blueprint: {exc}")
[ "def", "__init__", "(", "self", ",", "domain", ":", "str", ",", "blueprint_name", ":", "str", ",", "exc", ":", "Exception", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "domain", ",", "blueprint_name", ",", "f\"Failed to load blueprint: {exc}\"", ")" ]
[ 30, 4 ]
[ 32, 84 ]
python
fr
['fr', 'fr', 'en']
True
InvalidBlueprint.__init__
( self, domain: str, blueprint_name: str, blueprint_data: Any, msg_or_exc: vol.Invalid, )
Initialize an invalid blueprint error.
Initialize an invalid blueprint error.
def __init__( self, domain: str, blueprint_name: str, blueprint_data: Any, msg_or_exc: vol.Invalid, ): """Initialize an invalid blueprint error.""" if isinstance(msg_or_exc, vol.Invalid): msg_or_exc = humanize_error(blueprint_data, msg_or_exc) super().__init__( domain, blueprint_name, f"Invalid blueprint: {msg_or_exc}", ) self.blueprint_data = blueprint_data
[ "def", "__init__", "(", "self", ",", "domain", ":", "str", ",", "blueprint_name", ":", "str", ",", "blueprint_data", ":", "Any", ",", "msg_or_exc", ":", "vol", ".", "Invalid", ",", ")", ":", "if", "isinstance", "(", "msg_or_exc", ",", "vol", ".", "Invalid", ")", ":", "msg_or_exc", "=", "humanize_error", "(", "blueprint_data", ",", "msg_or_exc", ")", "super", "(", ")", ".", "__init__", "(", "domain", ",", "blueprint_name", ",", "f\"Invalid blueprint: {msg_or_exc}\"", ",", ")", "self", ".", "blueprint_data", "=", "blueprint_data" ]
[ 38, 4 ]
[ 54, 44 ]
python
br
['br', 'lb', 'en']
False
InvalidBlueprintInputs.__init__
(self, domain: str, msg: str)
Initialize an invalid blueprint inputs error.
Initialize an invalid blueprint inputs error.
def __init__(self, domain: str, msg: str): """Initialize an invalid blueprint inputs error.""" super().__init__( domain, f"Invalid blueprint inputs: {msg}", )
[ "def", "__init__", "(", "self", ",", "domain", ":", "str", ",", "msg", ":", "str", ")", ":", "super", "(", ")", ".", "__init__", "(", "domain", ",", "f\"Invalid blueprint inputs: {msg}\"", ",", ")" ]
[ 60, 4 ]
[ 65, 9 ]
python
en
['en', 'lb', 'en']
True
MissingPlaceholder.__init__
( self, domain: str, blueprint_name: str, placeholder_names: Iterable[str] )
Initialize blueprint exception.
Initialize blueprint exception.
def __init__( self, domain: str, blueprint_name: str, placeholder_names: Iterable[str] ) -> None: """Initialize blueprint exception.""" super().__init__( domain, blueprint_name, f"Missing placeholder {', '.join(sorted(placeholder_names))}", )
[ "def", "__init__", "(", "self", ",", "domain", ":", "str", ",", "blueprint_name", ":", "str", ",", "placeholder_names", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "domain", ",", "blueprint_name", ",", "f\"Missing placeholder {', '.join(sorted(placeholder_names))}\"", ",", ")" ]
[ 71, 4 ]
[ 79, 9 ]
python
fr
['fr', 'fr', 'en']
True
FileAlreadyExists.__init__
(self, domain: str, blueprint_name: str)
Initialize blueprint exception.
Initialize blueprint exception.
def __init__(self, domain: str, blueprint_name: str) -> None: """Initialize blueprint exception.""" super().__init__(domain, blueprint_name, "Blueprint already exists")
[ "def", "__init__", "(", "self", ",", "domain", ":", "str", ",", "blueprint_name", ":", "str", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", "domain", ",", "blueprint_name", ",", "\"Blueprint already exists\"", ")" ]
[ 85, 4 ]
[ 87, 76 ]
python
fr
['fr', 'fr', 'en']
True
async_setup
(hass: HomeAssistant, config: dict)
Set up the NEW_NAME component.
Set up the NEW_NAME component.
async def async_setup(hass: HomeAssistant, config: dict): """Set up the NEW_NAME component.""" return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ")", ":", "return", "True" ]
[ 17, 0 ]
[ 19, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass: HomeAssistant, entry: ConfigEntry)
Set up NEW_NAME from a config entry.
Set up NEW_NAME from a config entry.
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry): """Set up NEW_NAME from a config entry.""" # TODO Store an API object for your platforms to access # hass.data[DOMAIN][entry.entry_id] = MyApi(...) for component in PLATFORMS: hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, component) ) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "# TODO Store an API object for your platforms to access", "# hass.data[DOMAIN][entry.entry_id] = MyApi(...)", "for", "component", "in", "PLATFORMS", ":", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "component", ")", ")", "return", "True" ]
[ 22, 0 ]
[ 32, 15 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass: HomeAssistant, entry: ConfigEntry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry): """Unload a config entry.""" unload_ok = all( await asyncio.gather( *[ hass.config_entries.async_forward_entry_unload(entry, component) for component in PLATFORMS ] ) ) if unload_ok: hass.data[DOMAIN].pop(entry.entry_id) return unload_ok
[ "async", "def", "async_unload_entry", "(", "hass", ":", "HomeAssistant", ",", "entry", ":", "ConfigEntry", ")", ":", "unload_ok", "=", "all", "(", "await", "asyncio", ".", "gather", "(", "*", "[", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "component", ")", "for", "component", "in", "PLATFORMS", "]", ")", ")", "if", "unload_ok", ":", "hass", ".", "data", "[", "DOMAIN", "]", ".", "pop", "(", "entry", ".", "entry_id", ")", "return", "unload_ok" ]
[ 35, 0 ]
[ 48, 20 ]
python
en
['en', 'es', 'en']
True
test_automation_scenes
(hass)
Test creation automation scenes.
Test creation automation scenes.
async def test_automation_scenes(hass): """Test creation automation scenes.""" await async_init_integration(hass) state = hass.states.get("scene.away_short") expected_attributes = { "attribution": "Data provided by mynexia.com", "description": "When IFTTT activates the automation Upstairs " "West Wing will permanently hold the heat to 63.0 " "and cool to 80.0 AND Downstairs East Wing will " "permanently hold the heat to 63.0 and cool to " "79.0 AND Downstairs West Wing will permanently " "hold the heat to 63.0 and cool to 79.0 AND " "Upstairs West Wing will permanently hold the " "heat to 63.0 and cool to 81.0 AND Upstairs West " "Wing will change Fan Mode to Auto AND Downstairs " "East Wing will change Fan Mode to Auto AND " "Downstairs West Wing will change Fan Mode to " "Auto AND Activate the mode named 'Away Short' " "AND Master Suite will permanently hold the heat " "to 63.0 and cool to 79.0 AND Master Suite will " "change Fan Mode to Auto", "friendly_name": "Away Short", "icon": "mdi:script-text-outline", } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all( state.attributes[key] == expected_attributes[key] for key in expected_attributes ) state = hass.states.get("scene.power_outage") expected_attributes = { "attribution": "Data provided by mynexia.com", "description": "When IFTTT activates the automation Upstairs " "West Wing will permanently hold the heat to 55.0 " "and cool to 90.0 AND Downstairs East Wing will " "permanently hold the heat to 55.0 and cool to " "90.0 AND Downstairs West Wing will permanently " "hold the heat to 55.0 and cool to 90.0 AND " "Activate the mode named 'Power Outage'", "friendly_name": "Power Outage", "icon": "mdi:script-text-outline", } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all( state.attributes[key] == expected_attributes[key] for key in expected_attributes ) state = hass.states.get("scene.power_restored") expected_attributes = { "attribution": "Data provided by mynexia.com", "description": "When IFTTT activates the automation Upstairs " "West Wing will Run Schedule AND Downstairs East " "Wing will Run Schedule AND Downstairs West Wing " "will Run Schedule AND Activate the mode named " "'Home'", "friendly_name": "Power Restored", "icon": "mdi:script-text-outline", } # Only test for a subset of attributes in case # HA changes the implementation and a new one appears assert all( state.attributes[key] == expected_attributes[key] for key in expected_attributes )
[ "async", "def", "test_automation_scenes", "(", "hass", ")", ":", "await", "async_init_integration", "(", "hass", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"scene.away_short\"", ")", "expected_attributes", "=", "{", "\"attribution\"", ":", "\"Data provided by mynexia.com\"", ",", "\"description\"", ":", "\"When IFTTT activates the automation Upstairs \"", "\"West Wing will permanently hold the heat to 63.0 \"", "\"and cool to 80.0 AND Downstairs East Wing will \"", "\"permanently hold the heat to 63.0 and cool to \"", "\"79.0 AND Downstairs West Wing will permanently \"", "\"hold the heat to 63.0 and cool to 79.0 AND \"", "\"Upstairs West Wing will permanently hold the \"", "\"heat to 63.0 and cool to 81.0 AND Upstairs West \"", "\"Wing will change Fan Mode to Auto AND Downstairs \"", "\"East Wing will change Fan Mode to Auto AND \"", "\"Downstairs West Wing will change Fan Mode to \"", "\"Auto AND Activate the mode named 'Away Short' \"", "\"AND Master Suite will permanently hold the heat \"", "\"to 63.0 and cool to 79.0 AND Master Suite will \"", "\"change Fan Mode to Auto\"", ",", "\"friendly_name\"", ":", "\"Away Short\"", ",", "\"icon\"", ":", "\"mdi:script-text-outline\"", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "state", ".", "attributes", "[", "key", "]", "==", "expected_attributes", "[", "key", "]", "for", "key", "in", "expected_attributes", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"scene.power_outage\"", ")", "expected_attributes", "=", "{", "\"attribution\"", ":", "\"Data provided by mynexia.com\"", ",", "\"description\"", ":", "\"When IFTTT activates the automation Upstairs \"", "\"West Wing will permanently hold the heat to 55.0 \"", "\"and cool to 90.0 AND Downstairs East Wing will \"", "\"permanently hold the heat to 55.0 and cool to \"", "\"90.0 AND Downstairs West Wing will permanently \"", "\"hold the heat to 55.0 and cool to 90.0 AND \"", "\"Activate the mode named 'Power Outage'\"", ",", "\"friendly_name\"", ":", "\"Power Outage\"", ",", "\"icon\"", ":", "\"mdi:script-text-outline\"", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "state", ".", "attributes", "[", "key", "]", "==", "expected_attributes", "[", "key", "]", "for", "key", "in", "expected_attributes", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"scene.power_restored\"", ")", "expected_attributes", "=", "{", "\"attribution\"", ":", "\"Data provided by mynexia.com\"", ",", "\"description\"", ":", "\"When IFTTT activates the automation Upstairs \"", "\"West Wing will Run Schedule AND Downstairs East \"", "\"Wing will Run Schedule AND Downstairs West Wing \"", "\"will Run Schedule AND Activate the mode named \"", "\"'Home'\"", ",", "\"friendly_name\"", ":", "\"Power Restored\"", ",", "\"icon\"", ":", "\"mdi:script-text-outline\"", ",", "}", "# Only test for a subset of attributes in case", "# HA changes the implementation and a new one appears", "assert", "all", "(", "state", ".", "attributes", "[", "key", "]", "==", "expected_attributes", "[", "key", "]", "for", "key", "in", "expected_attributes", ")" ]
[ 5, 0 ]
[ 71, 5 ]
python
en
['de', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the XBee Zigbee platform. Uses the 'type' config value to work out which type of Zigbee sensor we're dealing with and instantiates the relevant classes to handle it.
Set up the XBee Zigbee platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the XBee Zigbee platform. Uses the 'type' config value to work out which type of Zigbee sensor we're dealing with and instantiates the relevant classes to handle it. """ zigbee_device = hass.data[DOMAIN] typ = config.get(CONF_TYPE) try: sensor_class, config_class = TYPE_CLASSES[typ] except KeyError: _LOGGER.exception("Unknown XBee Zigbee sensor type: %s", typ) return add_entities([sensor_class(config_class(config), zigbee_device)], True)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "zigbee_device", "=", "hass", ".", "data", "[", "DOMAIN", "]", "typ", "=", "config", ".", "get", "(", "CONF_TYPE", ")", "try", ":", "sensor_class", ",", "config_class", "=", "TYPE_CLASSES", "[", "typ", "]", "except", "KeyError", ":", "_LOGGER", ".", "exception", "(", "\"Unknown XBee Zigbee sensor type: %s\"", ",", "typ", ")", "return", "add_entities", "(", "[", "sensor_class", "(", "config_class", "(", "config", ")", ",", "zigbee_device", ")", "]", ",", "True", ")" ]
[ 28, 0 ]
[ 43, 75 ]
python
en
['en', 'xh', 'en']
True
XBeeTemperatureSensor.__init__
(self, config, device)
Initialize the sensor.
Initialize the sensor.
def __init__(self, config, device): """Initialize the sensor.""" self._config = config self._device = device self._temp = None
[ "def", "__init__", "(", "self", ",", "config", ",", "device", ")", ":", "self", ".", "_config", "=", "config", "self", ".", "_device", "=", "device", "self", ".", "_temp", "=", "None" ]
[ 49, 4 ]
[ 53, 25 ]
python
en
['en', 'en', 'en']
True
XBeeTemperatureSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._config.name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_config", ".", "name" ]
[ 56, 4 ]
[ 58, 32 ]
python
en
['en', 'mi', 'en']
True
XBeeTemperatureSensor.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._temp
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_temp" ]
[ 61, 4 ]
[ 63, 25 ]
python
en
['en', 'en', 'en']
True
XBeeTemperatureSensor.unit_of_measurement
(self)
Return the unit of measurement the value is expressed in.
Return the unit of measurement the value is expressed in.
def unit_of_measurement(self): """Return the unit of measurement the value is expressed in.""" return TEMP_CELSIUS
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "TEMP_CELSIUS" ]
[ 66, 4 ]
[ 68, 27 ]
python
en
['en', 'en', 'en']
True
XBeeTemperatureSensor.update
(self)
Get the latest data.
Get the latest data.
def update(self): """Get the latest data.""" try: self._temp = self._device.get_temperature(self._config.address) except ZigBeeTxFailure: _LOGGER.warning( "Transmission failure when attempting to get sample from " "Zigbee device at address: %s", hexlify(self._config.address), ) except ZigBeeException as exc: _LOGGER.exception("Unable to get sample from Zigbee device: %s", exc)
[ "def", "update", "(", "self", ")", ":", "try", ":", "self", ".", "_temp", "=", "self", ".", "_device", ".", "get_temperature", "(", "self", ".", "_config", ".", "address", ")", "except", "ZigBeeTxFailure", ":", "_LOGGER", ".", "warning", "(", "\"Transmission failure when attempting to get sample from \"", "\"Zigbee device at address: %s\"", ",", "hexlify", "(", "self", ".", "_config", ".", "address", ")", ",", ")", "except", "ZigBeeException", "as", "exc", ":", "_LOGGER", ".", "exception", "(", "\"Unable to get sample from Zigbee device: %s\"", ",", "exc", ")" ]
[ 70, 4 ]
[ 81, 81 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass: HomeAssistant)
Set up cloud account link.
Set up cloud account link.
def async_setup(hass: HomeAssistant): """Set up cloud account link.""" config_entry_oauth2_flow.async_add_implementation_provider( hass, DOMAIN, async_provide_implementation )
[ "def", "async_setup", "(", "hass", ":", "HomeAssistant", ")", ":", "config_entry_oauth2_flow", ".", "async_add_implementation_provider", "(", "hass", ",", "DOMAIN", ",", "async_provide_implementation", ")" ]
[ 20, 0 ]
[ 24, 5 ]
python
en
['en', 'ca', 'en']
True
async_provide_implementation
(hass: HomeAssistant, domain: str)
Provide an implementation for a domain.
Provide an implementation for a domain.
async def async_provide_implementation(hass: HomeAssistant, domain: str): """Provide an implementation for a domain.""" services = await _get_services(hass) for service in services: if service["service"] == domain and _is_older(service["min_version"]): return CloudOAuth2Implementation(hass, domain) return
[ "async", "def", "async_provide_implementation", "(", "hass", ":", "HomeAssistant", ",", "domain", ":", "str", ")", ":", "services", "=", "await", "_get_services", "(", "hass", ")", "for", "service", "in", "services", ":", "if", "service", "[", "\"service\"", "]", "==", "domain", "and", "_is_older", "(", "service", "[", "\"min_version\"", "]", ")", ":", "return", "CloudOAuth2Implementation", "(", "hass", ",", "domain", ")", "return" ]
[ 27, 0 ]
[ 35, 10 ]
python
en
['en', 'en', 'en']
True
_is_older
(version: str)
Test if a version is older than the current HA version.
Test if a version is older than the current HA version.
def _is_older(version: str) -> bool: """Test if a version is older than the current HA version.""" version_parts = version.split(".") if len(version_parts) != 3: return False try: version_parts = [int(val) for val in version_parts] except ValueError: return False patch_number_str = "" for char in PATCH_VERSION: if char.isnumeric(): patch_number_str += char else: break try: patch_number = int(patch_number_str) except ValueError: patch_number = 0 cur_version_parts = [MAJOR_VERSION, MINOR_VERSION, patch_number] return version_parts <= cur_version_parts
[ "def", "_is_older", "(", "version", ":", "str", ")", "->", "bool", ":", "version_parts", "=", "version", ".", "split", "(", "\".\"", ")", "if", "len", "(", "version_parts", ")", "!=", "3", ":", "return", "False", "try", ":", "version_parts", "=", "[", "int", "(", "val", ")", "for", "val", "in", "version_parts", "]", "except", "ValueError", ":", "return", "False", "patch_number_str", "=", "\"\"", "for", "char", "in", "PATCH_VERSION", ":", "if", "char", ".", "isnumeric", "(", ")", ":", "patch_number_str", "+=", "char", "else", ":", "break", "try", ":", "patch_number", "=", "int", "(", "patch_number_str", ")", "except", "ValueError", ":", "patch_number", "=", "0", "cur_version_parts", "=", "[", "MAJOR_VERSION", ",", "MINOR_VERSION", ",", "patch_number", "]", "return", "version_parts", "<=", "cur_version_parts" ]
[ 39, 0 ]
[ 66, 45 ]
python
en
['en', 'en', 'en']
True
_get_services
(hass)
Get the available services.
Get the available services.
async def _get_services(hass): """Get the available services.""" services = hass.data.get(DATA_SERVICES) if services is not None: return services try: services = await account_link.async_fetch_available_services(hass.data[DOMAIN]) except (aiohttp.ClientError, asyncio.TimeoutError): return [] hass.data[DATA_SERVICES] = services @callback def clear_services(_now): """Clear services cache.""" hass.data.pop(DATA_SERVICES, None) event.async_call_later(hass, CACHE_TIMEOUT, clear_services) return services
[ "async", "def", "_get_services", "(", "hass", ")", ":", "services", "=", "hass", ".", "data", ".", "get", "(", "DATA_SERVICES", ")", "if", "services", "is", "not", "None", ":", "return", "services", "try", ":", "services", "=", "await", "account_link", ".", "async_fetch_available_services", "(", "hass", ".", "data", "[", "DOMAIN", "]", ")", "except", "(", "aiohttp", ".", "ClientError", ",", "asyncio", ".", "TimeoutError", ")", ":", "return", "[", "]", "hass", ".", "data", "[", "DATA_SERVICES", "]", "=", "services", "@", "callback", "def", "clear_services", "(", "_now", ")", ":", "\"\"\"Clear services cache.\"\"\"", "hass", ".", "data", ".", "pop", "(", "DATA_SERVICES", ",", "None", ")", "event", ".", "async_call_later", "(", "hass", ",", "CACHE_TIMEOUT", ",", "clear_services", ")", "return", "services" ]
[ 69, 0 ]
[ 90, 19 ]
python
en
['en', 'en', 'en']
True
CloudOAuth2Implementation.__init__
(self, hass: HomeAssistant, service: str)
Initialize cloud OAuth2 implementation.
Initialize cloud OAuth2 implementation.
def __init__(self, hass: HomeAssistant, service: str): """Initialize cloud OAuth2 implementation.""" self.hass = hass self.service = service
[ "def", "__init__", "(", "self", ",", "hass", ":", "HomeAssistant", ",", "service", ":", "str", ")", ":", "self", ".", "hass", "=", "hass", "self", ".", "service", "=", "service" ]
[ 96, 4 ]
[ 99, 30 ]
python
en
['nl', 'en', 'en']
True
CloudOAuth2Implementation.name
(self)
Name of the implementation.
Name of the implementation.
def name(self) -> str: """Name of the implementation.""" return "Home Assistant Cloud"
[ "def", "name", "(", "self", ")", "->", "str", ":", "return", "\"Home Assistant Cloud\"" ]
[ 102, 4 ]
[ 104, 37 ]
python
en
['en', 'en', 'en']
True
CloudOAuth2Implementation.domain
(self)
Domain that is providing the implementation.
Domain that is providing the implementation.
def domain(self) -> str: """Domain that is providing the implementation.""" return DOMAIN
[ "def", "domain", "(", "self", ")", "->", "str", ":", "return", "DOMAIN" ]
[ 107, 4 ]
[ 109, 21 ]
python
en
['en', 'en', 'en']
True
CloudOAuth2Implementation.async_generate_authorize_url
(self, flow_id: str)
Generate a url for the user to authorize.
Generate a url for the user to authorize.
async def async_generate_authorize_url(self, flow_id: str) -> str: """Generate a url for the user to authorize.""" helper = account_link.AuthorizeAccountHelper( self.hass.data[DOMAIN], self.service ) authorize_url = await helper.async_get_authorize_url() async def await_tokens(): """Wait for tokens and pass them on when received.""" try: tokens = await helper.async_get_tokens() except asyncio.TimeoutError: _LOGGER.info("Timeout fetching tokens for flow %s", flow_id) except account_link.AccountLinkException as err: _LOGGER.info( "Failed to fetch tokens for flow %s: %s", flow_id, err.code ) else: await self.hass.config_entries.flow.async_configure( flow_id=flow_id, user_input=tokens ) self.hass.async_create_task(await_tokens()) return authorize_url
[ "async", "def", "async_generate_authorize_url", "(", "self", ",", "flow_id", ":", "str", ")", "->", "str", ":", "helper", "=", "account_link", ".", "AuthorizeAccountHelper", "(", "self", ".", "hass", ".", "data", "[", "DOMAIN", "]", ",", "self", ".", "service", ")", "authorize_url", "=", "await", "helper", ".", "async_get_authorize_url", "(", ")", "async", "def", "await_tokens", "(", ")", ":", "\"\"\"Wait for tokens and pass them on when received.\"\"\"", "try", ":", "tokens", "=", "await", "helper", ".", "async_get_tokens", "(", ")", "except", "asyncio", ".", "TimeoutError", ":", "_LOGGER", ".", "info", "(", "\"Timeout fetching tokens for flow %s\"", ",", "flow_id", ")", "except", "account_link", ".", "AccountLinkException", "as", "err", ":", "_LOGGER", ".", "info", "(", "\"Failed to fetch tokens for flow %s: %s\"", ",", "flow_id", ",", "err", ".", "code", ")", "else", ":", "await", "self", ".", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "flow_id", "=", "flow_id", ",", "user_input", "=", "tokens", ")", "self", ".", "hass", ".", "async_create_task", "(", "await_tokens", "(", ")", ")", "return", "authorize_url" ]
[ 111, 4 ]
[ 136, 28 ]
python
en
['en', 'en', 'en']
True
CloudOAuth2Implementation.async_resolve_external_data
(self, external_data: Any)
Resolve external data to tokens.
Resolve external data to tokens.
async def async_resolve_external_data(self, external_data: Any) -> dict: """Resolve external data to tokens.""" # We already passed in tokens return external_data
[ "async", "def", "async_resolve_external_data", "(", "self", ",", "external_data", ":", "Any", ")", "->", "dict", ":", "# We already passed in tokens", "return", "external_data" ]
[ 138, 4 ]
[ 141, 28 ]
python
en
['en', 'en', 'en']
True
CloudOAuth2Implementation._async_refresh_token
(self, token: dict)
Refresh a token.
Refresh a token.
async def _async_refresh_token(self, token: dict) -> dict: """Refresh a token.""" return await account_link.async_fetch_access_token( self.hass.data[DOMAIN], self.service, token["refresh_token"] )
[ "async", "def", "_async_refresh_token", "(", "self", ",", "token", ":", "dict", ")", "->", "dict", ":", "return", "await", "account_link", ".", "async_fetch_access_token", "(", "self", ".", "hass", ".", "data", "[", "DOMAIN", "]", ",", "self", ".", "service", ",", "token", "[", "\"refresh_token\"", "]", ")" ]
[ 143, 4 ]
[ 147, 9 ]
python
en
['en', 'gl', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up Airly air_quality entity based on a config entry.
Set up Airly air_quality entity based on a config entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up Airly air_quality entity based on a config entry.""" name = config_entry.data[CONF_NAME] coordinator = hass.data[DOMAIN][config_entry.entry_id] async_add_entities([AirlyAirQuality(coordinator, name)], False)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "name", "=", "config_entry", ".", "data", "[", "CONF_NAME", "]", "coordinator", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "config_entry", ".", "entry_id", "]", "async_add_entities", "(", "[", "AirlyAirQuality", "(", "coordinator", ",", "name", ")", "]", ",", "False", ")" ]
[ 39, 0 ]
[ 45, 67 ]
python
en
['en', 'en', 'en']
True
round_state
(func)
Round state.
Round state.
def round_state(func): """Round state.""" def _decorator(self): res = func(self) if isinstance(res, float): return round(res) return res return _decorator
[ "def", "round_state", "(", "func", ")", ":", "def", "_decorator", "(", "self", ")", ":", "res", "=", "func", "(", "self", ")", "if", "isinstance", "(", "res", ",", "float", ")", ":", "return", "round", "(", "res", ")", "return", "res", "return", "_decorator" ]
[ 48, 0 ]
[ 57, 21 ]
python
en
['en', 'sn', 'en']
False
AirlyAirQuality.__init__
(self, coordinator, name)
Initialize.
Initialize.
def __init__(self, coordinator, name): """Initialize.""" super().__init__(coordinator) self._name = name self._icon = "mdi:blur"
[ "def", "__init__", "(", "self", ",", "coordinator", ",", "name", ")", ":", "super", "(", ")", ".", "__init__", "(", "coordinator", ")", "self", ".", "_name", "=", "name", "self", ".", "_icon", "=", "\"mdi:blur\"" ]
[ 63, 4 ]
[ 67, 31 ]
python
en
['en', 'en', 'it']
False
AirlyAirQuality.name
(self)
Return the name.
Return the name.
def name(self): """Return the name.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 70, 4 ]
[ 72, 25 ]
python
en
['en', 'ig', 'en']
True
AirlyAirQuality.icon
(self)
Return the icon.
Return the icon.
def icon(self): """Return the icon.""" return self._icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "_icon" ]
[ 75, 4 ]
[ 77, 25 ]
python
en
['en', 'sr', 'en']
True
AirlyAirQuality.air_quality_index
(self)
Return the air quality index.
Return the air quality index.
def air_quality_index(self): """Return the air quality index.""" return self.coordinator.data[ATTR_API_CAQI]
[ "def", "air_quality_index", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_CAQI", "]" ]
[ 81, 4 ]
[ 83, 51 ]
python
en
['en', 'en', 'en']
True
AirlyAirQuality.particulate_matter_2_5
(self)
Return the particulate matter 2.5 level.
Return the particulate matter 2.5 level.
def particulate_matter_2_5(self): """Return the particulate matter 2.5 level.""" return self.coordinator.data[ATTR_API_PM25]
[ "def", "particulate_matter_2_5", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_PM25", "]" ]
[ 87, 4 ]
[ 89, 51 ]
python
en
['en', 'en', 'en']
True
AirlyAirQuality.particulate_matter_10
(self)
Return the particulate matter 10 level.
Return the particulate matter 10 level.
def particulate_matter_10(self): """Return the particulate matter 10 level.""" return self.coordinator.data[ATTR_API_PM10]
[ "def", "particulate_matter_10", "(", "self", ")", ":", "return", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_PM10", "]" ]
[ 93, 4 ]
[ 95, 51 ]
python
en
['en', 'en', 'en']
True
AirlyAirQuality.attribution
(self)
Return the attribution.
Return the attribution.
def attribution(self): """Return the attribution.""" return ATTRIBUTION
[ "def", "attribution", "(", "self", ")", ":", "return", "ATTRIBUTION" ]
[ 98, 4 ]
[ 100, 26 ]
python
en
['en', 'ja', 'en']
True
AirlyAirQuality.unique_id
(self)
Return a unique_id for this entity.
Return a unique_id for this entity.
def unique_id(self): """Return a unique_id for this entity.""" return f"{self.coordinator.latitude}-{self.coordinator.longitude}"
[ "def", "unique_id", "(", "self", ")", ":", "return", "f\"{self.coordinator.latitude}-{self.coordinator.longitude}\"" ]
[ 103, 4 ]
[ 105, 74 ]
python
en
['en', 'en', 'en']
True
AirlyAirQuality.device_info
(self)
Return the device info.
Return the device info.
def device_info(self): """Return the device info.""" return { "identifiers": { (DOMAIN, self.coordinator.latitude, self.coordinator.longitude) }, "name": DEFAULT_NAME, "manufacturer": MANUFACTURER, "entry_type": "service", }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "coordinator", ".", "latitude", ",", "self", ".", "coordinator", ".", "longitude", ")", "}", ",", "\"name\"", ":", "DEFAULT_NAME", ",", "\"manufacturer\"", ":", "MANUFACTURER", ",", "\"entry_type\"", ":", "\"service\"", ",", "}" ]
[ 108, 4 ]
[ 117, 9 ]
python
en
['en', 'en', 'en']
True
AirlyAirQuality.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" return { LABEL_AQI_DESCRIPTION: self.coordinator.data[ATTR_API_CAQI_DESCRIPTION], LABEL_ADVICE: self.coordinator.data[ATTR_API_ADVICE], LABEL_AQI_LEVEL: self.coordinator.data[ATTR_API_CAQI_LEVEL], LABEL_PM_2_5_LIMIT: self.coordinator.data[ATTR_API_PM25_LIMIT], LABEL_PM_2_5_PERCENT: round(self.coordinator.data[ATTR_API_PM25_PERCENT]), LABEL_PM_10_LIMIT: self.coordinator.data[ATTR_API_PM10_LIMIT], LABEL_PM_10_PERCENT: round(self.coordinator.data[ATTR_API_PM10_PERCENT]), }
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "{", "LABEL_AQI_DESCRIPTION", ":", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_CAQI_DESCRIPTION", "]", ",", "LABEL_ADVICE", ":", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_ADVICE", "]", ",", "LABEL_AQI_LEVEL", ":", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_CAQI_LEVEL", "]", ",", "LABEL_PM_2_5_LIMIT", ":", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_PM25_LIMIT", "]", ",", "LABEL_PM_2_5_PERCENT", ":", "round", "(", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_PM25_PERCENT", "]", ")", ",", "LABEL_PM_10_LIMIT", ":", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_PM10_LIMIT", "]", ",", "LABEL_PM_10_PERCENT", ":", "round", "(", "self", ".", "coordinator", ".", "data", "[", "ATTR_API_PM10_PERCENT", "]", ")", ",", "}" ]
[ 120, 4 ]
[ 130, 9 ]
python
en
['en', 'en', 'en']
True
NormalizationFactor.compute
(self, variable_value, dataset, x0_input=None)
:param variable_value: :param dataset: :param x0_input: :return:
def compute(self, variable_value, dataset, x0_input=None): """ :param variable_value: :param dataset: :param x0_input: :return: """ return np.asarray(variable_value['n_factor'])
[ "def", "compute", "(", "self", ",", "variable_value", ",", "dataset", ",", "x0_input", "=", "None", ")", ":", "return", "np", ".", "asarray", "(", "variable_value", "[", "'n_factor'", "]", ")" ]
[ 54, 4 ]
[ 63, 53 ]
python
en
['en', 'error', 'th']
False
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up a sensor for a Logi Circle device. Obsolete.
Set up a sensor for a Logi Circle device. Obsolete.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up a sensor for a Logi Circle device. Obsolete.""" _LOGGER.warning("Logi Circle no longer works with sensor platform configuration")
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "_LOGGER", ".", "warning", "(", "\"Logi Circle no longer works with sensor platform configuration\"", ")" ]
[ 25, 0 ]
[ 27, 85 ]
python
en
['en', 'sm', 'en']
True
async_setup_entry
(hass, entry, async_add_entities)
Set up a Logi Circle sensor based on a config entry.
Set up a Logi Circle sensor based on a config entry.
async def async_setup_entry(hass, entry, async_add_entities): """Set up a Logi Circle sensor based on a config entry.""" devices = await hass.data[LOGI_CIRCLE_DOMAIN].cameras time_zone = str(hass.config.time_zone) sensors = [] for sensor_type in entry.data.get(CONF_SENSORS).get(CONF_MONITORED_CONDITIONS): for device in devices: if device.supports_feature(sensor_type): sensors.append(LogiSensor(device, time_zone, sensor_type)) async_add_entities(sensors, True)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ",", "async_add_entities", ")", ":", "devices", "=", "await", "hass", ".", "data", "[", "LOGI_CIRCLE_DOMAIN", "]", ".", "cameras", "time_zone", "=", "str", "(", "hass", ".", "config", ".", "time_zone", ")", "sensors", "=", "[", "]", "for", "sensor_type", "in", "entry", ".", "data", ".", "get", "(", "CONF_SENSORS", ")", ".", "get", "(", "CONF_MONITORED_CONDITIONS", ")", ":", "for", "device", "in", "devices", ":", "if", "device", ".", "supports_feature", "(", "sensor_type", ")", ":", "sensors", ".", "append", "(", "LogiSensor", "(", "device", ",", "time_zone", ",", "sensor_type", ")", ")", "async_add_entities", "(", "sensors", ",", "True", ")" ]
[ 30, 0 ]
[ 41, 37 ]
python
en
['en', 'st', 'en']
True
LogiSensor.__init__
(self, camera, time_zone, sensor_type)
Initialize a sensor for Logi Circle camera.
Initialize a sensor for Logi Circle camera.
def __init__(self, camera, time_zone, sensor_type): """Initialize a sensor for Logi Circle camera.""" self._sensor_type = sensor_type self._camera = camera self._id = f"{self._camera.mac_address}-{self._sensor_type}" self._icon = f"mdi:{SENSOR_TYPES.get(self._sensor_type)[2]}" self._name = f"{self._camera.name} {SENSOR_TYPES.get(self._sensor_type)[0]}" self._activity = {} self._state = None self._tz = time_zone
[ "def", "__init__", "(", "self", ",", "camera", ",", "time_zone", ",", "sensor_type", ")", ":", "self", ".", "_sensor_type", "=", "sensor_type", "self", ".", "_camera", "=", "camera", "self", ".", "_id", "=", "f\"{self._camera.mac_address}-{self._sensor_type}\"", "self", ".", "_icon", "=", "f\"mdi:{SENSOR_TYPES.get(self._sensor_type)[2]}\"", "self", ".", "_name", "=", "f\"{self._camera.name} {SENSOR_TYPES.get(self._sensor_type)[0]}\"", "self", ".", "_activity", "=", "{", "}", "self", ".", "_state", "=", "None", "self", ".", "_tz", "=", "time_zone" ]
[ 47, 4 ]
[ 56, 28 ]
python
en
['en', 'pt', 'en']
True
LogiSensor.unique_id
(self)
Return a unique ID.
Return a unique ID.
def unique_id(self): """Return a unique ID.""" return self._id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_id" ]
[ 59, 4 ]
[ 61, 23 ]
python
ca
['fr', 'ca', 'en']
False
LogiSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 64, 4 ]
[ 66, 25 ]
python
en
['en', 'mi', 'en']
True
LogiSensor.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._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 69, 4 ]
[ 71, 26 ]
python
en
['en', 'en', 'en']
True
LogiSensor.device_info
(self)
Return information about the device.
Return information about the device.
def device_info(self): """Return information about the device.""" return { "name": self._camera.name, "identifiers": {(LOGI_CIRCLE_DOMAIN, self._camera.id)}, "model": self._camera.model_name, "sw_version": self._camera.firmware, "manufacturer": DEVICE_BRAND, }
[ "def", "device_info", "(", "self", ")", ":", "return", "{", "\"name\"", ":", "self", ".", "_camera", ".", "name", ",", "\"identifiers\"", ":", "{", "(", "LOGI_CIRCLE_DOMAIN", ",", "self", ".", "_camera", ".", "id", ")", "}", ",", "\"model\"", ":", "self", ".", "_camera", ".", "model_name", ",", "\"sw_version\"", ":", "self", ".", "_camera", ".", "firmware", ",", "\"manufacturer\"", ":", "DEVICE_BRAND", ",", "}" ]
[ 74, 4 ]
[ 82, 9 ]
python
en
['en', 'en', 'en']
True
LogiSensor.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" state = { ATTR_ATTRIBUTION: ATTRIBUTION, "battery_saving_mode": ( STATE_ON if self._camera.battery_saving else STATE_OFF ), "microphone_gain": self._camera.microphone_gain, } if self._sensor_type == "battery_level": state[ATTR_BATTERY_CHARGING] = self._camera.charging return state
[ "def", "device_state_attributes", "(", "self", ")", ":", "state", "=", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "\"battery_saving_mode\"", ":", "(", "STATE_ON", "if", "self", ".", "_camera", ".", "battery_saving", "else", "STATE_OFF", ")", ",", "\"microphone_gain\"", ":", "self", ".", "_camera", ".", "microphone_gain", ",", "}", "if", "self", ".", "_sensor_type", "==", "\"battery_level\"", ":", "state", "[", "ATTR_BATTERY_CHARGING", "]", "=", "self", ".", "_camera", ".", "charging", "return", "state" ]
[ 85, 4 ]
[ 98, 20 ]
python
en
['en', 'en', 'en']
True
LogiSensor.icon
(self)
Icon to use in the frontend, if any.
Icon to use in the frontend, if any.
def icon(self): """Icon to use in the frontend, if any.""" if self._sensor_type == "battery_level" and self._state is not None: return icon_for_battery_level( battery_level=int(self._state), charging=False ) if self._sensor_type == "recording_mode" and self._state is not None: return "mdi:eye" if self._state == STATE_ON else "mdi:eye-off" if self._sensor_type == "streaming_mode" and self._state is not None: return "mdi:camera" if self._state == STATE_ON else "mdi:camera-off" return self._icon
[ "def", "icon", "(", "self", ")", ":", "if", "self", ".", "_sensor_type", "==", "\"battery_level\"", "and", "self", ".", "_state", "is", "not", "None", ":", "return", "icon_for_battery_level", "(", "battery_level", "=", "int", "(", "self", ".", "_state", ")", ",", "charging", "=", "False", ")", "if", "self", ".", "_sensor_type", "==", "\"recording_mode\"", "and", "self", ".", "_state", "is", "not", "None", ":", "return", "\"mdi:eye\"", "if", "self", ".", "_state", "==", "STATE_ON", "else", "\"mdi:eye-off\"", "if", "self", ".", "_sensor_type", "==", "\"streaming_mode\"", "and", "self", ".", "_state", "is", "not", "None", ":", "return", "\"mdi:camera\"", "if", "self", ".", "_state", "==", "STATE_ON", "else", "\"mdi:camera-off\"", "return", "self", ".", "_icon" ]
[ 101, 4 ]
[ 111, 25 ]
python
en
['en', 'en', 'en']
True
LogiSensor.unit_of_measurement
(self)
Return the units of measurement.
Return the units of measurement.
def unit_of_measurement(self): """Return the units of measurement.""" return SENSOR_TYPES.get(self._sensor_type)[1]
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "SENSOR_TYPES", ".", "get", "(", "self", ".", "_sensor_type", ")", "[", "1", "]" ]
[ 114, 4 ]
[ 116, 53 ]
python
en
['en', 'bg', 'en']
True
LogiSensor.async_update
(self)
Get the latest data and updates the state.
Get the latest data and updates the state.
async def async_update(self): """Get the latest data and updates the state.""" _LOGGER.debug("Pulling data from %s sensor", self._name) await self._camera.update() if self._sensor_type == "last_activity_time": last_activity = await self._camera.get_last_activity(force_refresh=True) if last_activity is not None: last_activity_time = as_local(last_activity.end_time_utc) self._state = ( f"{last_activity_time.hour:0>2}:{last_activity_time.minute:0>2}" ) else: state = getattr(self._camera, self._sensor_type, None) if isinstance(state, bool): self._state = STATE_ON if state is True else STATE_OFF else: self._state = state self._state = state
[ "async", "def", "async_update", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Pulling data from %s sensor\"", ",", "self", ".", "_name", ")", "await", "self", ".", "_camera", ".", "update", "(", ")", "if", "self", ".", "_sensor_type", "==", "\"last_activity_time\"", ":", "last_activity", "=", "await", "self", ".", "_camera", ".", "get_last_activity", "(", "force_refresh", "=", "True", ")", "if", "last_activity", "is", "not", "None", ":", "last_activity_time", "=", "as_local", "(", "last_activity", ".", "end_time_utc", ")", "self", ".", "_state", "=", "(", "f\"{last_activity_time.hour:0>2}:{last_activity_time.minute:0>2}\"", ")", "else", ":", "state", "=", "getattr", "(", "self", ".", "_camera", ",", "self", ".", "_sensor_type", ",", "None", ")", "if", "isinstance", "(", "state", ",", "bool", ")", ":", "self", ".", "_state", "=", "STATE_ON", "if", "state", "is", "True", "else", "STATE_OFF", "else", ":", "self", ".", "_state", "=", "state", "self", ".", "_state", "=", "state" ]
[ 118, 4 ]
[ 136, 31 ]
python
en
['en', 'en', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the RMV departure sensor.
Set up the RMV departure sensor.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the RMV departure sensor.""" timeout = config.get(CONF_TIMEOUT) session = async_get_clientsession(hass) sensors = [] for next_departure in config.get(CONF_NEXT_DEPARTURE): sensors.append( RMVDepartureSensor( session, next_departure[CONF_STATION], next_departure.get(CONF_DESTINATIONS), next_departure.get(CONF_DIRECTION), next_departure.get(CONF_LINES), next_departure.get(CONF_PRODUCTS), next_departure.get(CONF_TIME_OFFSET), next_departure.get(CONF_MAX_JOURNEYS), next_departure.get(CONF_NAME), timeout, ) ) tasks = [sensor.async_update() for sensor in sensors] if tasks: await asyncio.wait(tasks) if not any(sensor.data for sensor in sensors): raise PlatformNotReady async_add_entities(sensors)
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "timeout", "=", "config", ".", "get", "(", "CONF_TIMEOUT", ")", "session", "=", "async_get_clientsession", "(", "hass", ")", "sensors", "=", "[", "]", "for", "next_departure", "in", "config", ".", "get", "(", "CONF_NEXT_DEPARTURE", ")", ":", "sensors", ".", "append", "(", "RMVDepartureSensor", "(", "session", ",", "next_departure", "[", "CONF_STATION", "]", ",", "next_departure", ".", "get", "(", "CONF_DESTINATIONS", ")", ",", "next_departure", ".", "get", "(", "CONF_DIRECTION", ")", ",", "next_departure", ".", "get", "(", "CONF_LINES", ")", ",", "next_departure", ".", "get", "(", "CONF_PRODUCTS", ")", ",", "next_departure", ".", "get", "(", "CONF_TIME_OFFSET", ")", ",", "next_departure", ".", "get", "(", "CONF_MAX_JOURNEYS", ")", ",", "next_departure", ".", "get", "(", "CONF_NAME", ")", ",", "timeout", ",", ")", ")", "tasks", "=", "[", "sensor", ".", "async_update", "(", ")", "for", "sensor", "in", "sensors", "]", "if", "tasks", ":", "await", "asyncio", ".", "wait", "(", "tasks", ")", "if", "not", "any", "(", "sensor", ".", "data", "for", "sensor", "in", "sensors", ")", ":", "raise", "PlatformNotReady", "async_add_entities", "(", "sensors", ")" ]
[ 76, 0 ]
[ 106, 31 ]
python
en
['en', 'da', 'en']
True
RMVDepartureSensor.__init__
( self, session, station, destinations, direction, lines, products, time_offset, max_journeys, name, timeout, )
Initialize the sensor.
Initialize the sensor.
def __init__( self, session, station, destinations, direction, lines, products, time_offset, max_journeys, name, timeout, ): """Initialize the sensor.""" self._station = station self._name = name self._state = None self.data = RMVDepartureData( session, station, destinations, direction, lines, products, time_offset, max_journeys, timeout, ) self._icon = ICONS[None]
[ "def", "__init__", "(", "self", ",", "session", ",", "station", ",", "destinations", ",", "direction", ",", "lines", ",", "products", ",", "time_offset", ",", "max_journeys", ",", "name", ",", "timeout", ",", ")", ":", "self", ".", "_station", "=", "station", "self", ".", "_name", "=", "name", "self", ".", "_state", "=", "None", "self", ".", "data", "=", "RMVDepartureData", "(", "session", ",", "station", ",", "destinations", ",", "direction", ",", "lines", ",", "products", ",", "time_offset", ",", "max_journeys", ",", "timeout", ",", ")", "self", ".", "_icon", "=", "ICONS", "[", "None", "]" ]
[ 112, 4 ]
[ 140, 32 ]
python
en
['en', 'en', 'en']
True
RMVDepartureSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 143, 4 ]
[ 145, 25 ]
python
en
['en', 'mi', 'en']
True
RMVDepartureSensor.available
(self)
Return True if entity is available.
Return True if entity is available.
def available(self): """Return True if entity is available.""" return self._state is not None
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_state", "is", "not", "None" ]
[ 148, 4 ]
[ 150, 38 ]
python
en
['en', 'en', 'en']
True
RMVDepartureSensor.state
(self)
Return the next departure time.
Return the next departure time.
def state(self): """Return the next departure time.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 153, 4 ]
[ 155, 26 ]
python
en
['en', 'en', 'en']
True
RMVDepartureSensor.state_attributes
(self)
Return the state attributes.
Return the state attributes.
def state_attributes(self): """Return the state attributes.""" try: return { "next_departures": self.data.departures[1:], "direction": self.data.departures[0].get("direction"), "line": self.data.departures[0].get("line"), "minutes": self.data.departures[0].get("minutes"), "departure_time": self.data.departures[0].get("departure_time"), "product": self.data.departures[0].get("product"), ATTR_ATTRIBUTION: ATTRIBUTION, } except IndexError: return {}
[ "def", "state_attributes", "(", "self", ")", ":", "try", ":", "return", "{", "\"next_departures\"", ":", "self", ".", "data", ".", "departures", "[", "1", ":", "]", ",", "\"direction\"", ":", "self", ".", "data", ".", "departures", "[", "0", "]", ".", "get", "(", "\"direction\"", ")", ",", "\"line\"", ":", "self", ".", "data", ".", "departures", "[", "0", "]", ".", "get", "(", "\"line\"", ")", ",", "\"minutes\"", ":", "self", ".", "data", ".", "departures", "[", "0", "]", ".", "get", "(", "\"minutes\"", ")", ",", "\"departure_time\"", ":", "self", ".", "data", ".", "departures", "[", "0", "]", ".", "get", "(", "\"departure_time\"", ")", ",", "\"product\"", ":", "self", ".", "data", ".", "departures", "[", "0", "]", ".", "get", "(", "\"product\"", ")", ",", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "}", "except", "IndexError", ":", "return", "{", "}" ]
[ 158, 4 ]
[ 171, 21 ]
python
en
['en', 'en', 'en']
True
RMVDepartureSensor.icon
(self)
Icon to use in the frontend, if any.
Icon to use in the frontend, if any.
def icon(self): """Icon to use in the frontend, if any.""" return self._icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "_icon" ]
[ 174, 4 ]
[ 176, 25 ]
python
en
['en', 'en', 'en']
True
RMVDepartureSensor.unit_of_measurement
(self)
Return the unit this state is expressed in.
Return the unit this state is expressed in.
def unit_of_measurement(self): """Return the unit this state is expressed in.""" return TIME_MINUTES
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "TIME_MINUTES" ]
[ 179, 4 ]
[ 181, 27 ]
python
en
['en', 'en', 'en']
True
RMVDepartureSensor.async_update
(self)
Get the latest data and update the state.
Get the latest data and update the state.
async def async_update(self): """Get the latest data and update the state.""" await self.data.async_update() if self._name == DEFAULT_NAME: self._name = self.data.station self._station = self.data.station if not self.data.departures: self._state = None self._icon = ICONS[None] return self._state = self.data.departures[0].get("minutes") self._icon = ICONS[self.data.departures[0].get("product")]
[ "async", "def", "async_update", "(", "self", ")", ":", "await", "self", ".", "data", ".", "async_update", "(", ")", "if", "self", ".", "_name", "==", "DEFAULT_NAME", ":", "self", ".", "_name", "=", "self", ".", "data", ".", "station", "self", ".", "_station", "=", "self", ".", "data", ".", "station", "if", "not", "self", ".", "data", ".", "departures", ":", "self", ".", "_state", "=", "None", "self", ".", "_icon", "=", "ICONS", "[", "None", "]", "return", "self", ".", "_state", "=", "self", ".", "data", ".", "departures", "[", "0", "]", ".", "get", "(", "\"minutes\"", ")", "self", ".", "_icon", "=", "ICONS", "[", "self", ".", "data", ".", "departures", "[", "0", "]", ".", "get", "(", "\"product\"", ")", "]" ]
[ 183, 4 ]
[ 198, 66 ]
python
en
['en', 'en', 'en']
True
RMVDepartureData.__init__
( self, session, station_id, destinations, direction, lines, products, time_offset, max_journeys, timeout, )
Initialize the sensor.
Initialize the sensor.
def __init__( self, session, station_id, destinations, direction, lines, products, time_offset, max_journeys, timeout, ): """Initialize the sensor.""" self.station = None self._station_id = station_id self._destinations = destinations self._direction = direction self._lines = lines self._products = products self._time_offset = time_offset self._max_journeys = max_journeys self.rmv = RMVtransport(session, timeout) self.departures = [] self._error_notification = False
[ "def", "__init__", "(", "self", ",", "session", ",", "station_id", ",", "destinations", ",", "direction", ",", "lines", ",", "products", ",", "time_offset", ",", "max_journeys", ",", "timeout", ",", ")", ":", "self", ".", "station", "=", "None", "self", ".", "_station_id", "=", "station_id", "self", ".", "_destinations", "=", "destinations", "self", ".", "_direction", "=", "direction", "self", ".", "_lines", "=", "lines", "self", ".", "_products", "=", "products", "self", ".", "_time_offset", "=", "time_offset", "self", ".", "_max_journeys", "=", "max_journeys", "self", ".", "rmv", "=", "RMVtransport", "(", "session", ",", "timeout", ")", "self", ".", "departures", "=", "[", "]", "self", ".", "_error_notification", "=", "False" ]
[ 204, 4 ]
[ 227, 40 ]
python
en
['en', 'en', 'en']
True
RMVDepartureData.async_update
(self)
Update the connection data.
Update the connection data.
async def async_update(self): """Update the connection data.""" try: _data = await self.rmv.get_departures( self._station_id, products=self._products, direction_id=self._direction, max_journeys=50, ) except RMVtransportApiConnectionError: self.departures = [] _LOGGER.warning("Could not retrieve data from rmv.de") return self.station = _data.get("station") _deps = [] _deps_not_found = set(self._destinations) for journey in _data["journeys"]: # find the first departure meeting the criteria _nextdep = {} if self._destinations: dest_found = False for dest in self._destinations: if dest in journey["stops"]: dest_found = True if dest in _deps_not_found: _deps_not_found.remove(dest) _nextdep["destination"] = dest if not dest_found: continue if self._lines and journey["number"] not in self._lines: continue if journey["minutes"] < self._time_offset: continue for attr in ["direction", "departure_time", "product", "minutes"]: _nextdep[attr] = journey.get(attr, "") _nextdep["line"] = journey.get("number", "") _deps.append(_nextdep) if len(_deps) > self._max_journeys: break if not self._error_notification and _deps_not_found: self._error_notification = True _LOGGER.info("Destination(s) %s not found", ", ".join(_deps_not_found)) self.departures = _deps
[ "async", "def", "async_update", "(", "self", ")", ":", "try", ":", "_data", "=", "await", "self", ".", "rmv", ".", "get_departures", "(", "self", ".", "_station_id", ",", "products", "=", "self", ".", "_products", ",", "direction_id", "=", "self", ".", "_direction", ",", "max_journeys", "=", "50", ",", ")", "except", "RMVtransportApiConnectionError", ":", "self", ".", "departures", "=", "[", "]", "_LOGGER", ".", "warning", "(", "\"Could not retrieve data from rmv.de\"", ")", "return", "self", ".", "station", "=", "_data", ".", "get", "(", "\"station\"", ")", "_deps", "=", "[", "]", "_deps_not_found", "=", "set", "(", "self", ".", "_destinations", ")", "for", "journey", "in", "_data", "[", "\"journeys\"", "]", ":", "# find the first departure meeting the criteria", "_nextdep", "=", "{", "}", "if", "self", ".", "_destinations", ":", "dest_found", "=", "False", "for", "dest", "in", "self", ".", "_destinations", ":", "if", "dest", "in", "journey", "[", "\"stops\"", "]", ":", "dest_found", "=", "True", "if", "dest", "in", "_deps_not_found", ":", "_deps_not_found", ".", "remove", "(", "dest", ")", "_nextdep", "[", "\"destination\"", "]", "=", "dest", "if", "not", "dest_found", ":", "continue", "if", "self", ".", "_lines", "and", "journey", "[", "\"number\"", "]", "not", "in", "self", ".", "_lines", ":", "continue", "if", "journey", "[", "\"minutes\"", "]", "<", "self", ".", "_time_offset", ":", "continue", "for", "attr", "in", "[", "\"direction\"", ",", "\"departure_time\"", ",", "\"product\"", ",", "\"minutes\"", "]", ":", "_nextdep", "[", "attr", "]", "=", "journey", ".", "get", "(", "attr", ",", "\"\"", ")", "_nextdep", "[", "\"line\"", "]", "=", "journey", ".", "get", "(", "\"number\"", ",", "\"\"", ")", "_deps", ".", "append", "(", "_nextdep", ")", "if", "len", "(", "_deps", ")", ">", "self", ".", "_max_journeys", ":", "break", "if", "not", "self", ".", "_error_notification", "and", "_deps_not_found", ":", "self", ".", "_error_notification", "=", "True", "_LOGGER", ".", "info", "(", "\"Destination(s) %s not found\"", ",", "\", \"", ".", "join", "(", "_deps_not_found", ")", ")", "self", ".", "departures", "=", "_deps" ]
[ 230, 4 ]
[ 284, 31 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Set up the deCONZ climate devices. Thermostats are based on the same device class as sensors in deCONZ.
Set up the deCONZ climate devices.
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the deCONZ climate devices. Thermostats are based on the same device class as sensors in deCONZ. """ gateway = get_gateway_from_config_entry(hass, config_entry) gateway.entities[DOMAIN] = set() @callback def async_add_climate(sensors): """Add climate devices from deCONZ.""" entities = [] for sensor in sensors: if ( sensor.type in Thermostat.ZHATYPE and sensor.uniqueid not in gateway.entities[DOMAIN] and ( gateway.option_allow_clip_sensor or not sensor.type.startswith("CLIP") ) ): entities.append(DeconzThermostat(sensor, gateway)) if entities: async_add_entities(entities) gateway.listeners.append( async_dispatcher_connect( hass, gateway.async_signal_new_device(NEW_SENSOR), async_add_climate ) ) async_add_climate(gateway.api.sensors.values())
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "gateway", "=", "get_gateway_from_config_entry", "(", "hass", ",", "config_entry", ")", "gateway", ".", "entities", "[", "DOMAIN", "]", "=", "set", "(", ")", "@", "callback", "def", "async_add_climate", "(", "sensors", ")", ":", "\"\"\"Add climate devices from deCONZ.\"\"\"", "entities", "=", "[", "]", "for", "sensor", "in", "sensors", ":", "if", "(", "sensor", ".", "type", "in", "Thermostat", ".", "ZHATYPE", "and", "sensor", ".", "uniqueid", "not", "in", "gateway", ".", "entities", "[", "DOMAIN", "]", "and", "(", "gateway", ".", "option_allow_clip_sensor", "or", "not", "sensor", ".", "type", ".", "startswith", "(", "\"CLIP\"", ")", ")", ")", ":", "entities", ".", "append", "(", "DeconzThermostat", "(", "sensor", ",", "gateway", ")", ")", "if", "entities", ":", "async_add_entities", "(", "entities", ")", "gateway", ".", "listeners", ".", "append", "(", "async_dispatcher_connect", "(", "hass", ",", "gateway", ".", "async_signal_new_device", "(", "NEW_SENSOR", ")", ",", "async_add_climate", ")", ")", "async_add_climate", "(", "gateway", ".", "api", ".", "sensors", ".", "values", "(", ")", ")" ]
[ 21, 0 ]
[ 55, 51 ]
python
en
['en', 'en', 'en']
True
DeconzThermostat.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self): """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_TARGET_TEMPERATURE" ]
[ 64, 4 ]
[ 66, 41 ]
python
en
['en', 'en', 'en']
True
DeconzThermostat.hvac_mode
(self)
Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*.
Return hvac operation ie. heat, cool mode.
def hvac_mode(self): """Return hvac operation ie. heat, cool mode. Need to be one of HVAC_MODE_*. """ for hass_hvac_mode, device_mode in HVAC_MODES.items(): if self._device.mode == device_mode: return hass_hvac_mode if self._device.state_on: return HVAC_MODE_HEAT return HVAC_MODE_OFF
[ "def", "hvac_mode", "(", "self", ")", ":", "for", "hass_hvac_mode", ",", "device_mode", "in", "HVAC_MODES", ".", "items", "(", ")", ":", "if", "self", ".", "_device", ".", "mode", "==", "device_mode", ":", "return", "hass_hvac_mode", "if", "self", ".", "_device", ".", "state_on", ":", "return", "HVAC_MODE_HEAT", "return", "HVAC_MODE_OFF" ]
[ 69, 4 ]
[ 81, 28 ]
python
bg
['en', 'bg', 'bg']
True
DeconzThermostat.hvac_modes
(self)
Return the list of available hvac operation modes.
Return the list of available hvac operation modes.
def hvac_modes(self) -> list: """Return the list of available hvac operation modes.""" return list(HVAC_MODES)
[ "def", "hvac_modes", "(", "self", ")", "->", "list", ":", "return", "list", "(", "HVAC_MODES", ")" ]
[ 84, 4 ]
[ 86, 31 ]
python
en
['en', 'en', 'en']
True
DeconzThermostat.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self): """Return the current temperature.""" return self._device.temperature
[ "def", "current_temperature", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "temperature" ]
[ 89, 4 ]
[ 91, 39 ]
python
en
['en', 'la', 'en']
True
DeconzThermostat.target_temperature
(self)
Return the target temperature.
Return the target temperature.
def target_temperature(self): """Return the target temperature.""" return self._device.heatsetpoint
[ "def", "target_temperature", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "heatsetpoint" ]
[ 94, 4 ]
[ 96, 40 ]
python
en
['en', 'la', 'en']
True
DeconzThermostat.async_set_temperature
(self, **kwargs)
Set new target temperature.
Set new target temperature.
async def async_set_temperature(self, **kwargs): """Set new target temperature.""" if ATTR_TEMPERATURE not in kwargs: raise ValueError(f"Expected attribute {ATTR_TEMPERATURE}") data = {"heatsetpoint": kwargs[ATTR_TEMPERATURE] * 100} await self._device.async_set_config(data)
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "ATTR_TEMPERATURE", "not", "in", "kwargs", ":", "raise", "ValueError", "(", "f\"Expected attribute {ATTR_TEMPERATURE}\"", ")", "data", "=", "{", "\"heatsetpoint\"", ":", "kwargs", "[", "ATTR_TEMPERATURE", "]", "*", "100", "}", "await", "self", ".", "_device", ".", "async_set_config", "(", "data", ")" ]
[ 98, 4 ]
[ 105, 49 ]
python
en
['en', 'ca', 'en']
True
DeconzThermostat.async_set_hvac_mode
(self, hvac_mode)
Set new target hvac mode.
Set new target hvac mode.
async def async_set_hvac_mode(self, hvac_mode): """Set new target hvac mode.""" if hvac_mode not in HVAC_MODES: raise ValueError(f"Unsupported mode {hvac_mode}") data = {"mode": HVAC_MODES[hvac_mode]} await self._device.async_set_config(data)
[ "async", "def", "async_set_hvac_mode", "(", "self", ",", "hvac_mode", ")", ":", "if", "hvac_mode", "not", "in", "HVAC_MODES", ":", "raise", "ValueError", "(", "f\"Unsupported mode {hvac_mode}\"", ")", "data", "=", "{", "\"mode\"", ":", "HVAC_MODES", "[", "hvac_mode", "]", "}", "await", "self", ".", "_device", ".", "async_set_config", "(", "data", ")" ]
[ 107, 4 ]
[ 114, 49 ]
python
da
['da', 'su', 'en']
False
DeconzThermostat.temperature_unit
(self)
Return the unit of measurement.
Return the unit of measurement.
def temperature_unit(self): """Return the unit of measurement.""" return TEMP_CELSIUS
[ "def", "temperature_unit", "(", "self", ")", ":", "return", "TEMP_CELSIUS" ]
[ 117, 4 ]
[ 119, 27 ]
python
en
['en', 'la', 'en']
True
DeconzThermostat.device_state_attributes
(self)
Return the state attributes of the thermostat.
Return the state attributes of the thermostat.
def device_state_attributes(self): """Return the state attributes of the thermostat.""" attr = {} if self._device.offset: attr[ATTR_OFFSET] = self._device.offset if self._device.valve is not None: attr[ATTR_VALVE] = self._device.valve return attr
[ "def", "device_state_attributes", "(", "self", ")", ":", "attr", "=", "{", "}", "if", "self", ".", "_device", ".", "offset", ":", "attr", "[", "ATTR_OFFSET", "]", "=", "self", ".", "_device", ".", "offset", "if", "self", ".", "_device", ".", "valve", "is", "not", "None", ":", "attr", "[", "ATTR_VALVE", "]", "=", "self", ".", "_device", ".", "valve", "return", "attr" ]
[ 122, 4 ]
[ 132, 19 ]
python
en
['en', 'en', 'en']
True
test_async_setup_entry
(mock_now, hass)
Test async_setup_entry.
Test async_setup_entry.
async def test_async_setup_entry(mock_now, hass): """Test async_setup_entry.""" entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: HOST, CONF_PORT: PORT}, unique_id=f"{HOST}:{PORT}", ) timestamp = future_timestamp(100) with patch( "homeassistant.components.cert_expiry.get_cert_expiry_timestamp", return_value=timestamp, ): entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() state = hass.states.get("sensor.cert_expiry_timestamp_example_com") assert state is not None assert state.state != STATE_UNAVAILABLE assert state.state == timestamp.isoformat() assert state.attributes.get("error") == "None" assert state.attributes.get("is_valid")
[ "async", "def", "test_async_setup_entry", "(", "mock_now", ",", "hass", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "CONF_HOST", ":", "HOST", ",", "CONF_PORT", ":", "PORT", "}", ",", "unique_id", "=", "f\"{HOST}:{PORT}\"", ",", ")", "timestamp", "=", "future_timestamp", "(", "100", ")", "with", "patch", "(", "\"homeassistant.components.cert_expiry.get_cert_expiry_timestamp\"", ",", "return_value", "=", "timestamp", ",", ")", ":", "entry", ".", "add_to_hass", "(", "hass", ")", "assert", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.cert_expiry_timestamp_example_com\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "assert", "state", ".", "state", "==", "timestamp", ".", "isoformat", "(", ")", "assert", "state", ".", "attributes", ".", "get", "(", "\"error\"", ")", "==", "\"None\"", "assert", "state", ".", "attributes", ".", "get", "(", "\"is_valid\"", ")" ]
[ 18, 0 ]
[ 41, 43 ]
python
en
['en', 'be', 'en']
False
test_async_setup_entry_bad_cert
(hass)
Test async_setup_entry with a bad/expired cert.
Test async_setup_entry with a bad/expired cert.
async def test_async_setup_entry_bad_cert(hass): """Test async_setup_entry with a bad/expired cert.""" entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: HOST, CONF_PORT: PORT}, unique_id=f"{HOST}:{PORT}", ) with patch( "homeassistant.components.cert_expiry.helper.get_cert", side_effect=ssl.SSLError("some error"), ): entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() state = hass.states.get("sensor.cert_expiry_timestamp_example_com") assert state is not None assert state.state != STATE_UNAVAILABLE assert state.attributes.get("error") == "some error" assert not state.attributes.get("is_valid")
[ "async", "def", "test_async_setup_entry_bad_cert", "(", "hass", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "CONF_HOST", ":", "HOST", ",", "CONF_PORT", ":", "PORT", "}", ",", "unique_id", "=", "f\"{HOST}:{PORT}\"", ",", ")", "with", "patch", "(", "\"homeassistant.components.cert_expiry.helper.get_cert\"", ",", "side_effect", "=", "ssl", ".", "SSLError", "(", "\"some error\"", ")", ",", ")", ":", "entry", ".", "add_to_hass", "(", "hass", ")", "assert", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.cert_expiry_timestamp_example_com\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "state", "!=", "STATE_UNAVAILABLE", "assert", "state", ".", "attributes", ".", "get", "(", "\"error\"", ")", "==", "\"some error\"", "assert", "not", "state", ".", "attributes", ".", "get", "(", "\"is_valid\"", ")" ]
[ 44, 0 ]
[ 64, 47 ]
python
en
['en', 'en', 'en']
True
test_async_setup_entry_host_unavailable
(hass)
Test async_setup_entry when host is unavailable.
Test async_setup_entry when host is unavailable.
async def test_async_setup_entry_host_unavailable(hass): """Test async_setup_entry when host is unavailable.""" entry = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: HOST, CONF_PORT: PORT}, unique_id=f"{HOST}:{PORT}", ) with patch( "homeassistant.components.cert_expiry.helper.get_cert", side_effect=socket.gaierror, ): entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) is False await hass.async_block_till_done() assert entry.state == ENTRY_STATE_SETUP_RETRY next_update = utcnow() + timedelta(seconds=45) async_fire_time_changed(hass, next_update) with patch( "homeassistant.components.cert_expiry.helper.get_cert", side_effect=socket.gaierror, ): await hass.async_block_till_done() state = hass.states.get("sensor.cert_expiry_timestamp_example_com") assert state is None
[ "async", "def", "test_async_setup_entry_host_unavailable", "(", "hass", ")", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "CONF_HOST", ":", "HOST", ",", "CONF_PORT", ":", "PORT", "}", ",", "unique_id", "=", "f\"{HOST}:{PORT}\"", ",", ")", "with", "patch", "(", "\"homeassistant.components.cert_expiry.helper.get_cert\"", ",", "side_effect", "=", "socket", ".", "gaierror", ",", ")", ":", "entry", ".", "add_to_hass", "(", "hass", ")", "assert", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "is", "False", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "entry", ".", "state", "==", "ENTRY_STATE_SETUP_RETRY", "next_update", "=", "utcnow", "(", ")", "+", "timedelta", "(", "seconds", "=", "45", ")", "async_fire_time_changed", "(", "hass", ",", "next_update", ")", "with", "patch", "(", "\"homeassistant.components.cert_expiry.helper.get_cert\"", ",", "side_effect", "=", "socket", ".", "gaierror", ",", ")", ":", "await", "hass", ".", "async_block_till_done", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"sensor.cert_expiry_timestamp_example_com\"", ")", "assert", "state", "is", "None" ]
[ 67, 0 ]
[ 94, 24 ]
python
en
['en', 'en', 'en']
True