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
SigfoxDevice.update
(self)
Fetch the latest device message.
Fetch the latest device message.
def update(self): """Fetch the latest device message.""" self._message_data = self.get_last_message() self._state = self._message_data["payload"]
[ "def", "update", "(", "self", ")", ":", "self", ".", "_message_data", "=", "self", ".", "get_last_message", "(", ")", "self", ".", "_state", "=", "self", ".", "_message_data", "[", "\"payload\"", "]" ]
[ 141, 4 ]
[ 144, 51 ]
python
en
['en', 'en', 'en']
True
SigfoxDevice.name
(self)
Return the HA name of the sensor.
Return the HA name of the sensor.
def name(self): """Return the HA name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 147, 4 ]
[ 149, 25 ]
python
en
['en', 'ig', 'en']
True
SigfoxDevice.state
(self)
Return the payload of the last message.
Return the payload of the last message.
def state(self): """Return the payload of the last message.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 152, 4 ]
[ 154, 26 ]
python
en
['en', 'en', 'en']
True
SigfoxDevice.device_state_attributes
(self)
Return other details about the last message.
Return other details about the last message.
def device_state_attributes(self): """Return other details about the last message.""" return self._message_data
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_message_data" ]
[ 157, 4 ]
[ 159, 33 ]
python
en
['en', 'en', 'en']
True
mock_connection
(aioclient_mock)
Mock syncthru connection.
Mock syncthru connection.
def mock_connection(aioclient_mock): """Mock syncthru connection.""" aioclient_mock.get( re.compile("."), text=""" { \tstatus: { \thrDeviceStatus: 2, \tstatus1: " Sleeping... " \t}, \tidentity: { \tserial_num: "000000000000000", \t} } """, )
[ "def", "mock_connection", "(", "aioclient_mock", ")", ":", "aioclient_mock", ".", "get", "(", "re", ".", "compile", "(", "\".\"", ")", ",", "text", "=", "\"\"\"\n{\n\\tstatus: {\n\\thrDeviceStatus: 2,\n\\tstatus1: \" Sleeping... \"\n\\t},\n\\tidentity: {\n\\tserial_num: \"000000000000000\",\n\\t}\n}\n \"\"\"", ",", ")" ]
[ 19, 0 ]
[ 34, 5 ]
python
en
['fr', 'en', 'en']
True
test_show_setup_form
(hass)
Test that the setup form is served.
Test that the setup form is served.
async def test_show_setup_form(hass): """Test that the setup form is served.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, data=None ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user"
[ "async", "def", "test_show_setup_form", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ",", "data", "=", "None", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"" ]
[ 37, 0 ]
[ 44, 38 ]
python
en
['en', 'en', 'en']
True
test_already_configured_by_url
(hass, aioclient_mock)
Test we match and update already configured devices by URL.
Test we match and update already configured devices by URL.
async def test_already_configured_by_url(hass, aioclient_mock): """Test we match and update already configured devices by URL.""" await setup.async_setup_component(hass, "persistent_notification", {}) udn = "uuid:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" MockConfigEntry( domain=DOMAIN, data={**FIXTURE_USER_INPUT, CONF_NAME: "Already configured"}, title="Already configured", unique_id=udn, ).add_to_hass(hass) mock_connection(aioclient_mock) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, data=FIXTURE_USER_INPUT, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_URL] == FIXTURE_USER_INPUT[CONF_URL] assert result["data"][CONF_NAME] == FIXTURE_USER_INPUT[CONF_NAME] assert result["result"].unique_id == udn
[ "async", "def", "test_already_configured_by_url", "(", "hass", ",", "aioclient_mock", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "udn", "=", "\"uuid:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\"", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "data", "=", "{", "*", "*", "FIXTURE_USER_INPUT", ",", "CONF_NAME", ":", "\"Already configured\"", "}", ",", "title", "=", "\"Already configured\"", ",", "unique_id", "=", "udn", ",", ")", ".", "add_to_hass", "(", "hass", ")", "mock_connection", "(", "aioclient_mock", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ",", "data", "=", "FIXTURE_USER_INPUT", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"data\"", "]", "[", "CONF_URL", "]", "==", "FIXTURE_USER_INPUT", "[", "CONF_URL", "]", "assert", "result", "[", "\"data\"", "]", "[", "CONF_NAME", "]", "==", "FIXTURE_USER_INPUT", "[", "CONF_NAME", "]", "assert", "result", "[", "\"result\"", "]", ".", "unique_id", "==", "udn" ]
[ 47, 0 ]
[ 68, 44 ]
python
en
['en', 'en', 'en']
True
test_syncthru_not_supported
(hass)
Test we show user form on unsupported device.
Test we show user form on unsupported device.
async def test_syncthru_not_supported(hass): """Test we show user form on unsupported device.""" with patch.object(SyncThru, "update", side_effect=ValueError): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, data=FIXTURE_USER_INPUT, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" assert result["errors"] == {CONF_URL: "syncthru_not_supported"}
[ "async", "def", "test_syncthru_not_supported", "(", "hass", ")", ":", "with", "patch", ".", "object", "(", "SyncThru", ",", "\"update\"", ",", "side_effect", "=", "ValueError", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ",", "data", "=", "FIXTURE_USER_INPUT", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"errors\"", "]", "==", "{", "CONF_URL", ":", "\"syncthru_not_supported\"", "}" ]
[ 71, 0 ]
[ 82, 67 ]
python
en
['en', 'en', 'en']
True
test_unknown_state
(hass)
Test we show user form on unsupported device.
Test we show user form on unsupported device.
async def test_unknown_state(hass): """Test we show user form on unsupported device.""" with patch.object(SyncThru, "update", return_value=mock_coro()), patch.object( SyncThru, "is_unknown_state", return_value=True ): result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, data=FIXTURE_USER_INPUT, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "user" assert result["errors"] == {CONF_URL: "unknown_state"}
[ "async", "def", "test_unknown_state", "(", "hass", ")", ":", "with", "patch", ".", "object", "(", "SyncThru", ",", "\"update\"", ",", "return_value", "=", "mock_coro", "(", ")", ")", ",", "patch", ".", "object", "(", "SyncThru", ",", "\"is_unknown_state\"", ",", "return_value", "=", "True", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ",", "data", "=", "FIXTURE_USER_INPUT", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"user\"", "assert", "result", "[", "\"errors\"", "]", "==", "{", "CONF_URL", ":", "\"unknown_state\"", "}" ]
[ 85, 0 ]
[ 98, 58 ]
python
en
['en', 'en', 'en']
True
test_success
(hass, aioclient_mock)
Test successful flow provides entry creation data.
Test successful flow provides entry creation data.
async def test_success(hass, aioclient_mock): """Test successful flow provides entry creation data.""" await setup.async_setup_component(hass, "persistent_notification", {}) mock_connection(aioclient_mock) with patch( "homeassistant.components.syncthru.async_setup_entry", return_value=True ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, data=FIXTURE_USER_INPUT, ) assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY assert result["data"][CONF_URL] == FIXTURE_USER_INPUT[CONF_URL] await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1
[ "async", "def", "test_success", "(", "hass", ",", "aioclient_mock", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "mock_connection", "(", "aioclient_mock", ")", "with", "patch", "(", "\"homeassistant.components.syncthru.async_setup_entry\"", ",", "return_value", "=", "True", ")", "as", "mock_setup_entry", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ",", "data", "=", "FIXTURE_USER_INPUT", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_CREATE_ENTRY", "assert", "result", "[", "\"data\"", "]", "[", "CONF_URL", "]", "==", "FIXTURE_USER_INPUT", "[", "CONF_URL", "]", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "mock_setup_entry", ".", "mock_calls", ")", "==", "1" ]
[ 101, 0 ]
[ 118, 48 ]
python
en
['en', 'en', 'en']
True
test_ssdp
(hass, aioclient_mock)
Test SSDP discovery initiates config properly.
Test SSDP discovery initiates config properly.
async def test_ssdp(hass, aioclient_mock): """Test SSDP discovery initiates config properly.""" await setup.async_setup_component(hass, "persistent_notification", {}) mock_connection(aioclient_mock) url = "http://192.168.1.2/" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_SSDP}, data={ ssdp.ATTR_SSDP_LOCATION: "http://192.168.1.2:5200/Printer.xml", ssdp.ATTR_UPNP_DEVICE_TYPE: "urn:schemas-upnp-org:device:Printer:1", ssdp.ATTR_UPNP_MANUFACTURER: "Samsung Electronics", ssdp.ATTR_UPNP_PRESENTATION_URL: url, ssdp.ATTR_UPNP_SERIAL: "00000000", ssdp.ATTR_UPNP_UDN: "uuid:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", }, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "confirm" assert CONF_URL in result["data_schema"].schema for k in result["data_schema"].schema: if k == CONF_URL: assert k.default() == url
[ "async", "def", "test_ssdp", "(", "hass", ",", "aioclient_mock", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "mock_connection", "(", "aioclient_mock", ")", "url", "=", "\"http://192.168.1.2/\"", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_SSDP", "}", ",", "data", "=", "{", "ssdp", ".", "ATTR_SSDP_LOCATION", ":", "\"http://192.168.1.2:5200/Printer.xml\"", ",", "ssdp", ".", "ATTR_UPNP_DEVICE_TYPE", ":", "\"urn:schemas-upnp-org:device:Printer:1\"", ",", "ssdp", ".", "ATTR_UPNP_MANUFACTURER", ":", "\"Samsung Electronics\"", ",", "ssdp", ".", "ATTR_UPNP_PRESENTATION_URL", ":", "url", ",", "ssdp", ".", "ATTR_UPNP_SERIAL", ":", "\"00000000\"", ",", "ssdp", ".", "ATTR_UPNP_UDN", ":", "\"uuid:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\"", ",", "}", ",", ")", "assert", "result", "[", "\"type\"", "]", "==", "data_entry_flow", ".", "RESULT_TYPE_FORM", "assert", "result", "[", "\"step_id\"", "]", "==", "\"confirm\"", "assert", "CONF_URL", "in", "result", "[", "\"data_schema\"", "]", ".", "schema", "for", "k", "in", "result", "[", "\"data_schema\"", "]", ".", "schema", ":", "if", "k", "==", "CONF_URL", ":", "assert", "k", ".", "default", "(", ")", "==", "url" ]
[ 121, 0 ]
[ 145, 37 ]
python
en
['en', 'en', 'en']
True
test_full_flow
(hass, aiohttp_client, aioclient_mock, current_request)
Check full flow.
Check full flow.
async def test_full_flow(hass, aiohttp_client, aioclient_mock, current_request): """Check full flow.""" assert await setup.async_setup_component( hass, DOMAIN, { DOMAIN: { "project_id": PROJECT_ID, "subscriber_id": SUBSCRIBER_ID, CONF_CLIENT_ID: CLIENT_ID, CONF_CLIENT_SECRET: CLIENT_SECRET, }, "http": {"base_url": "https://example.com"}, }, ) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) state = config_entry_oauth2_flow._encode_jwt(hass, {"flow_id": result["flow_id"]}) oauth_authorize = OAUTH2_AUTHORIZE.format(project_id=PROJECT_ID) assert result["url"] == ( f"{oauth_authorize}?response_type=code&client_id={CLIENT_ID}" "&redirect_uri=https://example.com/auth/external/callback" f"&state={state}&scope=https://www.googleapis.com/auth/sdm.service" "+https://www.googleapis.com/auth/pubsub" "&access_type=offline&prompt=consent" ) client = await aiohttp_client(hass.http.app) resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 assert resp.headers["content-type"] == "text/html; charset=utf-8" aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "type": "Bearer", "expires_in": 60, }, ) with patch( "homeassistant.components.nest.async_setup_entry", return_value=True ) as mock_setup: await hass.config_entries.flow.async_configure(result["flow_id"]) assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert len(mock_setup.mock_calls) == 1
[ "async", "def", "test_full_flow", "(", "hass", ",", "aiohttp_client", ",", "aioclient_mock", ",", "current_request", ")", ":", "assert", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "\"project_id\"", ":", "PROJECT_ID", ",", "\"subscriber_id\"", ":", "SUBSCRIBER_ID", ",", "CONF_CLIENT_ID", ":", "CLIENT_ID", ",", "CONF_CLIENT_SECRET", ":", "CLIENT_SECRET", ",", "}", ",", "\"http\"", ":", "{", "\"base_url\"", ":", "\"https://example.com\"", "}", ",", "}", ",", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "state", "=", "config_entry_oauth2_flow", ".", "_encode_jwt", "(", "hass", ",", "{", "\"flow_id\"", ":", "result", "[", "\"flow_id\"", "]", "}", ")", "oauth_authorize", "=", "OAUTH2_AUTHORIZE", ".", "format", "(", "project_id", "=", "PROJECT_ID", ")", "assert", "result", "[", "\"url\"", "]", "==", "(", "f\"{oauth_authorize}?response_type=code&client_id={CLIENT_ID}\"", "\"&redirect_uri=https://example.com/auth/external/callback\"", "f\"&state={state}&scope=https://www.googleapis.com/auth/sdm.service\"", "\"+https://www.googleapis.com/auth/pubsub\"", "\"&access_type=offline&prompt=consent\"", ")", "client", "=", "await", "aiohttp_client", "(", "hass", ".", "http", ".", "app", ")", "resp", "=", "await", "client", ".", "get", "(", "f\"/auth/external/callback?code=abcd&state={state}\"", ")", "assert", "resp", ".", "status", "==", "200", "assert", "resp", ".", "headers", "[", "\"content-type\"", "]", "==", "\"text/html; charset=utf-8\"", "aioclient_mock", ".", "post", "(", "OAUTH2_TOKEN", ",", "json", "=", "{", "\"refresh_token\"", ":", "\"mock-refresh-token\"", ",", "\"access_token\"", ":", "\"mock-access-token\"", ",", "\"type\"", ":", "\"Bearer\"", ",", "\"expires_in\"", ":", "60", ",", "}", ",", ")", "with", "patch", "(", "\"homeassistant.components.nest.async_setup_entry\"", ",", "return_value", "=", "True", ")", "as", "mock_setup", ":", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ")", "assert", "len", "(", "hass", ".", "config_entries", ".", "async_entries", "(", "DOMAIN", ")", ")", "==", "1", "assert", "len", "(", "mock_setup", ".", "mock_calls", ")", "==", "1" ]
[ 14, 0 ]
[ 65, 42 ]
python
en
['sv', 'no', 'en']
False
async_setup_entry
( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities )
Set up the Synology NAS binary sensor.
Set up the Synology NAS binary sensor.
async def async_setup_entry( hass: HomeAssistantType, entry: ConfigEntry, async_add_entities ) -> None: """Set up the Synology NAS binary sensor.""" api = hass.data[DOMAIN][entry.unique_id][SYNO_API] if SynoSurveillanceStation.CAMERA_API_KEY not in api.dsm.apis: return surveillance_station = api.surveillance_station await hass.async_add_executor_job(surveillance_station.update) cameras = surveillance_station.get_all_cameras() entities = [SynoDSMCamera(api, camera) for camera in cameras] async_add_entities(entities)
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ",", "async_add_entities", ")", "->", "None", ":", "api", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "unique_id", "]", "[", "SYNO_API", "]", "if", "SynoSurveillanceStation", ".", "CAMERA_API_KEY", "not", "in", "api", ".", "dsm", ".", "apis", ":", "return", "surveillance_station", "=", "api", ".", "surveillance_station", "await", "hass", ".", "async_add_executor_job", "(", "surveillance_station", ".", "update", ")", "cameras", "=", "surveillance_station", ".", "get_all_cameras", "(", ")", "entities", "=", "[", "SynoDSMCamera", "(", "api", ",", "camera", ")", "for", "camera", "in", "cameras", "]", "async_add_entities", "(", "entities", ")" ]
[ 22, 0 ]
[ 37, 32 ]
python
en
['en', 'haw', 'en']
True
SynoDSMCamera.__init__
(self, api: SynoApi, camera: SynoCamera)
Initialize a Synology camera.
Initialize a Synology camera.
def __init__(self, api: SynoApi, camera: SynoCamera): """Initialize a Synology camera.""" super().__init__( api, f"{SynoSurveillanceStation.CAMERA_API_KEY}:{camera.id}", { ENTITY_NAME: camera.name, ENTITY_CLASS: None, ENTITY_ICON: None, ENTITY_ENABLE: True, ENTITY_UNIT: None, }, ) self._camera = camera
[ "def", "__init__", "(", "self", ",", "api", ":", "SynoApi", ",", "camera", ":", "SynoCamera", ")", ":", "super", "(", ")", ".", "__init__", "(", "api", ",", "f\"{SynoSurveillanceStation.CAMERA_API_KEY}:{camera.id}\"", ",", "{", "ENTITY_NAME", ":", "camera", ".", "name", ",", "ENTITY_CLASS", ":", "None", ",", "ENTITY_ICON", ":", "None", ",", "ENTITY_ENABLE", ":", "True", ",", "ENTITY_UNIT", ":", "None", ",", "}", ",", ")", "self", ".", "_camera", "=", "camera" ]
[ 43, 4 ]
[ 56, 29 ]
python
en
['hu', 'en', 'en']
True
SynoDSMCamera.device_info
(self)
Return the device information.
Return the device information.
def device_info(self) -> Dict[str, any]: """Return the device information.""" return { "identifiers": {(DOMAIN, self._api.information.serial, self._camera.id)}, "name": self._camera.name, "model": self._camera.model, "via_device": ( DOMAIN, self._api.information.serial, SynoSurveillanceStation.INFO_API_KEY, ), }
[ "def", "device_info", "(", "self", ")", "->", "Dict", "[", "str", ",", "any", "]", ":", "return", "{", "\"identifiers\"", ":", "{", "(", "DOMAIN", ",", "self", ".", "_api", ".", "information", ".", "serial", ",", "self", ".", "_camera", ".", "id", ")", "}", ",", "\"name\"", ":", "self", ".", "_camera", ".", "name", ",", "\"model\"", ":", "self", ".", "_camera", ".", "model", ",", "\"via_device\"", ":", "(", "DOMAIN", ",", "self", ".", "_api", ".", "information", ".", "serial", ",", "SynoSurveillanceStation", ".", "INFO_API_KEY", ",", ")", ",", "}" ]
[ 59, 4 ]
[ 70, 9 ]
python
en
['en', 'en', 'en']
True
SynoDSMCamera.available
(self)
Return the availability of the camera.
Return the availability of the camera.
def available(self) -> bool: """Return the availability of the camera.""" return self._camera.is_enabled
[ "def", "available", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_camera", ".", "is_enabled" ]
[ 73, 4 ]
[ 75, 38 ]
python
en
['en', 'en', 'en']
True
SynoDSMCamera.supported_features
(self)
Return supported features of this camera.
Return supported features of this camera.
def supported_features(self) -> int: """Return supported features of this camera.""" return SUPPORT_STREAM
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_STREAM" ]
[ 78, 4 ]
[ 80, 29 ]
python
en
['en', 'en', 'en']
True
SynoDSMCamera.is_recording
(self)
Return true if the device is recording.
Return true if the device is recording.
def is_recording(self): """Return true if the device is recording.""" return self._camera.is_recording
[ "def", "is_recording", "(", "self", ")", ":", "return", "self", ".", "_camera", ".", "is_recording" ]
[ 83, 4 ]
[ 85, 40 ]
python
en
['en', 'en', 'en']
True
SynoDSMCamera.motion_detection_enabled
(self)
Return the camera motion detection status.
Return the camera motion detection status.
def motion_detection_enabled(self): """Return the camera motion detection status.""" return self._camera.is_motion_detection_enabled
[ "def", "motion_detection_enabled", "(", "self", ")", ":", "return", "self", ".", "_camera", ".", "is_motion_detection_enabled" ]
[ 88, 4 ]
[ 90, 55 ]
python
en
['en', 'en', 'en']
True
SynoDSMCamera.camera_image
(self)
Return bytes of camera image.
Return bytes of camera image.
def camera_image(self) -> bytes: """Return bytes of camera image.""" if not self.available: return None return self._api.surveillance_station.get_camera_image(self._camera.id)
[ "def", "camera_image", "(", "self", ")", "->", "bytes", ":", "if", "not", "self", ".", "available", ":", "return", "None", "return", "self", ".", "_api", ".", "surveillance_station", ".", "get_camera_image", "(", "self", ".", "_camera", ".", "id", ")" ]
[ 92, 4 ]
[ 96, 79 ]
python
en
['en', 'zu', 'en']
True
SynoDSMCamera.stream_source
(self)
Return the source of the stream.
Return the source of the stream.
async def stream_source(self) -> str: """Return the source of the stream.""" if not self.available: return None return self._camera.live_view.rtsp
[ "async", "def", "stream_source", "(", "self", ")", "->", "str", ":", "if", "not", "self", ".", "available", ":", "return", "None", "return", "self", ".", "_camera", ".", "live_view", ".", "rtsp" ]
[ 98, 4 ]
[ 102, 42 ]
python
en
['en', 'en', 'en']
True
SynoDSMCamera.enable_motion_detection
(self)
Enable motion detection in the camera.
Enable motion detection in the camera.
def enable_motion_detection(self): """Enable motion detection in the camera.""" self._api.surveillance_station.enable_motion_detection(self._camera.id)
[ "def", "enable_motion_detection", "(", "self", ")", ":", "self", ".", "_api", ".", "surveillance_station", ".", "enable_motion_detection", "(", "self", ".", "_camera", ".", "id", ")" ]
[ 104, 4 ]
[ 106, 79 ]
python
en
['en', 'en', 'en']
True
SynoDSMCamera.disable_motion_detection
(self)
Disable motion detection in camera.
Disable motion detection in camera.
def disable_motion_detection(self): """Disable motion detection in camera.""" self._api.surveillance_station.disable_motion_detection(self._camera.id)
[ "def", "disable_motion_detection", "(", "self", ")", ":", "self", ".", "_api", ".", "surveillance_station", ".", "disable_motion_detection", "(", "self", ".", "_camera", ".", "id", ")" ]
[ 108, 4 ]
[ 110, 80 ]
python
en
['it', 'en', 'en']
True
GdacsFlowHandler._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=DATA_SCHEMA, errors=errors or {} )
[ "async", "def", "_show_form", "(", "self", ",", "errors", "=", "None", ")", ":", "return", "self", ".", "async_show_form", "(", "step_id", "=", "\"user\"", ",", "data_schema", "=", "DATA_SCHEMA", ",", "errors", "=", "errors", "or", "{", "}", ")" ]
[ 33, 4 ]
[ 37, 9 ]
python
en
['en', 'en', 'en']
True
GdacsFlowHandler.async_step_import
(self, import_config)
Import a config entry from configuration.yaml.
Import a config entry from configuration.yaml.
async def async_step_import(self, import_config): """Import a config entry from configuration.yaml.""" return await self.async_step_user(import_config)
[ "async", "def", "async_step_import", "(", "self", ",", "import_config", ")", ":", "return", "await", "self", ".", "async_step_user", "(", "import_config", ")" ]
[ 39, 4 ]
[ 41, 56 ]
python
en
['en', 'en', 'en']
True
GdacsFlowHandler.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.""" _LOGGER.debug("User input: %s", user_input) if not user_input: return await self._show_form() latitude = user_input.get(CONF_LATITUDE, self.hass.config.latitude) user_input[CONF_LATITUDE] = latitude longitude = user_input.get(CONF_LONGITUDE, self.hass.config.longitude) user_input[CONF_LONGITUDE] = longitude identifier = f"{user_input[CONF_LATITUDE]}, {user_input[CONF_LONGITUDE]}" await self.async_set_unique_id(identifier) self._abort_if_unique_id_configured() scan_interval = user_input.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) user_input[CONF_SCAN_INTERVAL] = scan_interval.seconds categories = user_input.get(CONF_CATEGORIES, []) user_input[CONF_CATEGORIES] = categories return self.async_create_entry(title=identifier, data=user_input)
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "_LOGGER", ".", "debug", "(", "\"User input: %s\"", ",", "user_input", ")", "if", "not", "user_input", ":", "return", "await", "self", ".", "_show_form", "(", ")", "latitude", "=", "user_input", ".", "get", "(", "CONF_LATITUDE", ",", "self", ".", "hass", ".", "config", ".", "latitude", ")", "user_input", "[", "CONF_LATITUDE", "]", "=", "latitude", "longitude", "=", "user_input", ".", "get", "(", "CONF_LONGITUDE", ",", "self", ".", "hass", ".", "config", ".", "longitude", ")", "user_input", "[", "CONF_LONGITUDE", "]", "=", "longitude", "identifier", "=", "f\"{user_input[CONF_LATITUDE]}, {user_input[CONF_LONGITUDE]}\"", "await", "self", ".", "async_set_unique_id", "(", "identifier", ")", "self", ".", "_abort_if_unique_id_configured", "(", ")", "scan_interval", "=", "user_input", ".", "get", "(", "CONF_SCAN_INTERVAL", ",", "DEFAULT_SCAN_INTERVAL", ")", "user_input", "[", "CONF_SCAN_INTERVAL", "]", "=", "scan_interval", ".", "seconds", "categories", "=", "user_input", ".", "get", "(", "CONF_CATEGORIES", ",", "[", "]", ")", "user_input", "[", "CONF_CATEGORIES", "]", "=", "categories", "return", "self", ".", "async_create_entry", "(", "title", "=", "identifier", ",", "data", "=", "user_input", ")" ]
[ 43, 4 ]
[ 65, 73 ]
python
en
['en', 'en', 'en']
True
RuckusUnleashedDataUpdateCoordinator.__init__
(self, hass: HomeAssistant, *, ruckus: Ruckus)
Initialize global Ruckus Unleashed data updater.
Initialize global Ruckus Unleashed data updater.
def __init__(self, hass: HomeAssistant, *, ruckus: Ruckus): """Initialize global Ruckus Unleashed data updater.""" self.ruckus = ruckus update_interval = timedelta(seconds=SCAN_INTERVAL) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=update_interval, )
[ "def", "__init__", "(", "self", ",", "hass", ":", "HomeAssistant", ",", "*", ",", "ruckus", ":", "Ruckus", ")", ":", "self", ".", "ruckus", "=", "ruckus", "update_interval", "=", "timedelta", "(", "seconds", "=", "SCAN_INTERVAL", ")", "super", "(", ")", ".", "__init__", "(", "hass", ",", "_LOGGER", ",", "name", "=", "DOMAIN", ",", "update_interval", "=", "update_interval", ",", ")" ]
[ 24, 4 ]
[ 35, 9 ]
python
en
['en', 'en', 'it']
True
RuckusUnleashedDataUpdateCoordinator._fetch_clients
(self)
Fetch clients from the API and format them.
Fetch clients from the API and format them.
async def _fetch_clients(self) -> dict: """Fetch clients from the API and format them.""" clients = await self.hass.async_add_executor_job( self.ruckus.current_active_clients ) return {e[API_MAC]: e for e in clients[API_CURRENT_ACTIVE_CLIENTS][API_CLIENTS]}
[ "async", "def", "_fetch_clients", "(", "self", ")", "->", "dict", ":", "clients", "=", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "ruckus", ".", "current_active_clients", ")", "return", "{", "e", "[", "API_MAC", "]", ":", "e", "for", "e", "in", "clients", "[", "API_CURRENT_ACTIVE_CLIENTS", "]", "[", "API_CLIENTS", "]", "}" ]
[ 37, 4 ]
[ 42, 88 ]
python
en
['en', 'en', 'en']
True
RuckusUnleashedDataUpdateCoordinator._async_update_data
(self)
Fetch Ruckus Unleashed data.
Fetch Ruckus Unleashed data.
async def _async_update_data(self) -> dict: """Fetch Ruckus Unleashed data.""" try: return {API_CLIENTS: await self._fetch_clients()} except (AuthenticationError, ConnectionError) as error: raise UpdateFailed(error) from error
[ "async", "def", "_async_update_data", "(", "self", ")", "->", "dict", ":", "try", ":", "return", "{", "API_CLIENTS", ":", "await", "self", ".", "_fetch_clients", "(", ")", "}", "except", "(", "AuthenticationError", ",", "ConnectionError", ")", "as", "error", ":", "raise", "UpdateFailed", "(", "error", ")", "from", "error" ]
[ 44, 4 ]
[ 49, 48 ]
python
co
['en', 'co', 'it']
False
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the sensor from config.
Set up the sensor from config.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the sensor from config.""" host = config[CONF_HOST] token = config[CONF_TOKEN] name = config[CONF_NAME] _LOGGER.info("Initializing with host %s (token %s...)", host, token[:5]) miio_device = Device(host, token) try: device_info = await hass.async_add_executor_job(miio_device.info) except DeviceException as ex: raise PlatformNotReady from ex model = device_info.model unique_id = f"{model}-{device_info.mac_address}" _LOGGER.debug( "%s %s %s detected", model, device_info.firmware_version, device_info.hardware_version, ) device = AirQualityMonitor(host, token, model=model) if model == MODEL_AIRQUALITYMONITOR_S1: entity = AirMonitorS1(name, device, unique_id) elif model == MODEL_AIRQUALITYMONITOR_B1: entity = AirMonitorB1(name, device, unique_id) elif model == MODEL_AIRQUALITYMONITOR_V1: entity = AirMonitorV1(name, device, unique_id) else: raise NoEntitySpecifiedError(f"Not support for entity {unique_id}") async_add_entities([entity], update_before_add=True)
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "host", "=", "config", "[", "CONF_HOST", "]", "token", "=", "config", "[", "CONF_TOKEN", "]", "name", "=", "config", "[", "CONF_NAME", "]", "_LOGGER", ".", "info", "(", "\"Initializing with host %s (token %s...)\"", ",", "host", ",", "token", "[", ":", "5", "]", ")", "miio_device", "=", "Device", "(", "host", ",", "token", ")", "try", ":", "device_info", "=", "await", "hass", ".", "async_add_executor_job", "(", "miio_device", ".", "info", ")", "except", "DeviceException", "as", "ex", ":", "raise", "PlatformNotReady", "from", "ex", "model", "=", "device_info", ".", "model", "unique_id", "=", "f\"{model}-{device_info.mac_address}\"", "_LOGGER", ".", "debug", "(", "\"%s %s %s detected\"", ",", "model", ",", "device_info", ".", "firmware_version", ",", "device_info", ".", "hardware_version", ",", ")", "device", "=", "AirQualityMonitor", "(", "host", ",", "token", ",", "model", "=", "model", ")", "if", "model", "==", "MODEL_AIRQUALITYMONITOR_S1", ":", "entity", "=", "AirMonitorS1", "(", "name", ",", "device", ",", "unique_id", ")", "elif", "model", "==", "MODEL_AIRQUALITYMONITOR_B1", ":", "entity", "=", "AirMonitorB1", "(", "name", ",", "device", ",", "unique_id", ")", "elif", "model", "==", "MODEL_AIRQUALITYMONITOR_V1", ":", "entity", "=", "AirMonitorV1", "(", "name", ",", "device", ",", "unique_id", ")", "else", ":", "raise", "NoEntitySpecifiedError", "(", "f\"Not support for entity {unique_id}\"", ")", "async_add_entities", "(", "[", "entity", "]", ",", "update_before_add", "=", "True", ")" ]
[ 42, 0 ]
[ 78, 56 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.__init__
(self, name, device, unique_id)
Initialize the entity.
Initialize the entity.
def __init__(self, name, device, unique_id): """Initialize the entity.""" self._name = name self._device = device self._unique_id = unique_id self._icon = "mdi:cloud" self._available = None self._air_quality_index = None self._carbon_dioxide = None self._carbon_dioxide_equivalent = None self._particulate_matter_2_5 = None self._total_volatile_organic_compounds = None self._temperature = None self._humidity = None
[ "def", "__init__", "(", "self", ",", "name", ",", "device", ",", "unique_id", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_device", "=", "device", "self", ".", "_unique_id", "=", "unique_id", "self", ".", "_icon", "=", "\"mdi:cloud\"", "self", ".", "_available", "=", "None", "self", ".", "_air_quality_index", "=", "None", "self", ".", "_carbon_dioxide", "=", "None", "self", ".", "_carbon_dioxide_equivalent", "=", "None", "self", ".", "_particulate_matter_2_5", "=", "None", "self", ".", "_total_volatile_organic_compounds", "=", "None", "self", ".", "_temperature", "=", "None", "self", ".", "_humidity", "=", "None" ]
[ 84, 4 ]
[ 97, 29 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.async_update
(self)
Fetch state from the miio device.
Fetch state from the miio device.
async def async_update(self): """Fetch state from the miio device.""" try: state = await self.hass.async_add_executor_job(self._device.status) _LOGGER.debug("Got new state: %s", state) self._carbon_dioxide_equivalent = state.co2e self._particulate_matter_2_5 = round(state.pm25, 1) self._total_volatile_organic_compounds = round(state.tvoc, 3) self._temperature = round(state.temperature, 2) self._humidity = round(state.humidity, 2) self._available = True except DeviceException as ex: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex)
[ "async", "def", "async_update", "(", "self", ")", ":", "try", ":", "state", "=", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "_device", ".", "status", ")", "_LOGGER", ".", "debug", "(", "\"Got new state: %s\"", ",", "state", ")", "self", ".", "_carbon_dioxide_equivalent", "=", "state", ".", "co2e", "self", ".", "_particulate_matter_2_5", "=", "round", "(", "state", ".", "pm25", ",", "1", ")", "self", ".", "_total_volatile_organic_compounds", "=", "round", "(", "state", ".", "tvoc", ",", "3", ")", "self", ".", "_temperature", "=", "round", "(", "state", ".", "temperature", ",", "2", ")", "self", ".", "_humidity", "=", "round", "(", "state", ".", "humidity", ",", "2", ")", "self", ".", "_available", "=", "True", "except", "DeviceException", "as", "ex", ":", "self", ".", "_available", "=", "False", "_LOGGER", ".", "error", "(", "\"Got exception while fetching the state: %s\"", ",", "ex", ")" ]
[ 99, 4 ]
[ 112, 75 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.name
(self)
Return the name of this entity, if any.
Return the name of this entity, if any.
def name(self): """Return the name of this entity, if any.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 115, 4 ]
[ 117, 25 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.icon
(self)
Return the icon to use for device if any.
Return the icon to use for device if any.
def icon(self): """Return the icon to use for device if any.""" return self._icon
[ "def", "icon", "(", "self", ")", ":", "return", "self", ".", "_icon" ]
[ 120, 4 ]
[ 122, 25 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.available
(self)
Return true when state is known.
Return true when state is known.
def available(self): """Return true when state is known.""" return self._available
[ "def", "available", "(", "self", ")", ":", "return", "self", ".", "_available" ]
[ 125, 4 ]
[ 127, 30 ]
python
en
['en', 'de', 'en']
True
AirMonitorB1.unique_id
(self)
Return the unique ID.
Return the unique ID.
def unique_id(self): """Return the unique ID.""" return self._unique_id
[ "def", "unique_id", "(", "self", ")", ":", "return", "self", ".", "_unique_id" ]
[ 130, 4 ]
[ 132, 30 ]
python
en
['en', 'la', 'en']
True
AirMonitorB1.air_quality_index
(self)
Return the Air Quality Index (AQI).
Return the Air Quality Index (AQI).
def air_quality_index(self): """Return the Air Quality Index (AQI).""" return self._air_quality_index
[ "def", "air_quality_index", "(", "self", ")", ":", "return", "self", ".", "_air_quality_index" ]
[ 135, 4 ]
[ 137, 38 ]
python
en
['en', 'cy', 'en']
True
AirMonitorB1.carbon_dioxide
(self)
Return the CO2 (carbon dioxide) level.
Return the CO2 (carbon dioxide) level.
def carbon_dioxide(self): """Return the CO2 (carbon dioxide) level.""" return self._carbon_dioxide
[ "def", "carbon_dioxide", "(", "self", ")", ":", "return", "self", ".", "_carbon_dioxide" ]
[ 140, 4 ]
[ 142, 35 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.carbon_dioxide_equivalent
(self)
Return the CO2e (carbon dioxide equivalent) level.
Return the CO2e (carbon dioxide equivalent) level.
def carbon_dioxide_equivalent(self): """Return the CO2e (carbon dioxide equivalent) level.""" return self._carbon_dioxide_equivalent
[ "def", "carbon_dioxide_equivalent", "(", "self", ")", ":", "return", "self", ".", "_carbon_dioxide_equivalent" ]
[ 145, 4 ]
[ 147, 46 ]
python
en
['en', 'pt', 'en']
True
AirMonitorB1.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._particulate_matter_2_5
[ "def", "particulate_matter_2_5", "(", "self", ")", ":", "return", "self", ".", "_particulate_matter_2_5" ]
[ 150, 4 ]
[ 152, 43 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.total_volatile_organic_compounds
(self)
Return the total volatile organic compounds.
Return the total volatile organic compounds.
def total_volatile_organic_compounds(self): """Return the total volatile organic compounds.""" return self._total_volatile_organic_compounds
[ "def", "total_volatile_organic_compounds", "(", "self", ")", ":", "return", "self", ".", "_total_volatile_organic_compounds" ]
[ 155, 4 ]
[ 157, 53 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.temperature
(self)
Return the current temperature.
Return the current temperature.
def temperature(self): """Return the current temperature.""" return self._temperature
[ "def", "temperature", "(", "self", ")", ":", "return", "self", ".", "_temperature" ]
[ 160, 4 ]
[ 162, 32 ]
python
en
['en', 'la', 'en']
True
AirMonitorB1.humidity
(self)
Return the current humidity.
Return the current humidity.
def humidity(self): """Return the current humidity.""" return self._humidity
[ "def", "humidity", "(", "self", ")", ":", "return", "self", ".", "_humidity" ]
[ 165, 4 ]
[ 167, 29 ]
python
en
['en', 'en', 'en']
True
AirMonitorB1.device_state_attributes
(self)
Return the state attributes.
Return the state attributes.
def device_state_attributes(self): """Return the state attributes.""" data = {} for prop, attr in PROP_TO_ATTR.items(): value = getattr(self, prop) if value is not None: data[attr] = value return data
[ "def", "device_state_attributes", "(", "self", ")", ":", "data", "=", "{", "}", "for", "prop", ",", "attr", "in", "PROP_TO_ATTR", ".", "items", "(", ")", ":", "value", "=", "getattr", "(", "self", ",", "prop", ")", "if", "value", "is", "not", "None", ":", "data", "[", "attr", "]", "=", "value", "return", "data" ]
[ 170, 4 ]
[ 179, 19 ]
python
en
['en', 'en', 'en']
True
AirMonitorS1.async_update
(self)
Fetch state from the miio device.
Fetch state from the miio device.
async def async_update(self): """Fetch state from the miio device.""" try: state = await self.hass.async_add_executor_job(self._device.status) _LOGGER.debug("Got new state: %s", state) self._carbon_dioxide = state.co2 self._particulate_matter_2_5 = state.pm25 self._total_volatile_organic_compounds = state.tvoc self._temperature = state.temperature self._humidity = state.humidity self._available = True except DeviceException as ex: if self._available: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex)
[ "async", "def", "async_update", "(", "self", ")", ":", "try", ":", "state", "=", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "_device", ".", "status", ")", "_LOGGER", ".", "debug", "(", "\"Got new state: %s\"", ",", "state", ")", "self", ".", "_carbon_dioxide", "=", "state", ".", "co2", "self", ".", "_particulate_matter_2_5", "=", "state", ".", "pm25", "self", ".", "_total_volatile_organic_compounds", "=", "state", ".", "tvoc", "self", ".", "_temperature", "=", "state", ".", "temperature", "self", ".", "_humidity", "=", "state", ".", "humidity", "self", ".", "_available", "=", "True", "except", "DeviceException", "as", "ex", ":", "if", "self", ".", "_available", ":", "self", ".", "_available", "=", "False", "_LOGGER", ".", "error", "(", "\"Got exception while fetching the state: %s\"", ",", "ex", ")" ]
[ 185, 4 ]
[ 199, 79 ]
python
en
['en', 'en', 'en']
True
AirMonitorV1.async_update
(self)
Fetch state from the miio device.
Fetch state from the miio device.
async def async_update(self): """Fetch state from the miio device.""" try: state = await self.hass.async_add_executor_job(self._device.status) _LOGGER.debug("Got new state: %s", state) self._air_quality_index = state.aqi self._available = True except DeviceException as ex: if self._available: self._available = False _LOGGER.error("Got exception while fetching the state: %s", ex)
[ "async", "def", "async_update", "(", "self", ")", ":", "try", ":", "state", "=", "await", "self", ".", "hass", ".", "async_add_executor_job", "(", "self", ".", "_device", ".", "status", ")", "_LOGGER", ".", "debug", "(", "\"Got new state: %s\"", ",", "state", ")", "self", ".", "_air_quality_index", "=", "state", ".", "aqi", "self", ".", "_available", "=", "True", "except", "DeviceException", "as", "ex", ":", "if", "self", ".", "_available", ":", "self", ".", "_available", "=", "False", "_LOGGER", ".", "error", "(", "\"Got exception while fetching the state: %s\"", ",", "ex", ")" ]
[ 205, 4 ]
[ 215, 79 ]
python
en
['en', 'en', 'en']
True
AirMonitorV1.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 None
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "None" ]
[ 218, 4 ]
[ 220, 19 ]
python
en
['en', 'la', 'en']
True
load_fixture_binary
(filename)
Load a binary fixture.
Load a binary fixture.
def load_fixture_binary(filename): """Load a binary fixture.""" path = os.path.join(os.path.dirname(__file__), "..", "..", "fixtures", filename) with open(path, "rb") as fptr: return fptr.read()
[ "def", "load_fixture_binary", "(", "filename", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "\"..\"", ",", "\"..\"", ",", "\"fixtures\"", ",", "filename", ")", "with", "open", "(", "path", ",", "\"rb\"", ")", "as", "fptr", ":", "return", "fptr", ".", "read", "(", ")" ]
[ 63, 0 ]
[ 67, 26 ]
python
en
['en', 'haw', 'en']
True
mock_connection
( aioclient_mock: AiohttpClientMocker, host: str = HOST, port: int = PORT, ssl: bool = False, base_path: str = BASE_PATH, conn_error: bool = False, conn_upgrade_error: bool = False, ipp_error: bool = False, no_unique_id: bool = False, parse_error: bool = False, version_not_supported: bool = False, )
Mock the IPP connection.
Mock the IPP connection.
def mock_connection( aioclient_mock: AiohttpClientMocker, host: str = HOST, port: int = PORT, ssl: bool = False, base_path: str = BASE_PATH, conn_error: bool = False, conn_upgrade_error: bool = False, ipp_error: bool = False, no_unique_id: bool = False, parse_error: bool = False, version_not_supported: bool = False, ): """Mock the IPP connection.""" scheme = "https" if ssl else "http" ipp_url = f"{scheme}://{host}:{port}" if ipp_error: aioclient_mock.post(f"{ipp_url}{base_path}", exc=IPPError) return if conn_error: aioclient_mock.post(f"{ipp_url}{base_path}", exc=aiohttp.ClientError) return if conn_upgrade_error: aioclient_mock.post(f"{ipp_url}{base_path}", exc=IPPConnectionUpgradeRequired) return fixture = "ipp/get-printer-attributes.bin" if no_unique_id: fixture = "ipp/get-printer-attributes-success-nodata.bin" elif version_not_supported: fixture = "ipp/get-printer-attributes-error-0x0503.bin" if parse_error: content = "BAD" else: content = load_fixture_binary(fixture) aioclient_mock.post( f"{ipp_url}{base_path}", content=content, headers={"Content-Type": "application/ipp"}, )
[ "def", "mock_connection", "(", "aioclient_mock", ":", "AiohttpClientMocker", ",", "host", ":", "str", "=", "HOST", ",", "port", ":", "int", "=", "PORT", ",", "ssl", ":", "bool", "=", "False", ",", "base_path", ":", "str", "=", "BASE_PATH", ",", "conn_error", ":", "bool", "=", "False", ",", "conn_upgrade_error", ":", "bool", "=", "False", ",", "ipp_error", ":", "bool", "=", "False", ",", "no_unique_id", ":", "bool", "=", "False", ",", "parse_error", ":", "bool", "=", "False", ",", "version_not_supported", ":", "bool", "=", "False", ",", ")", ":", "scheme", "=", "\"https\"", "if", "ssl", "else", "\"http\"", "ipp_url", "=", "f\"{scheme}://{host}:{port}\"", "if", "ipp_error", ":", "aioclient_mock", ".", "post", "(", "f\"{ipp_url}{base_path}\"", ",", "exc", "=", "IPPError", ")", "return", "if", "conn_error", ":", "aioclient_mock", ".", "post", "(", "f\"{ipp_url}{base_path}\"", ",", "exc", "=", "aiohttp", ".", "ClientError", ")", "return", "if", "conn_upgrade_error", ":", "aioclient_mock", ".", "post", "(", "f\"{ipp_url}{base_path}\"", ",", "exc", "=", "IPPConnectionUpgradeRequired", ")", "return", "fixture", "=", "\"ipp/get-printer-attributes.bin\"", "if", "no_unique_id", ":", "fixture", "=", "\"ipp/get-printer-attributes-success-nodata.bin\"", "elif", "version_not_supported", ":", "fixture", "=", "\"ipp/get-printer-attributes-error-0x0503.bin\"", "if", "parse_error", ":", "content", "=", "\"BAD\"", "else", ":", "content", "=", "load_fixture_binary", "(", "fixture", ")", "aioclient_mock", ".", "post", "(", "f\"{ipp_url}{base_path}\"", ",", "content", "=", "content", ",", "headers", "=", "{", "\"Content-Type\"", ":", "\"application/ipp\"", "}", ",", ")" ]
[ 70, 0 ]
[ 114, 5 ]
python
en
['en', 'en', 'en']
True
init_integration
( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, skip_setup: bool = False, host: str = HOST, port: int = PORT, ssl: bool = False, base_path: str = BASE_PATH, uuid: str = "cfe92100-67c4-11d4-a45f-f8d027761251", unique_id: str = "cfe92100-67c4-11d4-a45f-f8d027761251", conn_error: bool = False, )
Set up the IPP integration in Home Assistant.
Set up the IPP integration in Home Assistant.
async def init_integration( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, skip_setup: bool = False, host: str = HOST, port: int = PORT, ssl: bool = False, base_path: str = BASE_PATH, uuid: str = "cfe92100-67c4-11d4-a45f-f8d027761251", unique_id: str = "cfe92100-67c4-11d4-a45f-f8d027761251", conn_error: bool = False, ) -> MockConfigEntry: """Set up the IPP integration in Home Assistant.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=unique_id, data={ CONF_HOST: host, CONF_PORT: port, CONF_SSL: ssl, CONF_VERIFY_SSL: True, CONF_BASE_PATH: base_path, CONF_UUID: uuid, }, ) entry.add_to_hass(hass) mock_connection( aioclient_mock, host=host, port=port, ssl=ssl, base_path=base_path, conn_error=conn_error, ) if not skip_setup: await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() return entry
[ "async", "def", "init_integration", "(", "hass", ":", "HomeAssistant", ",", "aioclient_mock", ":", "AiohttpClientMocker", ",", "skip_setup", ":", "bool", "=", "False", ",", "host", ":", "str", "=", "HOST", ",", "port", ":", "int", "=", "PORT", ",", "ssl", ":", "bool", "=", "False", ",", "base_path", ":", "str", "=", "BASE_PATH", ",", "uuid", ":", "str", "=", "\"cfe92100-67c4-11d4-a45f-f8d027761251\"", ",", "unique_id", ":", "str", "=", "\"cfe92100-67c4-11d4-a45f-f8d027761251\"", ",", "conn_error", ":", "bool", "=", "False", ",", ")", "->", "MockConfigEntry", ":", "entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "unique_id", "=", "unique_id", ",", "data", "=", "{", "CONF_HOST", ":", "host", ",", "CONF_PORT", ":", "port", ",", "CONF_SSL", ":", "ssl", ",", "CONF_VERIFY_SSL", ":", "True", ",", "CONF_BASE_PATH", ":", "base_path", ",", "CONF_UUID", ":", "uuid", ",", "}", ",", ")", "entry", ".", "add_to_hass", "(", "hass", ")", "mock_connection", "(", "aioclient_mock", ",", "host", "=", "host", ",", "port", "=", "port", ",", "ssl", "=", "ssl", ",", "base_path", "=", "base_path", ",", "conn_error", "=", "conn_error", ",", ")", "if", "not", "skip_setup", ":", "await", "hass", ".", "config_entries", ".", "async_setup", "(", "entry", ".", "entry_id", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "return", "entry" ]
[ 117, 0 ]
[ 158, 16 ]
python
en
['en', 'en', 'en']
True
storage_setup
(hass, hass_storage)
Storage setup.
Storage setup.
def storage_setup(hass, hass_storage): """Storage setup.""" async def _storage(items=None, config=None): if items is None: hass_storage[DOMAIN] = { "key": DOMAIN, "version": 1, "data": {"items": [{"id": "from_storage", "name": "from storage"}]}, } else: hass_storage[DOMAIN] = items if config is None: config = {DOMAIN: {}} return await async_setup_component(hass, DOMAIN, config) return _storage
[ "def", "storage_setup", "(", "hass", ",", "hass_storage", ")", ":", "async", "def", "_storage", "(", "items", "=", "None", ",", "config", "=", "None", ")", ":", "if", "items", "is", "None", ":", "hass_storage", "[", "DOMAIN", "]", "=", "{", "\"key\"", ":", "DOMAIN", ",", "\"version\"", ":", "1", ",", "\"data\"", ":", "{", "\"items\"", ":", "[", "{", "\"id\"", ":", "\"from_storage\"", ",", "\"name\"", ":", "\"from storage\"", "}", "]", "}", ",", "}", "else", ":", "hass_storage", "[", "DOMAIN", "]", "=", "items", "if", "config", "is", "None", ":", "config", "=", "{", "DOMAIN", ":", "{", "}", "}", "return", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "config", ")", "return", "_storage" ]
[ 31, 0 ]
[ 47, 19 ]
python
en
['en', 'bs', 'en']
False
test_config
(hass)
Test config.
Test config.
async def test_config(hass): """Test config.""" invalid_configs = [None, 1, {}, {"name with space": None}] for cfg in invalid_configs: assert not await async_setup_component(hass, DOMAIN, {DOMAIN: cfg})
[ "async", "def", "test_config", "(", "hass", ")", ":", "invalid_configs", "=", "[", "None", ",", "1", ",", "{", "}", ",", "{", "\"name with space\"", ":", "None", "}", "]", "for", "cfg", "in", "invalid_configs", ":", "assert", "not", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "cfg", "}", ")" ]
[ 50, 0 ]
[ 55, 75 ]
python
en
['en', 'en', 'en']
False
test_methods
(hass)
Test is_on, turn_on, turn_off methods.
Test is_on, turn_on, turn_off methods.
async def test_methods(hass): """Test is_on, turn_on, turn_off methods.""" assert await async_setup_component(hass, DOMAIN, {DOMAIN: {"test_1": None}}) entity_id = "input_boolean.test_1" assert not is_on(hass, entity_id) await hass.services.async_call(DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}) await hass.async_block_till_done() assert is_on(hass, entity_id) await hass.services.async_call( DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id} ) await hass.async_block_till_done() assert not is_on(hass, entity_id) await hass.services.async_call(DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: entity_id}) await hass.async_block_till_done() assert is_on(hass, entity_id)
[ "async", "def", "test_methods", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "\"test_1\"", ":", "None", "}", "}", ")", "entity_id", "=", "\"input_boolean.test_1\"", "assert", "not", "is_on", "(", "hass", ",", "entity_id", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_TURN_ON", ",", "{", "ATTR_ENTITY_ID", ":", "entity_id", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "is_on", "(", "hass", ",", "entity_id", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_TURN_OFF", ",", "{", "ATTR_ENTITY_ID", ":", "entity_id", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "is_on", "(", "hass", ",", "entity_id", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_TOGGLE", ",", "{", "ATTR_ENTITY_ID", ":", "entity_id", "}", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "is_on", "(", "hass", ",", "entity_id", ")" ]
[ 58, 0 ]
[ 83, 33 ]
python
en
['en', 'et', 'en']
True
test_config_options
(hass)
Test configuration options.
Test configuration options.
async def test_config_options(hass): """Test configuration options.""" count_start = len(hass.states.async_entity_ids()) _LOGGER.debug("ENTITIES @ start: %s", hass.states.async_entity_ids()) assert await async_setup_component( hass, DOMAIN, { DOMAIN: { "test_1": None, "test_2": {"name": "Hello World", "icon": "mdi:work", "initial": True}, } }, ) _LOGGER.debug("ENTITIES: %s", hass.states.async_entity_ids()) assert count_start + 2 == len(hass.states.async_entity_ids()) state_1 = hass.states.get("input_boolean.test_1") state_2 = hass.states.get("input_boolean.test_2") assert state_1 is not None assert state_2 is not None assert STATE_OFF == state_1.state assert ATTR_ICON not in state_1.attributes assert ATTR_FRIENDLY_NAME not in state_1.attributes assert STATE_ON == state_2.state assert "Hello World" == state_2.attributes.get(ATTR_FRIENDLY_NAME) assert "mdi:work" == state_2.attributes.get(ATTR_ICON)
[ "async", "def", "test_config_options", "(", "hass", ")", ":", "count_start", "=", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "_LOGGER", ".", "debug", "(", "\"ENTITIES @ start: %s\"", ",", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "\"test_1\"", ":", "None", ",", "\"test_2\"", ":", "{", "\"name\"", ":", "\"Hello World\"", ",", "\"icon\"", ":", "\"mdi:work\"", ",", "\"initial\"", ":", "True", "}", ",", "}", "}", ",", ")", "_LOGGER", ".", "debug", "(", "\"ENTITIES: %s\"", ",", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "assert", "count_start", "+", "2", "==", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "state_1", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.test_1\"", ")", "state_2", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.test_2\"", ")", "assert", "state_1", "is", "not", "None", "assert", "state_2", "is", "not", "None", "assert", "STATE_OFF", "==", "state_1", ".", "state", "assert", "ATTR_ICON", "not", "in", "state_1", ".", "attributes", "assert", "ATTR_FRIENDLY_NAME", "not", "in", "state_1", ".", "attributes", "assert", "STATE_ON", "==", "state_2", ".", "state", "assert", "\"Hello World\"", "==", "state_2", ".", "attributes", ".", "get", "(", "ATTR_FRIENDLY_NAME", ")", "assert", "\"mdi:work\"", "==", "state_2", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")" ]
[ 86, 0 ]
[ 119, 58 ]
python
en
['en', 'fr', 'en']
True
test_restore_state
(hass)
Ensure states are restored on startup.
Ensure states are restored on startup.
async def test_restore_state(hass): """Ensure states are restored on startup.""" mock_restore_cache( hass, ( State("input_boolean.b1", "on"), State("input_boolean.b2", "off"), State("input_boolean.b3", "on"), ), ) hass.state = CoreState.starting mock_component(hass, "recorder") await async_setup_component(hass, DOMAIN, {DOMAIN: {"b1": None, "b2": None}}) state = hass.states.get("input_boolean.b1") assert state assert state.state == "on" state = hass.states.get("input_boolean.b2") assert state assert state.state == "off"
[ "async", "def", "test_restore_state", "(", "hass", ")", ":", "mock_restore_cache", "(", "hass", ",", "(", "State", "(", "\"input_boolean.b1\"", ",", "\"on\"", ")", ",", "State", "(", "\"input_boolean.b2\"", ",", "\"off\"", ")", ",", "State", "(", "\"input_boolean.b3\"", ",", "\"on\"", ")", ",", ")", ",", ")", "hass", ".", "state", "=", "CoreState", ".", "starting", "mock_component", "(", "hass", ",", "\"recorder\"", ")", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "\"b1\"", ":", "None", ",", "\"b2\"", ":", "None", "}", "}", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.b1\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "\"on\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.b2\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "\"off\"" ]
[ 122, 0 ]
[ 144, 31 ]
python
en
['en', 'en', 'en']
True
test_initial_state_overrules_restore_state
(hass)
Ensure states are restored on startup.
Ensure states are restored on startup.
async def test_initial_state_overrules_restore_state(hass): """Ensure states are restored on startup.""" mock_restore_cache( hass, (State("input_boolean.b1", "on"), State("input_boolean.b2", "off")) ) hass.state = CoreState.starting await async_setup_component( hass, DOMAIN, {DOMAIN: {"b1": {CONF_INITIAL: False}, "b2": {CONF_INITIAL: True}}}, ) state = hass.states.get("input_boolean.b1") assert state assert state.state == "off" state = hass.states.get("input_boolean.b2") assert state assert state.state == "on"
[ "async", "def", "test_initial_state_overrules_restore_state", "(", "hass", ")", ":", "mock_restore_cache", "(", "hass", ",", "(", "State", "(", "\"input_boolean.b1\"", ",", "\"on\"", ")", ",", "State", "(", "\"input_boolean.b2\"", ",", "\"off\"", ")", ")", ")", "hass", ".", "state", "=", "CoreState", ".", "starting", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "\"b1\"", ":", "{", "CONF_INITIAL", ":", "False", "}", ",", "\"b2\"", ":", "{", "CONF_INITIAL", ":", "True", "}", "}", "}", ",", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.b1\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "\"off\"", "state", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.b2\"", ")", "assert", "state", "assert", "state", ".", "state", "==", "\"on\"" ]
[ 147, 0 ]
[ 167, 30 ]
python
en
['en', 'en', 'en']
True
test_input_boolean_context
(hass, hass_admin_user)
Test that input_boolean context works.
Test that input_boolean context works.
async def test_input_boolean_context(hass, hass_admin_user): """Test that input_boolean context works.""" assert await async_setup_component( hass, "input_boolean", {"input_boolean": {"ac": {CONF_INITIAL: True}}} ) state = hass.states.get("input_boolean.ac") assert state is not None await hass.services.async_call( "input_boolean", "turn_off", {"entity_id": state.entity_id}, True, Context(user_id=hass_admin_user.id), ) state2 = hass.states.get("input_boolean.ac") assert state2 is not None assert state.state != state2.state assert state2.context.user_id == hass_admin_user.id
[ "async", "def", "test_input_boolean_context", "(", "hass", ",", "hass_admin_user", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"input_boolean\"", ",", "{", "\"input_boolean\"", ":", "{", "\"ac\"", ":", "{", "CONF_INITIAL", ":", "True", "}", "}", "}", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.ac\"", ")", "assert", "state", "is", "not", "None", "await", "hass", ".", "services", ".", "async_call", "(", "\"input_boolean\"", ",", "\"turn_off\"", ",", "{", "\"entity_id\"", ":", "state", ".", "entity_id", "}", ",", "True", ",", "Context", "(", "user_id", "=", "hass_admin_user", ".", "id", ")", ",", ")", "state2", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.ac\"", ")", "assert", "state2", "is", "not", "None", "assert", "state", ".", "state", "!=", "state2", ".", "state", "assert", "state2", ".", "context", ".", "user_id", "==", "hass_admin_user", ".", "id" ]
[ 170, 0 ]
[ 190, 55 ]
python
en
['en', 'en', 'en']
True
test_reload
(hass, hass_admin_user)
Test reload service.
Test reload service.
async def test_reload(hass, hass_admin_user): """Test reload service.""" count_start = len(hass.states.async_entity_ids()) ent_reg = await entity_registry.async_get_registry(hass) _LOGGER.debug("ENTITIES @ start: %s", hass.states.async_entity_ids()) assert await async_setup_component( hass, DOMAIN, { DOMAIN: { "test_1": None, "test_2": {"name": "Hello World", "icon": "mdi:work", "initial": True}, } }, ) _LOGGER.debug("ENTITIES: %s", hass.states.async_entity_ids()) assert count_start + 2 == len(hass.states.async_entity_ids()) state_1 = hass.states.get("input_boolean.test_1") state_2 = hass.states.get("input_boolean.test_2") state_3 = hass.states.get("input_boolean.test_3") assert state_1 is not None assert state_2 is not None assert state_3 is None assert STATE_ON == state_2.state assert ent_reg.async_get_entity_id(DOMAIN, DOMAIN, "test_1") is not None assert ent_reg.async_get_entity_id(DOMAIN, DOMAIN, "test_2") is not None assert ent_reg.async_get_entity_id(DOMAIN, DOMAIN, "test_3") is None with patch( "homeassistant.config.load_yaml_config_file", autospec=True, return_value={ DOMAIN: { "test_2": { "name": "Hello World reloaded", "icon": "mdi:work_reloaded", "initial": False, }, "test_3": None, } }, ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, blocking=True, context=Context(user_id=hass_admin_user.id), ) await hass.async_block_till_done() assert count_start + 2 == len(hass.states.async_entity_ids()) state_1 = hass.states.get("input_boolean.test_1") state_2 = hass.states.get("input_boolean.test_2") state_3 = hass.states.get("input_boolean.test_3") assert state_1 is None assert state_2 is not None assert state_3 is not None assert ent_reg.async_get_entity_id(DOMAIN, DOMAIN, "test_1") is None assert ent_reg.async_get_entity_id(DOMAIN, DOMAIN, "test_2") is not None assert ent_reg.async_get_entity_id(DOMAIN, DOMAIN, "test_3") is not None assert STATE_ON == state_2.state # reload is not supposed to change entity state assert "Hello World reloaded" == state_2.attributes.get(ATTR_FRIENDLY_NAME) assert "mdi:work_reloaded" == state_2.attributes.get(ATTR_ICON)
[ "async", "def", "test_reload", "(", "hass", ",", "hass_admin_user", ")", ":", "count_start", "=", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "ent_reg", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "_LOGGER", ".", "debug", "(", "\"ENTITIES @ start: %s\"", ",", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "\"test_1\"", ":", "None", ",", "\"test_2\"", ":", "{", "\"name\"", ":", "\"Hello World\"", ",", "\"icon\"", ":", "\"mdi:work\"", ",", "\"initial\"", ":", "True", "}", ",", "}", "}", ",", ")", "_LOGGER", ".", "debug", "(", "\"ENTITIES: %s\"", ",", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "assert", "count_start", "+", "2", "==", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "state_1", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.test_1\"", ")", "state_2", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.test_2\"", ")", "state_3", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.test_3\"", ")", "assert", "state_1", "is", "not", "None", "assert", "state_2", "is", "not", "None", "assert", "state_3", "is", "None", "assert", "STATE_ON", "==", "state_2", ".", "state", "assert", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "\"test_1\"", ")", "is", "not", "None", "assert", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "\"test_2\"", ")", "is", "not", "None", "assert", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "\"test_3\"", ")", "is", "None", "with", "patch", "(", "\"homeassistant.config.load_yaml_config_file\"", ",", "autospec", "=", "True", ",", "return_value", "=", "{", "DOMAIN", ":", "{", "\"test_2\"", ":", "{", "\"name\"", ":", "\"Hello World reloaded\"", ",", "\"icon\"", ":", "\"mdi:work_reloaded\"", ",", "\"initial\"", ":", "False", ",", "}", ",", "\"test_3\"", ":", "None", ",", "}", "}", ",", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_RELOAD", ",", "blocking", "=", "True", ",", "context", "=", "Context", "(", "user_id", "=", "hass_admin_user", ".", "id", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "count_start", "+", "2", "==", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "state_1", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.test_1\"", ")", "state_2", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.test_2\"", ")", "state_3", "=", "hass", ".", "states", ".", "get", "(", "\"input_boolean.test_3\"", ")", "assert", "state_1", "is", "None", "assert", "state_2", "is", "not", "None", "assert", "state_3", "is", "not", "None", "assert", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "\"test_1\"", ")", "is", "None", "assert", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "\"test_2\"", ")", "is", "not", "None", "assert", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "\"test_3\"", ")", "is", "not", "None", "assert", "STATE_ON", "==", "state_2", ".", "state", "# reload is not supposed to change entity state", "assert", "\"Hello World reloaded\"", "==", "state_2", ".", "attributes", ".", "get", "(", "ATTR_FRIENDLY_NAME", ")", "assert", "\"mdi:work_reloaded\"", "==", "state_2", ".", "attributes", ".", "get", "(", "ATTR_ICON", ")" ]
[ 193, 0 ]
[ 266, 67 ]
python
en
['en', 'da', 'en']
True
test_load_person_storage
(hass, storage_setup)
Test set up from storage.
Test set up from storage.
async def test_load_person_storage(hass, storage_setup): """Test set up from storage.""" assert await storage_setup() state = hass.states.get(f"{DOMAIN}.from_storage") assert state.state == STATE_OFF assert state.attributes.get(ATTR_FRIENDLY_NAME) == "from storage" assert state.attributes.get(ATTR_EDITABLE)
[ "async", "def", "test_load_person_storage", "(", "hass", ",", "storage_setup", ")", ":", "assert", "await", "storage_setup", "(", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{DOMAIN}.from_storage\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_FRIENDLY_NAME", ")", "==", "\"from storage\"", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_EDITABLE", ")" ]
[ 269, 0 ]
[ 275, 46 ]
python
en
['en', 'en', 'en']
True
test_editable_state_attribute
(hass, storage_setup)
Test editable attribute.
Test editable attribute.
async def test_editable_state_attribute(hass, storage_setup): """Test editable attribute.""" assert await storage_setup(config={DOMAIN: {"from_yaml": None}}) state = hass.states.get(f"{DOMAIN}.from_storage") assert state.state == STATE_OFF assert state.attributes.get(ATTR_FRIENDLY_NAME) == "from storage" assert state.attributes.get(ATTR_EDITABLE) state = hass.states.get(f"{DOMAIN}.from_yaml") assert state.state == STATE_OFF assert not state.attributes.get(ATTR_EDITABLE)
[ "async", "def", "test_editable_state_attribute", "(", "hass", ",", "storage_setup", ")", ":", "assert", "await", "storage_setup", "(", "config", "=", "{", "DOMAIN", ":", "{", "\"from_yaml\"", ":", "None", "}", "}", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{DOMAIN}.from_storage\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_FRIENDLY_NAME", ")", "==", "\"from storage\"", "assert", "state", ".", "attributes", ".", "get", "(", "ATTR_EDITABLE", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "f\"{DOMAIN}.from_yaml\"", ")", "assert", "state", ".", "state", "==", "STATE_OFF", "assert", "not", "state", ".", "attributes", ".", "get", "(", "ATTR_EDITABLE", ")" ]
[ 278, 0 ]
[ 289, 50 ]
python
de
['de', 'et', 'en']
False
test_ws_list
(hass, hass_ws_client, storage_setup)
Test listing via WS.
Test listing via WS.
async def test_ws_list(hass, hass_ws_client, storage_setup): """Test listing via WS.""" assert await storage_setup(config={DOMAIN: {"from_yaml": None}}) client = await hass_ws_client(hass) await client.send_json({"id": 6, "type": f"{DOMAIN}/list"}) resp = await client.receive_json() assert resp["success"] storage_ent = "from_storage" yaml_ent = "from_yaml" result = {item["id"]: item for item in resp["result"]} assert len(result) == 1 assert storage_ent in result assert yaml_ent not in result assert result[storage_ent][ATTR_NAME] == "from storage"
[ "async", "def", "test_ws_list", "(", "hass", ",", "hass_ws_client", ",", "storage_setup", ")", ":", "assert", "await", "storage_setup", "(", "config", "=", "{", "DOMAIN", ":", "{", "\"from_yaml\"", ":", "None", "}", "}", ")", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "6", ",", "\"type\"", ":", "f\"{DOMAIN}/list\"", "}", ")", "resp", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "resp", "[", "\"success\"", "]", "storage_ent", "=", "\"from_storage\"", "yaml_ent", "=", "\"from_yaml\"", "result", "=", "{", "item", "[", "\"id\"", "]", ":", "item", "for", "item", "in", "resp", "[", "\"result\"", "]", "}", "assert", "len", "(", "result", ")", "==", "1", "assert", "storage_ent", "in", "result", "assert", "yaml_ent", "not", "in", "result", "assert", "result", "[", "storage_ent", "]", "[", "ATTR_NAME", "]", "==", "\"from storage\"" ]
[ 292, 0 ]
[ 309, 59 ]
python
hmn
['nl', 'hmn', 'it']
False
test_ws_delete
(hass, hass_ws_client, storage_setup)
Test WS delete cleans up entity registry.
Test WS delete cleans up entity registry.
async def test_ws_delete(hass, hass_ws_client, storage_setup): """Test WS delete cleans up entity registry.""" assert await storage_setup() input_id = "from_storage" input_entity_id = f"{DOMAIN}.{input_id}" ent_reg = await entity_registry.async_get_registry(hass) state = hass.states.get(input_entity_id) assert state is not None assert ent_reg.async_get_entity_id(DOMAIN, DOMAIN, input_id) is not None client = await hass_ws_client(hass) await client.send_json( {"id": 6, "type": f"{DOMAIN}/delete", f"{DOMAIN}_id": f"{input_id}"} ) resp = await client.receive_json() assert resp["success"] state = hass.states.get(input_entity_id) assert state is None assert ent_reg.async_get_entity_id(DOMAIN, DOMAIN, input_id) is None
[ "async", "def", "test_ws_delete", "(", "hass", ",", "hass_ws_client", ",", "storage_setup", ")", ":", "assert", "await", "storage_setup", "(", ")", "input_id", "=", "\"from_storage\"", "input_entity_id", "=", "f\"{DOMAIN}.{input_id}\"", "ent_reg", "=", "await", "entity_registry", ".", "async_get_registry", "(", "hass", ")", "state", "=", "hass", ".", "states", ".", "get", "(", "input_entity_id", ")", "assert", "state", "is", "not", "None", "assert", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "input_id", ")", "is", "not", "None", "client", "=", "await", "hass_ws_client", "(", "hass", ")", "await", "client", ".", "send_json", "(", "{", "\"id\"", ":", "6", ",", "\"type\"", ":", "f\"{DOMAIN}/delete\"", ",", "f\"{DOMAIN}_id\"", ":", "f\"{input_id}\"", "}", ")", "resp", "=", "await", "client", ".", "receive_json", "(", ")", "assert", "resp", "[", "\"success\"", "]", "state", "=", "hass", ".", "states", ".", "get", "(", "input_entity_id", ")", "assert", "state", "is", "None", "assert", "ent_reg", ".", "async_get_entity_id", "(", "DOMAIN", ",", "DOMAIN", ",", "input_id", ")", "is", "None" ]
[ 312, 0 ]
[ 334, 72 ]
python
en
['en', 'en', 'en']
True
test_setup_no_config
(hass, hass_admin_user)
Test component setup with no config.
Test component setup with no config.
async def test_setup_no_config(hass, hass_admin_user): """Test component setup with no config.""" count_start = len(hass.states.async_entity_ids()) assert await async_setup_component(hass, DOMAIN, {}) with patch( "homeassistant.config.load_yaml_config_file", autospec=True, return_value={} ): await hass.services.async_call( DOMAIN, SERVICE_RELOAD, blocking=True, context=Context(user_id=hass_admin_user.id), ) await hass.async_block_till_done() assert count_start == len(hass.states.async_entity_ids())
[ "async", "def", "test_setup_no_config", "(", "hass", ",", "hass_admin_user", ")", ":", "count_start", "=", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "}", ")", "with", "patch", "(", "\"homeassistant.config.load_yaml_config_file\"", ",", "autospec", "=", "True", ",", "return_value", "=", "{", "}", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_RELOAD", ",", "blocking", "=", "True", ",", "context", "=", "Context", "(", "user_id", "=", "hass_admin_user", ".", "id", ")", ",", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "count_start", "==", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", ")", ")" ]
[ 337, 0 ]
[ 353, 61 ]
python
en
['en', 'pt', 'en']
True
get_new_port_number
(experiment_name: str)
Get the latest episode number of real-time episode. Args: experiment_name (str): Name of the experiment. Returns: json: Number of episodes.
Get the latest episode number of real-time episode.
def get_new_port_number(experiment_name: str) -> json: """Get the latest episode number of real-time episode. Args: experiment_name (str): Name of the experiment. Returns: json: Number of episodes. """ params = { "query": f"select count(episode) from {experiment_name}.port_details", "count": "true" } episode_number_data = requests.get( url=request_settings.request_url.value, headers=request_settings.request_header.value, params=params ).json() return episode_number_data
[ "def", "get_new_port_number", "(", "experiment_name", ":", "str", ")", "->", "json", ":", "params", "=", "{", "\"query\"", ":", "f\"select count(episode) from {experiment_name}.port_details\"", ",", "\"count\"", ":", "\"true\"", "}", "episode_number_data", "=", "requests", ".", "get", "(", "url", "=", "request_settings", ".", "request_url", ".", "value", ",", "headers", "=", "request_settings", ".", "request_header", ".", "value", ",", "params", "=", "params", ")", ".", "json", "(", ")", "return", "episode_number_data" ]
[ 12, 0 ]
[ 31, 30 ]
python
en
['en', 'en', 'en']
True
get_port_data
(experiment_name: str, episode: str, tick: str)
Get the port data within one tick. Args: experiment_name (str): Name of the experiment expected to be displayed. episode (str) : Number of the episode of expected data. tick (str): Number of tick of expected data. Returns: json: Formatted port value of current tick.
Get the port data within one tick.
def get_port_data(experiment_name: str, episode: str, tick: str) -> json: """Get the port data within one tick. Args: experiment_name (str): Name of the experiment expected to be displayed. episode (str) : Number of the episode of expected data. tick (str): Number of tick of expected data. Returns: json: Formatted port value of current tick. """ params = { "query": f"select {request_column.port_header.value} from {experiment_name}.port_details" f" where episode='{episode}' and tick='{tick}'", "count": "true" } db_port_data = requests.get( url=request_settings.request_url.value, headers=request_settings.request_header.value, params=params ).json() return process_port_data(db_port_data)
[ "def", "get_port_data", "(", "experiment_name", ":", "str", ",", "episode", ":", "str", ",", "tick", ":", "str", ")", "->", "json", ":", "params", "=", "{", "\"query\"", ":", "f\"select {request_column.port_header.value} from {experiment_name}.port_details\"", "f\" where episode='{episode}' and tick='{tick}'\"", ",", "\"count\"", ":", "\"true\"", "}", "db_port_data", "=", "requests", ".", "get", "(", "url", "=", "request_settings", ".", "request_url", ".", "value", ",", "headers", "=", "request_settings", ".", "request_header", ".", "value", ",", "params", "=", "params", ")", ".", "json", "(", ")", "return", "process_port_data", "(", "db_port_data", ")" ]
[ 34, 0 ]
[ 56, 42 ]
python
en
['en', 'en', 'en']
True
get_acc_port_data
(experiment_name: str, episode: str, start_tick: str, end_tick: str)
Get the port data within a range. Args: experiment_name (str): Name of the experiment expected to be displayed. episode (str) : Number of the episode of expected data. start_tick (str): Number of tick to the start point of port data. end_tick(str): Number of tick to the end point of port data. Returns: json: Jsonified formatted port value through a selected range.
Get the port data within a range.
def get_acc_port_data(experiment_name: str, episode: str, start_tick: str, end_tick: str) -> json: """Get the port data within a range. Args: experiment_name (str): Name of the experiment expected to be displayed. episode (str) : Number of the episode of expected data. start_tick (str): Number of tick to the start point of port data. end_tick(str): Number of tick to the end point of port data. Returns: json: Jsonified formatted port value through a selected range. """ input_range = get_input_range(start_tick, end_tick) params = { "query": f"select {request_column.port_header.value} from {experiment_name}.port_details" f" where episode='{episode}' and tick in {input_range}", "count": "true" } db_port_data = requests.get( url=request_settings.request_url.value, headers=request_settings.request_header.value, params=params ).json() return process_port_data(db_port_data)
[ "def", "get_acc_port_data", "(", "experiment_name", ":", "str", ",", "episode", ":", "str", ",", "start_tick", ":", "str", ",", "end_tick", ":", "str", ")", "->", "json", ":", "input_range", "=", "get_input_range", "(", "start_tick", ",", "end_tick", ")", "params", "=", "{", "\"query\"", ":", "f\"select {request_column.port_header.value} from {experiment_name}.port_details\"", "f\" where episode='{episode}' and tick in {input_range}\"", ",", "\"count\"", ":", "\"true\"", "}", "db_port_data", "=", "requests", ".", "get", "(", "url", "=", "request_settings", ".", "request_url", ".", "value", ",", "headers", "=", "request_settings", ".", "request_header", ".", "value", ",", "params", "=", "params", ")", ".", "json", "(", ")", "return", "process_port_data", "(", "db_port_data", ")" ]
[ 59, 0 ]
[ 83, 42 ]
python
en
['en', 'en', 'en']
True
process_port_data
(db_port_data: json)
Generate compulsory columns and process with topoly information. Args: db_port_data(json): Original port data. Returns: json: Jsonfied port value of current tick.
Generate compulsory columns and process with topoly information.
def process_port_data(db_port_data: json) -> json: """Generate compulsory columns and process with topoly information. Args: db_port_data(json): Original port data. Returns: json: Jsonfied port value of current tick. """ exec_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))) config_file_path = f"{exec_path}/nginx/static/" with open(f"{config_file_path}port_list.json", "r", encoding="utf8")as port_list_file: port_list = json.load(port_list_file) port_list = port_list[0]["port_list"] with open(f"{config_file_path}port.json", "r", encoding="utf8")as port_file: port_json_data = json.load(port_file) original_port_data = get_data_in_format(db_port_data) original_port_data["port_name"] = list( map( lambda x: port_json_data[int(x)]['tooltip'], original_port_data["index"] ) ) original_port_data["position"] = list( map( lambda x: port_json_data[int(x)]['position'], original_port_data["index"] ) ) original_port_data["status"] = list( map( lambda x, y: 'surplus' if (x - y * 5 > 50) else ('demand' if (x - y * 5 < -50) else 'balance'), original_port_data['empty'], original_port_data['booking'] ) ) port_data = original_port_data.to_json(orient='records') return port_data
[ "def", "process_port_data", "(", "db_port_data", ":", "json", ")", "->", "json", ":", "exec_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", ")", ")", ")", "config_file_path", "=", "f\"{exec_path}/nginx/static/\"", "with", "open", "(", "f\"{config_file_path}port_list.json\"", ",", "\"r\"", ",", "encoding", "=", "\"utf8\"", ")", "as", "port_list_file", ":", "port_list", "=", "json", ".", "load", "(", "port_list_file", ")", "port_list", "=", "port_list", "[", "0", "]", "[", "\"port_list\"", "]", "with", "open", "(", "f\"{config_file_path}port.json\"", ",", "\"r\"", ",", "encoding", "=", "\"utf8\"", ")", "as", "port_file", ":", "port_json_data", "=", "json", ".", "load", "(", "port_file", ")", "original_port_data", "=", "get_data_in_format", "(", "db_port_data", ")", "original_port_data", "[", "\"port_name\"", "]", "=", "list", "(", "map", "(", "lambda", "x", ":", "port_json_data", "[", "int", "(", "x", ")", "]", "[", "'tooltip'", "]", ",", "original_port_data", "[", "\"index\"", "]", ")", ")", "original_port_data", "[", "\"position\"", "]", "=", "list", "(", "map", "(", "lambda", "x", ":", "port_json_data", "[", "int", "(", "x", ")", "]", "[", "'position'", "]", ",", "original_port_data", "[", "\"index\"", "]", ")", ")", "original_port_data", "[", "\"status\"", "]", "=", "list", "(", "map", "(", "lambda", "x", ",", "y", ":", "'surplus'", "if", "(", "x", "-", "y", "*", "5", ">", "50", ")", "else", "(", "'demand'", "if", "(", "x", "-", "y", "*", "5", "<", "-", "50", ")", "else", "'balance'", ")", ",", "original_port_data", "[", "'empty'", "]", ",", "original_port_data", "[", "'booking'", "]", ")", ")", "port_data", "=", "original_port_data", ".", "to_json", "(", "orient", "=", "'records'", ")", "return", "port_data" ]
[ 86, 0 ]
[ 124, 20 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, config_entry, async_add_entities)
Add lights for a config entry.
Add lights for a config entry.
async def async_setup_entry(hass, config_entry, async_add_entities): """Add lights for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] async_add_entities( [ SmartThingsLight(device) for device in broker.devices.values() if broker.any_assigned(device.device_id, "light") ], True, )
[ "async", "def", "async_setup_entry", "(", "hass", ",", "config_entry", ",", "async_add_entities", ")", ":", "broker", "=", "hass", ".", "data", "[", "DOMAIN", "]", "[", "DATA_BROKERS", "]", "[", "config_entry", ".", "entry_id", "]", "async_add_entities", "(", "[", "SmartThingsLight", "(", "device", ")", "for", "device", "in", "broker", ".", "devices", ".", "values", "(", ")", "if", "broker", ".", "any_assigned", "(", "device", ".", "device_id", ",", "\"light\"", ")", "]", ",", "True", ",", ")" ]
[ 23, 0 ]
[ 33, 5 ]
python
en
['en', 'en', 'en']
True
get_capabilities
(capabilities: Sequence[str])
Return all capabilities supported if minimum required are present.
Return all capabilities supported if minimum required are present.
def get_capabilities(capabilities: Sequence[str]) -> Optional[Sequence[str]]: """Return all capabilities supported if minimum required are present.""" supported = [ Capability.switch, Capability.switch_level, Capability.color_control, Capability.color_temperature, ] # Must be able to be turned on/off. if Capability.switch not in capabilities: return None # Must have one of these light_capabilities = [ Capability.color_control, Capability.color_temperature, Capability.switch_level, ] if any(capability in capabilities for capability in light_capabilities): return supported return None
[ "def", "get_capabilities", "(", "capabilities", ":", "Sequence", "[", "str", "]", ")", "->", "Optional", "[", "Sequence", "[", "str", "]", "]", ":", "supported", "=", "[", "Capability", ".", "switch", ",", "Capability", ".", "switch_level", ",", "Capability", ".", "color_control", ",", "Capability", ".", "color_temperature", ",", "]", "# Must be able to be turned on/off.", "if", "Capability", ".", "switch", "not", "in", "capabilities", ":", "return", "None", "# Must have one of these", "light_capabilities", "=", "[", "Capability", ".", "color_control", ",", "Capability", ".", "color_temperature", ",", "Capability", ".", "switch_level", ",", "]", "if", "any", "(", "capability", "in", "capabilities", "for", "capability", "in", "light_capabilities", ")", ":", "return", "supported", "return", "None" ]
[ 36, 0 ]
[ 55, 15 ]
python
en
['en', 'en', 'en']
True
convert_scale
(value, value_scale, target_scale, round_digits=4)
Convert a value to a different scale.
Convert a value to a different scale.
def convert_scale(value, value_scale, target_scale, round_digits=4): """Convert a value to a different scale.""" return round(value * target_scale / value_scale, round_digits)
[ "def", "convert_scale", "(", "value", ",", "value_scale", ",", "target_scale", ",", "round_digits", "=", "4", ")", ":", "return", "round", "(", "value", "*", "target_scale", "/", "value_scale", ",", "round_digits", ")" ]
[ 58, 0 ]
[ 60, 66 ]
python
en
['it', 'en', 'en']
True
SmartThingsLight.__init__
(self, device)
Initialize a SmartThingsLight.
Initialize a SmartThingsLight.
def __init__(self, device): """Initialize a SmartThingsLight.""" super().__init__(device) self._brightness = None self._color_temp = None self._hs_color = None self._supported_features = self._determine_features()
[ "def", "__init__", "(", "self", ",", "device", ")", ":", "super", "(", ")", ".", "__init__", "(", "device", ")", "self", ".", "_brightness", "=", "None", "self", ".", "_color_temp", "=", "None", "self", ".", "_hs_color", "=", "None", "self", ".", "_supported_features", "=", "self", ".", "_determine_features", "(", ")" ]
[ 66, 4 ]
[ 72, 61 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight._determine_features
(self)
Get features supported by the device.
Get features supported by the device.
def _determine_features(self): """Get features supported by the device.""" features = 0 # Brightness and transition if Capability.switch_level in self._device.capabilities: features |= SUPPORT_BRIGHTNESS | SUPPORT_TRANSITION # Color Temperature if Capability.color_temperature in self._device.capabilities: features |= SUPPORT_COLOR_TEMP # Color if Capability.color_control in self._device.capabilities: features |= SUPPORT_COLOR return features
[ "def", "_determine_features", "(", "self", ")", ":", "features", "=", "0", "# Brightness and transition", "if", "Capability", ".", "switch_level", "in", "self", ".", "_device", ".", "capabilities", ":", "features", "|=", "SUPPORT_BRIGHTNESS", "|", "SUPPORT_TRANSITION", "# Color Temperature", "if", "Capability", ".", "color_temperature", "in", "self", ".", "_device", ".", "capabilities", ":", "features", "|=", "SUPPORT_COLOR_TEMP", "# Color", "if", "Capability", ".", "color_control", "in", "self", ".", "_device", ".", "capabilities", ":", "features", "|=", "SUPPORT_COLOR", "return", "features" ]
[ 74, 4 ]
[ 87, 23 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.async_turn_on
(self, **kwargs)
Turn the light on.
Turn the light on.
async def async_turn_on(self, **kwargs) -> None: """Turn the light on.""" tasks = [] # Color temperature if self._supported_features & SUPPORT_COLOR_TEMP and ATTR_COLOR_TEMP in kwargs: tasks.append(self.async_set_color_temp(kwargs[ATTR_COLOR_TEMP])) # Color if self._supported_features & SUPPORT_COLOR and ATTR_HS_COLOR in kwargs: tasks.append(self.async_set_color(kwargs[ATTR_HS_COLOR])) if tasks: # Set temp/color first await asyncio.gather(*tasks) # Switch/brightness/transition if self._supported_features & SUPPORT_BRIGHTNESS and ATTR_BRIGHTNESS in kwargs: await self.async_set_level( kwargs[ATTR_BRIGHTNESS], kwargs.get(ATTR_TRANSITION, 0) ) else: await self._device.switch_on(set_status=True) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True)
[ "async", "def", "async_turn_on", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "tasks", "=", "[", "]", "# Color temperature", "if", "self", ".", "_supported_features", "&", "SUPPORT_COLOR_TEMP", "and", "ATTR_COLOR_TEMP", "in", "kwargs", ":", "tasks", ".", "append", "(", "self", ".", "async_set_color_temp", "(", "kwargs", "[", "ATTR_COLOR_TEMP", "]", ")", ")", "# Color", "if", "self", ".", "_supported_features", "&", "SUPPORT_COLOR", "and", "ATTR_HS_COLOR", "in", "kwargs", ":", "tasks", ".", "append", "(", "self", ".", "async_set_color", "(", "kwargs", "[", "ATTR_HS_COLOR", "]", ")", ")", "if", "tasks", ":", "# Set temp/color first", "await", "asyncio", ".", "gather", "(", "*", "tasks", ")", "# Switch/brightness/transition", "if", "self", ".", "_supported_features", "&", "SUPPORT_BRIGHTNESS", "and", "ATTR_BRIGHTNESS", "in", "kwargs", ":", "await", "self", ".", "async_set_level", "(", "kwargs", "[", "ATTR_BRIGHTNESS", "]", ",", "kwargs", ".", "get", "(", "ATTR_TRANSITION", ",", "0", ")", ")", "else", ":", "await", "self", ".", "_device", ".", "switch_on", "(", "set_status", "=", "True", ")", "# State is set optimistically in the commands above, therefore update", "# the entity state ahead of receiving the confirming push updates", "self", ".", "async_schedule_update_ha_state", "(", "True", ")" ]
[ 89, 4 ]
[ 112, 49 ]
python
en
['en', 'et', 'en']
True
SmartThingsLight.async_turn_off
(self, **kwargs)
Turn the light off.
Turn the light off.
async def async_turn_off(self, **kwargs) -> None: """Turn the light off.""" # Switch/transition if self._supported_features & SUPPORT_TRANSITION and ATTR_TRANSITION in kwargs: await self.async_set_level(0, int(kwargs[ATTR_TRANSITION])) else: await self._device.switch_off(set_status=True) # State is set optimistically in the commands above, therefore update # the entity state ahead of receiving the confirming push updates self.async_schedule_update_ha_state(True)
[ "async", "def", "async_turn_off", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "# Switch/transition", "if", "self", ".", "_supported_features", "&", "SUPPORT_TRANSITION", "and", "ATTR_TRANSITION", "in", "kwargs", ":", "await", "self", ".", "async_set_level", "(", "0", ",", "int", "(", "kwargs", "[", "ATTR_TRANSITION", "]", ")", ")", "else", ":", "await", "self", ".", "_device", ".", "switch_off", "(", "set_status", "=", "True", ")", "# State is set optimistically in the commands above, therefore update", "# the entity state ahead of receiving the confirming push updates", "self", ".", "async_schedule_update_ha_state", "(", "True", ")" ]
[ 114, 4 ]
[ 124, 49 ]
python
en
['en', 'zh', 'en']
True
SmartThingsLight.async_update
(self)
Update entity attributes when the device status has changed.
Update entity attributes when the device status has changed.
async def async_update(self): """Update entity attributes when the device status has changed.""" # Brightness and transition if self._supported_features & SUPPORT_BRIGHTNESS: self._brightness = int( convert_scale(self._device.status.level, 100, 255, 0) ) # Color Temperature if self._supported_features & SUPPORT_COLOR_TEMP: self._color_temp = color_util.color_temperature_kelvin_to_mired( self._device.status.color_temperature ) # Color if self._supported_features & SUPPORT_COLOR: self._hs_color = ( convert_scale(self._device.status.hue, 100, 360), self._device.status.saturation, )
[ "async", "def", "async_update", "(", "self", ")", ":", "# Brightness and transition", "if", "self", ".", "_supported_features", "&", "SUPPORT_BRIGHTNESS", ":", "self", ".", "_brightness", "=", "int", "(", "convert_scale", "(", "self", ".", "_device", ".", "status", ".", "level", ",", "100", ",", "255", ",", "0", ")", ")", "# Color Temperature", "if", "self", ".", "_supported_features", "&", "SUPPORT_COLOR_TEMP", ":", "self", ".", "_color_temp", "=", "color_util", ".", "color_temperature_kelvin_to_mired", "(", "self", ".", "_device", ".", "status", ".", "color_temperature", ")", "# Color", "if", "self", ".", "_supported_features", "&", "SUPPORT_COLOR", ":", "self", ".", "_hs_color", "=", "(", "convert_scale", "(", "self", ".", "_device", ".", "status", ".", "hue", ",", "100", ",", "360", ")", ",", "self", ".", "_device", ".", "status", ".", "saturation", ",", ")" ]
[ 126, 4 ]
[ 143, 13 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.async_set_color
(self, hs_color)
Set the color of the device.
Set the color of the device.
async def async_set_color(self, hs_color): """Set the color of the device.""" hue = convert_scale(float(hs_color[0]), 360, 100) hue = max(min(hue, 100.0), 0.0) saturation = max(min(float(hs_color[1]), 100.0), 0.0) await self._device.set_color(hue, saturation, set_status=True)
[ "async", "def", "async_set_color", "(", "self", ",", "hs_color", ")", ":", "hue", "=", "convert_scale", "(", "float", "(", "hs_color", "[", "0", "]", ")", ",", "360", ",", "100", ")", "hue", "=", "max", "(", "min", "(", "hue", ",", "100.0", ")", ",", "0.0", ")", "saturation", "=", "max", "(", "min", "(", "float", "(", "hs_color", "[", "1", "]", ")", ",", "100.0", ")", ",", "0.0", ")", "await", "self", ".", "_device", ".", "set_color", "(", "hue", ",", "saturation", ",", "set_status", "=", "True", ")" ]
[ 145, 4 ]
[ 150, 70 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.async_set_color_temp
(self, value: float)
Set the color temperature of the device.
Set the color temperature of the device.
async def async_set_color_temp(self, value: float): """Set the color temperature of the device.""" kelvin = color_util.color_temperature_mired_to_kelvin(value) kelvin = max(min(kelvin, 30000.0), 1.0) await self._device.set_color_temperature(kelvin, set_status=True)
[ "async", "def", "async_set_color_temp", "(", "self", ",", "value", ":", "float", ")", ":", "kelvin", "=", "color_util", ".", "color_temperature_mired_to_kelvin", "(", "value", ")", "kelvin", "=", "max", "(", "min", "(", "kelvin", ",", "30000.0", ")", ",", "1.0", ")", "await", "self", ".", "_device", ".", "set_color_temperature", "(", "kelvin", ",", "set_status", "=", "True", ")" ]
[ 152, 4 ]
[ 156, 73 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.async_set_level
(self, brightness: int, transition: int)
Set the brightness of the light over transition.
Set the brightness of the light over transition.
async def async_set_level(self, brightness: int, transition: int): """Set the brightness of the light over transition.""" level = int(convert_scale(brightness, 255, 100, 0)) # Due to rounding, set level to 1 (one) so we don't inadvertently # turn off the light when a low brightness is set. level = 1 if level == 0 and brightness > 0 else level level = max(min(level, 100), 0) duration = int(transition) await self._device.set_level(level, duration, set_status=True)
[ "async", "def", "async_set_level", "(", "self", ",", "brightness", ":", "int", ",", "transition", ":", "int", ")", ":", "level", "=", "int", "(", "convert_scale", "(", "brightness", ",", "255", ",", "100", ",", "0", ")", ")", "# Due to rounding, set level to 1 (one) so we don't inadvertently", "# turn off the light when a low brightness is set.", "level", "=", "1", "if", "level", "==", "0", "and", "brightness", ">", "0", "else", "level", "level", "=", "max", "(", "min", "(", "level", ",", "100", ")", ",", "0", ")", "duration", "=", "int", "(", "transition", ")", "await", "self", ".", "_device", ".", "set_level", "(", "level", ",", "duration", ",", "set_status", "=", "True", ")" ]
[ 158, 4 ]
[ 166, 70 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.brightness
(self)
Return the brightness of this light between 0..255.
Return the brightness of this light between 0..255.
def brightness(self): """Return the brightness of this light between 0..255.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 169, 4 ]
[ 171, 31 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.color_temp
(self)
Return the CT color value in mireds.
Return the CT color value in mireds.
def color_temp(self): """Return the CT color value in mireds.""" return self._color_temp
[ "def", "color_temp", "(", "self", ")", ":", "return", "self", ".", "_color_temp" ]
[ 174, 4 ]
[ 176, 31 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.hs_color
(self)
Return the hue and saturation color value [float, float].
Return the hue and saturation color value [float, float].
def hs_color(self): """Return the hue and saturation color value [float, float].""" return self._hs_color
[ "def", "hs_color", "(", "self", ")", ":", "return", "self", ".", "_hs_color" ]
[ 179, 4 ]
[ 181, 29 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.is_on
(self)
Return true if light is on.
Return true if light is on.
def is_on(self) -> bool: """Return true if light is on.""" return self._device.status.switch
[ "def", "is_on", "(", "self", ")", "->", "bool", ":", "return", "self", ".", "_device", ".", "status", ".", "switch" ]
[ 184, 4 ]
[ 186, 41 ]
python
en
['en', 'et', 'en']
True
SmartThingsLight.max_mireds
(self)
Return the warmest color_temp that this light supports.
Return the warmest color_temp that this light supports.
def max_mireds(self): """Return the warmest color_temp that this light supports.""" # SmartThings does not expose this attribute, instead it's # implemented within each device-type handler. This value is the # lowest kelvin found supported across 20+ handlers. return 500
[ "def", "max_mireds", "(", "self", ")", ":", "# SmartThings does not expose this attribute, instead it's", "# implemented within each device-type handler. This value is the", "# lowest kelvin found supported across 20+ handlers.", "return", "500" ]
[ 189, 4 ]
[ 194, 18 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.min_mireds
(self)
Return the coldest color_temp that this light supports.
Return the coldest color_temp that this light supports.
def min_mireds(self): """Return the coldest color_temp that this light supports.""" # SmartThings does not expose this attribute, instead it's # implemented within each device-type handler. This value is the # highest kelvin found supported across 20+ handlers. return 111
[ "def", "min_mireds", "(", "self", ")", ":", "# SmartThings does not expose this attribute, instead it's", "# implemented within each device-type handler. This value is the", "# highest kelvin found supported across 20+ handlers.", "return", "111" ]
[ 197, 4 ]
[ 202, 18 ]
python
en
['en', 'en', 'en']
True
SmartThingsLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self) -> int: """Flag supported features.""" return self._supported_features
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "self", ".", "_supported_features" ]
[ 205, 4 ]
[ 207, 39 ]
python
en
['da', 'en', 'en']
True
setup_platform
(hass, config, add_entities, discovery_info=None)
Set up the Piglow Light platform.
Set up the Piglow Light platform.
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the Piglow Light platform.""" if subprocess.getoutput("i2cdetect -q -y 1 | grep -o 54") != "54": _LOGGER.error("A Piglow device was not found") return False name = config.get(CONF_NAME) add_entities([PiglowLight(name)])
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "if", "subprocess", ".", "getoutput", "(", "\"i2cdetect -q -y 1 | grep -o 54\"", ")", "!=", "\"54\"", ":", "_LOGGER", ".", "error", "(", "\"A Piglow device was not found\"", ")", "return", "False", "name", "=", "config", ".", "get", "(", "CONF_NAME", ")", "add_entities", "(", "[", "PiglowLight", "(", "name", ")", "]", ")" ]
[ 30, 0 ]
[ 38, 37 ]
python
en
['en', 'lv', 'en']
True
PiglowLight.__init__
(self, name)
Initialize an PiglowLight.
Initialize an PiglowLight.
def __init__(self, name): """Initialize an PiglowLight.""" self._name = name self._is_on = False self._brightness = 255 self._hs_color = [0, 0]
[ "def", "__init__", "(", "self", ",", "name", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_is_on", "=", "False", "self", ".", "_brightness", "=", "255", "self", ".", "_hs_color", "=", "[", "0", ",", "0", "]" ]
[ 44, 4 ]
[ 49, 31 ]
python
en
['en', 'pl', 'nl']
False
PiglowLight.name
(self)
Return the display name of this light.
Return the display name of this light.
def name(self): """Return the display name of this light.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 52, 4 ]
[ 54, 25 ]
python
en
['en', 'en', 'en']
True
PiglowLight.brightness
(self)
Return the brightness of the light.
Return the brightness of the light.
def brightness(self): """Return the brightness of the light.""" return self._brightness
[ "def", "brightness", "(", "self", ")", ":", "return", "self", ".", "_brightness" ]
[ 57, 4 ]
[ 59, 31 ]
python
en
['en', 'no', 'en']
True
PiglowLight.hs_color
(self)
Read back the color of the light.
Read back the color of the light.
def hs_color(self): """Read back the color of the light.""" return self._hs_color
[ "def", "hs_color", "(", "self", ")", ":", "return", "self", ".", "_hs_color" ]
[ 62, 4 ]
[ 64, 29 ]
python
en
['en', 'en', 'en']
True
PiglowLight.supported_features
(self)
Flag supported features.
Flag supported features.
def supported_features(self): """Flag supported features.""" return SUPPORT_PIGLOW
[ "def", "supported_features", "(", "self", ")", ":", "return", "SUPPORT_PIGLOW" ]
[ 67, 4 ]
[ 69, 29 ]
python
en
['da', 'en', 'en']
True
PiglowLight.should_poll
(self)
Return if we should poll this device.
Return if we should poll this device.
def should_poll(self): """Return if we should poll this device.""" return False
[ "def", "should_poll", "(", "self", ")", ":", "return", "False" ]
[ 72, 4 ]
[ 74, 20 ]
python
en
['en', 'en', 'en']
True
PiglowLight.assumed_state
(self)
Return True if unable to access real state of the entity.
Return True if unable to access real state of the entity.
def assumed_state(self) -> bool: """Return True if unable to access real state of the entity.""" return True
[ "def", "assumed_state", "(", "self", ")", "->", "bool", ":", "return", "True" ]
[ 77, 4 ]
[ 79, 19 ]
python
en
['en', 'en', 'en']
True
PiglowLight.is_on
(self)
Return true if light is on.
Return true if light is on.
def is_on(self): """Return true if light is on.""" return self._is_on
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_is_on" ]
[ 82, 4 ]
[ 84, 26 ]
python
en
['en', 'et', 'en']
True
PiglowLight.turn_on
(self, **kwargs)
Instruct the light to turn on.
Instruct the light to turn on.
def turn_on(self, **kwargs): """Instruct the light to turn on.""" piglow.clear() if ATTR_BRIGHTNESS in kwargs: self._brightness = kwargs[ATTR_BRIGHTNESS] if ATTR_HS_COLOR in kwargs: self._hs_color = kwargs[ATTR_HS_COLOR] rgb = color_util.color_hsv_to_RGB( self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100 ) piglow.red(rgb[0]) piglow.green(rgb[1]) piglow.blue(rgb[2]) piglow.show() self._is_on = True self.schedule_update_ha_state()
[ "def", "turn_on", "(", "self", ",", "*", "*", "kwargs", ")", ":", "piglow", ".", "clear", "(", ")", "if", "ATTR_BRIGHTNESS", "in", "kwargs", ":", "self", ".", "_brightness", "=", "kwargs", "[", "ATTR_BRIGHTNESS", "]", "if", "ATTR_HS_COLOR", "in", "kwargs", ":", "self", ".", "_hs_color", "=", "kwargs", "[", "ATTR_HS_COLOR", "]", "rgb", "=", "color_util", ".", "color_hsv_to_RGB", "(", "self", ".", "_hs_color", "[", "0", "]", ",", "self", ".", "_hs_color", "[", "1", "]", ",", "self", ".", "_brightness", "/", "255", "*", "100", ")", "piglow", ".", "red", "(", "rgb", "[", "0", "]", ")", "piglow", ".", "green", "(", "rgb", "[", "1", "]", ")", "piglow", ".", "blue", "(", "rgb", "[", "2", "]", ")", "piglow", ".", "show", "(", ")", "self", ".", "_is_on", "=", "True", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 86, 4 ]
[ 104, 39 ]
python
en
['en', 'en', 'en']
True
PiglowLight.turn_off
(self, **kwargs)
Instruct the light to turn off.
Instruct the light to turn off.
def turn_off(self, **kwargs): """Instruct the light to turn off.""" piglow.clear() piglow.show() self._is_on = False self.schedule_update_ha_state()
[ "def", "turn_off", "(", "self", ",", "*", "*", "kwargs", ")", ":", "piglow", ".", "clear", "(", ")", "piglow", ".", "show", "(", ")", "self", ".", "_is_on", "=", "False", "self", ".", "schedule_update_ha_state", "(", ")" ]
[ 106, 4 ]
[ 111, 39 ]
python
en
['en', 'en', 'en']
True
async_setup
(hass: HomeAssistant)
Set up the websocket API.
Set up the websocket API.
def async_setup(hass: HomeAssistant): """Set up the websocket API.""" websocket_api.async_register_command(hass, ws_list_blueprints) websocket_api.async_register_command(hass, ws_import_blueprint) websocket_api.async_register_command(hass, ws_save_blueprint) websocket_api.async_register_command(hass, ws_delete_blueprint)
[ "def", "async_setup", "(", "hass", ":", "HomeAssistant", ")", ":", "websocket_api", ".", "async_register_command", "(", "hass", ",", "ws_list_blueprints", ")", "websocket_api", ".", "async_register_command", "(", "hass", ",", "ws_import_blueprint", ")", "websocket_api", ".", "async_register_command", "(", "hass", ",", "ws_save_blueprint", ")", "websocket_api", ".", "async_register_command", "(", "hass", ",", "ws_delete_blueprint", ")" ]
[ 21, 0 ]
[ 26, 67 ]
python
en
['en', 'da', 'en']
True
ws_list_blueprints
(hass, connection, msg)
List available blueprints.
List available blueprints.
async def ws_list_blueprints(hass, connection, msg): """List available blueprints.""" domain_blueprints: Optional[Dict[str, models.DomainBlueprints]] = hass.data.get( DOMAIN, {} ) results = {} if msg["domain"] not in domain_blueprints: connection.send_result(msg["id"], results) return domain_results = await domain_blueprints[msg["domain"]].async_get_blueprints() for path, value in domain_results.items(): if isinstance(value, models.Blueprint): results[path] = { "metadata": value.metadata, } else: results[path] = {"error": str(value)} connection.send_result(msg["id"], results)
[ "async", "def", "ws_list_blueprints", "(", "hass", ",", "connection", ",", "msg", ")", ":", "domain_blueprints", ":", "Optional", "[", "Dict", "[", "str", ",", "models", ".", "DomainBlueprints", "]", "]", "=", "hass", ".", "data", ".", "get", "(", "DOMAIN", ",", "{", "}", ")", "results", "=", "{", "}", "if", "msg", "[", "\"domain\"", "]", "not", "in", "domain_blueprints", ":", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "results", ")", "return", "domain_results", "=", "await", "domain_blueprints", "[", "msg", "[", "\"domain\"", "]", "]", ".", "async_get_blueprints", "(", ")", "for", "path", ",", "value", "in", "domain_results", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "models", ".", "Blueprint", ")", ":", "results", "[", "path", "]", "=", "{", "\"metadata\"", ":", "value", ".", "metadata", ",", "}", "else", ":", "results", "[", "path", "]", "=", "{", "\"error\"", ":", "str", "(", "value", ")", "}", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "results", ")" ]
[ 36, 0 ]
[ 57, 46 ]
python
fr
['fr', 'fr', 'en']
True
ws_import_blueprint
(hass, connection, msg)
Import a blueprint.
Import a blueprint.
async def ws_import_blueprint(hass, connection, msg): """Import a blueprint.""" async with async_timeout.timeout(10): imported_blueprint = await importer.fetch_blueprint_from_url(hass, msg["url"]) if imported_blueprint is None: connection.send_error( msg["id"], websocket_api.ERR_NOT_SUPPORTED, "This url is not supported" ) return connection.send_result( msg["id"], { "url": imported_blueprint.url, "suggested_filename": imported_blueprint.suggested_filename, "raw_data": imported_blueprint.raw_data, "blueprint": { "metadata": imported_blueprint.blueprint.metadata, }, "validation_errors": imported_blueprint.blueprint.validate(), }, )
[ "async", "def", "ws_import_blueprint", "(", "hass", ",", "connection", ",", "msg", ")", ":", "async", "with", "async_timeout", ".", "timeout", "(", "10", ")", ":", "imported_blueprint", "=", "await", "importer", ".", "fetch_blueprint_from_url", "(", "hass", ",", "msg", "[", "\"url\"", "]", ")", "if", "imported_blueprint", "is", "None", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "websocket_api", ".", "ERR_NOT_SUPPORTED", ",", "\"This url is not supported\"", ")", "return", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", "{", "\"url\"", ":", "imported_blueprint", ".", "url", ",", "\"suggested_filename\"", ":", "imported_blueprint", ".", "suggested_filename", ",", "\"raw_data\"", ":", "imported_blueprint", ".", "raw_data", ",", "\"blueprint\"", ":", "{", "\"metadata\"", ":", "imported_blueprint", ".", "blueprint", ".", "metadata", ",", "}", ",", "\"validation_errors\"", ":", "imported_blueprint", ".", "blueprint", ".", "validate", "(", ")", ",", "}", ",", ")" ]
[ 67, 0 ]
[ 89, 5 ]
python
en
['en', 'hu', 'en']
True
ws_save_blueprint
(hass, connection, msg)
Save a blueprint.
Save a blueprint.
async def ws_save_blueprint(hass, connection, msg): """Save a blueprint.""" path = msg["path"] domain = msg["domain"] domain_blueprints: Optional[Dict[str, models.DomainBlueprints]] = hass.data.get( DOMAIN, {} ) if domain not in domain_blueprints: connection.send_error( msg["id"], websocket_api.ERR_INVALID_FORMAT, "Unsupported domain" ) try: blueprint = models.Blueprint( yaml.parse_yaml(msg["yaml"]), expected_domain=domain ) if "source_url" in msg: blueprint.update_metadata(source_url=msg["source_url"]) except HomeAssistantError as err: connection.send_error(msg["id"], websocket_api.ERR_INVALID_FORMAT, str(err)) return try: await domain_blueprints[domain].async_add_blueprint(blueprint, path) except FileAlreadyExists: connection.send_error(msg["id"], "already_exists", "File already exists") return except OSError as err: connection.send_error(msg["id"], websocket_api.ERR_UNKNOWN_ERROR, str(err)) return connection.send_result( msg["id"], )
[ "async", "def", "ws_save_blueprint", "(", "hass", ",", "connection", ",", "msg", ")", ":", "path", "=", "msg", "[", "\"path\"", "]", "domain", "=", "msg", "[", "\"domain\"", "]", "domain_blueprints", ":", "Optional", "[", "Dict", "[", "str", ",", "models", ".", "DomainBlueprints", "]", "]", "=", "hass", ".", "data", ".", "get", "(", "DOMAIN", ",", "{", "}", ")", "if", "domain", "not", "in", "domain_blueprints", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "websocket_api", ".", "ERR_INVALID_FORMAT", ",", "\"Unsupported domain\"", ")", "try", ":", "blueprint", "=", "models", ".", "Blueprint", "(", "yaml", ".", "parse_yaml", "(", "msg", "[", "\"yaml\"", "]", ")", ",", "expected_domain", "=", "domain", ")", "if", "\"source_url\"", "in", "msg", ":", "blueprint", ".", "update_metadata", "(", "source_url", "=", "msg", "[", "\"source_url\"", "]", ")", "except", "HomeAssistantError", "as", "err", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "websocket_api", ".", "ERR_INVALID_FORMAT", ",", "str", "(", "err", ")", ")", "return", "try", ":", "await", "domain_blueprints", "[", "domain", "]", ".", "async_add_blueprint", "(", "blueprint", ",", "path", ")", "except", "FileAlreadyExists", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "\"already_exists\"", ",", "\"File already exists\"", ")", "return", "except", "OSError", "as", "err", ":", "connection", ".", "send_error", "(", "msg", "[", "\"id\"", "]", ",", "websocket_api", ".", "ERR_UNKNOWN_ERROR", ",", "str", "(", "err", ")", ")", "return", "connection", ".", "send_result", "(", "msg", "[", "\"id\"", "]", ",", ")" ]
[ 102, 0 ]
[ 138, 5 ]
python
en
['en', 'lb', 'en']
True