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
toggle
(hass, entity_id)
Toggle the script. This is a legacy helper method. Do not use it for new tests.
Toggle the script.
def toggle(hass, entity_id): """Toggle the script. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: entity_id})
[ "def", "toggle", "(", "hass", ",", "entity_id", ")", ":", "hass", ".", "services", ".", "call", "(", "DOMAIN", ",", "SERVICE_TOGGLE", ",", "{", "ATTR_ENTITY_ID", ":", "entity_id", "}", ")" ]
[ 53, 0 ]
[ 58, 75 ]
python
en
['en', 'it', 'en']
True
reload
(hass)
Reload script component. This is a legacy helper method. Do not use it for new tests.
Reload script component.
def reload(hass): """Reload script component. This is a legacy helper method. Do not use it for new tests. """ hass.services.call(DOMAIN, SERVICE_RELOAD)
[ "def", "reload", "(", "hass", ")", ":", "hass", ".", "services", ".", "call", "(", "DOMAIN", ",", "SERVICE_RELOAD", ")" ]
[ 62, 0 ]
[ 67, 46 ]
python
ca
['de', 'ca', 'en']
False
test_turn_on_off_toggle
(hass, toggle)
Verify turn_on, turn_off & toggle services.
Verify turn_on, turn_off & toggle services.
async def test_turn_on_off_toggle(hass, toggle): """Verify turn_on, turn_off & toggle services.""" event = "test_event" event_mock = Mock() hass.bus.async_listen(event, event_mock) was_on = False @callback def state_listener(entity_id, old_state, new_state): nonlocal was_on was_on = True async_track_state_change(hass, ENTITY_ID, state_listener, to_state="on") if toggle: turn_off_step = {"service": "script.toggle", "entity_id": ENTITY_ID} else: turn_off_step = {"service": "script.turn_off", "entity_id": ENTITY_ID} assert await async_setup_component( hass, "script", { "script": { "test": { "sequence": [{"event": event}, turn_off_step, {"event": event}] } } }, ) assert not script.is_on(hass, ENTITY_ID) if toggle: await hass.services.async_call( DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: ENTITY_ID} ) else: await hass.services.async_call(DOMAIN, split_entity_id(ENTITY_ID)[1]) await hass.async_block_till_done() assert not script.is_on(hass, ENTITY_ID) assert was_on assert 1 == event_mock.call_count
[ "async", "def", "test_turn_on_off_toggle", "(", "hass", ",", "toggle", ")", ":", "event", "=", "\"test_event\"", "event_mock", "=", "Mock", "(", ")", "hass", ".", "bus", ".", "async_listen", "(", "event", ",", "event_mock", ")", "was_on", "=", "False", "@", "callback", "def", "state_listener", "(", "entity_id", ",", "old_state", ",", "new_state", ")", ":", "nonlocal", "was_on", "was_on", "=", "True", "async_track_state_change", "(", "hass", ",", "ENTITY_ID", ",", "state_listener", ",", "to_state", "=", "\"on\"", ")", "if", "toggle", ":", "turn_off_step", "=", "{", "\"service\"", ":", "\"script.toggle\"", ",", "\"entity_id\"", ":", "ENTITY_ID", "}", "else", ":", "turn_off_step", "=", "{", "\"service\"", ":", "\"script.turn_off\"", ",", "\"entity_id\"", ":", "ENTITY_ID", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"test\"", ":", "{", "\"sequence\"", ":", "[", "{", "\"event\"", ":", "event", "}", ",", "turn_off_step", ",", "{", "\"event\"", ":", "event", "}", "]", "}", "}", "}", ",", ")", "assert", "not", "script", ".", "is_on", "(", "hass", ",", "ENTITY_ID", ")", "if", "toggle", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_TOGGLE", ",", "{", "ATTR_ENTITY_ID", ":", "ENTITY_ID", "}", ")", "else", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "split_entity_id", "(", "ENTITY_ID", ")", "[", "1", "]", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "script", ".", "is_on", "(", "hass", ",", "ENTITY_ID", ")", "assert", "was_on", "assert", "1", "==", "event_mock", ".", "call_count" ]
[ 131, 0 ]
[ 175, 37 ]
python
en
['en', 'en', 'en']
True
test_setup_with_invalid_configs
(hass, value)
Test setup with invalid configs.
Test setup with invalid configs.
async def test_setup_with_invalid_configs(hass, value): """Test setup with invalid configs.""" assert await async_setup_component( hass, "script", {"script": value} ), f"Script loaded with wrong config {value}" assert 0 == len(hass.states.async_entity_ids("script"))
[ "async", "def", "test_setup_with_invalid_configs", "(", "hass", ",", "value", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "value", "}", ")", ",", "f\"Script loaded with wrong config {value}\"", "assert", "0", "==", "len", "(", "hass", ".", "states", ".", "async_entity_ids", "(", "\"script\"", ")", ")" ]
[ 186, 0 ]
[ 192, 59 ]
python
en
['en', 'en', 'en']
True
test_reload_service
(hass, running)
Verify the reload service.
Verify the reload service.
async def test_reload_service(hass, running): """Verify the reload service.""" event = "test_event" event_flag = asyncio.Event() @callback def event_handler(event): event_flag.set() hass.bus.async_listen_once(event, event_handler) hass.states.async_set("test.script", "off") assert await async_setup_component( hass, "script", { "script": { "test": { "sequence": [ {"event": event}, {"wait_template": "{{ is_state('test.script', 'on') }}"}, ] } } }, ) assert hass.states.get(ENTITY_ID) is not None assert hass.services.has_service(script.DOMAIN, "test") if running != "no": _, object_id = split_entity_id(ENTITY_ID) await hass.services.async_call(DOMAIN, object_id) await asyncio.wait_for(event_flag.wait(), 1) assert script.is_on(hass, ENTITY_ID) object_id = "test" if running == "same" else "test2" with patch( "homeassistant.config.load_yaml_config_file", return_value={"script": {object_id: {"sequence": [{"delay": {"seconds": 5}}]}}}, ): await hass.services.async_call(DOMAIN, SERVICE_RELOAD, blocking=True) await hass.async_block_till_done() if running != "same": assert hass.states.get(ENTITY_ID) is None assert not hass.services.has_service(script.DOMAIN, "test") assert hass.states.get("script.test2") is not None assert hass.services.has_service(script.DOMAIN, "test2") else: assert hass.states.get(ENTITY_ID) is not None assert hass.services.has_service(script.DOMAIN, "test")
[ "async", "def", "test_reload_service", "(", "hass", ",", "running", ")", ":", "event", "=", "\"test_event\"", "event_flag", "=", "asyncio", ".", "Event", "(", ")", "@", "callback", "def", "event_handler", "(", "event", ")", ":", "event_flag", ".", "set", "(", ")", "hass", ".", "bus", ".", "async_listen_once", "(", "event", ",", "event_handler", ")", "hass", ".", "states", ".", "async_set", "(", "\"test.script\"", ",", "\"off\"", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"test\"", ":", "{", "\"sequence\"", ":", "[", "{", "\"event\"", ":", "event", "}", ",", "{", "\"wait_template\"", ":", "\"{{ is_state('test.script', 'on') }}\"", "}", ",", "]", "}", "}", "}", ",", ")", "assert", "hass", ".", "states", ".", "get", "(", "ENTITY_ID", ")", "is", "not", "None", "assert", "hass", ".", "services", ".", "has_service", "(", "script", ".", "DOMAIN", ",", "\"test\"", ")", "if", "running", "!=", "\"no\"", ":", "_", ",", "object_id", "=", "split_entity_id", "(", "ENTITY_ID", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "object_id", ")", "await", "asyncio", ".", "wait_for", "(", "event_flag", ".", "wait", "(", ")", ",", "1", ")", "assert", "script", ".", "is_on", "(", "hass", ",", "ENTITY_ID", ")", "object_id", "=", "\"test\"", "if", "running", "==", "\"same\"", "else", "\"test2\"", "with", "patch", "(", "\"homeassistant.config.load_yaml_config_file\"", ",", "return_value", "=", "{", "\"script\"", ":", "{", "object_id", ":", "{", "\"sequence\"", ":", "[", "{", "\"delay\"", ":", "{", "\"seconds\"", ":", "5", "}", "}", "]", "}", "}", "}", ",", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_RELOAD", ",", "blocking", "=", "True", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "if", "running", "!=", "\"same\"", ":", "assert", "hass", ".", "states", ".", "get", "(", "ENTITY_ID", ")", "is", "None", "assert", "not", "hass", ".", "services", ".", "has_service", "(", "script", ".", "DOMAIN", ",", "\"test\"", ")", "assert", "hass", ".", "states", ".", "get", "(", "\"script.test2\"", ")", "is", "not", "None", "assert", "hass", ".", "services", ".", "has_service", "(", "script", ".", "DOMAIN", ",", "\"test2\"", ")", "else", ":", "assert", "hass", ".", "states", ".", "get", "(", "ENTITY_ID", ")", "is", "not", "None", "assert", "hass", ".", "services", ".", "has_service", "(", "script", ".", "DOMAIN", ",", "\"test\"", ")" ]
[ 196, 0 ]
[ 250, 63 ]
python
en
['en', 'en', 'en']
True
test_service_descriptions
(hass)
Test that service descriptions are loaded and reloaded correctly.
Test that service descriptions are loaded and reloaded correctly.
async def test_service_descriptions(hass): """Test that service descriptions are loaded and reloaded correctly.""" # Test 1: has "description" but no "fields" assert await async_setup_component( hass, "script", { "script": { "test": { "description": "test description", "sequence": [{"delay": {"seconds": 5}}], } } }, ) descriptions = await async_get_all_descriptions(hass) assert descriptions[DOMAIN]["test"]["description"] == "test description" assert not descriptions[DOMAIN]["test"]["fields"] # Test 2: has "fields" but no "description" with patch( "homeassistant.config.load_yaml_config_file", return_value={ "script": { "test": { "fields": { "test_param": { "description": "test_param description", "example": "test_param example", } }, "sequence": [{"delay": {"seconds": 5}}], } } }, ): await hass.services.async_call(DOMAIN, SERVICE_RELOAD, blocking=True) descriptions = await async_get_all_descriptions(hass) assert descriptions[script.DOMAIN]["test"]["description"] == "" assert ( descriptions[script.DOMAIN]["test"]["fields"]["test_param"]["description"] == "test_param description" ) assert ( descriptions[script.DOMAIN]["test"]["fields"]["test_param"]["example"] == "test_param example" )
[ "async", "def", "test_service_descriptions", "(", "hass", ")", ":", "# Test 1: has \"description\" but no \"fields\"", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"test\"", ":", "{", "\"description\"", ":", "\"test description\"", ",", "\"sequence\"", ":", "[", "{", "\"delay\"", ":", "{", "\"seconds\"", ":", "5", "}", "}", "]", ",", "}", "}", "}", ",", ")", "descriptions", "=", "await", "async_get_all_descriptions", "(", "hass", ")", "assert", "descriptions", "[", "DOMAIN", "]", "[", "\"test\"", "]", "[", "\"description\"", "]", "==", "\"test description\"", "assert", "not", "descriptions", "[", "DOMAIN", "]", "[", "\"test\"", "]", "[", "\"fields\"", "]", "# Test 2: has \"fields\" but no \"description\"", "with", "patch", "(", "\"homeassistant.config.load_yaml_config_file\"", ",", "return_value", "=", "{", "\"script\"", ":", "{", "\"test\"", ":", "{", "\"fields\"", ":", "{", "\"test_param\"", ":", "{", "\"description\"", ":", "\"test_param description\"", ",", "\"example\"", ":", "\"test_param example\"", ",", "}", "}", ",", "\"sequence\"", ":", "[", "{", "\"delay\"", ":", "{", "\"seconds\"", ":", "5", "}", "}", "]", ",", "}", "}", "}", ",", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_RELOAD", ",", "blocking", "=", "True", ")", "descriptions", "=", "await", "async_get_all_descriptions", "(", "hass", ")", "assert", "descriptions", "[", "script", ".", "DOMAIN", "]", "[", "\"test\"", "]", "[", "\"description\"", "]", "==", "\"\"", "assert", "(", "descriptions", "[", "script", ".", "DOMAIN", "]", "[", "\"test\"", "]", "[", "\"fields\"", "]", "[", "\"test_param\"", "]", "[", "\"description\"", "]", "==", "\"test_param description\"", ")", "assert", "(", "descriptions", "[", "script", ".", "DOMAIN", "]", "[", "\"test\"", "]", "[", "\"fields\"", "]", "[", "\"test_param\"", "]", "[", "\"example\"", "]", "==", "\"test_param example\"", ")" ]
[ 253, 0 ]
[ 303, 5 ]
python
en
['en', 'en', 'en']
True
test_shared_context
(hass)
Test that the shared context is passed down the chain.
Test that the shared context is passed down the chain.
async def test_shared_context(hass): """Test that the shared context is passed down the chain.""" event = "test_event" context = Context() event_mock = Mock() run_mock = Mock() hass.bus.async_listen(event, event_mock) hass.bus.async_listen(EVENT_SCRIPT_STARTED, run_mock) assert await async_setup_component( hass, "script", {"script": {"test": {"sequence": [{"event": event}]}}} ) await hass.services.async_call( DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ENTITY_ID}, context=context ) await hass.async_block_till_done() assert event_mock.call_count == 1 assert run_mock.call_count == 1 args, kwargs = run_mock.call_args assert args[0].context == context # Ensure event data has all attributes set assert args[0].data.get(ATTR_NAME) == "test" assert args[0].data.get(ATTR_ENTITY_ID) == "script.test" # Ensure context carries through the event args, kwargs = event_mock.call_args assert args[0].context == context # Ensure the script state shares the same context state = hass.states.get("script.test") assert state is not None assert state.context == context
[ "async", "def", "test_shared_context", "(", "hass", ")", ":", "event", "=", "\"test_event\"", "context", "=", "Context", "(", ")", "event_mock", "=", "Mock", "(", ")", "run_mock", "=", "Mock", "(", ")", "hass", ".", "bus", ".", "async_listen", "(", "event", ",", "event_mock", ")", "hass", ".", "bus", ".", "async_listen", "(", "EVENT_SCRIPT_STARTED", ",", "run_mock", ")", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"test\"", ":", "{", "\"sequence\"", ":", "[", "{", "\"event\"", ":", "event", "}", "]", "}", "}", "}", ")", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_TURN_ON", ",", "{", "ATTR_ENTITY_ID", ":", "ENTITY_ID", "}", ",", "context", "=", "context", ")", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "event_mock", ".", "call_count", "==", "1", "assert", "run_mock", ".", "call_count", "==", "1", "args", ",", "kwargs", "=", "run_mock", ".", "call_args", "assert", "args", "[", "0", "]", ".", "context", "==", "context", "# Ensure event data has all attributes set", "assert", "args", "[", "0", "]", ".", "data", ".", "get", "(", "ATTR_NAME", ")", "==", "\"test\"", "assert", "args", "[", "0", "]", ".", "data", ".", "get", "(", "ATTR_ENTITY_ID", ")", "==", "\"script.test\"", "# Ensure context carries through the event", "args", ",", "kwargs", "=", "event_mock", ".", "call_args", "assert", "args", "[", "0", "]", ".", "context", "==", "context", "# Ensure the script state shares the same context", "state", "=", "hass", ".", "states", ".", "get", "(", "\"script.test\"", ")", "assert", "state", "is", "not", "None", "assert", "state", ".", "context", "==", "context" ]
[ 306, 0 ]
[ 342, 35 ]
python
en
['en', 'en', 'en']
True
test_logging_script_error
(hass, caplog)
Test logging script error.
Test logging script error.
async def test_logging_script_error(hass, caplog): """Test logging script error.""" assert await async_setup_component( hass, "script", {"script": {"hello": {"sequence": [{"service": "non.existing"}]}}}, ) with pytest.raises(ServiceNotFound) as err: await hass.services.async_call("script", "hello", blocking=True) assert err.value.domain == "non" assert err.value.service == "existing" assert "Error executing script" in caplog.text
[ "async", "def", "test_logging_script_error", "(", "hass", ",", "caplog", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"hello\"", ":", "{", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"non.existing\"", "}", "]", "}", "}", "}", ",", ")", "with", "pytest", ".", "raises", "(", "ServiceNotFound", ")", "as", "err", ":", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"hello\"", ",", "blocking", "=", "True", ")", "assert", "err", ".", "value", ".", "domain", "==", "\"non\"", "assert", "err", ".", "value", ".", "service", "==", "\"existing\"", "assert", "\"Error executing script\"", "in", "caplog", ".", "text" ]
[ 345, 0 ]
[ 357, 50 ]
python
en
['nb', 'la', 'en']
False
test_turning_no_scripts_off
(hass)
Test it is possible to turn two scripts off.
Test it is possible to turn two scripts off.
async def test_turning_no_scripts_off(hass): """Test it is possible to turn two scripts off.""" assert await async_setup_component(hass, "script", {}) # Testing it doesn't raise await hass.services.async_call( DOMAIN, SERVICE_TURN_OFF, {"entity_id": []}, blocking=True )
[ "async", "def", "test_turning_no_scripts_off", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "}", ")", "# Testing it doesn't raise", "await", "hass", ".", "services", ".", "async_call", "(", "DOMAIN", ",", "SERVICE_TURN_OFF", ",", "{", "\"entity_id\"", ":", "[", "]", "}", ",", "blocking", "=", "True", ")" ]
[ 360, 0 ]
[ 367, 5 ]
python
en
['en', 'en', 'en']
True
test_async_get_descriptions_script
(hass)
Test async_set_service_schema for the script integration.
Test async_set_service_schema for the script integration.
async def test_async_get_descriptions_script(hass): """Test async_set_service_schema for the script integration.""" script_config = { DOMAIN: { "test1": {"sequence": [{"service": "homeassistant.restart"}]}, "test2": { "description": "test2", "fields": { "param": { "description": "param_description", "example": "param_example", } }, "sequence": [{"service": "homeassistant.restart"}], }, } } await async_setup_component(hass, DOMAIN, script_config) descriptions = await hass.helpers.service.async_get_all_descriptions() assert descriptions[DOMAIN]["test1"]["description"] == "" assert not descriptions[DOMAIN]["test1"]["fields"] assert descriptions[DOMAIN]["test2"]["description"] == "test2" assert ( descriptions[DOMAIN]["test2"]["fields"]["param"]["description"] == "param_description" ) assert ( descriptions[DOMAIN]["test2"]["fields"]["param"]["example"] == "param_example" )
[ "async", "def", "test_async_get_descriptions_script", "(", "hass", ")", ":", "script_config", "=", "{", "DOMAIN", ":", "{", "\"test1\"", ":", "{", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"homeassistant.restart\"", "}", "]", "}", ",", "\"test2\"", ":", "{", "\"description\"", ":", "\"test2\"", ",", "\"fields\"", ":", "{", "\"param\"", ":", "{", "\"description\"", ":", "\"param_description\"", ",", "\"example\"", ":", "\"param_example\"", ",", "}", "}", ",", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"homeassistant.restart\"", "}", "]", ",", "}", ",", "}", "}", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "script_config", ")", "descriptions", "=", "await", "hass", ".", "helpers", ".", "service", ".", "async_get_all_descriptions", "(", ")", "assert", "descriptions", "[", "DOMAIN", "]", "[", "\"test1\"", "]", "[", "\"description\"", "]", "==", "\"\"", "assert", "not", "descriptions", "[", "DOMAIN", "]", "[", "\"test1\"", "]", "[", "\"fields\"", "]", "assert", "descriptions", "[", "DOMAIN", "]", "[", "\"test2\"", "]", "[", "\"description\"", "]", "==", "\"test2\"", "assert", "(", "descriptions", "[", "DOMAIN", "]", "[", "\"test2\"", "]", "[", "\"fields\"", "]", "[", "\"param\"", "]", "[", "\"description\"", "]", "==", "\"param_description\"", ")", "assert", "(", "descriptions", "[", "DOMAIN", "]", "[", "\"test2\"", "]", "[", "\"fields\"", "]", "[", "\"param\"", "]", "[", "\"example\"", "]", "==", "\"param_example\"", ")" ]
[ 370, 0 ]
[ 401, 5 ]
python
en
['en', 'fr', 'en']
True
test_extraction_functions
(hass)
Test extraction functions.
Test extraction functions.
async def test_extraction_functions(hass): """Test extraction functions.""" assert await async_setup_component( hass, DOMAIN, { DOMAIN: { "test1": { "sequence": [ { "service": "test.script", "data": {"entity_id": "light.in_both"}, }, { "service": "test.script", "data": {"entity_id": "light.in_first"}, }, { "entity_id": "light.device_in_both", "domain": "light", "type": "turn_on", "device_id": "device-in-both", }, ] }, "test2": { "sequence": [ { "service": "test.script", "data": {"entity_id": "light.in_both"}, }, { "condition": "state", "entity_id": "sensor.condition", "state": "100", }, {"scene": "scene.hello"}, { "entity_id": "light.device_in_both", "domain": "light", "type": "turn_on", "device_id": "device-in-both", }, { "entity_id": "light.device_in_last", "domain": "light", "type": "turn_on", "device_id": "device-in-last", }, ], }, } }, ) assert set(script.scripts_with_entity(hass, "light.in_both")) == { "script.test1", "script.test2", } assert set(script.entities_in_script(hass, "script.test1")) == { "light.in_both", "light.in_first", } assert set(script.scripts_with_device(hass, "device-in-both")) == { "script.test1", "script.test2", } assert set(script.devices_in_script(hass, "script.test2")) == { "device-in-both", "device-in-last", }
[ "async", "def", "test_extraction_functions", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "DOMAIN", ":", "{", "\"test1\"", ":", "{", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"entity_id\"", ":", "\"light.in_both\"", "}", ",", "}", ",", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"entity_id\"", ":", "\"light.in_first\"", "}", ",", "}", ",", "{", "\"entity_id\"", ":", "\"light.device_in_both\"", ",", "\"domain\"", ":", "\"light\"", ",", "\"type\"", ":", "\"turn_on\"", ",", "\"device_id\"", ":", "\"device-in-both\"", ",", "}", ",", "]", "}", ",", "\"test2\"", ":", "{", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"entity_id\"", ":", "\"light.in_both\"", "}", ",", "}", ",", "{", "\"condition\"", ":", "\"state\"", ",", "\"entity_id\"", ":", "\"sensor.condition\"", ",", "\"state\"", ":", "\"100\"", ",", "}", ",", "{", "\"scene\"", ":", "\"scene.hello\"", "}", ",", "{", "\"entity_id\"", ":", "\"light.device_in_both\"", ",", "\"domain\"", ":", "\"light\"", ",", "\"type\"", ":", "\"turn_on\"", ",", "\"device_id\"", ":", "\"device-in-both\"", ",", "}", ",", "{", "\"entity_id\"", ":", "\"light.device_in_last\"", ",", "\"domain\"", ":", "\"light\"", ",", "\"type\"", ":", "\"turn_on\"", ",", "\"device_id\"", ":", "\"device-in-last\"", ",", "}", ",", "]", ",", "}", ",", "}", "}", ",", ")", "assert", "set", "(", "script", ".", "scripts_with_entity", "(", "hass", ",", "\"light.in_both\"", ")", ")", "==", "{", "\"script.test1\"", ",", "\"script.test2\"", ",", "}", "assert", "set", "(", "script", ".", "entities_in_script", "(", "hass", ",", "\"script.test1\"", ")", ")", "==", "{", "\"light.in_both\"", ",", "\"light.in_first\"", ",", "}", "assert", "set", "(", "script", ".", "scripts_with_device", "(", "hass", ",", "\"device-in-both\"", ")", ")", "==", "{", "\"script.test1\"", ",", "\"script.test2\"", ",", "}", "assert", "set", "(", "script", ".", "devices_in_script", "(", "hass", ",", "\"script.test2\"", ")", ")", "==", "{", "\"device-in-both\"", ",", "\"device-in-last\"", ",", "}" ]
[ 404, 0 ]
[ 474, 5 ]
python
en
['en', 'en', 'en']
True
test_config_basic
(hass)
Test passing info in config.
Test passing info in config.
async def test_config_basic(hass): """Test passing info in config.""" assert await async_setup_component( hass, "script", { "script": { "test_script": { "alias": "Script Name", "icon": "mdi:party", "sequence": [], } } }, ) test_script = hass.states.get("script.test_script") assert test_script.name == "Script Name" assert test_script.attributes["icon"] == "mdi:party"
[ "async", "def", "test_config_basic", "(", "hass", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"test_script\"", ":", "{", "\"alias\"", ":", "\"Script Name\"", ",", "\"icon\"", ":", "\"mdi:party\"", ",", "\"sequence\"", ":", "[", "]", ",", "}", "}", "}", ",", ")", "test_script", "=", "hass", ".", "states", ".", "get", "(", "\"script.test_script\"", ")", "assert", "test_script", ".", "name", "==", "\"Script Name\"", "assert", "test_script", ".", "attributes", "[", "\"icon\"", "]", "==", "\"mdi:party\"" ]
[ 477, 0 ]
[ 495, 56 ]
python
en
['en', 'en', 'en']
True
test_logbook_humanify_script_started_event
(hass)
Test humanifying script started event.
Test humanifying script started event.
async def test_logbook_humanify_script_started_event(hass): """Test humanifying script started event.""" hass.config.components.add("recorder") await async_setup_component(hass, DOMAIN, {}) await async_setup_component(hass, "logbook", {}) entity_attr_cache = logbook.EntityAttributeCache(hass) event1, event2 = list( logbook.humanify( hass, [ MockLazyEventPartialState( EVENT_SCRIPT_STARTED, {ATTR_ENTITY_ID: "script.hello", ATTR_NAME: "Hello Script"}, ), MockLazyEventPartialState( EVENT_SCRIPT_STARTED, {ATTR_ENTITY_ID: "script.bye", ATTR_NAME: "Bye Script"}, ), ], entity_attr_cache, {}, ) ) assert event1["name"] == "Hello Script" assert event1["domain"] == "script" assert event1["message"] == "started" assert event1["entity_id"] == "script.hello" assert event2["name"] == "Bye Script" assert event2["domain"] == "script" assert event2["message"] == "started" assert event2["entity_id"] == "script.bye"
[ "async", "def", "test_logbook_humanify_script_started_event", "(", "hass", ")", ":", "hass", ".", "config", ".", "components", ".", "add", "(", "\"recorder\"", ")", "await", "async_setup_component", "(", "hass", ",", "DOMAIN", ",", "{", "}", ")", "await", "async_setup_component", "(", "hass", ",", "\"logbook\"", ",", "{", "}", ")", "entity_attr_cache", "=", "logbook", ".", "EntityAttributeCache", "(", "hass", ")", "event1", ",", "event2", "=", "list", "(", "logbook", ".", "humanify", "(", "hass", ",", "[", "MockLazyEventPartialState", "(", "EVENT_SCRIPT_STARTED", ",", "{", "ATTR_ENTITY_ID", ":", "\"script.hello\"", ",", "ATTR_NAME", ":", "\"Hello Script\"", "}", ",", ")", ",", "MockLazyEventPartialState", "(", "EVENT_SCRIPT_STARTED", ",", "{", "ATTR_ENTITY_ID", ":", "\"script.bye\"", ",", "ATTR_NAME", ":", "\"Bye Script\"", "}", ",", ")", ",", "]", ",", "entity_attr_cache", ",", "{", "}", ",", ")", ")", "assert", "event1", "[", "\"name\"", "]", "==", "\"Hello Script\"", "assert", "event1", "[", "\"domain\"", "]", "==", "\"script\"", "assert", "event1", "[", "\"message\"", "]", "==", "\"started\"", "assert", "event1", "[", "\"entity_id\"", "]", "==", "\"script.hello\"", "assert", "event2", "[", "\"name\"", "]", "==", "\"Bye Script\"", "assert", "event2", "[", "\"domain\"", "]", "==", "\"script\"", "assert", "event2", "[", "\"message\"", "]", "==", "\"started\"", "assert", "event2", "[", "\"entity_id\"", "]", "==", "\"script.bye\"" ]
[ 498, 0 ]
[ 531, 46 ]
python
en
['en', 'en', 'en']
True
test_concurrent_script
(hass, concurrently)
Test calling script concurrently or not.
Test calling script concurrently or not.
async def test_concurrent_script(hass, concurrently): """Test calling script concurrently or not.""" if concurrently: call_script_2 = { "service": "script.turn_on", "data": {"entity_id": "script.script2"}, } else: call_script_2 = {"service": "script.script2"} assert await async_setup_component( hass, "script", { "script": { "script1": { "mode": "parallel", "sequence": [ call_script_2, { "wait_template": "{{ is_state('input_boolean.test1', 'on') }}" }, {"service": "test.script", "data": {"value": "script1"}}, ], }, "script2": { "mode": "parallel", "sequence": [ {"service": "test.script", "data": {"value": "script2a"}}, { "wait_template": "{{ is_state('input_boolean.test2', 'on') }}" }, {"service": "test.script", "data": {"value": "script2b"}}, ], }, } }, ) service_called = asyncio.Event() service_values = [] async def async_service_handler(service): nonlocal service_values service_values.append(service.data.get("value")) service_called.set() hass.services.async_register("test", "script", async_service_handler) hass.states.async_set("input_boolean.test1", "off") hass.states.async_set("input_boolean.test2", "off") await hass.services.async_call("script", "script1") await asyncio.wait_for(service_called.wait(), 1) service_called.clear() assert "script2a" == service_values[-1] assert script.is_on(hass, "script.script1") assert script.is_on(hass, "script.script2") if not concurrently: hass.states.async_set("input_boolean.test2", "on") await asyncio.wait_for(service_called.wait(), 1) service_called.clear() assert "script2b" == service_values[-1] hass.states.async_set("input_boolean.test1", "on") await asyncio.wait_for(service_called.wait(), 1) service_called.clear() assert "script1" == service_values[-1] assert concurrently == script.is_on(hass, "script.script2") if concurrently: hass.states.async_set("input_boolean.test2", "on") await asyncio.wait_for(service_called.wait(), 1) service_called.clear() assert "script2b" == service_values[-1] await hass.async_block_till_done() assert not script.is_on(hass, "script.script1") assert not script.is_on(hass, "script.script2")
[ "async", "def", "test_concurrent_script", "(", "hass", ",", "concurrently", ")", ":", "if", "concurrently", ":", "call_script_2", "=", "{", "\"service\"", ":", "\"script.turn_on\"", ",", "\"data\"", ":", "{", "\"entity_id\"", ":", "\"script.script2\"", "}", ",", "}", "else", ":", "call_script_2", "=", "{", "\"service\"", ":", "\"script.script2\"", "}", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"script1\"", ":", "{", "\"mode\"", ":", "\"parallel\"", ",", "\"sequence\"", ":", "[", "call_script_2", ",", "{", "\"wait_template\"", ":", "\"{{ is_state('input_boolean.test1', 'on') }}\"", "}", ",", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"value\"", ":", "\"script1\"", "}", "}", ",", "]", ",", "}", ",", "\"script2\"", ":", "{", "\"mode\"", ":", "\"parallel\"", ",", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"value\"", ":", "\"script2a\"", "}", "}", ",", "{", "\"wait_template\"", ":", "\"{{ is_state('input_boolean.test2', 'on') }}\"", "}", ",", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"value\"", ":", "\"script2b\"", "}", "}", ",", "]", ",", "}", ",", "}", "}", ",", ")", "service_called", "=", "asyncio", ".", "Event", "(", ")", "service_values", "=", "[", "]", "async", "def", "async_service_handler", "(", "service", ")", ":", "nonlocal", "service_values", "service_values", ".", "append", "(", "service", ".", "data", ".", "get", "(", "\"value\"", ")", ")", "service_called", ".", "set", "(", ")", "hass", ".", "services", ".", "async_register", "(", "\"test\"", ",", "\"script\"", ",", "async_service_handler", ")", "hass", ".", "states", ".", "async_set", "(", "\"input_boolean.test1\"", ",", "\"off\"", ")", "hass", ".", "states", ".", "async_set", "(", "\"input_boolean.test2\"", ",", "\"off\"", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"script1\"", ")", "await", "asyncio", ".", "wait_for", "(", "service_called", ".", "wait", "(", ")", ",", "1", ")", "service_called", ".", "clear", "(", ")", "assert", "\"script2a\"", "==", "service_values", "[", "-", "1", "]", "assert", "script", ".", "is_on", "(", "hass", ",", "\"script.script1\"", ")", "assert", "script", ".", "is_on", "(", "hass", ",", "\"script.script2\"", ")", "if", "not", "concurrently", ":", "hass", ".", "states", ".", "async_set", "(", "\"input_boolean.test2\"", ",", "\"on\"", ")", "await", "asyncio", ".", "wait_for", "(", "service_called", ".", "wait", "(", ")", ",", "1", ")", "service_called", ".", "clear", "(", ")", "assert", "\"script2b\"", "==", "service_values", "[", "-", "1", "]", "hass", ".", "states", ".", "async_set", "(", "\"input_boolean.test1\"", ",", "\"on\"", ")", "await", "asyncio", ".", "wait_for", "(", "service_called", ".", "wait", "(", ")", ",", "1", ")", "service_called", ".", "clear", "(", ")", "assert", "\"script1\"", "==", "service_values", "[", "-", "1", "]", "assert", "concurrently", "==", "script", ".", "is_on", "(", "hass", ",", "\"script.script2\"", ")", "if", "concurrently", ":", "hass", ".", "states", ".", "async_set", "(", "\"input_boolean.test2\"", ",", "\"on\"", ")", "await", "asyncio", ".", "wait_for", "(", "service_called", ".", "wait", "(", ")", ",", "1", ")", "service_called", ".", "clear", "(", ")", "assert", "\"script2b\"", "==", "service_values", "[", "-", "1", "]", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "not", "script", ".", "is_on", "(", "hass", ",", "\"script.script1\"", ")", "assert", "not", "script", ".", "is_on", "(", "hass", ",", "\"script.script2\"", ")" ]
[ 535, 0 ]
[ 617, 51 ]
python
en
['en', 'en', 'en']
True
test_script_variables
(hass, caplog)
Test defining scripts.
Test defining scripts.
async def test_script_variables(hass, caplog): """Test defining scripts.""" assert await async_setup_component( hass, "script", { "script": { "script1": { "variables": { "test_var": "from_config", "templated_config_var": "{{ var_from_service | default('config-default') }}", }, "sequence": [ { "service": "test.script", "data": { "value": "{{ test_var }}", "templated_config_var": "{{ templated_config_var }}", }, }, ], }, "script2": { "variables": { "test_var": "from_config", }, "sequence": [ { "service": "test.script", "data": { "value": "{{ test_var }}", }, }, ], }, "script3": { "variables": { "test_var": "{{ break + 1 }}", }, "sequence": [ { "service": "test.script", "data": { "value": "{{ test_var }}", }, }, ], }, } }, ) mock_calls = async_mock_service(hass, "test", "script") await hass.services.async_call( "script", "script1", {"var_from_service": "hello"}, blocking=True ) assert len(mock_calls) == 1 assert mock_calls[0].data["value"] == "from_config" assert mock_calls[0].data["templated_config_var"] == "hello" await hass.services.async_call( "script", "script1", {"test_var": "from_service"}, blocking=True ) assert len(mock_calls) == 2 assert mock_calls[1].data["value"] == "from_service" assert mock_calls[1].data["templated_config_var"] == "config-default" # Call script with vars but no templates in it await hass.services.async_call( "script", "script2", {"test_var": "from_service"}, blocking=True ) assert len(mock_calls) == 3 assert mock_calls[2].data["value"] == "from_service" assert "Error rendering variables" not in caplog.text with pytest.raises(template.TemplateError): await hass.services.async_call("script", "script3", blocking=True) assert "Error rendering variables" in caplog.text assert len(mock_calls) == 3 await hass.services.async_call("script", "script3", {"break": 0}, blocking=True) assert len(mock_calls) == 4 assert mock_calls[3].data["value"] == 1
[ "async", "def", "test_script_variables", "(", "hass", ",", "caplog", ")", ":", "assert", "await", "async_setup_component", "(", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"script1\"", ":", "{", "\"variables\"", ":", "{", "\"test_var\"", ":", "\"from_config\"", ",", "\"templated_config_var\"", ":", "\"{{ var_from_service | default('config-default') }}\"", ",", "}", ",", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"value\"", ":", "\"{{ test_var }}\"", ",", "\"templated_config_var\"", ":", "\"{{ templated_config_var }}\"", ",", "}", ",", "}", ",", "]", ",", "}", ",", "\"script2\"", ":", "{", "\"variables\"", ":", "{", "\"test_var\"", ":", "\"from_config\"", ",", "}", ",", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"value\"", ":", "\"{{ test_var }}\"", ",", "}", ",", "}", ",", "]", ",", "}", ",", "\"script3\"", ":", "{", "\"variables\"", ":", "{", "\"test_var\"", ":", "\"{{ break + 1 }}\"", ",", "}", ",", "\"sequence\"", ":", "[", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data\"", ":", "{", "\"value\"", ":", "\"{{ test_var }}\"", ",", "}", ",", "}", ",", "]", ",", "}", ",", "}", "}", ",", ")", "mock_calls", "=", "async_mock_service", "(", "hass", ",", "\"test\"", ",", "\"script\"", ")", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"script1\"", ",", "{", "\"var_from_service\"", ":", "\"hello\"", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "mock_calls", ")", "==", "1", "assert", "mock_calls", "[", "0", "]", ".", "data", "[", "\"value\"", "]", "==", "\"from_config\"", "assert", "mock_calls", "[", "0", "]", ".", "data", "[", "\"templated_config_var\"", "]", "==", "\"hello\"", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"script1\"", ",", "{", "\"test_var\"", ":", "\"from_service\"", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "mock_calls", ")", "==", "2", "assert", "mock_calls", "[", "1", "]", ".", "data", "[", "\"value\"", "]", "==", "\"from_service\"", "assert", "mock_calls", "[", "1", "]", ".", "data", "[", "\"templated_config_var\"", "]", "==", "\"config-default\"", "# Call script with vars but no templates in it", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"script2\"", ",", "{", "\"test_var\"", ":", "\"from_service\"", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "mock_calls", ")", "==", "3", "assert", "mock_calls", "[", "2", "]", ".", "data", "[", "\"value\"", "]", "==", "\"from_service\"", "assert", "\"Error rendering variables\"", "not", "in", "caplog", ".", "text", "with", "pytest", ".", "raises", "(", "template", ".", "TemplateError", ")", ":", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"script3\"", ",", "blocking", "=", "True", ")", "assert", "\"Error rendering variables\"", "in", "caplog", ".", "text", "assert", "len", "(", "mock_calls", ")", "==", "3", "await", "hass", ".", "services", ".", "async_call", "(", "\"script\"", ",", "\"script3\"", ",", "{", "\"break\"", ":", "0", "}", ",", "blocking", "=", "True", ")", "assert", "len", "(", "mock_calls", ")", "==", "4", "assert", "mock_calls", "[", "3", "]", ".", "data", "[", "\"value\"", "]", "==", "1" ]
[ 620, 0 ]
[ 707, 43 ]
python
cy
['fr', 'cy', 'en']
False
TestScriptComponent.setUp
(self)
Set up things to be run when tests are started.
Set up things to be run when tests are started.
def setUp(self): """Set up things to be run when tests are started.""" self.hass = get_test_home_assistant() self.addCleanup(self.tear_down_cleanup)
[ "def", "setUp", "(", "self", ")", ":", "self", ".", "hass", "=", "get_test_home_assistant", "(", ")", "self", ".", "addCleanup", "(", "self", ".", "tear_down_cleanup", ")" ]
[ 74, 4 ]
[ 78, 47 ]
python
en
['en', 'en', 'en']
True
TestScriptComponent.tear_down_cleanup
(self)
Stop down everything that was started.
Stop down everything that was started.
def tear_down_cleanup(self): """Stop down everything that was started.""" self.hass.stop()
[ "def", "tear_down_cleanup", "(", "self", ")", ":", "self", ".", "hass", ".", "stop", "(", ")" ]
[ 80, 4 ]
[ 82, 24 ]
python
en
['en', 'en', 'en']
True
TestScriptComponent.test_passing_variables
(self)
Test different ways of passing in variables.
Test different ways of passing in variables.
def test_passing_variables(self): """Test different ways of passing in variables.""" calls = [] context = Context() @callback def record_call(service): """Add recorded event to set.""" calls.append(service) self.hass.services.register("test", "script", record_call) assert setup_component( self.hass, "script", { "script": { "test": { "sequence": { "service": "test.script", "data_template": {"hello": "{{ greeting }}"}, } } } }, ) turn_on(self.hass, ENTITY_ID, {"greeting": "world"}, context=context) self.hass.block_till_done() assert len(calls) == 1 assert calls[0].context is context assert calls[0].data["hello"] == "world" self.hass.services.call( "script", "test", {"greeting": "universe"}, context=context ) self.hass.block_till_done() assert len(calls) == 2 assert calls[1].context is context assert calls[1].data["hello"] == "universe"
[ "def", "test_passing_variables", "(", "self", ")", ":", "calls", "=", "[", "]", "context", "=", "Context", "(", ")", "@", "callback", "def", "record_call", "(", "service", ")", ":", "\"\"\"Add recorded event to set.\"\"\"", "calls", ".", "append", "(", "service", ")", "self", ".", "hass", ".", "services", ".", "register", "(", "\"test\"", ",", "\"script\"", ",", "record_call", ")", "assert", "setup_component", "(", "self", ".", "hass", ",", "\"script\"", ",", "{", "\"script\"", ":", "{", "\"test\"", ":", "{", "\"sequence\"", ":", "{", "\"service\"", ":", "\"test.script\"", ",", "\"data_template\"", ":", "{", "\"hello\"", ":", "\"{{ greeting }}\"", "}", ",", "}", "}", "}", "}", ",", ")", "turn_on", "(", "self", ".", "hass", ",", "ENTITY_ID", ",", "{", "\"greeting\"", ":", "\"world\"", "}", ",", "context", "=", "context", ")", "self", ".", "hass", ".", "block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "1", "assert", "calls", "[", "0", "]", ".", "context", "is", "context", "assert", "calls", "[", "0", "]", ".", "data", "[", "\"hello\"", "]", "==", "\"world\"", "self", ".", "hass", ".", "services", ".", "call", "(", "\"script\"", ",", "\"test\"", ",", "{", "\"greeting\"", ":", "\"universe\"", "}", ",", "context", "=", "context", ")", "self", ".", "hass", ".", "block_till_done", "(", ")", "assert", "len", "(", "calls", ")", "==", "2", "assert", "calls", "[", "1", "]", ".", "context", "is", "context", "assert", "calls", "[", "1", "]", ".", "data", "[", "\"hello\"", "]", "==", "\"universe\"" ]
[ 84, 4 ]
[ 127, 51 ]
python
en
['en', 'en', 'en']
True
patch_requests
()
Stub out services that makes requests.
Stub out services that makes requests.
def patch_requests(): """Stub out services that makes requests.""" patch_client = patch("homeassistant.components.meteo_france.MeteoFranceClient") with patch_client: yield
[ "def", "patch_requests", "(", ")", ":", "patch_client", "=", "patch", "(", "\"homeassistant.components.meteo_france.MeteoFranceClient\"", ")", "with", "patch_client", ":", "yield" ]
[ 7, 0 ]
[ 12, 13 ]
python
en
['en', 'en', 'en']
True
get_indent
(line)
Returns the indent in `line`.
Returns the indent in `line`.
def get_indent(line): """Returns the indent in `line`.""" search = _re_indent.search(line) return "" if search is None else search.groups()[0]
[ "def", "get_indent", "(", "line", ")", ":", "search", "=", "_re_indent", ".", "search", "(", "line", ")", "return", "\"\"", "if", "search", "is", "None", "else", "search", ".", "groups", "(", ")", "[", "0", "]" ]
[ 34, 0 ]
[ 37, 55 ]
python
en
['en', 'en', 'en']
True
split_code_in_indented_blocks
(code, indent_level="", start_prompt=None, end_prompt=None)
Split `code` into its indented blocks, starting at `indent_level`. If provided, begins splitting after `start_prompt` and stops at `end_prompt` (but returns what's before `start_prompt` as a first block and what's after `end_prompt` as a last block, so `code` is always the same as joining the result of this function).
Split `code` into its indented blocks, starting at `indent_level`. If provided, begins splitting after `start_prompt` and stops at `end_prompt` (but returns what's before `start_prompt` as a first block and what's after `end_prompt` as a last block, so `code` is always the same as joining the result of this function).
def split_code_in_indented_blocks(code, indent_level="", start_prompt=None, end_prompt=None): """ Split `code` into its indented blocks, starting at `indent_level`. If provided, begins splitting after `start_prompt` and stops at `end_prompt` (but returns what's before `start_prompt` as a first block and what's after `end_prompt` as a last block, so `code` is always the same as joining the result of this function). """ # Let's split the code into lines and move to start_index. index = 0 lines = code.split("\n") if start_prompt is not None: while not lines[index].startswith(start_prompt): index += 1 blocks = ["\n".join(lines[:index])] else: blocks = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). current_block = [lines[index]] index += 1 while index < len(lines) and (end_prompt is None or not lines[index].startswith(end_prompt)): if len(lines[index]) > 0 and get_indent(lines[index]) == indent_level: if len(current_block) > 0 and get_indent(current_block[-1]).startswith(indent_level + " "): current_block.append(lines[index]) blocks.append("\n".join(current_block)) if index < len(lines) - 1: current_block = [lines[index + 1]] index += 1 else: current_block = [] else: blocks.append("\n".join(current_block)) current_block = [lines[index]] else: current_block.append(lines[index]) index += 1 # Adds current block if it's nonempty. if len(current_block) > 0: blocks.append("\n".join(current_block)) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(lines): blocks.append("\n".join(lines[index:])) return blocks
[ "def", "split_code_in_indented_blocks", "(", "code", ",", "indent_level", "=", "\"\"", ",", "start_prompt", "=", "None", ",", "end_prompt", "=", "None", ")", ":", "# Let's split the code into lines and move to start_index.", "index", "=", "0", "lines", "=", "code", ".", "split", "(", "\"\\n\"", ")", "if", "start_prompt", "is", "not", "None", ":", "while", "not", "lines", "[", "index", "]", ".", "startswith", "(", "start_prompt", ")", ":", "index", "+=", "1", "blocks", "=", "[", "\"\\n\"", ".", "join", "(", "lines", "[", ":", "index", "]", ")", "]", "else", ":", "blocks", "=", "[", "]", "# We split into blocks until we get to the `end_prompt` (or the end of the block).", "current_block", "=", "[", "lines", "[", "index", "]", "]", "index", "+=", "1", "while", "index", "<", "len", "(", "lines", ")", "and", "(", "end_prompt", "is", "None", "or", "not", "lines", "[", "index", "]", ".", "startswith", "(", "end_prompt", ")", ")", ":", "if", "len", "(", "lines", "[", "index", "]", ")", ">", "0", "and", "get_indent", "(", "lines", "[", "index", "]", ")", "==", "indent_level", ":", "if", "len", "(", "current_block", ")", ">", "0", "and", "get_indent", "(", "current_block", "[", "-", "1", "]", ")", ".", "startswith", "(", "indent_level", "+", "\" \"", ")", ":", "current_block", ".", "append", "(", "lines", "[", "index", "]", ")", "blocks", ".", "append", "(", "\"\\n\"", ".", "join", "(", "current_block", ")", ")", "if", "index", "<", "len", "(", "lines", ")", "-", "1", ":", "current_block", "=", "[", "lines", "[", "index", "+", "1", "]", "]", "index", "+=", "1", "else", ":", "current_block", "=", "[", "]", "else", ":", "blocks", ".", "append", "(", "\"\\n\"", ".", "join", "(", "current_block", ")", ")", "current_block", "=", "[", "lines", "[", "index", "]", "]", "else", ":", "current_block", ".", "append", "(", "lines", "[", "index", "]", ")", "index", "+=", "1", "# Adds current block if it's nonempty.", "if", "len", "(", "current_block", ")", ">", "0", ":", "blocks", ".", "append", "(", "\"\\n\"", ".", "join", "(", "current_block", ")", ")", "# Add final block after end_prompt if provided.", "if", "end_prompt", "is", "not", "None", "and", "index", "<", "len", "(", "lines", ")", ":", "blocks", ".", "append", "(", "\"\\n\"", ".", "join", "(", "lines", "[", "index", ":", "]", ")", ")", "return", "blocks" ]
[ 40, 0 ]
[ 84, 17 ]
python
en
['en', 'error', 'th']
False
ignore_underscore
(key)
Wraps a `key` (that maps an object to string) to lower case and remove underscores.
Wraps a `key` (that maps an object to string) to lower case and remove underscores.
def ignore_underscore(key): "Wraps a `key` (that maps an object to string) to lower case and remove underscores." def _inner(x): return key(x).lower().replace("_", "") return _inner
[ "def", "ignore_underscore", "(", "key", ")", ":", "def", "_inner", "(", "x", ")", ":", "return", "key", "(", "x", ")", ".", "lower", "(", ")", ".", "replace", "(", "\"_\"", ",", "\"\"", ")", "return", "_inner" ]
[ 87, 0 ]
[ 93, 17 ]
python
en
['en', 'en', 'en']
True
sort_objects
(objects, key=None)
Sort a list of `objects` following the rules of isort. `key` optionally maps an object to a str.
Sort a list of `objects` following the rules of isort. `key` optionally maps an object to a str.
def sort_objects(objects, key=None): "Sort a list of `objects` following the rules of isort. `key` optionally maps an object to a str." # If no key is provided, we use a noop. def noop(x): return x if key is None: key = noop # Constants are all uppercase, they go first. constants = [obj for obj in objects if key(obj).isupper()] # Classes are not all uppercase but start with a capital, they go second. classes = [obj for obj in objects if key(obj)[0].isupper() and not key(obj).isupper()] # Functions begin with a lowercase, they go last. functions = [obj for obj in objects if not key(obj)[0].isupper()] key1 = ignore_underscore(key) return sorted(constants, key=key1) + sorted(classes, key=key1) + sorted(functions, key=key1)
[ "def", "sort_objects", "(", "objects", ",", "key", "=", "None", ")", ":", "# If no key is provided, we use a noop.", "def", "noop", "(", "x", ")", ":", "return", "x", "if", "key", "is", "None", ":", "key", "=", "noop", "# Constants are all uppercase, they go first.", "constants", "=", "[", "obj", "for", "obj", "in", "objects", "if", "key", "(", "obj", ")", ".", "isupper", "(", ")", "]", "# Classes are not all uppercase but start with a capital, they go second.", "classes", "=", "[", "obj", "for", "obj", "in", "objects", "if", "key", "(", "obj", ")", "[", "0", "]", ".", "isupper", "(", ")", "and", "not", "key", "(", "obj", ")", ".", "isupper", "(", ")", "]", "# Functions begin with a lowercase, they go last.", "functions", "=", "[", "obj", "for", "obj", "in", "objects", "if", "not", "key", "(", "obj", ")", "[", "0", "]", ".", "isupper", "(", ")", "]", "key1", "=", "ignore_underscore", "(", "key", ")", "return", "sorted", "(", "constants", ",", "key", "=", "key1", ")", "+", "sorted", "(", "classes", ",", "key", "=", "key1", ")", "+", "sorted", "(", "functions", ",", "key", "=", "key1", ")" ]
[ 96, 0 ]
[ 112, 96 ]
python
en
['en', 'en', 'en']
True
sort_objects_in_import
(import_statement)
Return the same `import_statement` but with objects properly sorted.
Return the same `import_statement` but with objects properly sorted.
def sort_objects_in_import(import_statement): """ Return the same `import_statement` but with objects properly sorted. """ # This inner function sort imports between [ ]. def _replace(match): imports = match.groups()[0] if "," not in imports: return f"[{imports}]" keys = [part.strip().replace('"', "") for part in imports.split(",")] # We will have a final empty element if the line finished with a comma. if len(keys[-1]) == 0: keys = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + "]" lines = import_statement.split("\n") if len(lines) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. idx = 2 if lines[1].strip() == "[" else 1 keys_to_sort = [(i, _re_strip_line.search(line).groups()[0]) for i, line in enumerate(lines[idx:-idx])] sorted_indices = sort_objects(keys_to_sort, key=lambda x: x[1]) sorted_lines = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:]) elif len(lines) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1]) is not None: lines[1] = _re_bracket_content.sub(_replace, lines[1]) else: keys = [part.strip().replace('"', "") for part in lines[1].split(",")] # We will have a final empty element if the line finished with a comma. if len(keys[-1]) == 0: keys = keys[:-1] lines[1] = get_indent(lines[1]) + ", ".join([f'"{k}"' for k in sort_objects(keys)]) return "\n".join(lines) else: # Finally we have to deal with imports fitting on one line import_statement = _re_bracket_content.sub(_replace, import_statement) return import_statement
[ "def", "sort_objects_in_import", "(", "import_statement", ")", ":", "# This inner function sort imports between [ ].", "def", "_replace", "(", "match", ")", ":", "imports", "=", "match", ".", "groups", "(", ")", "[", "0", "]", "if", "\",\"", "not", "in", "imports", ":", "return", "f\"[{imports}]\"", "keys", "=", "[", "part", ".", "strip", "(", ")", ".", "replace", "(", "'\"'", ",", "\"\"", ")", "for", "part", "in", "imports", ".", "split", "(", "\",\"", ")", "]", "# We will have a final empty element if the line finished with a comma.", "if", "len", "(", "keys", "[", "-", "1", "]", ")", "==", "0", ":", "keys", "=", "keys", "[", ":", "-", "1", "]", "return", "\"[\"", "+", "\", \"", ".", "join", "(", "[", "f'\"{k}\"'", "for", "k", "in", "sort_objects", "(", "keys", ")", "]", ")", "+", "\"]\"", "lines", "=", "import_statement", ".", "split", "(", "\"\\n\"", ")", "if", "len", "(", "lines", ")", ">", "3", ":", "# Here we have to sort internal imports that are on several lines (one per name):", "# key: [", "# \"object1\",", "# \"object2\",", "# ...", "# ]", "# We may have to ignore one or two lines on each side.", "idx", "=", "2", "if", "lines", "[", "1", "]", ".", "strip", "(", ")", "==", "\"[\"", "else", "1", "keys_to_sort", "=", "[", "(", "i", ",", "_re_strip_line", ".", "search", "(", "line", ")", ".", "groups", "(", ")", "[", "0", "]", ")", "for", "i", ",", "line", "in", "enumerate", "(", "lines", "[", "idx", ":", "-", "idx", "]", ")", "]", "sorted_indices", "=", "sort_objects", "(", "keys_to_sort", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "sorted_lines", "=", "[", "lines", "[", "x", "[", "0", "]", "+", "idx", "]", "for", "x", "in", "sorted_indices", "]", "return", "\"\\n\"", ".", "join", "(", "lines", "[", ":", "idx", "]", "+", "sorted_lines", "+", "lines", "[", "-", "idx", ":", "]", ")", "elif", "len", "(", "lines", ")", "==", "3", ":", "# Here we have to sort internal imports that are on one separate line:", "# key: [", "# \"object1\", \"object2\", ...", "# ]", "if", "_re_bracket_content", ".", "search", "(", "lines", "[", "1", "]", ")", "is", "not", "None", ":", "lines", "[", "1", "]", "=", "_re_bracket_content", ".", "sub", "(", "_replace", ",", "lines", "[", "1", "]", ")", "else", ":", "keys", "=", "[", "part", ".", "strip", "(", ")", ".", "replace", "(", "'\"'", ",", "\"\"", ")", "for", "part", "in", "lines", "[", "1", "]", ".", "split", "(", "\",\"", ")", "]", "# We will have a final empty element if the line finished with a comma.", "if", "len", "(", "keys", "[", "-", "1", "]", ")", "==", "0", ":", "keys", "=", "keys", "[", ":", "-", "1", "]", "lines", "[", "1", "]", "=", "get_indent", "(", "lines", "[", "1", "]", ")", "+", "\", \"", ".", "join", "(", "[", "f'\"{k}\"'", "for", "k", "in", "sort_objects", "(", "keys", ")", "]", ")", "return", "\"\\n\"", ".", "join", "(", "lines", ")", "else", ":", "# Finally we have to deal with imports fitting on one line", "import_statement", "=", "_re_bracket_content", ".", "sub", "(", "_replace", ",", "import_statement", ")", "return", "import_statement" ]
[ 115, 0 ]
[ 162, 31 ]
python
en
['en', 'error', 'th']
False
sort_imports
(file, check_only=True)
Sort `_import_structure` imports in `file`, `check_only` determines if we only check or overwrite.
Sort `_import_structure` imports in `file`, `check_only` determines if we only check or overwrite.
def sort_imports(file, check_only=True): """ Sort `_import_structure` imports in `file`, `check_only` determines if we only check or overwrite. """ with open(file, "r") as f: code = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 main_blocks = split_code_in_indented_blocks( code, start_prompt="_import_structure = {", end_prompt="if TYPE_CHECKING:" ) # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). for block_idx in range(1, len(main_blocks) - 1): # Check if the block contains some `_import_structure`s thingy to sort. block = main_blocks[block_idx] block_lines = block.split("\n") if len(block_lines) < 3 or "_import_structure" not in "".join(block_lines[:2]): continue # Ignore first and last line: they don't contain anything. internal_block_code = "\n".join(block_lines[1:-1]) indent = get_indent(block_lines[1]) # Slit the internal block into blocks of indent level 1. internal_blocks = split_code_in_indented_blocks(internal_block_code, indent_level=indent) # We have two categories of import key: list or _import_structu[key].append/extend pattern = _re_direct_key if "_import_structure" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or jsut comments. keys = [(pattern.search(b).groups()[0] if pattern.search(b) is not None else None) for b in internal_blocks] # We only sort the lines with a key. keys_to_sort = [(i, key) for i, key in enumerate(keys) if key is not None] sorted_indices = [x[0] for x in sorted(keys_to_sort, key=lambda x: x[1])] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. count = 0 reorderded_blocks = [] for i in range(len(internal_blocks)): if keys[i] is None: reorderded_blocks.append(internal_blocks[i]) else: block = sort_objects_in_import(internal_blocks[sorted_indices[count]]) reorderded_blocks.append(block) count += 1 # And we put our main block back together with its first and last line. main_blocks[block_idx] = "\n".join([block_lines[0]] + reorderded_blocks + [block_lines[-1]]) if code != "\n".join(main_blocks): if check_only: return True else: print(f"Overwriting {file}.") with open(file, "w") as f: f.write("\n".join(main_blocks))
[ "def", "sort_imports", "(", "file", ",", "check_only", "=", "True", ")", ":", "with", "open", "(", "file", ",", "\"r\"", ")", "as", "f", ":", "code", "=", "f", ".", "read", "(", ")", "if", "\"_import_structure\"", "not", "in", "code", ":", "return", "# Blocks of indent level 0", "main_blocks", "=", "split_code_in_indented_blocks", "(", "code", ",", "start_prompt", "=", "\"_import_structure = {\"", ",", "end_prompt", "=", "\"if TYPE_CHECKING:\"", ")", "# We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt).", "for", "block_idx", "in", "range", "(", "1", ",", "len", "(", "main_blocks", ")", "-", "1", ")", ":", "# Check if the block contains some `_import_structure`s thingy to sort.", "block", "=", "main_blocks", "[", "block_idx", "]", "block_lines", "=", "block", ".", "split", "(", "\"\\n\"", ")", "if", "len", "(", "block_lines", ")", "<", "3", "or", "\"_import_structure\"", "not", "in", "\"\"", ".", "join", "(", "block_lines", "[", ":", "2", "]", ")", ":", "continue", "# Ignore first and last line: they don't contain anything.", "internal_block_code", "=", "\"\\n\"", ".", "join", "(", "block_lines", "[", "1", ":", "-", "1", "]", ")", "indent", "=", "get_indent", "(", "block_lines", "[", "1", "]", ")", "# Slit the internal block into blocks of indent level 1.", "internal_blocks", "=", "split_code_in_indented_blocks", "(", "internal_block_code", ",", "indent_level", "=", "indent", ")", "# We have two categories of import key: list or _import_structu[key].append/extend", "pattern", "=", "_re_direct_key", "if", "\"_import_structure\"", "in", "block_lines", "[", "0", "]", "else", "_re_indirect_key", "# Grab the keys, but there is a trap: some lines are empty or jsut comments.", "keys", "=", "[", "(", "pattern", ".", "search", "(", "b", ")", ".", "groups", "(", ")", "[", "0", "]", "if", "pattern", ".", "search", "(", "b", ")", "is", "not", "None", "else", "None", ")", "for", "b", "in", "internal_blocks", "]", "# We only sort the lines with a key.", "keys_to_sort", "=", "[", "(", "i", ",", "key", ")", "for", "i", ",", "key", "in", "enumerate", "(", "keys", ")", "if", "key", "is", "not", "None", "]", "sorted_indices", "=", "[", "x", "[", "0", "]", "for", "x", "in", "sorted", "(", "keys_to_sort", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ")", "]", "# We reorder the blocks by leaving empty lines/comments as they were and reorder the rest.", "count", "=", "0", "reorderded_blocks", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "internal_blocks", ")", ")", ":", "if", "keys", "[", "i", "]", "is", "None", ":", "reorderded_blocks", ".", "append", "(", "internal_blocks", "[", "i", "]", ")", "else", ":", "block", "=", "sort_objects_in_import", "(", "internal_blocks", "[", "sorted_indices", "[", "count", "]", "]", ")", "reorderded_blocks", ".", "append", "(", "block", ")", "count", "+=", "1", "# And we put our main block back together with its first and last line.", "main_blocks", "[", "block_idx", "]", "=", "\"\\n\"", ".", "join", "(", "[", "block_lines", "[", "0", "]", "]", "+", "reorderded_blocks", "+", "[", "block_lines", "[", "-", "1", "]", "]", ")", "if", "code", "!=", "\"\\n\"", ".", "join", "(", "main_blocks", ")", ":", "if", "check_only", ":", "return", "True", "else", ":", "print", "(", "f\"Overwriting {file}.\"", ")", "with", "open", "(", "file", ",", "\"w\"", ")", "as", "f", ":", "f", ".", "write", "(", "\"\\n\"", ".", "join", "(", "main_blocks", ")", ")" ]
[ 165, 0 ]
[ 221, 47 ]
python
en
['en', 'error', 'th']
False
setup_platform
(hass, config, add_entities, discovery_info=None)
Iterate through all MAX! Devices and add window shutters.
Iterate through all MAX! Devices and add window shutters.
def setup_platform(hass, config, add_entities, discovery_info=None): """Iterate through all MAX! Devices and add window shutters.""" devices = [] for handler in hass.data[DATA_KEY].values(): cube = handler.cube for device in cube.devices: name = f"{cube.room_by_id(device.room_id).name} {device.name}" # Only add Window Shutters if cube.is_windowshutter(device): devices.append(MaxCubeShutter(handler, name, device.rf_address)) if devices: add_entities(devices)
[ "def", "setup_platform", "(", "hass", ",", "config", ",", "add_entities", ",", "discovery_info", "=", "None", ")", ":", "devices", "=", "[", "]", "for", "handler", "in", "hass", ".", "data", "[", "DATA_KEY", "]", ".", "values", "(", ")", ":", "cube", "=", "handler", ".", "cube", "for", "device", "in", "cube", ".", "devices", ":", "name", "=", "f\"{cube.room_by_id(device.room_id).name} {device.name}\"", "# Only add Window Shutters", "if", "cube", ".", "is_windowshutter", "(", "device", ")", ":", "devices", ".", "append", "(", "MaxCubeShutter", "(", "handler", ",", "name", ",", "device", ".", "rf_address", ")", ")", "if", "devices", ":", "add_entities", "(", "devices", ")" ]
[ 9, 0 ]
[ 22, 29 ]
python
en
['en', 'en', 'en']
True
MaxCubeShutter.__init__
(self, handler, name, rf_address)
Initialize MAX! Cube BinarySensorEntity.
Initialize MAX! Cube BinarySensorEntity.
def __init__(self, handler, name, rf_address): """Initialize MAX! Cube BinarySensorEntity.""" self._name = name self._sensor_type = DEVICE_CLASS_WINDOW self._rf_address = rf_address self._cubehandle = handler self._state = None
[ "def", "__init__", "(", "self", ",", "handler", ",", "name", ",", "rf_address", ")", ":", "self", ".", "_name", "=", "name", "self", ".", "_sensor_type", "=", "DEVICE_CLASS_WINDOW", "self", ".", "_rf_address", "=", "rf_address", "self", ".", "_cubehandle", "=", "handler", "self", ".", "_state", "=", "None" ]
[ 28, 4 ]
[ 34, 26 ]
python
en
['en', 'ny', 'it']
False
MaxCubeShutter.name
(self)
Return the name of the BinarySensorEntity.
Return the name of the BinarySensorEntity.
def name(self): """Return the name of the BinarySensorEntity.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 37, 4 ]
[ 39, 25 ]
python
en
['en', 'ig', 'en']
True
MaxCubeShutter.device_class
(self)
Return the class of this sensor.
Return the class of this sensor.
def device_class(self): """Return the class of this sensor.""" return self._sensor_type
[ "def", "device_class", "(", "self", ")", ":", "return", "self", ".", "_sensor_type" ]
[ 42, 4 ]
[ 44, 32 ]
python
en
['en', 'en', 'en']
True
MaxCubeShutter.is_on
(self)
Return true if the binary sensor is on/open.
Return true if the binary sensor is on/open.
def is_on(self): """Return true if the binary sensor is on/open.""" return self._state
[ "def", "is_on", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 47, 4 ]
[ 49, 26 ]
python
en
['en', 'fy', 'en']
True
MaxCubeShutter.update
(self)
Get latest data from MAX! Cube.
Get latest data from MAX! Cube.
def update(self): """Get latest data from MAX! Cube.""" self._cubehandle.update() device = self._cubehandle.cube.device_by_rf(self._rf_address) self._state = device.is_open
[ "def", "update", "(", "self", ")", ":", "self", ".", "_cubehandle", ".", "update", "(", ")", "device", "=", "self", ".", "_cubehandle", ".", "cube", ".", "device_by_rf", "(", "self", ".", "_rf_address", ")", "self", ".", "_state", "=", "device", ".", "is_open" ]
[ 51, 4 ]
[ 55, 36 ]
python
en
['en', 'en', 'en']
True
_update_twentemilieu
( hass: HomeAssistantType, unique_id: Optional[str] )
Update Twente Milieu.
Update Twente Milieu.
async def _update_twentemilieu( hass: HomeAssistantType, unique_id: Optional[str] ) -> None: """Update Twente Milieu.""" if unique_id is not None: twentemilieu = hass.data[DOMAIN].get(unique_id) if twentemilieu is not None: await twentemilieu.update() async_dispatcher_send(hass, DATA_UPDATE, unique_id) else: tasks = [] for twentemilieu in hass.data[DOMAIN].values(): tasks.append(twentemilieu.update()) await asyncio.wait(tasks) for uid in hass.data[DOMAIN]: async_dispatcher_send(hass, DATA_UPDATE, uid)
[ "async", "def", "_update_twentemilieu", "(", "hass", ":", "HomeAssistantType", ",", "unique_id", ":", "Optional", "[", "str", "]", ")", "->", "None", ":", "if", "unique_id", "is", "not", "None", ":", "twentemilieu", "=", "hass", ".", "data", "[", "DOMAIN", "]", ".", "get", "(", "unique_id", ")", "if", "twentemilieu", "is", "not", "None", ":", "await", "twentemilieu", ".", "update", "(", ")", "async_dispatcher_send", "(", "hass", ",", "DATA_UPDATE", ",", "unique_id", ")", "else", ":", "tasks", "=", "[", "]", "for", "twentemilieu", "in", "hass", ".", "data", "[", "DOMAIN", "]", ".", "values", "(", ")", ":", "tasks", ".", "append", "(", "twentemilieu", ".", "update", "(", ")", ")", "await", "asyncio", ".", "wait", "(", "tasks", ")", "for", "uid", "in", "hass", ".", "data", "[", "DOMAIN", "]", ":", "async_dispatcher_send", "(", "hass", ",", "DATA_UPDATE", ",", "uid", ")" ]
[ 29, 0 ]
[ 45, 57 ]
python
fr
['fr', 'nl', 'it']
False
async_setup
(hass: HomeAssistantType, config: ConfigType)
Set up the Twente Milieu components.
Set up the Twente Milieu components.
async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool: """Set up the Twente Milieu components.""" async def update(call) -> None: """Service call to manually update the data.""" unique_id = call.data.get(CONF_ID) await _update_twentemilieu(hass, unique_id) hass.services.async_register(DOMAIN, SERVICE_UPDATE, update, schema=SERVICE_SCHEMA) return True
[ "async", "def", "async_setup", "(", "hass", ":", "HomeAssistantType", ",", "config", ":", "ConfigType", ")", "->", "bool", ":", "async", "def", "update", "(", "call", ")", "->", "None", ":", "\"\"\"Service call to manually update the data.\"\"\"", "unique_id", "=", "call", ".", "data", ".", "get", "(", "CONF_ID", ")", "await", "_update_twentemilieu", "(", "hass", ",", "unique_id", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_UPDATE", ",", "update", ",", "schema", "=", "SERVICE_SCHEMA", ")", "return", "True" ]
[ 48, 0 ]
[ 58, 15 ]
python
en
['en', 'fr', 'en']
True
async_setup_entry
(hass: HomeAssistantType, entry: ConfigEntry)
Set up Twente Milieu from a config entry.
Set up Twente Milieu from a config entry.
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Set up Twente Milieu from a config entry.""" session = async_get_clientsession(hass) twentemilieu = TwenteMilieu( post_code=entry.data[CONF_POST_CODE], house_number=entry.data[CONF_HOUSE_NUMBER], house_letter=entry.data[CONF_HOUSE_LETTER], session=session, ) unique_id = entry.data[CONF_ID] hass.data.setdefault(DOMAIN, {})[unique_id] = twentemilieu hass.async_create_task( hass.config_entries.async_forward_entry_setup(entry, "sensor") ) async def _interval_update(now=None) -> None: """Update Twente Milieu data.""" await _update_twentemilieu(hass, unique_id) async_track_time_interval(hass, _interval_update, SCAN_INTERVAL) return True
[ "async", "def", "async_setup_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ")", "->", "bool", ":", "session", "=", "async_get_clientsession", "(", "hass", ")", "twentemilieu", "=", "TwenteMilieu", "(", "post_code", "=", "entry", ".", "data", "[", "CONF_POST_CODE", "]", ",", "house_number", "=", "entry", ".", "data", "[", "CONF_HOUSE_NUMBER", "]", ",", "house_letter", "=", "entry", ".", "data", "[", "CONF_HOUSE_LETTER", "]", ",", "session", "=", "session", ",", ")", "unique_id", "=", "entry", ".", "data", "[", "CONF_ID", "]", "hass", ".", "data", ".", "setdefault", "(", "DOMAIN", ",", "{", "}", ")", "[", "unique_id", "]", "=", "twentemilieu", "hass", ".", "async_create_task", "(", "hass", ".", "config_entries", ".", "async_forward_entry_setup", "(", "entry", ",", "\"sensor\"", ")", ")", "async", "def", "_interval_update", "(", "now", "=", "None", ")", "->", "None", ":", "\"\"\"Update Twente Milieu data.\"\"\"", "await", "_update_twentemilieu", "(", "hass", ",", "unique_id", ")", "async_track_time_interval", "(", "hass", ",", "_interval_update", ",", "SCAN_INTERVAL", ")", "return", "True" ]
[ 61, 0 ]
[ 84, 15 ]
python
en
['en', 'pt', 'en']
True
async_unload_entry
(hass: HomeAssistantType, entry: ConfigEntry)
Unload Twente Milieu config entry.
Unload Twente Milieu config entry.
async def async_unload_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool: """Unload Twente Milieu config entry.""" await hass.config_entries.async_forward_entry_unload(entry, "sensor") del hass.data[DOMAIN][entry.data[CONF_ID]] return True
[ "async", "def", "async_unload_entry", "(", "hass", ":", "HomeAssistantType", ",", "entry", ":", "ConfigEntry", ")", "->", "bool", ":", "await", "hass", ".", "config_entries", ".", "async_forward_entry_unload", "(", "entry", ",", "\"sensor\"", ")", "del", "hass", ".", "data", "[", "DOMAIN", "]", "[", "entry", ".", "data", "[", "CONF_ID", "]", "]", "return", "True" ]
[ 87, 0 ]
[ 93, 15 ]
python
en
['fr', 'es', 'en']
False
async_condition_from_config
( config: ConfigType, config_validation: bool )
Evaluate state based on configuration.
Evaluate state based on configuration.
def async_condition_from_config( config: ConfigType, config_validation: bool ) -> ConditionCheckerType: """Evaluate state based on configuration.""" if config_validation: config = CONDITION_SCHEMA(config) return toggle_entity.async_condition_from_config(config)
[ "def", "async_condition_from_config", "(", "config", ":", "ConfigType", ",", "config_validation", ":", "bool", ")", "->", "ConditionCheckerType", ":", "if", "config_validation", ":", "config", "=", "CONDITION_SCHEMA", "(", "config", ")", "return", "toggle_entity", ".", "async_condition_from_config", "(", "config", ")" ]
[ 19, 0 ]
[ 25, 60 ]
python
en
['en', 'en', 'en']
True
async_get_conditions
( hass: HomeAssistant, device_id: str )
List device conditions.
List device conditions.
async def async_get_conditions( hass: HomeAssistant, device_id: str ) -> List[Dict[str, str]]: """List device conditions.""" return await toggle_entity.async_get_conditions(hass, device_id, DOMAIN)
[ "async", "def", "async_get_conditions", "(", "hass", ":", "HomeAssistant", ",", "device_id", ":", "str", ")", "->", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ":", "return", "await", "toggle_entity", ".", "async_get_conditions", "(", "hass", ",", "device_id", ",", "DOMAIN", ")" ]
[ 28, 0 ]
[ 32, 76 ]
python
en
['fr', 'en', 'en']
True
async_get_condition_capabilities
(hass: HomeAssistant, config: dict)
List condition capabilities.
List condition capabilities.
async def async_get_condition_capabilities(hass: HomeAssistant, config: dict) -> dict: """List condition capabilities.""" return await toggle_entity.async_get_condition_capabilities(hass, config)
[ "async", "def", "async_get_condition_capabilities", "(", "hass", ":", "HomeAssistant", ",", "config", ":", "dict", ")", "->", "dict", ":", "return", "await", "toggle_entity", ".", "async_get_condition_capabilities", "(", "hass", ",", "config", ")" ]
[ 35, 0 ]
[ 37, 77 ]
python
en
['ro', 'sr', 'en']
False
call_from_config
( hass: HomeAssistantType, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, )
Call a service based on a config hash.
Call a service based on a config hash.
def call_from_config( hass: HomeAssistantType, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, ) -> None: """Call a service based on a config hash.""" asyncio.run_coroutine_threadsafe( async_call_from_config(hass, config, blocking, variables, validate_config), hass.loop, ).result()
[ "def", "call_from_config", "(", "hass", ":", "HomeAssistantType", ",", "config", ":", "ConfigType", ",", "blocking", ":", "bool", "=", "False", ",", "variables", ":", "TemplateVarsType", "=", "None", ",", "validate_config", ":", "bool", "=", "True", ",", ")", "->", "None", ":", "asyncio", ".", "run_coroutine_threadsafe", "(", "async_call_from_config", "(", "hass", ",", "config", ",", "blocking", ",", "variables", ",", "validate_config", ")", ",", "hass", ".", "loop", ",", ")", ".", "result", "(", ")" ]
[ 65, 0 ]
[ 76, 14 ]
python
en
['en', 'en', 'en']
True
async_call_from_config
( hass: HomeAssistantType, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, context: Optional[ha.Context] = None, )
Call a service based on a config hash.
Call a service based on a config hash.
async def async_call_from_config( hass: HomeAssistantType, config: ConfigType, blocking: bool = False, variables: TemplateVarsType = None, validate_config: bool = True, context: Optional[ha.Context] = None, ) -> None: """Call a service based on a config hash.""" try: parms = async_prepare_call_from_config(hass, config, variables, validate_config) except HomeAssistantError as ex: if blocking: raise _LOGGER.error(ex) else: await hass.services.async_call(*parms, blocking, context)
[ "async", "def", "async_call_from_config", "(", "hass", ":", "HomeAssistantType", ",", "config", ":", "ConfigType", ",", "blocking", ":", "bool", "=", "False", ",", "variables", ":", "TemplateVarsType", "=", "None", ",", "validate_config", ":", "bool", "=", "True", ",", "context", ":", "Optional", "[", "ha", ".", "Context", "]", "=", "None", ",", ")", "->", "None", ":", "try", ":", "parms", "=", "async_prepare_call_from_config", "(", "hass", ",", "config", ",", "variables", ",", "validate_config", ")", "except", "HomeAssistantError", "as", "ex", ":", "if", "blocking", ":", "raise", "_LOGGER", ".", "error", "(", "ex", ")", "else", ":", "await", "hass", ".", "services", ".", "async_call", "(", "*", "parms", ",", "blocking", ",", "context", ")" ]
[ 80, 0 ]
[ 96, 65 ]
python
en
['en', 'en', 'en']
True
async_prepare_call_from_config
( hass: HomeAssistantType, config: ConfigType, variables: TemplateVarsType = None, validate_config: bool = False, )
Prepare to call a service based on a config hash.
Prepare to call a service based on a config hash.
def async_prepare_call_from_config( hass: HomeAssistantType, config: ConfigType, variables: TemplateVarsType = None, validate_config: bool = False, ) -> Tuple[str, str, Dict[str, Any]]: """Prepare to call a service based on a config hash.""" if validate_config: try: config = cv.SERVICE_SCHEMA(config) except vol.Invalid as ex: raise HomeAssistantError( f"Invalid config for calling service: {ex}" ) from ex if CONF_SERVICE in config: domain_service = config[CONF_SERVICE] else: domain_service = config[CONF_SERVICE_TEMPLATE] if isinstance(domain_service, Template): try: domain_service.hass = hass domain_service = domain_service.async_render(variables) domain_service = cv.service(domain_service) except TemplateError as ex: raise HomeAssistantError( f"Error rendering service name template: {ex}" ) from ex except vol.Invalid as ex: raise HomeAssistantError( f"Template rendered invalid service: {domain_service}" ) from ex domain, service = domain_service.split(".", 1) service_data = {} for conf in [CONF_SERVICE_DATA, CONF_SERVICE_DATA_TEMPLATE]: if conf not in config: continue try: template.attach(hass, config[conf]) service_data.update(template.render_complex(config[conf], variables)) except TemplateError as ex: raise HomeAssistantError(f"Error rendering data template: {ex}") from ex if CONF_SERVICE_ENTITY_ID in config: service_data[ATTR_ENTITY_ID] = config[CONF_SERVICE_ENTITY_ID] return domain, service, service_data
[ "def", "async_prepare_call_from_config", "(", "hass", ":", "HomeAssistantType", ",", "config", ":", "ConfigType", ",", "variables", ":", "TemplateVarsType", "=", "None", ",", "validate_config", ":", "bool", "=", "False", ",", ")", "->", "Tuple", "[", "str", ",", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "if", "validate_config", ":", "try", ":", "config", "=", "cv", ".", "SERVICE_SCHEMA", "(", "config", ")", "except", "vol", ".", "Invalid", "as", "ex", ":", "raise", "HomeAssistantError", "(", "f\"Invalid config for calling service: {ex}\"", ")", "from", "ex", "if", "CONF_SERVICE", "in", "config", ":", "domain_service", "=", "config", "[", "CONF_SERVICE", "]", "else", ":", "domain_service", "=", "config", "[", "CONF_SERVICE_TEMPLATE", "]", "if", "isinstance", "(", "domain_service", ",", "Template", ")", ":", "try", ":", "domain_service", ".", "hass", "=", "hass", "domain_service", "=", "domain_service", ".", "async_render", "(", "variables", ")", "domain_service", "=", "cv", ".", "service", "(", "domain_service", ")", "except", "TemplateError", "as", "ex", ":", "raise", "HomeAssistantError", "(", "f\"Error rendering service name template: {ex}\"", ")", "from", "ex", "except", "vol", ".", "Invalid", "as", "ex", ":", "raise", "HomeAssistantError", "(", "f\"Template rendered invalid service: {domain_service}\"", ")", "from", "ex", "domain", ",", "service", "=", "domain_service", ".", "split", "(", "\".\"", ",", "1", ")", "service_data", "=", "{", "}", "for", "conf", "in", "[", "CONF_SERVICE_DATA", ",", "CONF_SERVICE_DATA_TEMPLATE", "]", ":", "if", "conf", "not", "in", "config", ":", "continue", "try", ":", "template", ".", "attach", "(", "hass", ",", "config", "[", "conf", "]", ")", "service_data", ".", "update", "(", "template", ".", "render_complex", "(", "config", "[", "conf", "]", ",", "variables", ")", ")", "except", "TemplateError", "as", "ex", ":", "raise", "HomeAssistantError", "(", "f\"Error rendering data template: {ex}\"", ")", "from", "ex", "if", "CONF_SERVICE_ENTITY_ID", "in", "config", ":", "service_data", "[", "ATTR_ENTITY_ID", "]", "=", "config", "[", "CONF_SERVICE_ENTITY_ID", "]", "return", "domain", ",", "service", ",", "service_data" ]
[ 101, 0 ]
[ 150, 40 ]
python
en
['en', 'en', 'en']
True
extract_entity_ids
( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True )
Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents.
Extract a list of entity ids from a service call.
def extract_entity_ids( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True ) -> Set[str]: """Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ return asyncio.run_coroutine_threadsafe( async_extract_entity_ids(hass, service_call, expand_group), hass.loop ).result()
[ "def", "extract_entity_ids", "(", "hass", ":", "HomeAssistantType", ",", "service_call", ":", "ha", ".", "ServiceCall", ",", "expand_group", ":", "bool", "=", "True", ")", "->", "Set", "[", "str", "]", ":", "return", "asyncio", ".", "run_coroutine_threadsafe", "(", "async_extract_entity_ids", "(", "hass", ",", "service_call", ",", "expand_group", ")", ",", "hass", ".", "loop", ")", ".", "result", "(", ")" ]
[ 154, 0 ]
[ 163, 14 ]
python
en
['en', 'en', 'en']
True
async_extract_entities
( hass: HomeAssistantType, entities: Iterable["Entity"], service_call: ha.ServiceCall, expand_group: bool = True, )
Extract a list of entity objects from a service call. Will convert group entity ids to the entity ids it represents.
Extract a list of entity objects from a service call.
async def async_extract_entities( hass: HomeAssistantType, entities: Iterable["Entity"], service_call: ha.ServiceCall, expand_group: bool = True, ) -> List["Entity"]: """Extract a list of entity objects from a service call. Will convert group entity ids to the entity ids it represents. """ data_ent_id = service_call.data.get(ATTR_ENTITY_ID) if data_ent_id == ENTITY_MATCH_ALL: return [entity for entity in entities if entity.available] entity_ids = await async_extract_entity_ids(hass, service_call, expand_group) found = [] for entity in entities: if entity.entity_id not in entity_ids: continue entity_ids.remove(entity.entity_id) if not entity.available: continue found.append(entity) if entity_ids: _LOGGER.warning( "Unable to find referenced entities %s", ", ".join(sorted(entity_ids)) ) return found
[ "async", "def", "async_extract_entities", "(", "hass", ":", "HomeAssistantType", ",", "entities", ":", "Iterable", "[", "\"Entity\"", "]", ",", "service_call", ":", "ha", ".", "ServiceCall", ",", "expand_group", ":", "bool", "=", "True", ",", ")", "->", "List", "[", "\"Entity\"", "]", ":", "data_ent_id", "=", "service_call", ".", "data", ".", "get", "(", "ATTR_ENTITY_ID", ")", "if", "data_ent_id", "==", "ENTITY_MATCH_ALL", ":", "return", "[", "entity", "for", "entity", "in", "entities", "if", "entity", ".", "available", "]", "entity_ids", "=", "await", "async_extract_entity_ids", "(", "hass", ",", "service_call", ",", "expand_group", ")", "found", "=", "[", "]", "for", "entity", "in", "entities", ":", "if", "entity", ".", "entity_id", "not", "in", "entity_ids", ":", "continue", "entity_ids", ".", "remove", "(", "entity", ".", "entity_id", ")", "if", "not", "entity", ".", "available", ":", "continue", "found", ".", "append", "(", "entity", ")", "if", "entity_ids", ":", "_LOGGER", ".", "warning", "(", "\"Unable to find referenced entities %s\"", ",", "\", \"", ".", "join", "(", "sorted", "(", "entity_ids", ")", ")", ")", "return", "found" ]
[ 167, 0 ]
[ 202, 16 ]
python
en
['en', 'en', 'en']
True
async_extract_entity_ids
( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True )
Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents.
Extract a list of entity ids from a service call.
async def async_extract_entity_ids( hass: HomeAssistantType, service_call: ha.ServiceCall, expand_group: bool = True ) -> Set[str]: """Extract a list of entity ids from a service call. Will convert group entity ids to the entity ids it represents. """ entity_ids = service_call.data.get(ATTR_ENTITY_ID) area_ids = service_call.data.get(ATTR_AREA_ID) extracted: Set[str] = set() if entity_ids in (None, ENTITY_MATCH_NONE) and area_ids in ( None, ENTITY_MATCH_NONE, ): return extracted if entity_ids and entity_ids != ENTITY_MATCH_NONE: # Entity ID attr can be a list or a string if isinstance(entity_ids, str): entity_ids = [entity_ids] if expand_group: entity_ids = hass.components.group.expand_entity_ids(entity_ids) extracted.update(entity_ids) if area_ids and area_ids != ENTITY_MATCH_NONE: if isinstance(area_ids, str): area_ids = [area_ids] dev_reg, ent_reg = await asyncio.gather( hass.helpers.device_registry.async_get_registry(), hass.helpers.entity_registry.async_get_registry(), ) extracted.update( entry.entity_id for area_id in area_ids for entry in hass.helpers.entity_registry.async_entries_for_area( ent_reg, area_id ) ) devices = [ device for area_id in area_ids for device in hass.helpers.device_registry.async_entries_for_area( dev_reg, area_id ) ] extracted.update( entry.entity_id for device in devices for entry in hass.helpers.entity_registry.async_entries_for_device( ent_reg, device.id ) if not entry.area_id ) return extracted
[ "async", "def", "async_extract_entity_ids", "(", "hass", ":", "HomeAssistantType", ",", "service_call", ":", "ha", ".", "ServiceCall", ",", "expand_group", ":", "bool", "=", "True", ")", "->", "Set", "[", "str", "]", ":", "entity_ids", "=", "service_call", ".", "data", ".", "get", "(", "ATTR_ENTITY_ID", ")", "area_ids", "=", "service_call", ".", "data", ".", "get", "(", "ATTR_AREA_ID", ")", "extracted", ":", "Set", "[", "str", "]", "=", "set", "(", ")", "if", "entity_ids", "in", "(", "None", ",", "ENTITY_MATCH_NONE", ")", "and", "area_ids", "in", "(", "None", ",", "ENTITY_MATCH_NONE", ",", ")", ":", "return", "extracted", "if", "entity_ids", "and", "entity_ids", "!=", "ENTITY_MATCH_NONE", ":", "# Entity ID attr can be a list or a string", "if", "isinstance", "(", "entity_ids", ",", "str", ")", ":", "entity_ids", "=", "[", "entity_ids", "]", "if", "expand_group", ":", "entity_ids", "=", "hass", ".", "components", ".", "group", ".", "expand_entity_ids", "(", "entity_ids", ")", "extracted", ".", "update", "(", "entity_ids", ")", "if", "area_ids", "and", "area_ids", "!=", "ENTITY_MATCH_NONE", ":", "if", "isinstance", "(", "area_ids", ",", "str", ")", ":", "area_ids", "=", "[", "area_ids", "]", "dev_reg", ",", "ent_reg", "=", "await", "asyncio", ".", "gather", "(", "hass", ".", "helpers", ".", "device_registry", ".", "async_get_registry", "(", ")", ",", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", ",", ")", "extracted", ".", "update", "(", "entry", ".", "entity_id", "for", "area_id", "in", "area_ids", "for", "entry", "in", "hass", ".", "helpers", ".", "entity_registry", ".", "async_entries_for_area", "(", "ent_reg", ",", "area_id", ")", ")", "devices", "=", "[", "device", "for", "area_id", "in", "area_ids", "for", "device", "in", "hass", ".", "helpers", ".", "device_registry", ".", "async_entries_for_area", "(", "dev_reg", ",", "area_id", ")", "]", "extracted", ".", "update", "(", "entry", ".", "entity_id", "for", "device", "in", "devices", "for", "entry", "in", "hass", ".", "helpers", ".", "entity_registry", ".", "async_entries_for_device", "(", "ent_reg", ",", "device", ".", "id", ")", "if", "not", "entry", ".", "area_id", ")", "return", "extracted" ]
[ 206, 0 ]
[ 267, 20 ]
python
en
['en', 'en', 'en']
True
_load_services_file
(hass: HomeAssistantType, integration: Integration)
Load services file for an integration.
Load services file for an integration.
def _load_services_file(hass: HomeAssistantType, integration: Integration) -> JSON_TYPE: """Load services file for an integration.""" try: return load_yaml(str(integration.file_path / "services.yaml")) except FileNotFoundError: _LOGGER.warning( "Unable to find services.yaml for the %s integration", integration.domain ) return {} except HomeAssistantError: _LOGGER.warning( "Unable to parse services.yaml for the %s integration", integration.domain ) return {}
[ "def", "_load_services_file", "(", "hass", ":", "HomeAssistantType", ",", "integration", ":", "Integration", ")", "->", "JSON_TYPE", ":", "try", ":", "return", "load_yaml", "(", "str", "(", "integration", ".", "file_path", "/", "\"services.yaml\"", ")", ")", "except", "FileNotFoundError", ":", "_LOGGER", ".", "warning", "(", "\"Unable to find services.yaml for the %s integration\"", ",", "integration", ".", "domain", ")", "return", "{", "}", "except", "HomeAssistantError", ":", "_LOGGER", ".", "warning", "(", "\"Unable to parse services.yaml for the %s integration\"", ",", "integration", ".", "domain", ")", "return", "{", "}" ]
[ 270, 0 ]
[ 283, 17 ]
python
en
['en', 'en', 'en']
True
_load_services_files
( hass: HomeAssistantType, integrations: Iterable[Integration] )
Load service files for multiple intergrations.
Load service files for multiple intergrations.
def _load_services_files( hass: HomeAssistantType, integrations: Iterable[Integration] ) -> List[JSON_TYPE]: """Load service files for multiple intergrations.""" return [_load_services_file(hass, integration) for integration in integrations]
[ "def", "_load_services_files", "(", "hass", ":", "HomeAssistantType", ",", "integrations", ":", "Iterable", "[", "Integration", "]", ")", "->", "List", "[", "JSON_TYPE", "]", ":", "return", "[", "_load_services_file", "(", "hass", ",", "integration", ")", "for", "integration", "in", "integrations", "]" ]
[ 286, 0 ]
[ 290, 83 ]
python
en
['en', 'en', 'en']
True
async_get_all_descriptions
( hass: HomeAssistantType, )
Return descriptions (i.e. user documentation) for all service calls.
Return descriptions (i.e. user documentation) for all service calls.
async def async_get_all_descriptions( hass: HomeAssistantType, ) -> Dict[str, Dict[str, Any]]: """Return descriptions (i.e. user documentation) for all service calls.""" descriptions_cache = hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {}) format_cache_key = "{}.{}".format services = hass.services.async_services() # See if there are new services not seen before. # Any service that we saw before already has an entry in description_cache. missing = set() for domain in services: for service in services[domain]: if format_cache_key(domain, service) not in descriptions_cache: missing.add(domain) break # Files we loaded for missing descriptions loaded = {} if missing: integrations = await gather_with_concurrency( MAX_LOAD_CONCURRENTLY, *(async_get_integration(hass, domain) for domain in missing), ) contents = await hass.async_add_executor_job( _load_services_files, hass, integrations ) for domain, content in zip(missing, contents): loaded[domain] = content # Build response descriptions: Dict[str, Dict[str, Any]] = {} for domain in services: descriptions[domain] = {} for service in services[domain]: cache_key = format_cache_key(domain, service) description = descriptions_cache.get(cache_key) # Cache missing descriptions if description is None: domain_yaml = loaded[domain] yaml_description = domain_yaml.get(service, {}) # type: ignore # Don't warn for missing services, because it triggers false # positives for things like scripts, that register as a service description = descriptions_cache[cache_key] = { "description": yaml_description.get("description", ""), "fields": yaml_description.get("fields", {}), } descriptions[domain][service] = description return descriptions
[ "async", "def", "async_get_all_descriptions", "(", "hass", ":", "HomeAssistantType", ",", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", ":", "descriptions_cache", "=", "hass", ".", "data", ".", "setdefault", "(", "SERVICE_DESCRIPTION_CACHE", ",", "{", "}", ")", "format_cache_key", "=", "\"{}.{}\"", ".", "format", "services", "=", "hass", ".", "services", ".", "async_services", "(", ")", "# See if there are new services not seen before.", "# Any service that we saw before already has an entry in description_cache.", "missing", "=", "set", "(", ")", "for", "domain", "in", "services", ":", "for", "service", "in", "services", "[", "domain", "]", ":", "if", "format_cache_key", "(", "domain", ",", "service", ")", "not", "in", "descriptions_cache", ":", "missing", ".", "add", "(", "domain", ")", "break", "# Files we loaded for missing descriptions", "loaded", "=", "{", "}", "if", "missing", ":", "integrations", "=", "await", "gather_with_concurrency", "(", "MAX_LOAD_CONCURRENTLY", ",", "*", "(", "async_get_integration", "(", "hass", ",", "domain", ")", "for", "domain", "in", "missing", ")", ",", ")", "contents", "=", "await", "hass", ".", "async_add_executor_job", "(", "_load_services_files", ",", "hass", ",", "integrations", ")", "for", "domain", ",", "content", "in", "zip", "(", "missing", ",", "contents", ")", ":", "loaded", "[", "domain", "]", "=", "content", "# Build response", "descriptions", ":", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Any", "]", "]", "=", "{", "}", "for", "domain", "in", "services", ":", "descriptions", "[", "domain", "]", "=", "{", "}", "for", "service", "in", "services", "[", "domain", "]", ":", "cache_key", "=", "format_cache_key", "(", "domain", ",", "service", ")", "description", "=", "descriptions_cache", ".", "get", "(", "cache_key", ")", "# Cache missing descriptions", "if", "description", "is", "None", ":", "domain_yaml", "=", "loaded", "[", "domain", "]", "yaml_description", "=", "domain_yaml", ".", "get", "(", "service", ",", "{", "}", ")", "# type: ignore", "# Don't warn for missing services, because it triggers false", "# positives for things like scripts, that register as a service", "description", "=", "descriptions_cache", "[", "cache_key", "]", "=", "{", "\"description\"", ":", "yaml_description", ".", "get", "(", "\"description\"", ",", "\"\"", ")", ",", "\"fields\"", ":", "yaml_description", ".", "get", "(", "\"fields\"", ",", "{", "}", ")", ",", "}", "descriptions", "[", "domain", "]", "[", "service", "]", "=", "description", "return", "descriptions" ]
[ 294, 0 ]
[ 351, 23 ]
python
en
['en', 'pt', 'en']
True
async_set_service_schema
( hass: HomeAssistantType, domain: str, service: str, schema: Dict[str, Any] )
Register a description for a service.
Register a description for a service.
def async_set_service_schema( hass: HomeAssistantType, domain: str, service: str, schema: Dict[str, Any] ) -> None: """Register a description for a service.""" hass.data.setdefault(SERVICE_DESCRIPTION_CACHE, {}) description = { "description": schema.get("description") or "", "fields": schema.get("fields") or {}, } hass.data[SERVICE_DESCRIPTION_CACHE][f"{domain}.{service}"] = description
[ "def", "async_set_service_schema", "(", "hass", ":", "HomeAssistantType", ",", "domain", ":", "str", ",", "service", ":", "str", ",", "schema", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "None", ":", "hass", ".", "data", ".", "setdefault", "(", "SERVICE_DESCRIPTION_CACHE", ",", "{", "}", ")", "description", "=", "{", "\"description\"", ":", "schema", ".", "get", "(", "\"description\"", ")", "or", "\"\"", ",", "\"fields\"", ":", "schema", ".", "get", "(", "\"fields\"", ")", "or", "{", "}", ",", "}", "hass", ".", "data", "[", "SERVICE_DESCRIPTION_CACHE", "]", "[", "f\"{domain}.{service}\"", "]", "=", "description" ]
[ 356, 0 ]
[ 367, 77 ]
python
en
['es', 'fr', 'en']
False
entity_service_call
( hass: HomeAssistantType, platforms: Iterable["EntityPlatform"], func: Union[str, Callable[..., Any]], call: ha.ServiceCall, required_features: Optional[Iterable[int]] = None, )
Handle an entity service call. Calls all platforms simultaneously.
Handle an entity service call.
async def entity_service_call( hass: HomeAssistantType, platforms: Iterable["EntityPlatform"], func: Union[str, Callable[..., Any]], call: ha.ServiceCall, required_features: Optional[Iterable[int]] = None, ) -> None: """Handle an entity service call. Calls all platforms simultaneously. """ if call.context.user_id: user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser(context=call.context) entity_perms: Optional[ Callable[[str, str], bool] ] = user.permissions.check_entity else: entity_perms = None target_all_entities = call.data.get(ATTR_ENTITY_ID) == ENTITY_MATCH_ALL if not target_all_entities: # A set of entities we're trying to target. entity_ids = await async_extract_entity_ids(hass, call, True) # If the service function is a string, we'll pass it the service call data if isinstance(func, str): data: Union[Dict, ha.ServiceCall] = { key: val for key, val in call.data.items() if key not in cv.ENTITY_SERVICE_FIELDS } # If the service function is not a string, we pass the service call else: data = call # Check the permissions # A list with entities to call the service on. entity_candidates: List["Entity"] = [] if entity_perms is None: for platform in platforms: if target_all_entities: entity_candidates.extend(platform.entities.values()) else: entity_candidates.extend( [ entity for entity in platform.entities.values() if entity.entity_id in entity_ids ] ) elif target_all_entities: # If we target all entities, we will select all entities the user # is allowed to control. for platform in platforms: entity_candidates.extend( [ entity for entity in platform.entities.values() if entity_perms(entity.entity_id, POLICY_CONTROL) ] ) else: for platform in platforms: platform_entities = [] for entity in platform.entities.values(): if entity.entity_id not in entity_ids: continue if not entity_perms(entity.entity_id, POLICY_CONTROL): raise Unauthorized( context=call.context, entity_id=entity.entity_id, permission=POLICY_CONTROL, ) platform_entities.append(entity) entity_candidates.extend(platform_entities) if not target_all_entities: for entity in entity_candidates: entity_ids.remove(entity.entity_id) if entity_ids: _LOGGER.warning( "Unable to find referenced entities %s", ", ".join(sorted(entity_ids)) ) entities = [] for entity in entity_candidates: if not entity.available: continue # Skip entities that don't have the required feature. if required_features is not None and ( entity.supported_features is None or not any( entity.supported_features & feature_set == feature_set for feature_set in required_features ) ): continue entities.append(entity) if not entities: return done, pending = await asyncio.wait( [ entity.async_request_call( _handle_entity_call(hass, entity, func, data, call.context) ) for entity in entities ] ) assert not pending for future in done: future.result() # pop exception if have tasks = [] for entity in entities: if not entity.should_poll: continue # Context expires if the turn on commands took a long time. # Set context again so it's there when we update entity.async_set_context(call.context) tasks.append(entity.async_update_ha_state(True)) if tasks: done, pending = await asyncio.wait(tasks) assert not pending for future in done: future.result()
[ "async", "def", "entity_service_call", "(", "hass", ":", "HomeAssistantType", ",", "platforms", ":", "Iterable", "[", "\"EntityPlatform\"", "]", ",", "func", ":", "Union", "[", "str", ",", "Callable", "[", "...", ",", "Any", "]", "]", ",", "call", ":", "ha", ".", "ServiceCall", ",", "required_features", ":", "Optional", "[", "Iterable", "[", "int", "]", "]", "=", "None", ",", ")", "->", "None", ":", "if", "call", ".", "context", ".", "user_id", ":", "user", "=", "await", "hass", ".", "auth", ".", "async_get_user", "(", "call", ".", "context", ".", "user_id", ")", "if", "user", "is", "None", ":", "raise", "UnknownUser", "(", "context", "=", "call", ".", "context", ")", "entity_perms", ":", "Optional", "[", "Callable", "[", "[", "str", ",", "str", "]", ",", "bool", "]", "]", "=", "user", ".", "permissions", ".", "check_entity", "else", ":", "entity_perms", "=", "None", "target_all_entities", "=", "call", ".", "data", ".", "get", "(", "ATTR_ENTITY_ID", ")", "==", "ENTITY_MATCH_ALL", "if", "not", "target_all_entities", ":", "# A set of entities we're trying to target.", "entity_ids", "=", "await", "async_extract_entity_ids", "(", "hass", ",", "call", ",", "True", ")", "# If the service function is a string, we'll pass it the service call data", "if", "isinstance", "(", "func", ",", "str", ")", ":", "data", ":", "Union", "[", "Dict", ",", "ha", ".", "ServiceCall", "]", "=", "{", "key", ":", "val", "for", "key", ",", "val", "in", "call", ".", "data", ".", "items", "(", ")", "if", "key", "not", "in", "cv", ".", "ENTITY_SERVICE_FIELDS", "}", "# If the service function is not a string, we pass the service call", "else", ":", "data", "=", "call", "# Check the permissions", "# A list with entities to call the service on.", "entity_candidates", ":", "List", "[", "\"Entity\"", "]", "=", "[", "]", "if", "entity_perms", "is", "None", ":", "for", "platform", "in", "platforms", ":", "if", "target_all_entities", ":", "entity_candidates", ".", "extend", "(", "platform", ".", "entities", ".", "values", "(", ")", ")", "else", ":", "entity_candidates", ".", "extend", "(", "[", "entity", "for", "entity", "in", "platform", ".", "entities", ".", "values", "(", ")", "if", "entity", ".", "entity_id", "in", "entity_ids", "]", ")", "elif", "target_all_entities", ":", "# If we target all entities, we will select all entities the user", "# is allowed to control.", "for", "platform", "in", "platforms", ":", "entity_candidates", ".", "extend", "(", "[", "entity", "for", "entity", "in", "platform", ".", "entities", ".", "values", "(", ")", "if", "entity_perms", "(", "entity", ".", "entity_id", ",", "POLICY_CONTROL", ")", "]", ")", "else", ":", "for", "platform", "in", "platforms", ":", "platform_entities", "=", "[", "]", "for", "entity", "in", "platform", ".", "entities", ".", "values", "(", ")", ":", "if", "entity", ".", "entity_id", "not", "in", "entity_ids", ":", "continue", "if", "not", "entity_perms", "(", "entity", ".", "entity_id", ",", "POLICY_CONTROL", ")", ":", "raise", "Unauthorized", "(", "context", "=", "call", ".", "context", ",", "entity_id", "=", "entity", ".", "entity_id", ",", "permission", "=", "POLICY_CONTROL", ",", ")", "platform_entities", ".", "append", "(", "entity", ")", "entity_candidates", ".", "extend", "(", "platform_entities", ")", "if", "not", "target_all_entities", ":", "for", "entity", "in", "entity_candidates", ":", "entity_ids", ".", "remove", "(", "entity", ".", "entity_id", ")", "if", "entity_ids", ":", "_LOGGER", ".", "warning", "(", "\"Unable to find referenced entities %s\"", ",", "\", \"", ".", "join", "(", "sorted", "(", "entity_ids", ")", ")", ")", "entities", "=", "[", "]", "for", "entity", "in", "entity_candidates", ":", "if", "not", "entity", ".", "available", ":", "continue", "# Skip entities that don't have the required feature.", "if", "required_features", "is", "not", "None", "and", "(", "entity", ".", "supported_features", "is", "None", "or", "not", "any", "(", "entity", ".", "supported_features", "&", "feature_set", "==", "feature_set", "for", "feature_set", "in", "required_features", ")", ")", ":", "continue", "entities", ".", "append", "(", "entity", ")", "if", "not", "entities", ":", "return", "done", ",", "pending", "=", "await", "asyncio", ".", "wait", "(", "[", "entity", ".", "async_request_call", "(", "_handle_entity_call", "(", "hass", ",", "entity", ",", "func", ",", "data", ",", "call", ".", "context", ")", ")", "for", "entity", "in", "entities", "]", ")", "assert", "not", "pending", "for", "future", "in", "done", ":", "future", ".", "result", "(", ")", "# pop exception if have", "tasks", "=", "[", "]", "for", "entity", "in", "entities", ":", "if", "not", "entity", ".", "should_poll", ":", "continue", "# Context expires if the turn on commands took a long time.", "# Set context again so it's there when we update", "entity", ".", "async_set_context", "(", "call", ".", "context", ")", "tasks", ".", "append", "(", "entity", ".", "async_update_ha_state", "(", "True", ")", ")", "if", "tasks", ":", "done", ",", "pending", "=", "await", "asyncio", ".", "wait", "(", "tasks", ")", "assert", "not", "pending", "for", "future", "in", "done", ":", "future", ".", "result", "(", ")" ]
[ 371, 0 ]
[ 515, 27 ]
python
en
['en', 'en', 'en']
True
_handle_entity_call
( hass: HomeAssistantType, entity: "Entity", func: Union[str, Callable[..., Any]], data: Union[Dict, ha.ServiceCall], context: ha.Context, )
Handle calling service method.
Handle calling service method.
async def _handle_entity_call( hass: HomeAssistantType, entity: "Entity", func: Union[str, Callable[..., Any]], data: Union[Dict, ha.ServiceCall], context: ha.Context, ) -> None: """Handle calling service method.""" entity.async_set_context(context) if isinstance(func, str): result = hass.async_add_job(partial(getattr(entity, func), **data)) # type: ignore else: result = hass.async_add_job(func, entity, data) # Guard because callback functions do not return a task when passed to async_add_job. if result is not None: await result if asyncio.iscoroutine(result): _LOGGER.error( "Service %s for %s incorrectly returns a coroutine object. Await result instead in service handler. Report bug to integration author", func, entity.entity_id, ) await result
[ "async", "def", "_handle_entity_call", "(", "hass", ":", "HomeAssistantType", ",", "entity", ":", "\"Entity\"", ",", "func", ":", "Union", "[", "str", ",", "Callable", "[", "...", ",", "Any", "]", "]", ",", "data", ":", "Union", "[", "Dict", ",", "ha", ".", "ServiceCall", "]", ",", "context", ":", "ha", ".", "Context", ",", ")", "->", "None", ":", "entity", ".", "async_set_context", "(", "context", ")", "if", "isinstance", "(", "func", ",", "str", ")", ":", "result", "=", "hass", ".", "async_add_job", "(", "partial", "(", "getattr", "(", "entity", ",", "func", ")", ",", "*", "*", "data", ")", ")", "# type: ignore", "else", ":", "result", "=", "hass", ".", "async_add_job", "(", "func", ",", "entity", ",", "data", ")", "# Guard because callback functions do not return a task when passed to async_add_job.", "if", "result", "is", "not", "None", ":", "await", "result", "if", "asyncio", ".", "iscoroutine", "(", "result", ")", ":", "_LOGGER", ".", "error", "(", "\"Service %s for %s incorrectly returns a coroutine object. Await result instead in service handler. Report bug to integration author\"", ",", "func", ",", "entity", ".", "entity_id", ",", ")", "await", "result" ]
[ 518, 0 ]
[ 543, 20 ]
python
en
['en', 'xh', 'en']
True
async_register_admin_service
( hass: HomeAssistantType, domain: str, service: str, service_func: Callable[[ha.ServiceCall], Optional[Awaitable]], schema: vol.Schema = vol.Schema({}, extra=vol.PREVENT_EXTRA), )
Register a service that requires admin access.
Register a service that requires admin access.
def async_register_admin_service( hass: HomeAssistantType, domain: str, service: str, service_func: Callable[[ha.ServiceCall], Optional[Awaitable]], schema: vol.Schema = vol.Schema({}, extra=vol.PREVENT_EXTRA), ) -> None: """Register a service that requires admin access.""" @wraps(service_func) async def admin_handler(call: ha.ServiceCall) -> None: if call.context.user_id: user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser(context=call.context) if not user.is_admin: raise Unauthorized(context=call.context) result = hass.async_add_job(service_func, call) if result is not None: await result hass.services.async_register(domain, service, admin_handler, schema)
[ "def", "async_register_admin_service", "(", "hass", ":", "HomeAssistantType", ",", "domain", ":", "str", ",", "service", ":", "str", ",", "service_func", ":", "Callable", "[", "[", "ha", ".", "ServiceCall", "]", ",", "Optional", "[", "Awaitable", "]", "]", ",", "schema", ":", "vol", ".", "Schema", "=", "vol", ".", "Schema", "(", "{", "}", ",", "extra", "=", "vol", ".", "PREVENT_EXTRA", ")", ",", ")", "->", "None", ":", "@", "wraps", "(", "service_func", ")", "async", "def", "admin_handler", "(", "call", ":", "ha", ".", "ServiceCall", ")", "->", "None", ":", "if", "call", ".", "context", ".", "user_id", ":", "user", "=", "await", "hass", ".", "auth", ".", "async_get_user", "(", "call", ".", "context", ".", "user_id", ")", "if", "user", "is", "None", ":", "raise", "UnknownUser", "(", "context", "=", "call", ".", "context", ")", "if", "not", "user", ".", "is_admin", ":", "raise", "Unauthorized", "(", "context", "=", "call", ".", "context", ")", "result", "=", "hass", ".", "async_add_job", "(", "service_func", ",", "call", ")", "if", "result", "is", "not", "None", ":", "await", "result", "hass", ".", "services", ".", "async_register", "(", "domain", ",", "service", ",", "admin_handler", ",", "schema", ")" ]
[ 548, 0 ]
[ 570, 72 ]
python
en
['en', 'en', 'en']
True
verify_domain_control
(hass: HomeAssistantType, domain: str)
Ensure permission to access any entity under domain in service call.
Ensure permission to access any entity under domain in service call.
def verify_domain_control(hass: HomeAssistantType, domain: str) -> Callable: """Ensure permission to access any entity under domain in service call.""" def decorator(service_handler: Callable[[ha.ServiceCall], Any]) -> Callable: """Decorate.""" if not asyncio.iscoroutinefunction(service_handler): raise HomeAssistantError("Can only decorate async functions.") async def check_permissions(call: ha.ServiceCall) -> Any: """Check user permission and raise before call if unauthorized.""" if not call.context.user_id: return await service_handler(call) user = await hass.auth.async_get_user(call.context.user_id) if user is None: raise UnknownUser( context=call.context, permission=POLICY_CONTROL, user_id=call.context.user_id, ) reg = await hass.helpers.entity_registry.async_get_registry() authorized = False for entity in reg.entities.values(): if entity.platform != domain: continue if user.permissions.check_entity(entity.entity_id, POLICY_CONTROL): authorized = True break if not authorized: raise Unauthorized( context=call.context, permission=POLICY_CONTROL, user_id=call.context.user_id, perm_category=CAT_ENTITIES, ) return await service_handler(call) return check_permissions return decorator
[ "def", "verify_domain_control", "(", "hass", ":", "HomeAssistantType", ",", "domain", ":", "str", ")", "->", "Callable", ":", "def", "decorator", "(", "service_handler", ":", "Callable", "[", "[", "ha", ".", "ServiceCall", "]", ",", "Any", "]", ")", "->", "Callable", ":", "\"\"\"Decorate.\"\"\"", "if", "not", "asyncio", ".", "iscoroutinefunction", "(", "service_handler", ")", ":", "raise", "HomeAssistantError", "(", "\"Can only decorate async functions.\"", ")", "async", "def", "check_permissions", "(", "call", ":", "ha", ".", "ServiceCall", ")", "->", "Any", ":", "\"\"\"Check user permission and raise before call if unauthorized.\"\"\"", "if", "not", "call", ".", "context", ".", "user_id", ":", "return", "await", "service_handler", "(", "call", ")", "user", "=", "await", "hass", ".", "auth", ".", "async_get_user", "(", "call", ".", "context", ".", "user_id", ")", "if", "user", "is", "None", ":", "raise", "UnknownUser", "(", "context", "=", "call", ".", "context", ",", "permission", "=", "POLICY_CONTROL", ",", "user_id", "=", "call", ".", "context", ".", "user_id", ",", ")", "reg", "=", "await", "hass", ".", "helpers", ".", "entity_registry", ".", "async_get_registry", "(", ")", "authorized", "=", "False", "for", "entity", "in", "reg", ".", "entities", ".", "values", "(", ")", ":", "if", "entity", ".", "platform", "!=", "domain", ":", "continue", "if", "user", ".", "permissions", ".", "check_entity", "(", "entity", ".", "entity_id", ",", "POLICY_CONTROL", ")", ":", "authorized", "=", "True", "break", "if", "not", "authorized", ":", "raise", "Unauthorized", "(", "context", "=", "call", ".", "context", ",", "permission", "=", "POLICY_CONTROL", ",", "user_id", "=", "call", ".", "context", ".", "user_id", ",", "perm_category", "=", "CAT_ENTITIES", ",", ")", "return", "await", "service_handler", "(", "call", ")", "return", "check_permissions", "return", "decorator" ]
[ 575, 0 ]
[ 621, 20 ]
python
en
['en', 'en', 'en']
True
test_form
(hass)
Test we get the form.
Test we get the form.
async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} result2 = await hass.config_entries.flow.async_configure( result["flow_id"], {"country": OPTION_WORLDWIDE}, ) assert result2["type"] == "create_entry" assert result2["title"] == "Worldwide" assert result2["result"].unique_id == OPTION_WORLDWIDE assert result2["data"] == { "country": OPTION_WORLDWIDE, } await hass.async_block_till_done() assert len(hass.states.async_all()) == 4
[ "async", "def", "test_form", "(", "hass", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", ")", "assert", "result", "[", "\"type\"", "]", "==", "\"form\"", "assert", "result", "[", "\"errors\"", "]", "==", "{", "}", "result2", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_configure", "(", "result", "[", "\"flow_id\"", "]", ",", "{", "\"country\"", ":", "OPTION_WORLDWIDE", "}", ",", ")", "assert", "result2", "[", "\"type\"", "]", "==", "\"create_entry\"", "assert", "result2", "[", "\"title\"", "]", "==", "\"Worldwide\"", "assert", "result2", "[", "\"result\"", "]", ".", "unique_id", "==", "OPTION_WORLDWIDE", "assert", "result2", "[", "\"data\"", "]", "==", "{", "\"country\"", ":", "OPTION_WORLDWIDE", ",", "}", "await", "hass", ".", "async_block_till_done", "(", ")", "assert", "len", "(", "hass", ".", "states", ".", "async_all", "(", ")", ")", "==", "4" ]
[ 5, 0 ]
[ 25, 44 ]
python
en
['en', 'en', 'en']
True
test_bridge_setup
(hass)
Test a successful setup.
Test a successful setup.
async def test_bridge_setup(hass): """Test a successful setup.""" entry = Mock() api = Mock(initialize=AsyncMock()) entry.data = {"host": "1.2.3.4", "username": "mock-username"} entry.options = {CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False} hue_bridge = bridge.HueBridge(hass, entry) with patch("aiohue.Bridge", return_value=api), patch.object( hass.config_entries, "async_forward_entry_setup" ) as mock_forward: assert await hue_bridge.async_setup() is True assert hue_bridge.api is api assert len(mock_forward.mock_calls) == 3 forward_entries = {c[1][1] for c in mock_forward.mock_calls} assert forward_entries == {"light", "binary_sensor", "sensor"}
[ "async", "def", "test_bridge_setup", "(", "hass", ")", ":", "entry", "=", "Mock", "(", ")", "api", "=", "Mock", "(", "initialize", "=", "AsyncMock", "(", ")", ")", "entry", ".", "data", "=", "{", "\"host\"", ":", "\"1.2.3.4\"", ",", "\"username\"", ":", "\"mock-username\"", "}", "entry", ".", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "False", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "entry", ")", "with", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "api", ")", ",", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_forward_entry_setup\"", ")", "as", "mock_forward", ":", "assert", "await", "hue_bridge", ".", "async_setup", "(", ")", "is", "True", "assert", "hue_bridge", ".", "api", "is", "api", "assert", "len", "(", "mock_forward", ".", "mock_calls", ")", "==", "3", "forward_entries", "=", "{", "c", "[", "1", "]", "[", "1", "]", "for", "c", "in", "mock_forward", ".", "mock_calls", "}", "assert", "forward_entries", "==", "{", "\"light\"", ",", "\"binary_sensor\"", ",", "\"sensor\"", "}" ]
[ 15, 0 ]
[ 31, 66 ]
python
en
['en', 'co', 'en']
True
test_bridge_setup_invalid_username
(hass)
Test we start config flow if username is no longer whitelisted.
Test we start config flow if username is no longer whitelisted.
async def test_bridge_setup_invalid_username(hass): """Test we start config flow if username is no longer whitelisted.""" entry = Mock() entry.data = {"host": "1.2.3.4", "username": "mock-username"} entry.options = {CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False} hue_bridge = bridge.HueBridge(hass, entry) with patch.object( bridge, "authenticate_bridge", side_effect=errors.AuthenticationRequired ), patch.object(hass.config_entries.flow, "async_init") as mock_init: assert await hue_bridge.async_setup() is False assert len(mock_init.mock_calls) == 1 assert mock_init.mock_calls[0][2]["data"] == {"host": "1.2.3.4"}
[ "async", "def", "test_bridge_setup_invalid_username", "(", "hass", ")", ":", "entry", "=", "Mock", "(", ")", "entry", ".", "data", "=", "{", "\"host\"", ":", "\"1.2.3.4\"", ",", "\"username\"", ":", "\"mock-username\"", "}", "entry", ".", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "False", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "entry", ")", "with", "patch", ".", "object", "(", "bridge", ",", "\"authenticate_bridge\"", ",", "side_effect", "=", "errors", ".", "AuthenticationRequired", ")", ",", "patch", ".", "object", "(", "hass", ".", "config_entries", ".", "flow", ",", "\"async_init\"", ")", "as", "mock_init", ":", "assert", "await", "hue_bridge", ".", "async_setup", "(", ")", "is", "False", "assert", "len", "(", "mock_init", ".", "mock_calls", ")", "==", "1", "assert", "mock_init", ".", "mock_calls", "[", "0", "]", "[", "2", "]", "[", "\"data\"", "]", "==", "{", "\"host\"", ":", "\"1.2.3.4\"", "}" ]
[ 34, 0 ]
[ 47, 68 ]
python
en
['en', 'en', 'en']
True
test_bridge_setup_timeout
(hass)
Test we retry to connect if we cannot connect.
Test we retry to connect if we cannot connect.
async def test_bridge_setup_timeout(hass): """Test we retry to connect if we cannot connect.""" entry = Mock() entry.data = {"host": "1.2.3.4", "username": "mock-username"} entry.options = {CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False} hue_bridge = bridge.HueBridge(hass, entry) with patch.object( bridge, "authenticate_bridge", side_effect=errors.CannotConnect ), pytest.raises(ConfigEntryNotReady): await hue_bridge.async_setup()
[ "async", "def", "test_bridge_setup_timeout", "(", "hass", ")", ":", "entry", "=", "Mock", "(", ")", "entry", ".", "data", "=", "{", "\"host\"", ":", "\"1.2.3.4\"", ",", "\"username\"", ":", "\"mock-username\"", "}", "entry", ".", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "False", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "entry", ")", "with", "patch", ".", "object", "(", "bridge", ",", "\"authenticate_bridge\"", ",", "side_effect", "=", "errors", ".", "CannotConnect", ")", ",", "pytest", ".", "raises", "(", "ConfigEntryNotReady", ")", ":", "await", "hue_bridge", ".", "async_setup", "(", ")" ]
[ 50, 0 ]
[ 60, 38 ]
python
en
['en', 'en', 'en']
True
test_reset_if_entry_had_wrong_auth
(hass)
Test calling reset when the entry contained wrong auth.
Test calling reset when the entry contained wrong auth.
async def test_reset_if_entry_had_wrong_auth(hass): """Test calling reset when the entry contained wrong auth.""" entry = Mock() entry.data = {"host": "1.2.3.4", "username": "mock-username"} entry.options = {CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False} hue_bridge = bridge.HueBridge(hass, entry) with patch.object( bridge, "authenticate_bridge", side_effect=errors.AuthenticationRequired ), patch.object(bridge, "create_config_flow") as mock_create: assert await hue_bridge.async_setup() is False assert len(mock_create.mock_calls) == 1 assert await hue_bridge.async_reset()
[ "async", "def", "test_reset_if_entry_had_wrong_auth", "(", "hass", ")", ":", "entry", "=", "Mock", "(", ")", "entry", ".", "data", "=", "{", "\"host\"", ":", "\"1.2.3.4\"", ",", "\"username\"", ":", "\"mock-username\"", "}", "entry", ".", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "False", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "entry", ")", "with", "patch", ".", "object", "(", "bridge", ",", "\"authenticate_bridge\"", ",", "side_effect", "=", "errors", ".", "AuthenticationRequired", ")", ",", "patch", ".", "object", "(", "bridge", ",", "\"create_config_flow\"", ")", "as", "mock_create", ":", "assert", "await", "hue_bridge", ".", "async_setup", "(", ")", "is", "False", "assert", "len", "(", "mock_create", ".", "mock_calls", ")", "==", "1", "assert", "await", "hue_bridge", ".", "async_reset", "(", ")" ]
[ 63, 0 ]
[ 77, 41 ]
python
en
['en', 'en', 'en']
True
test_reset_unloads_entry_if_setup
(hass)
Test calling reset while the entry has been setup.
Test calling reset while the entry has been setup.
async def test_reset_unloads_entry_if_setup(hass): """Test calling reset while the entry has been setup.""" entry = Mock() entry.data = {"host": "1.2.3.4", "username": "mock-username"} entry.options = {CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False} hue_bridge = bridge.HueBridge(hass, entry) with patch.object(bridge, "authenticate_bridge", return_value=Mock()), patch( "aiohue.Bridge", return_value=Mock() ), patch.object(hass.config_entries, "async_forward_entry_setup") as mock_forward: assert await hue_bridge.async_setup() is True assert len(hass.services.async_services()) == 0 assert len(mock_forward.mock_calls) == 3 with patch.object( hass.config_entries, "async_forward_entry_unload", return_value=True ) as mock_forward: assert await hue_bridge.async_reset() assert len(mock_forward.mock_calls) == 3 assert len(hass.services.async_services()) == 0
[ "async", "def", "test_reset_unloads_entry_if_setup", "(", "hass", ")", ":", "entry", "=", "Mock", "(", ")", "entry", ".", "data", "=", "{", "\"host\"", ":", "\"1.2.3.4\"", ",", "\"username\"", ":", "\"mock-username\"", "}", "entry", ".", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "False", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "entry", ")", "with", "patch", ".", "object", "(", "bridge", ",", "\"authenticate_bridge\"", ",", "return_value", "=", "Mock", "(", ")", ")", ",", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "Mock", "(", ")", ")", ",", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_forward_entry_setup\"", ")", "as", "mock_forward", ":", "assert", "await", "hue_bridge", ".", "async_setup", "(", ")", "is", "True", "assert", "len", "(", "hass", ".", "services", ".", "async_services", "(", ")", ")", "==", "0", "assert", "len", "(", "mock_forward", ".", "mock_calls", ")", "==", "3", "with", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_forward_entry_unload\"", ",", "return_value", "=", "True", ")", "as", "mock_forward", ":", "assert", "await", "hue_bridge", ".", "async_reset", "(", ")", "assert", "len", "(", "mock_forward", ".", "mock_calls", ")", "==", "3", "assert", "len", "(", "hass", ".", "services", ".", "async_services", "(", ")", ")", "==", "0" ]
[ 80, 0 ]
[ 101, 51 ]
python
en
['en', 'en', 'en']
True
test_handle_unauthorized
(hass)
Test handling an unauthorized error on update.
Test handling an unauthorized error on update.
async def test_handle_unauthorized(hass): """Test handling an unauthorized error on update.""" entry = Mock(async_setup=AsyncMock()) entry.data = {"host": "1.2.3.4", "username": "mock-username"} entry.options = {CONF_ALLOW_HUE_GROUPS: False, CONF_ALLOW_UNREACHABLE: False} hue_bridge = bridge.HueBridge(hass, entry) with patch.object(bridge, "authenticate_bridge", return_value=Mock()), patch( "aiohue.Bridge", return_value=Mock() ): assert await hue_bridge.async_setup() is True assert hue_bridge.authorized is True with patch.object(bridge, "create_config_flow") as mock_create: await hue_bridge.handle_unauthorized_error() assert hue_bridge.authorized is False assert len(mock_create.mock_calls) == 1 assert mock_create.mock_calls[0][1][1] == "1.2.3.4"
[ "async", "def", "test_handle_unauthorized", "(", "hass", ")", ":", "entry", "=", "Mock", "(", "async_setup", "=", "AsyncMock", "(", ")", ")", "entry", ".", "data", "=", "{", "\"host\"", ":", "\"1.2.3.4\"", ",", "\"username\"", ":", "\"mock-username\"", "}", "entry", ".", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "False", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "entry", ")", "with", "patch", ".", "object", "(", "bridge", ",", "\"authenticate_bridge\"", ",", "return_value", "=", "Mock", "(", ")", ")", ",", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "Mock", "(", ")", ")", ":", "assert", "await", "hue_bridge", ".", "async_setup", "(", ")", "is", "True", "assert", "hue_bridge", ".", "authorized", "is", "True", "with", "patch", ".", "object", "(", "bridge", ",", "\"create_config_flow\"", ")", "as", "mock_create", ":", "await", "hue_bridge", ".", "handle_unauthorized_error", "(", ")", "assert", "hue_bridge", ".", "authorized", "is", "False", "assert", "len", "(", "mock_create", ".", "mock_calls", ")", "==", "1", "assert", "mock_create", ".", "mock_calls", "[", "0", "]", "[", "1", "]", "[", "1", "]", "==", "\"1.2.3.4\"" ]
[ 104, 0 ]
[ 123, 55 ]
python
en
['en', 'de', 'en']
True
test_hue_activate_scene
(hass, mock_api)
Test successful hue_activate_scene.
Test successful hue_activate_scene.
async def test_hue_activate_scene(hass, mock_api): """Test successful hue_activate_scene.""" config_entry = config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host", "username": "mock-username"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, options={CONF_ALLOW_HUE_GROUPS: True, CONF_ALLOW_UNREACHABLE: False}, ) hue_bridge = bridge.HueBridge(hass, config_entry) mock_api.mock_group_responses.append(GROUP_RESPONSE) mock_api.mock_scene_responses.append(SCENE_RESPONSE) with patch("aiohue.Bridge", return_value=mock_api), patch.object( hass.config_entries, "async_forward_entry_setup" ): assert await hue_bridge.async_setup() is True assert hue_bridge.api is mock_api call = Mock() call.data = {"group_name": "Group 1", "scene_name": "Cozy dinner"} with patch("aiohue.Bridge", return_value=mock_api): assert await hue_bridge.hue_activate_scene(call) is None assert len(mock_api.mock_requests) == 3 assert mock_api.mock_requests[2]["json"]["scene"] == "scene_1" assert mock_api.mock_requests[2]["path"] == "groups/group_1/action"
[ "async", "def", "test_hue_activate_scene", "(", "hass", ",", "mock_api", ")", ":", "config_entry", "=", "config_entries", ".", "ConfigEntry", "(", "1", ",", "hue", ".", "DOMAIN", ",", "\"Mock Title\"", ",", "{", "\"host\"", ":", "\"mock-host\"", ",", "\"username\"", ":", "\"mock-username\"", "}", ",", "\"test\"", ",", "config_entries", ".", "CONN_CLASS_LOCAL_POLL", ",", "system_options", "=", "{", "}", ",", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "True", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", ",", ")", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "config_entry", ")", "mock_api", ".", "mock_group_responses", ".", "append", "(", "GROUP_RESPONSE", ")", "mock_api", ".", "mock_scene_responses", ".", "append", "(", "SCENE_RESPONSE", ")", "with", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "mock_api", ")", ",", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_forward_entry_setup\"", ")", ":", "assert", "await", "hue_bridge", ".", "async_setup", "(", ")", "is", "True", "assert", "hue_bridge", ".", "api", "is", "mock_api", "call", "=", "Mock", "(", ")", "call", ".", "data", "=", "{", "\"group_name\"", ":", "\"Group 1\"", ",", "\"scene_name\"", ":", "\"Cozy dinner\"", "}", "with", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "mock_api", ")", ":", "assert", "await", "hue_bridge", ".", "hue_activate_scene", "(", "call", ")", "is", "None", "assert", "len", "(", "mock_api", ".", "mock_requests", ")", "==", "3", "assert", "mock_api", ".", "mock_requests", "[", "2", "]", "[", "\"json\"", "]", "[", "\"scene\"", "]", "==", "\"scene_1\"", "assert", "mock_api", ".", "mock_requests", "[", "2", "]", "[", "\"path\"", "]", "==", "\"groups/group_1/action\"" ]
[ 160, 0 ]
[ 191, 71 ]
python
en
['en', 'la', 'en']
True
test_hue_activate_scene_group_not_found
(hass, mock_api)
Test failed hue_activate_scene due to missing group.
Test failed hue_activate_scene due to missing group.
async def test_hue_activate_scene_group_not_found(hass, mock_api): """Test failed hue_activate_scene due to missing group.""" config_entry = config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host", "username": "mock-username"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, options={CONF_ALLOW_HUE_GROUPS: True, CONF_ALLOW_UNREACHABLE: False}, ) hue_bridge = bridge.HueBridge(hass, config_entry) mock_api.mock_group_responses.append({}) mock_api.mock_scene_responses.append(SCENE_RESPONSE) with patch("aiohue.Bridge", return_value=mock_api), patch.object( hass.config_entries, "async_forward_entry_setup" ): assert await hue_bridge.async_setup() is True assert hue_bridge.api is mock_api call = Mock() call.data = {"group_name": "Group 1", "scene_name": "Cozy dinner"} with patch("aiohue.Bridge", return_value=mock_api): assert await hue_bridge.hue_activate_scene(call) is False
[ "async", "def", "test_hue_activate_scene_group_not_found", "(", "hass", ",", "mock_api", ")", ":", "config_entry", "=", "config_entries", ".", "ConfigEntry", "(", "1", ",", "hue", ".", "DOMAIN", ",", "\"Mock Title\"", ",", "{", "\"host\"", ":", "\"mock-host\"", ",", "\"username\"", ":", "\"mock-username\"", "}", ",", "\"test\"", ",", "config_entries", ".", "CONN_CLASS_LOCAL_POLL", ",", "system_options", "=", "{", "}", ",", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "True", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", ",", ")", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "config_entry", ")", "mock_api", ".", "mock_group_responses", ".", "append", "(", "{", "}", ")", "mock_api", ".", "mock_scene_responses", ".", "append", "(", "SCENE_RESPONSE", ")", "with", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "mock_api", ")", ",", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_forward_entry_setup\"", ")", ":", "assert", "await", "hue_bridge", ".", "async_setup", "(", ")", "is", "True", "assert", "hue_bridge", ".", "api", "is", "mock_api", "call", "=", "Mock", "(", ")", "call", ".", "data", "=", "{", "\"group_name\"", ":", "\"Group 1\"", ",", "\"scene_name\"", ":", "\"Cozy dinner\"", "}", "with", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "mock_api", ")", ":", "assert", "await", "hue_bridge", ".", "hue_activate_scene", "(", "call", ")", "is", "False" ]
[ 194, 0 ]
[ 221, 65 ]
python
en
['en', 'en', 'en']
True
test_hue_activate_scene_scene_not_found
(hass, mock_api)
Test failed hue_activate_scene due to missing scene.
Test failed hue_activate_scene due to missing scene.
async def test_hue_activate_scene_scene_not_found(hass, mock_api): """Test failed hue_activate_scene due to missing scene.""" config_entry = config_entries.ConfigEntry( 1, hue.DOMAIN, "Mock Title", {"host": "mock-host", "username": "mock-username"}, "test", config_entries.CONN_CLASS_LOCAL_POLL, system_options={}, options={CONF_ALLOW_HUE_GROUPS: True, CONF_ALLOW_UNREACHABLE: False}, ) hue_bridge = bridge.HueBridge(hass, config_entry) mock_api.mock_group_responses.append(GROUP_RESPONSE) mock_api.mock_scene_responses.append({}) with patch("aiohue.Bridge", return_value=mock_api), patch.object( hass.config_entries, "async_forward_entry_setup" ): assert await hue_bridge.async_setup() is True assert hue_bridge.api is mock_api call = Mock() call.data = {"group_name": "Group 1", "scene_name": "Cozy dinner"} with patch("aiohue.Bridge", return_value=mock_api): assert await hue_bridge.hue_activate_scene(call) is False
[ "async", "def", "test_hue_activate_scene_scene_not_found", "(", "hass", ",", "mock_api", ")", ":", "config_entry", "=", "config_entries", ".", "ConfigEntry", "(", "1", ",", "hue", ".", "DOMAIN", ",", "\"Mock Title\"", ",", "{", "\"host\"", ":", "\"mock-host\"", ",", "\"username\"", ":", "\"mock-username\"", "}", ",", "\"test\"", ",", "config_entries", ".", "CONN_CLASS_LOCAL_POLL", ",", "system_options", "=", "{", "}", ",", "options", "=", "{", "CONF_ALLOW_HUE_GROUPS", ":", "True", ",", "CONF_ALLOW_UNREACHABLE", ":", "False", "}", ",", ")", "hue_bridge", "=", "bridge", ".", "HueBridge", "(", "hass", ",", "config_entry", ")", "mock_api", ".", "mock_group_responses", ".", "append", "(", "GROUP_RESPONSE", ")", "mock_api", ".", "mock_scene_responses", ".", "append", "(", "{", "}", ")", "with", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "mock_api", ")", ",", "patch", ".", "object", "(", "hass", ".", "config_entries", ",", "\"async_forward_entry_setup\"", ")", ":", "assert", "await", "hue_bridge", ".", "async_setup", "(", ")", "is", "True", "assert", "hue_bridge", ".", "api", "is", "mock_api", "call", "=", "Mock", "(", ")", "call", ".", "data", "=", "{", "\"group_name\"", ":", "\"Group 1\"", ",", "\"scene_name\"", ":", "\"Cozy dinner\"", "}", "with", "patch", "(", "\"aiohue.Bridge\"", ",", "return_value", "=", "mock_api", ")", ":", "assert", "await", "hue_bridge", ".", "hue_activate_scene", "(", "call", ")", "is", "False" ]
[ 224, 0 ]
[ 251, 65 ]
python
en
['en', 'en', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up climate(s) for KNX platform.
Set up climate(s) for KNX platform.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up climate(s) for KNX platform.""" entities = [] for device in hass.data[DOMAIN].xknx.devices: if isinstance(device, XknxClimate): entities.append(KNXClimate(device)) async_add_entities(entities)
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "entities", "=", "[", "]", "for", "device", "in", "hass", ".", "data", "[", "DOMAIN", "]", ".", "xknx", ".", "devices", ":", "if", "isinstance", "(", "device", ",", "XknxClimate", ")", ":", "entities", ".", "append", "(", "KNXClimate", "(", "device", ")", ")", "async_add_entities", "(", "entities", ")" ]
[ 23, 0 ]
[ 29, 32 ]
python
en
['en', 'da', 'en']
True
KNXClimate.__init__
(self, device: XknxClimate)
Initialize of a KNX climate device.
Initialize of a KNX climate device.
def __init__(self, device: XknxClimate): """Initialize of a KNX climate device.""" super().__init__(device) self._unit_of_measurement = TEMP_CELSIUS
[ "def", "__init__", "(", "self", ",", "device", ":", "XknxClimate", ")", ":", "super", "(", ")", ".", "__init__", "(", "device", ")", "self", ".", "_unit_of_measurement", "=", "TEMP_CELSIUS" ]
[ 35, 4 ]
[ 39, 48 ]
python
en
['en', 'en', 'en']
True
KNXClimate.supported_features
(self)
Return the list of supported features.
Return the list of supported features.
def supported_features(self) -> int: """Return the list of supported features.""" return SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE
[ "def", "supported_features", "(", "self", ")", "->", "int", ":", "return", "SUPPORT_TARGET_TEMPERATURE", "|", "SUPPORT_PRESET_MODE" ]
[ 42, 4 ]
[ 44, 63 ]
python
en
['en', 'en', 'en']
True
KNXClimate.async_update
(self)
Request a state update from KNX bus.
Request a state update from KNX bus.
async def async_update(self): """Request a state update from KNX bus.""" await self._device.sync() await self._device.mode.sync()
[ "async", "def", "async_update", "(", "self", ")", ":", "await", "self", ".", "_device", ".", "sync", "(", ")", "await", "self", ".", "_device", ".", "mode", ".", "sync", "(", ")" ]
[ 46, 4 ]
[ 49, 38 ]
python
en
['en', 'en', 'en']
True
KNXClimate.temperature_unit
(self)
Return the unit of measurement.
Return the unit of measurement.
def temperature_unit(self): """Return the unit of measurement.""" return self._unit_of_measurement
[ "def", "temperature_unit", "(", "self", ")", ":", "return", "self", ".", "_unit_of_measurement" ]
[ 52, 4 ]
[ 54, 40 ]
python
en
['en', 'la', 'en']
True
KNXClimate.current_temperature
(self)
Return the current temperature.
Return the current temperature.
def current_temperature(self): """Return the current temperature.""" return self._device.temperature.value
[ "def", "current_temperature", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "temperature", ".", "value" ]
[ 57, 4 ]
[ 59, 45 ]
python
en
['en', 'la', 'en']
True
KNXClimate.target_temperature_step
(self)
Return the supported step of target temperature.
Return the supported step of target temperature.
def target_temperature_step(self): """Return the supported step of target temperature.""" return self._device.temperature_step
[ "def", "target_temperature_step", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "temperature_step" ]
[ 62, 4 ]
[ 64, 44 ]
python
en
['en', 'en', 'en']
True
KNXClimate.target_temperature
(self)
Return the temperature we try to reach.
Return the temperature we try to reach.
def target_temperature(self): """Return the temperature we try to reach.""" return self._device.target_temperature.value
[ "def", "target_temperature", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "target_temperature", ".", "value" ]
[ 67, 4 ]
[ 69, 52 ]
python
en
['en', 'en', 'en']
True
KNXClimate.min_temp
(self)
Return the minimum temperature.
Return the minimum temperature.
def min_temp(self): """Return the minimum temperature.""" return self._device.target_temperature_min
[ "def", "min_temp", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "target_temperature_min" ]
[ 72, 4 ]
[ 74, 50 ]
python
en
['en', 'la', 'en']
True
KNXClimate.max_temp
(self)
Return the maximum temperature.
Return the maximum temperature.
def max_temp(self): """Return the maximum temperature.""" return self._device.target_temperature_max
[ "def", "max_temp", "(", "self", ")", ":", "return", "self", ".", "_device", ".", "target_temperature_max" ]
[ 77, 4 ]
[ 79, 50 ]
python
en
['en', 'la', 'en']
True
KNXClimate.async_set_temperature
(self, **kwargs)
Set new target temperature.
Set new target temperature.
async def async_set_temperature(self, **kwargs) -> None: """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return await self._device.set_target_temperature(temperature) self.async_write_ha_state()
[ "async", "def", "async_set_temperature", "(", "self", ",", "*", "*", "kwargs", ")", "->", "None", ":", "temperature", "=", "kwargs", ".", "get", "(", "ATTR_TEMPERATURE", ")", "if", "temperature", "is", "None", ":", "return", "await", "self", ".", "_device", ".", "set_target_temperature", "(", "temperature", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 81, 4 ]
[ 87, 35 ]
python
en
['en', 'ca', 'en']
True
KNXClimate.hvac_mode
(self)
Return current operation ie. heat, cool, idle.
Return current operation ie. heat, cool, idle.
def hvac_mode(self) -> Optional[str]: """Return current operation ie. heat, cool, idle.""" if self._device.supports_on_off and not self._device.is_on: return HVAC_MODE_OFF if self._device.mode.supports_controller_mode: return CONTROLLER_MODES.get( self._device.mode.controller_mode.value, HVAC_MODE_HEAT ) # default to "heat" return HVAC_MODE_HEAT
[ "def", "hvac_mode", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "_device", ".", "supports_on_off", "and", "not", "self", ".", "_device", ".", "is_on", ":", "return", "HVAC_MODE_OFF", "if", "self", ".", "_device", ".", "mode", ".", "supports_controller_mode", ":", "return", "CONTROLLER_MODES", ".", "get", "(", "self", ".", "_device", ".", "mode", ".", "controller_mode", ".", "value", ",", "HVAC_MODE_HEAT", ")", "# default to \"heat\"", "return", "HVAC_MODE_HEAT" ]
[ 90, 4 ]
[ 99, 29 ]
python
en
['nl', 'en', 'en']
True
KNXClimate.hvac_modes
(self)
Return the list of available operation/controller modes.
Return the list of available operation/controller modes.
def hvac_modes(self) -> Optional[List[str]]: """Return the list of available operation/controller modes.""" _controller_modes = [ CONTROLLER_MODES.get(controller_mode.value) for controller_mode in self._device.mode.controller_modes ] if self._device.supports_on_off: if not _controller_modes: _controller_modes.append(HVAC_MODE_HEAT) _controller_modes.append(HVAC_MODE_OFF) _modes = list(set(filter(None, _controller_modes))) # default to ["heat"] return _modes if _modes else [HVAC_MODE_HEAT]
[ "def", "hvac_modes", "(", "self", ")", "->", "Optional", "[", "List", "[", "str", "]", "]", ":", "_controller_modes", "=", "[", "CONTROLLER_MODES", ".", "get", "(", "controller_mode", ".", "value", ")", "for", "controller_mode", "in", "self", ".", "_device", ".", "mode", ".", "controller_modes", "]", "if", "self", ".", "_device", ".", "supports_on_off", ":", "if", "not", "_controller_modes", ":", "_controller_modes", ".", "append", "(", "HVAC_MODE_HEAT", ")", "_controller_modes", ".", "append", "(", "HVAC_MODE_OFF", ")", "_modes", "=", "list", "(", "set", "(", "filter", "(", "None", ",", "_controller_modes", ")", ")", ")", "# default to [\"heat\"]", "return", "_modes", "if", "_modes", "else", "[", "HVAC_MODE_HEAT", "]" ]
[ 102, 4 ]
[ 116, 53 ]
python
en
['en', 'en', 'en']
True
KNXClimate.async_set_hvac_mode
(self, hvac_mode: str)
Set operation mode.
Set operation mode.
async def async_set_hvac_mode(self, hvac_mode: str) -> None: """Set operation mode.""" if self._device.supports_on_off and hvac_mode == HVAC_MODE_OFF: await self._device.turn_off() else: if self._device.supports_on_off and not self._device.is_on: await self._device.turn_on() if self._device.mode.supports_controller_mode: knx_controller_mode = HVACControllerMode( CONTROLLER_MODES_INV.get(hvac_mode) ) await self._device.mode.set_controller_mode(knx_controller_mode) self.async_write_ha_state()
[ "async", "def", "async_set_hvac_mode", "(", "self", ",", "hvac_mode", ":", "str", ")", "->", "None", ":", "if", "self", ".", "_device", ".", "supports_on_off", "and", "hvac_mode", "==", "HVAC_MODE_OFF", ":", "await", "self", ".", "_device", ".", "turn_off", "(", ")", "else", ":", "if", "self", ".", "_device", ".", "supports_on_off", "and", "not", "self", ".", "_device", ".", "is_on", ":", "await", "self", ".", "_device", ".", "turn_on", "(", ")", "if", "self", ".", "_device", ".", "mode", ".", "supports_controller_mode", ":", "knx_controller_mode", "=", "HVACControllerMode", "(", "CONTROLLER_MODES_INV", ".", "get", "(", "hvac_mode", ")", ")", "await", "self", ".", "_device", ".", "mode", ".", "set_controller_mode", "(", "knx_controller_mode", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 118, 4 ]
[ 130, 35 ]
python
en
['nl', 'ny', 'en']
False
KNXClimate.preset_mode
(self)
Return the current preset mode, e.g., home, away, temp. Requires SUPPORT_PRESET_MODE.
Return the current preset mode, e.g., home, away, temp.
def preset_mode(self) -> Optional[str]: """Return the current preset mode, e.g., home, away, temp. Requires SUPPORT_PRESET_MODE. """ if self._device.mode.supports_operation_mode: return PRESET_MODES.get(self._device.mode.operation_mode.value, PRESET_AWAY) return None
[ "def", "preset_mode", "(", "self", ")", "->", "Optional", "[", "str", "]", ":", "if", "self", ".", "_device", ".", "mode", ".", "supports_operation_mode", ":", "return", "PRESET_MODES", ".", "get", "(", "self", ".", "_device", ".", "mode", ".", "operation_mode", ".", "value", ",", "PRESET_AWAY", ")", "return", "None" ]
[ 133, 4 ]
[ 140, 19 ]
python
en
['en', 'pt', 'en']
True
KNXClimate.preset_modes
(self)
Return a list of available preset modes. Requires SUPPORT_PRESET_MODE.
Return a list of available preset modes.
def preset_modes(self) -> Optional[List[str]]: """Return a list of available preset modes. Requires SUPPORT_PRESET_MODE. """ _presets = [ PRESET_MODES.get(operation_mode.value) for operation_mode in self._device.mode.operation_modes ] return list(filter(None, _presets))
[ "def", "preset_modes", "(", "self", ")", "->", "Optional", "[", "List", "[", "str", "]", "]", ":", "_presets", "=", "[", "PRESET_MODES", ".", "get", "(", "operation_mode", ".", "value", ")", "for", "operation_mode", "in", "self", ".", "_device", ".", "mode", ".", "operation_modes", "]", "return", "list", "(", "filter", "(", "None", ",", "_presets", ")", ")" ]
[ 143, 4 ]
[ 153, 43 ]
python
en
['en', 'en', 'en']
True
KNXClimate.async_set_preset_mode
(self, preset_mode: str)
Set new preset mode.
Set new preset mode.
async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" if self._device.mode.supports_operation_mode: knx_operation_mode = HVACOperationMode(PRESET_MODES_INV.get(preset_mode)) await self._device.mode.set_operation_mode(knx_operation_mode) self.async_write_ha_state()
[ "async", "def", "async_set_preset_mode", "(", "self", ",", "preset_mode", ":", "str", ")", "->", "None", ":", "if", "self", ".", "_device", ".", "mode", ".", "supports_operation_mode", ":", "knx_operation_mode", "=", "HVACOperationMode", "(", "PRESET_MODES_INV", ".", "get", "(", "preset_mode", ")", ")", "await", "self", ".", "_device", ".", "mode", ".", "set_operation_mode", "(", "knx_operation_mode", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 155, 4 ]
[ 160, 39 ]
python
en
['en', 'sr', 'en']
True
async_setup_platform
(hass, config, async_add_entities, discovery_info=None)
Set up the AfterShip sensor platform.
Set up the AfterShip sensor platform.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the AfterShip sensor platform.""" apikey = config[CONF_API_KEY] name = config[CONF_NAME] session = async_get_clientsession(hass) aftership = Tracking(hass.loop, session, apikey) await aftership.get_trackings() if not aftership.meta or aftership.meta["code"] != HTTP_OK: _LOGGER.error( "No tracking data found. Check API key is correct: %s", aftership.meta ) return instance = AfterShipSensor(aftership, name) async_add_entities([instance], True) async def handle_add_tracking(call): """Call when a user adds a new Aftership tracking from Home Assistant.""" title = call.data.get(CONF_TITLE) slug = call.data.get(CONF_SLUG) tracking_number = call.data[CONF_TRACKING_NUMBER] await aftership.add_package_tracking(tracking_number, title, slug) async_dispatcher_send(hass, UPDATE_TOPIC) hass.services.async_register( DOMAIN, SERVICE_ADD_TRACKING, handle_add_tracking, schema=ADD_TRACKING_SERVICE_SCHEMA, ) async def handle_remove_tracking(call): """Call when a user removes an Aftership tracking from Home Assistant.""" slug = call.data[CONF_SLUG] tracking_number = call.data[CONF_TRACKING_NUMBER] await aftership.remove_package_tracking(slug, tracking_number) async_dispatcher_send(hass, UPDATE_TOPIC) hass.services.async_register( DOMAIN, SERVICE_REMOVE_TRACKING, handle_remove_tracking, schema=REMOVE_TRACKING_SERVICE_SCHEMA, )
[ "async", "def", "async_setup_platform", "(", "hass", ",", "config", ",", "async_add_entities", ",", "discovery_info", "=", "None", ")", ":", "apikey", "=", "config", "[", "CONF_API_KEY", "]", "name", "=", "config", "[", "CONF_NAME", "]", "session", "=", "async_get_clientsession", "(", "hass", ")", "aftership", "=", "Tracking", "(", "hass", ".", "loop", ",", "session", ",", "apikey", ")", "await", "aftership", ".", "get_trackings", "(", ")", "if", "not", "aftership", ".", "meta", "or", "aftership", ".", "meta", "[", "\"code\"", "]", "!=", "HTTP_OK", ":", "_LOGGER", ".", "error", "(", "\"No tracking data found. Check API key is correct: %s\"", ",", "aftership", ".", "meta", ")", "return", "instance", "=", "AfterShipSensor", "(", "aftership", ",", "name", ")", "async_add_entities", "(", "[", "instance", "]", ",", "True", ")", "async", "def", "handle_add_tracking", "(", "call", ")", ":", "\"\"\"Call when a user adds a new Aftership tracking from Home Assistant.\"\"\"", "title", "=", "call", ".", "data", ".", "get", "(", "CONF_TITLE", ")", "slug", "=", "call", ".", "data", ".", "get", "(", "CONF_SLUG", ")", "tracking_number", "=", "call", ".", "data", "[", "CONF_TRACKING_NUMBER", "]", "await", "aftership", ".", "add_package_tracking", "(", "tracking_number", ",", "title", ",", "slug", ")", "async_dispatcher_send", "(", "hass", ",", "UPDATE_TOPIC", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_ADD_TRACKING", ",", "handle_add_tracking", ",", "schema", "=", "ADD_TRACKING_SERVICE_SCHEMA", ",", ")", "async", "def", "handle_remove_tracking", "(", "call", ")", ":", "\"\"\"Call when a user removes an Aftership tracking from Home Assistant.\"\"\"", "slug", "=", "call", ".", "data", "[", "CONF_SLUG", "]", "tracking_number", "=", "call", ".", "data", "[", "CONF_TRACKING_NUMBER", "]", "await", "aftership", ".", "remove_package_tracking", "(", "slug", ",", "tracking_number", ")", "async_dispatcher_send", "(", "hass", ",", "UPDATE_TOPIC", ")", "hass", ".", "services", ".", "async_register", "(", "DOMAIN", ",", "SERVICE_REMOVE_TRACKING", ",", "handle_remove_tracking", ",", "schema", "=", "REMOVE_TRACKING_SERVICE_SCHEMA", ",", ")" ]
[ 58, 0 ]
[ 107, 5 ]
python
en
['en', 'da', 'en']
True
AfterShipSensor.__init__
(self, aftership, name)
Initialize the sensor.
Initialize the sensor.
def __init__(self, aftership, name): """Initialize the sensor.""" self._attributes = {} self._name = name self._state = None self.aftership = aftership
[ "def", "__init__", "(", "self", ",", "aftership", ",", "name", ")", ":", "self", ".", "_attributes", "=", "{", "}", "self", ".", "_name", "=", "name", "self", ".", "_state", "=", "None", "self", ".", "aftership", "=", "aftership" ]
[ 113, 4 ]
[ 118, 34 ]
python
en
['en', 'en', 'en']
True
AfterShipSensor.name
(self)
Return the name of the sensor.
Return the name of the sensor.
def name(self): """Return the name of the sensor.""" return self._name
[ "def", "name", "(", "self", ")", ":", "return", "self", ".", "_name" ]
[ 121, 4 ]
[ 123, 25 ]
python
en
['en', 'mi', 'en']
True
AfterShipSensor.state
(self)
Return the state of the sensor.
Return the state of the sensor.
def state(self): """Return the state of the sensor.""" return self._state
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "_state" ]
[ 126, 4 ]
[ 128, 26 ]
python
en
['en', 'en', 'en']
True
AfterShipSensor.unit_of_measurement
(self)
Return the unit of measurement of this entity, if any.
Return the unit of measurement of this entity, if any.
def unit_of_measurement(self): """Return the unit of measurement of this entity, if any.""" return "packages"
[ "def", "unit_of_measurement", "(", "self", ")", ":", "return", "\"packages\"" ]
[ 131, 4 ]
[ 133, 25 ]
python
en
['en', 'en', 'en']
True
AfterShipSensor.device_state_attributes
(self)
Return attributes for the sensor.
Return attributes for the sensor.
def device_state_attributes(self): """Return attributes for the sensor.""" return self._attributes
[ "def", "device_state_attributes", "(", "self", ")", ":", "return", "self", ".", "_attributes" ]
[ 136, 4 ]
[ 138, 31 ]
python
en
['en', 'no', 'en']
True
AfterShipSensor.icon
(self)
Icon to use in the frontend.
Icon to use in the frontend.
def icon(self): """Icon to use in the frontend.""" return ICON
[ "def", "icon", "(", "self", ")", ":", "return", "ICON" ]
[ 141, 4 ]
[ 143, 19 ]
python
en
['en', 'en', 'en']
True
AfterShipSensor.async_added_to_hass
(self)
Register callbacks.
Register callbacks.
async def async_added_to_hass(self): """Register callbacks.""" self.async_on_remove( self.hass.helpers.dispatcher.async_dispatcher_connect( UPDATE_TOPIC, self._force_update ) )
[ "async", "def", "async_added_to_hass", "(", "self", ")", ":", "self", ".", "async_on_remove", "(", "self", ".", "hass", ".", "helpers", ".", "dispatcher", ".", "async_dispatcher_connect", "(", "UPDATE_TOPIC", ",", "self", ".", "_force_update", ")", ")" ]
[ 145, 4 ]
[ 151, 9 ]
python
en
['en', 'no', 'en']
False
AfterShipSensor._force_update
(self)
Force update of data.
Force update of data.
async def _force_update(self): """Force update of data.""" await self.async_update(no_throttle=True) self.async_write_ha_state()
[ "async", "def", "_force_update", "(", "self", ")", ":", "await", "self", ".", "async_update", "(", "no_throttle", "=", "True", ")", "self", ".", "async_write_ha_state", "(", ")" ]
[ 153, 4 ]
[ 156, 35 ]
python
en
['en', 'en', 'en']
True
AfterShipSensor.async_update
(self, **kwargs)
Get the latest data from the AfterShip API.
Get the latest data from the AfterShip API.
async def async_update(self, **kwargs): """Get the latest data from the AfterShip API.""" await self.aftership.get_trackings() if not self.aftership.meta: _LOGGER.error("Unknown errors when querying") return if self.aftership.meta["code"] != HTTP_OK: _LOGGER.error( "Errors when querying AfterShip. %s", str(self.aftership.meta) ) return status_to_ignore = {"delivered"} status_counts = {} trackings = [] not_delivered_count = 0 for track in self.aftership.trackings["trackings"]: status = track["tag"].lower() name = ( track["tracking_number"] if track["title"] is None else track["title"] ) last_checkpoint = ( "Shipment pending" if track["tag"] == "Pending" else track["checkpoints"][-1] ) status_counts[status] = status_counts.get(status, 0) + 1 trackings.append( { "name": name, "tracking_number": track["tracking_number"], "slug": track["slug"], "link": f"{BASE}{track['slug']}/{track['tracking_number']}", "last_update": track["updated_at"], "expected_delivery": track["expected_delivery"], "status": track["tag"], "last_checkpoint": last_checkpoint, } ) if status not in status_to_ignore: not_delivered_count += 1 else: _LOGGER.debug("Ignoring %s as it has status: %s", name, status) self._attributes = { ATTR_ATTRIBUTION: ATTRIBUTION, **status_counts, ATTR_TRACKINGS: trackings, } self._state = not_delivered_count
[ "async", "def", "async_update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "await", "self", ".", "aftership", ".", "get_trackings", "(", ")", "if", "not", "self", ".", "aftership", ".", "meta", ":", "_LOGGER", ".", "error", "(", "\"Unknown errors when querying\"", ")", "return", "if", "self", ".", "aftership", ".", "meta", "[", "\"code\"", "]", "!=", "HTTP_OK", ":", "_LOGGER", ".", "error", "(", "\"Errors when querying AfterShip. %s\"", ",", "str", "(", "self", ".", "aftership", ".", "meta", ")", ")", "return", "status_to_ignore", "=", "{", "\"delivered\"", "}", "status_counts", "=", "{", "}", "trackings", "=", "[", "]", "not_delivered_count", "=", "0", "for", "track", "in", "self", ".", "aftership", ".", "trackings", "[", "\"trackings\"", "]", ":", "status", "=", "track", "[", "\"tag\"", "]", ".", "lower", "(", ")", "name", "=", "(", "track", "[", "\"tracking_number\"", "]", "if", "track", "[", "\"title\"", "]", "is", "None", "else", "track", "[", "\"title\"", "]", ")", "last_checkpoint", "=", "(", "\"Shipment pending\"", "if", "track", "[", "\"tag\"", "]", "==", "\"Pending\"", "else", "track", "[", "\"checkpoints\"", "]", "[", "-", "1", "]", ")", "status_counts", "[", "status", "]", "=", "status_counts", ".", "get", "(", "status", ",", "0", ")", "+", "1", "trackings", ".", "append", "(", "{", "\"name\"", ":", "name", ",", "\"tracking_number\"", ":", "track", "[", "\"tracking_number\"", "]", ",", "\"slug\"", ":", "track", "[", "\"slug\"", "]", ",", "\"link\"", ":", "f\"{BASE}{track['slug']}/{track['tracking_number']}\"", ",", "\"last_update\"", ":", "track", "[", "\"updated_at\"", "]", ",", "\"expected_delivery\"", ":", "track", "[", "\"expected_delivery\"", "]", ",", "\"status\"", ":", "track", "[", "\"tag\"", "]", ",", "\"last_checkpoint\"", ":", "last_checkpoint", ",", "}", ")", "if", "status", "not", "in", "status_to_ignore", ":", "not_delivered_count", "+=", "1", "else", ":", "_LOGGER", ".", "debug", "(", "\"Ignoring %s as it has status: %s\"", ",", "name", ",", "status", ")", "self", ".", "_attributes", "=", "{", "ATTR_ATTRIBUTION", ":", "ATTRIBUTION", ",", "*", "*", "status_counts", ",", "ATTR_TRACKINGS", ":", "trackings", ",", "}", "self", ".", "_state", "=", "not_delivered_count" ]
[ 159, 4 ]
[ 212, 41 ]
python
en
['en', 'en', 'en']
True
MPNetTokenizerFast.mask_token
(self)
:obj:`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not having been set. MPNet tokenizer has a special mask token to be usble in the fill-mask pipeline. The mask token will greedily comprise the space before the `<mask>`.
:obj:`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not having been set.
def mask_token(self) -> str: """ :obj:`str`: Mask token, to use when training a model with masked-language modeling. Log an error if used while not having been set. MPNet tokenizer has a special mask token to be usble in the fill-mask pipeline. The mask token will greedily comprise the space before the `<mask>`. """ if self._mask_token is None and self.verbose: logger.error("Using mask_token, but it is not set yet.") return None return str(self._mask_token)
[ "def", "mask_token", "(", "self", ")", "->", "str", ":", "if", "self", ".", "_mask_token", "is", "None", "and", "self", ".", "verbose", ":", "logger", ".", "error", "(", "\"Using mask_token, but it is not set yet.\"", ")", "return", "None", "return", "str", "(", "self", ".", "_mask_token", ")" ]
[ 151, 4 ]
[ 162, 36 ]
python
en
['en', 'error', 'th']
False
MPNetTokenizerFast.mask_token
(self, value)
Overriding the default behavior of the mask token to have it eat the space before it. This is needed to preserve backward compatibility with all the previously used models based on MPNet.
Overriding the default behavior of the mask token to have it eat the space before it.
def mask_token(self, value): """ Overriding the default behavior of the mask token to have it eat the space before it. This is needed to preserve backward compatibility with all the previously used models based on MPNet. """ # Mask token behave like a normal word, i.e. include the space before it # So we set lstrip to True value = AddedToken(value, lstrip=True, rstrip=False) if isinstance(value, str) else value self._mask_token = value
[ "def", "mask_token", "(", "self", ",", "value", ")", ":", "# Mask token behave like a normal word, i.e. include the space before it", "# So we set lstrip to True", "value", "=", "AddedToken", "(", "value", ",", "lstrip", "=", "True", ",", "rstrip", "=", "False", ")", "if", "isinstance", "(", "value", ",", "str", ")", "else", "value", "self", ".", "_mask_token", "=", "value" ]
[ 165, 4 ]
[ 174, 32 ]
python
en
['en', 'error', 'th']
False
MPNetTokenizerFast.create_token_type_ids_from_sequences
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None )
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not make use of token type ids, therefore a list of zeros is returned Args: token_ids_0 (:obj:`List[int]`): List of ids. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs Returns: :obj:`List[int]`: List of zeros.
Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not make use of token type ids, therefore a list of zeros is returned
def create_token_type_ids_from_sequences( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. MPNet does not make use of token type ids, therefore a list of zeros is returned Args: token_ids_0 (:obj:`List[int]`): List of ids. token_ids_1 (:obj:`List[int]`, `optional`): Optional second list of IDs for sequence pairs Returns: :obj:`List[int]`: List of zeros. """ sep = [self.sep_token_id] cls = [self.cls_token_id] if token_ids_1 is None: return len(cls + token_ids_0 + sep) * [0] return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
[ "def", "create_token_type_ids_from_sequences", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", "->", "List", "[", "int", "]", ":", "sep", "=", "[", "self", ".", "sep_token_id", "]", "cls", "=", "[", "self", ".", "cls_token_id", "]", "if", "token_ids_1", "is", "None", ":", "return", "len", "(", "cls", "+", "token_ids_0", "+", "sep", ")", "*", "[", "0", "]", "return", "len", "(", "cls", "+", "token_ids_0", "+", "sep", "+", "sep", "+", "token_ids_1", "+", "sep", ")", "*", "[", "0", "]" ]
[ 183, 4 ]
[ 204, 75 ]
python
en
['en', 'error', 'th']
False
async_setup
(hass, config)
Set up water_heater devices.
Set up water_heater devices.
async def async_setup(hass, config): """Set up water_heater devices.""" component = hass.data[DOMAIN] = EntityComponent( _LOGGER, DOMAIN, hass, SCAN_INTERVAL ) await component.async_setup(config) component.async_register_entity_service( SERVICE_SET_AWAY_MODE, SET_AWAY_MODE_SCHEMA, async_service_away_mode ) component.async_register_entity_service( SERVICE_SET_TEMPERATURE, SET_TEMPERATURE_SCHEMA, async_service_temperature_set ) component.async_register_entity_service( SERVICE_SET_OPERATION_MODE, SET_OPERATION_MODE_SCHEMA, "async_set_operation_mode", ) component.async_register_entity_service( SERVICE_TURN_OFF, ON_OFF_SERVICE_SCHEMA, "async_turn_off" ) component.async_register_entity_service( SERVICE_TURN_ON, ON_OFF_SERVICE_SCHEMA, "async_turn_on" ) return True
[ "async", "def", "async_setup", "(", "hass", ",", "config", ")", ":", "component", "=", "hass", ".", "data", "[", "DOMAIN", "]", "=", "EntityComponent", "(", "_LOGGER", ",", "DOMAIN", ",", "hass", ",", "SCAN_INTERVAL", ")", "await", "component", ".", "async_setup", "(", "config", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_SET_AWAY_MODE", ",", "SET_AWAY_MODE_SCHEMA", ",", "async_service_away_mode", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_SET_TEMPERATURE", ",", "SET_TEMPERATURE_SCHEMA", ",", "async_service_temperature_set", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_SET_OPERATION_MODE", ",", "SET_OPERATION_MODE_SCHEMA", ",", "\"async_set_operation_mode\"", ",", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_TURN_OFF", ",", "ON_OFF_SERVICE_SCHEMA", ",", "\"async_turn_off\"", ")", "component", ".", "async_register_entity_service", "(", "SERVICE_TURN_ON", ",", "ON_OFF_SERVICE_SCHEMA", ",", "\"async_turn_on\"", ")", "return", "True" ]
[ 92, 0 ]
[ 117, 15 ]
python
en
['en', 'en', 'en']
True
async_setup_entry
(hass, entry)
Set up a config entry.
Set up a config entry.
async def async_setup_entry(hass, entry): """Set up a config entry.""" return await hass.data[DOMAIN].async_setup_entry(entry)
[ "async", "def", "async_setup_entry", "(", "hass", ",", "entry", ")", ":", "return", "await", "hass", ".", "data", "[", "DOMAIN", "]", ".", "async_setup_entry", "(", "entry", ")" ]
[ 120, 0 ]
[ 122, 59 ]
python
en
['en', 'en', 'en']
True
async_unload_entry
(hass, entry)
Unload a config entry.
Unload a config entry.
async def async_unload_entry(hass, entry): """Unload a config entry.""" return await hass.data[DOMAIN].async_unload_entry(entry)
[ "async", "def", "async_unload_entry", "(", "hass", ",", "entry", ")", ":", "return", "await", "hass", ".", "data", "[", "DOMAIN", "]", ".", "async_unload_entry", "(", "entry", ")" ]
[ 125, 0 ]
[ 127, 60 ]
python
en
['en', 'es', 'en']
True
async_service_away_mode
(entity, service)
Handle away mode service.
Handle away mode service.
async def async_service_away_mode(entity, service): """Handle away mode service.""" if service.data[ATTR_AWAY_MODE]: await entity.async_turn_away_mode_on() else: await entity.async_turn_away_mode_off()
[ "async", "def", "async_service_away_mode", "(", "entity", ",", "service", ")", ":", "if", "service", ".", "data", "[", "ATTR_AWAY_MODE", "]", ":", "await", "entity", ".", "async_turn_away_mode_on", "(", ")", "else", ":", "await", "entity", ".", "async_turn_away_mode_off", "(", ")" ]
[ 299, 0 ]
[ 304, 47 ]
python
en
['en', 'en', 'en']
True
async_service_temperature_set
(entity, service)
Handle set temperature service.
Handle set temperature service.
async def async_service_temperature_set(entity, service): """Handle set temperature service.""" hass = entity.hass kwargs = {} for value, temp in service.data.items(): if value in CONVERTIBLE_ATTRIBUTE: kwargs[value] = convert_temperature( temp, hass.config.units.temperature_unit, entity.temperature_unit ) else: kwargs[value] = temp await entity.async_set_temperature(**kwargs)
[ "async", "def", "async_service_temperature_set", "(", "entity", ",", "service", ")", ":", "hass", "=", "entity", ".", "hass", "kwargs", "=", "{", "}", "for", "value", ",", "temp", "in", "service", ".", "data", ".", "items", "(", ")", ":", "if", "value", "in", "CONVERTIBLE_ATTRIBUTE", ":", "kwargs", "[", "value", "]", "=", "convert_temperature", "(", "temp", ",", "hass", ".", "config", ".", "units", ".", "temperature_unit", ",", "entity", ".", "temperature_unit", ")", "else", ":", "kwargs", "[", "value", "]", "=", "temp", "await", "entity", ".", "async_set_temperature", "(", "*", "*", "kwargs", ")" ]
[ 307, 0 ]
[ 320, 48 ]
python
ca
['es', 'ca', 'en']
False
WaterHeaterEntity.state
(self)
Return the current state.
Return the current state.
def state(self): """Return the current state.""" return self.current_operation
[ "def", "state", "(", "self", ")", ":", "return", "self", ".", "current_operation" ]
[ 134, 4 ]
[ 136, 37 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.precision
(self)
Return the precision of the system.
Return the precision of the system.
def precision(self): """Return the precision of the system.""" if self.hass.config.units.temperature_unit == TEMP_CELSIUS: return PRECISION_TENTHS return PRECISION_WHOLE
[ "def", "precision", "(", "self", ")", ":", "if", "self", ".", "hass", ".", "config", ".", "units", ".", "temperature_unit", "==", "TEMP_CELSIUS", ":", "return", "PRECISION_TENTHS", "return", "PRECISION_WHOLE" ]
[ 139, 4 ]
[ 143, 30 ]
python
en
['en', 'en', 'en']
True
WaterHeaterEntity.capability_attributes
(self)
Return capability attributes.
Return capability attributes.
def capability_attributes(self): """Return capability attributes.""" supported_features = self.supported_features or 0 data = { ATTR_MIN_TEMP: show_temp( self.hass, self.min_temp, self.temperature_unit, self.precision ), ATTR_MAX_TEMP: show_temp( self.hass, self.max_temp, self.temperature_unit, self.precision ), } if supported_features & SUPPORT_OPERATION_MODE: data[ATTR_OPERATION_LIST] = self.operation_list return data
[ "def", "capability_attributes", "(", "self", ")", ":", "supported_features", "=", "self", ".", "supported_features", "or", "0", "data", "=", "{", "ATTR_MIN_TEMP", ":", "show_temp", "(", "self", ".", "hass", ",", "self", ".", "min_temp", ",", "self", ".", "temperature_unit", ",", "self", ".", "precision", ")", ",", "ATTR_MAX_TEMP", ":", "show_temp", "(", "self", ".", "hass", ",", "self", ".", "max_temp", ",", "self", ".", "temperature_unit", ",", "self", ".", "precision", ")", ",", "}", "if", "supported_features", "&", "SUPPORT_OPERATION_MODE", ":", "data", "[", "ATTR_OPERATION_LIST", "]", "=", "self", ".", "operation_list", "return", "data" ]
[ 146, 4 ]
[ 162, 19 ]
python
en
['en', 'la', 'en']
True