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 |
---|---|---|---|---|---|---|---|---|---|---|---|
test_entity_device_info_with_connection | (hass, mqtt_mock) | Test MQTT camera device registry integration. | Test MQTT camera device registry integration. | async def test_entity_device_info_with_connection(hass, mqtt_mock):
"""Test MQTT camera device registry integration."""
await help_test_entity_device_info_with_connection(
hass, mqtt_mock, camera.DOMAIN, DEFAULT_CONFIG
) | [
"async",
"def",
"test_entity_device_info_with_connection",
"(",
"hass",
",",
"mqtt_mock",
")",
":",
"await",
"help_test_entity_device_info_with_connection",
"(",
"hass",
",",
"mqtt_mock",
",",
"camera",
".",
"DOMAIN",
",",
"DEFAULT_CONFIG",
")"
] | [
183,
0
] | [
187,
5
] | python | en | ['en', 'sv', 'en'] | True |
test_entity_device_info_with_identifier | (hass, mqtt_mock) | Test MQTT camera device registry integration. | Test MQTT camera device registry integration. | async def test_entity_device_info_with_identifier(hass, mqtt_mock):
"""Test MQTT camera device registry integration."""
await help_test_entity_device_info_with_identifier(
hass, mqtt_mock, camera.DOMAIN, DEFAULT_CONFIG
) | [
"async",
"def",
"test_entity_device_info_with_identifier",
"(",
"hass",
",",
"mqtt_mock",
")",
":",
"await",
"help_test_entity_device_info_with_identifier",
"(",
"hass",
",",
"mqtt_mock",
",",
"camera",
".",
"DOMAIN",
",",
"DEFAULT_CONFIG",
")"
] | [
190,
0
] | [
194,
5
] | python | en | ['en', 'sv', 'en'] | True |
test_entity_device_info_update | (hass, mqtt_mock) | Test device registry update. | Test device registry update. | async def test_entity_device_info_update(hass, mqtt_mock):
"""Test device registry update."""
await help_test_entity_device_info_update(
hass, mqtt_mock, camera.DOMAIN, DEFAULT_CONFIG
) | [
"async",
"def",
"test_entity_device_info_update",
"(",
"hass",
",",
"mqtt_mock",
")",
":",
"await",
"help_test_entity_device_info_update",
"(",
"hass",
",",
"mqtt_mock",
",",
"camera",
".",
"DOMAIN",
",",
"DEFAULT_CONFIG",
")"
] | [
197,
0
] | [
201,
5
] | python | en | ['fr', 'fy', 'en'] | False |
test_entity_device_info_remove | (hass, mqtt_mock) | Test device registry remove. | Test device registry remove. | async def test_entity_device_info_remove(hass, mqtt_mock):
"""Test device registry remove."""
await help_test_entity_device_info_remove(
hass, mqtt_mock, camera.DOMAIN, DEFAULT_CONFIG
) | [
"async",
"def",
"test_entity_device_info_remove",
"(",
"hass",
",",
"mqtt_mock",
")",
":",
"await",
"help_test_entity_device_info_remove",
"(",
"hass",
",",
"mqtt_mock",
",",
"camera",
".",
"DOMAIN",
",",
"DEFAULT_CONFIG",
")"
] | [
204,
0
] | [
208,
5
] | python | en | ['fr', 'en', 'en'] | True |
test_entity_id_update_subscriptions | (hass, mqtt_mock) | Test MQTT subscriptions are managed when entity_id is updated. | Test MQTT subscriptions are managed when entity_id is updated. | async def test_entity_id_update_subscriptions(hass, mqtt_mock):
"""Test MQTT subscriptions are managed when entity_id is updated."""
await help_test_entity_id_update_subscriptions(
hass, mqtt_mock, camera.DOMAIN, DEFAULT_CONFIG, ["test_topic"]
) | [
"async",
"def",
"test_entity_id_update_subscriptions",
"(",
"hass",
",",
"mqtt_mock",
")",
":",
"await",
"help_test_entity_id_update_subscriptions",
"(",
"hass",
",",
"mqtt_mock",
",",
"camera",
".",
"DOMAIN",
",",
"DEFAULT_CONFIG",
",",
"[",
"\"test_topic\"",
"]",
")"
] | [
211,
0
] | [
215,
5
] | python | en | ['en', 'en', 'en'] | True |
test_entity_id_update_discovery_update | (hass, mqtt_mock) | Test MQTT discovery update when entity_id is updated. | Test MQTT discovery update when entity_id is updated. | async def test_entity_id_update_discovery_update(hass, mqtt_mock):
"""Test MQTT discovery update when entity_id is updated."""
await help_test_entity_id_update_discovery_update(
hass, mqtt_mock, camera.DOMAIN, DEFAULT_CONFIG
) | [
"async",
"def",
"test_entity_id_update_discovery_update",
"(",
"hass",
",",
"mqtt_mock",
")",
":",
"await",
"help_test_entity_id_update_discovery_update",
"(",
"hass",
",",
"mqtt_mock",
",",
"camera",
".",
"DOMAIN",
",",
"DEFAULT_CONFIG",
")"
] | [
218,
0
] | [
222,
5
] | python | en | ['en', 'en', 'en'] | True |
test_entity_debug_info_message | (hass, mqtt_mock) | Test MQTT debug info. | Test MQTT debug info. | async def test_entity_debug_info_message(hass, mqtt_mock):
"""Test MQTT debug info."""
await help_test_entity_debug_info_message(
hass, mqtt_mock, camera.DOMAIN, DEFAULT_CONFIG, "test_topic", b"ON"
) | [
"async",
"def",
"test_entity_debug_info_message",
"(",
"hass",
",",
"mqtt_mock",
")",
":",
"await",
"help_test_entity_debug_info_message",
"(",
"hass",
",",
"mqtt_mock",
",",
"camera",
".",
"DOMAIN",
",",
"DEFAULT_CONFIG",
",",
"\"test_topic\"",
",",
"b\"ON\"",
")"
] | [
225,
0
] | [
229,
5
] | python | es | ['es', 'mt', 'it'] | False |
test_setup_minimal_config | (hass) | Tests component setup with minimal config. | Tests component setup with minimal config. | async def test_setup_minimal_config(hass):
"""Tests component setup with minimal config."""
mocked_hole = _create_mocked_hole()
with _patch_config_flow_hole(mocked_hole), _patch_init_hole(mocked_hole):
assert await async_setup_component(
hass, pi_hole.DOMAIN, {pi_hole.DOMAIN: [{"host": "pi.hole"}]}
)
await hass.async_block_till_done()
assert (
hass.states.get("sensor.pi_hole_ads_blocked_today").name
== "Pi-Hole Ads Blocked Today"
)
assert (
hass.states.get("sensor.pi_hole_ads_percentage_blocked_today").name
== "Pi-Hole Ads Percentage Blocked Today"
)
assert (
hass.states.get("sensor.pi_hole_dns_queries_cached").name
== "Pi-Hole DNS Queries Cached"
)
assert (
hass.states.get("sensor.pi_hole_dns_queries_forwarded").name
== "Pi-Hole DNS Queries Forwarded"
)
assert (
hass.states.get("sensor.pi_hole_dns_queries_today").name
== "Pi-Hole DNS Queries Today"
)
assert (
hass.states.get("sensor.pi_hole_dns_unique_clients").name
== "Pi-Hole DNS Unique Clients"
)
assert (
hass.states.get("sensor.pi_hole_dns_unique_domains").name
== "Pi-Hole DNS Unique Domains"
)
assert (
hass.states.get("sensor.pi_hole_domains_blocked").name
== "Pi-Hole Domains Blocked"
)
assert hass.states.get("sensor.pi_hole_seen_clients").name == "Pi-Hole Seen Clients"
assert hass.states.get("sensor.pi_hole_ads_blocked_today").state == "0"
assert hass.states.get("sensor.pi_hole_ads_percentage_blocked_today").state == "0"
assert hass.states.get("sensor.pi_hole_dns_queries_cached").state == "0"
assert hass.states.get("sensor.pi_hole_dns_queries_forwarded").state == "0"
assert hass.states.get("sensor.pi_hole_dns_queries_today").state == "0"
assert hass.states.get("sensor.pi_hole_dns_unique_clients").state == "0"
assert hass.states.get("sensor.pi_hole_dns_unique_domains").state == "0"
assert hass.states.get("sensor.pi_hole_domains_blocked").state == "0"
assert hass.states.get("sensor.pi_hole_seen_clients").state == "0"
assert hass.states.get("binary_sensor.pi_hole").name == "Pi-Hole"
assert hass.states.get("binary_sensor.pi_hole").state == "off" | [
"async",
"def",
"test_setup_minimal_config",
"(",
"hass",
")",
":",
"mocked_hole",
"=",
"_create_mocked_hole",
"(",
")",
"with",
"_patch_config_flow_hole",
"(",
"mocked_hole",
")",
",",
"_patch_init_hole",
"(",
"mocked_hole",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"pi_hole",
".",
"DOMAIN",
",",
"{",
"pi_hole",
".",
"DOMAIN",
":",
"[",
"{",
"\"host\"",
":",
"\"pi.hole\"",
"}",
"]",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_ads_blocked_today\"",
")",
".",
"name",
"==",
"\"Pi-Hole Ads Blocked Today\"",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_ads_percentage_blocked_today\"",
")",
".",
"name",
"==",
"\"Pi-Hole Ads Percentage Blocked Today\"",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_queries_cached\"",
")",
".",
"name",
"==",
"\"Pi-Hole DNS Queries Cached\"",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_queries_forwarded\"",
")",
".",
"name",
"==",
"\"Pi-Hole DNS Queries Forwarded\"",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_queries_today\"",
")",
".",
"name",
"==",
"\"Pi-Hole DNS Queries Today\"",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_unique_clients\"",
")",
".",
"name",
"==",
"\"Pi-Hole DNS Unique Clients\"",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_unique_domains\"",
")",
".",
"name",
"==",
"\"Pi-Hole DNS Unique Domains\"",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_domains_blocked\"",
")",
".",
"name",
"==",
"\"Pi-Hole Domains Blocked\"",
")",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_seen_clients\"",
")",
".",
"name",
"==",
"\"Pi-Hole Seen Clients\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_ads_blocked_today\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_ads_percentage_blocked_today\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_queries_cached\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_queries_forwarded\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_queries_today\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_unique_clients\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_dns_unique_domains\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_domains_blocked\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.pi_hole_seen_clients\"",
")",
".",
"state",
"==",
"\"0\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.pi_hole\"",
")",
".",
"name",
"==",
"\"Pi-Hole\"",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"binary_sensor.pi_hole\"",
")",
".",
"state",
"==",
"\"off\""
] | [
35,
0
] | [
90,
66
] | python | en | ['en', 'en', 'en'] | True |
test_setup_name_config | (hass) | Tests component setup with a custom name. | Tests component setup with a custom name. | async def test_setup_name_config(hass):
"""Tests component setup with a custom name."""
mocked_hole = _create_mocked_hole()
with _patch_config_flow_hole(mocked_hole), _patch_init_hole(mocked_hole):
assert await async_setup_component(
hass,
pi_hole.DOMAIN,
{pi_hole.DOMAIN: [{"host": "pi.hole", "name": "Custom"}]},
)
await hass.async_block_till_done()
assert (
hass.states.get("sensor.custom_ads_blocked_today").name
== "Custom Ads Blocked Today"
) | [
"async",
"def",
"test_setup_name_config",
"(",
"hass",
")",
":",
"mocked_hole",
"=",
"_create_mocked_hole",
"(",
")",
"with",
"_patch_config_flow_hole",
"(",
"mocked_hole",
")",
",",
"_patch_init_hole",
"(",
"mocked_hole",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"pi_hole",
".",
"DOMAIN",
",",
"{",
"pi_hole",
".",
"DOMAIN",
":",
"[",
"{",
"\"host\"",
":",
"\"pi.hole\"",
",",
"\"name\"",
":",
"\"Custom\"",
"}",
"]",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"(",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.custom_ads_blocked_today\"",
")",
".",
"name",
"==",
"\"Custom Ads Blocked Today\"",
")"
] | [
93,
0
] | [
108,
5
] | python | en | ['en', 'en', 'en'] | True |
test_switch | (hass, caplog) | Test Pi-hole switch. | Test Pi-hole switch. | async def test_switch(hass, caplog):
"""Test Pi-hole switch."""
mocked_hole = _create_mocked_hole()
with _patch_config_flow_hole(mocked_hole), _patch_init_hole(mocked_hole):
assert await async_setup_component(
hass,
pi_hole.DOMAIN,
{pi_hole.DOMAIN: [{"host": "pi.hole1", "api_key": "1"}]},
)
await hass.async_block_till_done()
await hass.services.async_call(
switch.DOMAIN,
switch.SERVICE_TURN_ON,
{"entity_id": SWITCH_ENTITY_ID},
blocking=True,
)
mocked_hole.enable.assert_called_once()
await hass.services.async_call(
switch.DOMAIN,
switch.SERVICE_TURN_OFF,
{"entity_id": SWITCH_ENTITY_ID},
blocking=True,
)
mocked_hole.disable.assert_called_once_with(True)
# Failed calls
type(mocked_hole).enable = AsyncMock(side_effect=HoleError("Error1"))
await hass.services.async_call(
switch.DOMAIN,
switch.SERVICE_TURN_ON,
{"entity_id": SWITCH_ENTITY_ID},
blocking=True,
)
type(mocked_hole).disable = AsyncMock(side_effect=HoleError("Error2"))
await hass.services.async_call(
switch.DOMAIN,
switch.SERVICE_TURN_OFF,
{"entity_id": SWITCH_ENTITY_ID},
blocking=True,
)
errors = [x for x in caplog.records if x.levelno == logging.ERROR]
assert errors[-2].message == "Unable to enable Pi-hole: Error1"
assert errors[-1].message == "Unable to disable Pi-hole: Error2" | [
"async",
"def",
"test_switch",
"(",
"hass",
",",
"caplog",
")",
":",
"mocked_hole",
"=",
"_create_mocked_hole",
"(",
")",
"with",
"_patch_config_flow_hole",
"(",
"mocked_hole",
")",
",",
"_patch_init_hole",
"(",
"mocked_hole",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"pi_hole",
".",
"DOMAIN",
",",
"{",
"pi_hole",
".",
"DOMAIN",
":",
"[",
"{",
"\"host\"",
":",
"\"pi.hole1\"",
",",
"\"api_key\"",
":",
"\"1\"",
"}",
"]",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"switch",
".",
"DOMAIN",
",",
"switch",
".",
"SERVICE_TURN_ON",
",",
"{",
"\"entity_id\"",
":",
"SWITCH_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mocked_hole",
".",
"enable",
".",
"assert_called_once",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"switch",
".",
"DOMAIN",
",",
"switch",
".",
"SERVICE_TURN_OFF",
",",
"{",
"\"entity_id\"",
":",
"SWITCH_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"mocked_hole",
".",
"disable",
".",
"assert_called_once_with",
"(",
"True",
")",
"# Failed calls",
"type",
"(",
"mocked_hole",
")",
".",
"enable",
"=",
"AsyncMock",
"(",
"side_effect",
"=",
"HoleError",
"(",
"\"Error1\"",
")",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"switch",
".",
"DOMAIN",
",",
"switch",
".",
"SERVICE_TURN_ON",
",",
"{",
"\"entity_id\"",
":",
"SWITCH_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"type",
"(",
"mocked_hole",
")",
".",
"disable",
"=",
"AsyncMock",
"(",
"side_effect",
"=",
"HoleError",
"(",
"\"Error2\"",
")",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"switch",
".",
"DOMAIN",
",",
"switch",
".",
"SERVICE_TURN_OFF",
",",
"{",
"\"entity_id\"",
":",
"SWITCH_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"errors",
"=",
"[",
"x",
"for",
"x",
"in",
"caplog",
".",
"records",
"if",
"x",
".",
"levelno",
"==",
"logging",
".",
"ERROR",
"]",
"assert",
"errors",
"[",
"-",
"2",
"]",
".",
"message",
"==",
"\"Unable to enable Pi-hole: Error1\"",
"assert",
"errors",
"[",
"-",
"1",
"]",
".",
"message",
"==",
"\"Unable to disable Pi-hole: Error2\""
] | [
111,
0
] | [
156,
72
] | python | en | ['en', 'pl', 'en'] | True |
test_disable_service_call | (hass) | Test disable service call with no Pi-hole named. | Test disable service call with no Pi-hole named. | async def test_disable_service_call(hass):
"""Test disable service call with no Pi-hole named."""
mocked_hole = _create_mocked_hole()
with _patch_config_flow_hole(mocked_hole), _patch_init_hole(mocked_hole):
assert await async_setup_component(
hass,
pi_hole.DOMAIN,
{
pi_hole.DOMAIN: [
{"host": "pi.hole1", "api_key": "1"},
{"host": "pi.hole2", "name": "Custom"},
]
},
)
await hass.async_block_till_done()
await hass.services.async_call(
pi_hole.DOMAIN,
SERVICE_DISABLE,
{ATTR_ENTITY_ID: "all", SERVICE_DISABLE_ATTR_DURATION: "00:00:01"},
blocking=True,
)
await hass.async_block_till_done()
mocked_hole.disable.assert_called_once_with(1) | [
"async",
"def",
"test_disable_service_call",
"(",
"hass",
")",
":",
"mocked_hole",
"=",
"_create_mocked_hole",
"(",
")",
"with",
"_patch_config_flow_hole",
"(",
"mocked_hole",
")",
",",
"_patch_init_hole",
"(",
"mocked_hole",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"pi_hole",
".",
"DOMAIN",
",",
"{",
"pi_hole",
".",
"DOMAIN",
":",
"[",
"{",
"\"host\"",
":",
"\"pi.hole1\"",
",",
"\"api_key\"",
":",
"\"1\"",
"}",
",",
"{",
"\"host\"",
":",
"\"pi.hole2\"",
",",
"\"name\"",
":",
"\"Custom\"",
"}",
",",
"]",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"pi_hole",
".",
"DOMAIN",
",",
"SERVICE_DISABLE",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"all\"",
",",
"SERVICE_DISABLE_ATTR_DURATION",
":",
"\"00:00:01\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"mocked_hole",
".",
"disable",
".",
"assert_called_once_with",
"(",
"1",
")"
] | [
159,
0
] | [
185,
54
] | python | en | ['en', 'en', 'en'] | True |
test_unload | (hass) | Test unload entities. | Test unload entities. | async def test_unload(hass):
"""Test unload entities."""
entry = MockConfigEntry(
domain=pi_hole.DOMAIN,
data={
CONF_NAME: DEFAULT_NAME,
CONF_HOST: "pi.hole",
CONF_LOCATION: DEFAULT_LOCATION,
CONF_SSL: DEFAULT_SSL,
CONF_VERIFY_SSL: DEFAULT_VERIFY_SSL,
},
)
entry.add_to_hass(hass)
mocked_hole = _create_mocked_hole()
with _patch_config_flow_hole(mocked_hole), _patch_init_hole(mocked_hole):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.entry_id in hass.data[pi_hole.DOMAIN]
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.entry_id not in hass.data[pi_hole.DOMAIN] | [
"async",
"def",
"test_unload",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"pi_hole",
".",
"DOMAIN",
",",
"data",
"=",
"{",
"CONF_NAME",
":",
"DEFAULT_NAME",
",",
"CONF_HOST",
":",
"\"pi.hole\"",
",",
"CONF_LOCATION",
":",
"DEFAULT_LOCATION",
",",
"CONF_SSL",
":",
"DEFAULT_SSL",
",",
"CONF_VERIFY_SSL",
":",
"DEFAULT_VERIFY_SSL",
",",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"mocked_hole",
"=",
"_create_mocked_hole",
"(",
")",
"with",
"_patch_config_flow_hole",
"(",
"mocked_hole",
")",
",",
"_patch_init_hole",
"(",
"mocked_hole",
")",
":",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"entry",
".",
"entry_id",
"in",
"hass",
".",
"data",
"[",
"pi_hole",
".",
"DOMAIN",
"]",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"entry",
".",
"entry_id",
"not",
"in",
"hass",
".",
"data",
"[",
"pi_hole",
".",
"DOMAIN",
"]"
] | [
188,
0
] | [
209,
58
] | python | de | ['de', 'fy', 'it'] | False |
test_is_on | (hass) | Test is_on. | Test is_on. | async def test_is_on(hass):
"""Test is_on."""
hass.states.async_set("remote.test", STATE_ON)
assert remote.is_on(hass, "remote.test")
hass.states.async_set("remote.test", STATE_OFF)
assert not remote.is_on(hass, "remote.test") | [
"async",
"def",
"test_is_on",
"(",
"hass",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"remote.test\"",
",",
"STATE_ON",
")",
"assert",
"remote",
".",
"is_on",
"(",
"hass",
",",
"\"remote.test\"",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"remote.test\"",
",",
"STATE_OFF",
")",
"assert",
"not",
"remote",
".",
"is_on",
"(",
"hass",
",",
"\"remote.test\"",
")"
] | [
31,
0
] | [
37,
48
] | python | en | ['en', 'en', 'en'] | False |
test_turn_on | (hass) | Test turn_on. | Test turn_on. | async def test_turn_on(hass):
"""Test turn_on."""
turn_on_calls = async_mock_service(hass, DOMAIN, SERVICE_TURN_ON)
await hass.services.async_call(DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ENTITY_ID})
await hass.async_block_till_done()
assert len(turn_on_calls) == 1
call = turn_on_calls[-1]
assert DOMAIN == call.domain | [
"async",
"def",
"test_turn_on",
"(",
"hass",
")",
":",
"turn_on_calls",
"=",
"async_mock_service",
"(",
"hass",
",",
"DOMAIN",
",",
"SERVICE_TURN_ON",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"ENTITY_ID",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"turn_on_calls",
")",
"==",
"1",
"call",
"=",
"turn_on_calls",
"[",
"-",
"1",
"]",
"assert",
"DOMAIN",
"==",
"call",
".",
"domain"
] | [
40,
0
] | [
50,
32
] | python | en | ['en', 'et', 'en'] | False |
test_turn_off | (hass) | Test turn_off. | Test turn_off. | async def test_turn_off(hass):
"""Test turn_off."""
turn_off_calls = async_mock_service(hass, DOMAIN, SERVICE_TURN_OFF)
await hass.services.async_call(
DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ENTITY_ID}
)
await hass.async_block_till_done()
assert len(turn_off_calls) == 1
call = turn_off_calls[-1]
assert call.domain == DOMAIN
assert call.service == SERVICE_TURN_OFF
assert call.data[ATTR_ENTITY_ID] == ENTITY_ID | [
"async",
"def",
"test_turn_off",
"(",
"hass",
")",
":",
"turn_off_calls",
"=",
"async_mock_service",
"(",
"hass",
",",
"DOMAIN",
",",
"SERVICE_TURN_OFF",
")",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_TURN_OFF",
",",
"{",
"ATTR_ENTITY_ID",
":",
"ENTITY_ID",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"turn_off_calls",
")",
"==",
"1",
"call",
"=",
"turn_off_calls",
"[",
"-",
"1",
"]",
"assert",
"call",
".",
"domain",
"==",
"DOMAIN",
"assert",
"call",
".",
"service",
"==",
"SERVICE_TURN_OFF",
"assert",
"call",
".",
"data",
"[",
"ATTR_ENTITY_ID",
"]",
"==",
"ENTITY_ID"
] | [
53,
0
] | [
68,
49
] | python | en | ['en', 'cy', 'en'] | False |
test_send_command | (hass) | Test send_command. | Test send_command. | async def test_send_command(hass):
"""Test send_command."""
send_command_calls = async_mock_service(hass, DOMAIN, SERVICE_SEND_COMMAND)
data = {
ATTR_ENTITY_ID: ENTITY_ID,
ATTR_DEVICE: "test_device",
ATTR_COMMAND: ["test_command"],
ATTR_NUM_REPEATS: "4",
ATTR_DELAY_SECS: "0.6",
}
await hass.services.async_call(DOMAIN, SERVICE_SEND_COMMAND, data)
await hass.async_block_till_done()
assert len(send_command_calls) == 1
call = send_command_calls[-1]
assert call.domain == DOMAIN
assert call.service == SERVICE_SEND_COMMAND
assert call.data[ATTR_ENTITY_ID] == ENTITY_ID | [
"async",
"def",
"test_send_command",
"(",
"hass",
")",
":",
"send_command_calls",
"=",
"async_mock_service",
"(",
"hass",
",",
"DOMAIN",
",",
"SERVICE_SEND_COMMAND",
")",
"data",
"=",
"{",
"ATTR_ENTITY_ID",
":",
"ENTITY_ID",
",",
"ATTR_DEVICE",
":",
"\"test_device\"",
",",
"ATTR_COMMAND",
":",
"[",
"\"test_command\"",
"]",
",",
"ATTR_NUM_REPEATS",
":",
"\"4\"",
",",
"ATTR_DELAY_SECS",
":",
"\"0.6\"",
",",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_SEND_COMMAND",
",",
"data",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"send_command_calls",
")",
"==",
"1",
"call",
"=",
"send_command_calls",
"[",
"-",
"1",
"]",
"assert",
"call",
".",
"domain",
"==",
"DOMAIN",
"assert",
"call",
".",
"service",
"==",
"SERVICE_SEND_COMMAND",
"assert",
"call",
".",
"data",
"[",
"ATTR_ENTITY_ID",
"]",
"==",
"ENTITY_ID"
] | [
71,
0
] | [
92,
49
] | python | en | ['en', 'en', 'en'] | False |
test_learn_command | (hass) | Test learn_command. | Test learn_command. | async def test_learn_command(hass):
"""Test learn_command."""
learn_command_calls = async_mock_service(hass, DOMAIN, SERVICE_LEARN_COMMAND)
data = {
ATTR_ENTITY_ID: ENTITY_ID,
ATTR_DEVICE: "test_device",
ATTR_COMMAND: ["test_command"],
ATTR_COMMAND_TYPE: "rf",
ATTR_ALTERNATIVE: True,
ATTR_TIMEOUT: 20,
}
await hass.services.async_call(DOMAIN, SERVICE_LEARN_COMMAND, data)
await hass.async_block_till_done()
assert len(learn_command_calls) == 1
call = learn_command_calls[-1]
assert call.domain == DOMAIN
assert call.service == SERVICE_LEARN_COMMAND
assert call.data[ATTR_ENTITY_ID] == ENTITY_ID | [
"async",
"def",
"test_learn_command",
"(",
"hass",
")",
":",
"learn_command_calls",
"=",
"async_mock_service",
"(",
"hass",
",",
"DOMAIN",
",",
"SERVICE_LEARN_COMMAND",
")",
"data",
"=",
"{",
"ATTR_ENTITY_ID",
":",
"ENTITY_ID",
",",
"ATTR_DEVICE",
":",
"\"test_device\"",
",",
"ATTR_COMMAND",
":",
"[",
"\"test_command\"",
"]",
",",
"ATTR_COMMAND_TYPE",
":",
"\"rf\"",
",",
"ATTR_ALTERNATIVE",
":",
"True",
",",
"ATTR_TIMEOUT",
":",
"20",
",",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_LEARN_COMMAND",
",",
"data",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"learn_command_calls",
")",
"==",
"1",
"call",
"=",
"learn_command_calls",
"[",
"-",
"1",
"]",
"assert",
"call",
".",
"domain",
"==",
"DOMAIN",
"assert",
"call",
".",
"service",
"==",
"SERVICE_LEARN_COMMAND",
"assert",
"call",
".",
"data",
"[",
"ATTR_ENTITY_ID",
"]",
"==",
"ENTITY_ID"
] | [
95,
0
] | [
116,
49
] | python | en | ['en', 'en', 'en'] | False |
test_delete_command | (hass) | Test delete_command. | Test delete_command. | async def test_delete_command(hass):
"""Test delete_command."""
delete_command_calls = async_mock_service(
hass, remote.DOMAIN, SERVICE_DELETE_COMMAND
)
data = {
ATTR_ENTITY_ID: ENTITY_ID,
ATTR_DEVICE: "test_device",
ATTR_COMMAND: ["test_command"],
}
await hass.services.async_call(DOMAIN, SERVICE_DELETE_COMMAND, data)
await hass.async_block_till_done()
assert len(delete_command_calls) == 1
call = delete_command_calls[-1]
assert call.domain == remote.DOMAIN
assert call.service == SERVICE_DELETE_COMMAND
assert call.data[ATTR_ENTITY_ID] == ENTITY_ID | [
"async",
"def",
"test_delete_command",
"(",
"hass",
")",
":",
"delete_command_calls",
"=",
"async_mock_service",
"(",
"hass",
",",
"remote",
".",
"DOMAIN",
",",
"SERVICE_DELETE_COMMAND",
")",
"data",
"=",
"{",
"ATTR_ENTITY_ID",
":",
"ENTITY_ID",
",",
"ATTR_DEVICE",
":",
"\"test_device\"",
",",
"ATTR_COMMAND",
":",
"[",
"\"test_command\"",
"]",
",",
"}",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_DELETE_COMMAND",
",",
"data",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"delete_command_calls",
")",
"==",
"1",
"call",
"=",
"delete_command_calls",
"[",
"-",
"1",
"]",
"assert",
"call",
".",
"domain",
"==",
"remote",
".",
"DOMAIN",
"assert",
"call",
".",
"service",
"==",
"SERVICE_DELETE_COMMAND",
"assert",
"call",
".",
"data",
"[",
"ATTR_ENTITY_ID",
"]",
"==",
"ENTITY_ID"
] | [
119,
0
] | [
140,
49
] | python | ca | ['ca', 'it', 'en'] | False |
test_deprecated_base_class | (caplog) | Test deprecated base class. | Test deprecated base class. | async def test_deprecated_base_class(caplog):
"""Test deprecated base class."""
class CustomRemote(remote.RemoteDevice):
pass
CustomRemote()
assert "RemoteDevice is deprecated, modify CustomRemote" in caplog.text | [
"async",
"def",
"test_deprecated_base_class",
"(",
"caplog",
")",
":",
"class",
"CustomRemote",
"(",
"remote",
".",
"RemoteDevice",
")",
":",
"pass",
"CustomRemote",
"(",
")",
"assert",
"\"RemoteDevice is deprecated, modify CustomRemote\"",
"in",
"caplog",
".",
"text"
] | [
143,
0
] | [
150,
75
] | python | en | ['en', 'en', 'en'] | True |
setup | (hass, config) | Set up the Homematic component. | Set up the Homematic component. | def setup(hass, config):
"""Set up the Homematic component."""
conf = config[DOMAIN]
hass.data[DATA_CONF] = remotes = {}
hass.data[DATA_STORE] = set()
# Create hosts-dictionary for pyhomematic
for rname, rconfig in conf[CONF_INTERFACES].items():
remotes[rname] = {
"ip": rconfig.get(CONF_HOST),
"port": rconfig.get(CONF_PORT),
"path": rconfig.get(CONF_PATH),
"resolvenames": rconfig.get(CONF_RESOLVENAMES),
"jsonport": rconfig.get(CONF_JSONPORT),
"username": rconfig.get(CONF_USERNAME),
"password": rconfig.get(CONF_PASSWORD),
"callbackip": rconfig.get(CONF_CALLBACK_IP),
"callbackport": rconfig.get(CONF_CALLBACK_PORT),
"ssl": rconfig[CONF_SSL],
"verify_ssl": rconfig.get(CONF_VERIFY_SSL),
"connect": True,
}
for sname, sconfig in conf[CONF_HOSTS].items():
remotes[sname] = {
"ip": sconfig.get(CONF_HOST),
"port": sconfig[CONF_PORT],
"username": sconfig.get(CONF_USERNAME),
"password": sconfig.get(CONF_PASSWORD),
"connect": False,
}
# Create server thread
bound_system_callback = partial(_system_callback_handler, hass, config)
hass.data[DATA_HOMEMATIC] = homematic = HMConnection(
local=config[DOMAIN].get(CONF_LOCAL_IP),
localport=config[DOMAIN].get(CONF_LOCAL_PORT, DEFAULT_LOCAL_PORT),
remotes=remotes,
systemcallback=bound_system_callback,
interface_id="homeassistant",
)
# Start server thread, connect to hosts, initialize to receive events
homematic.start()
# Stops server when Home Assistant is shutting down
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, hass.data[DATA_HOMEMATIC].stop)
# Init homematic hubs
entity_hubs = []
for hub_name in conf[CONF_HOSTS]:
entity_hubs.append(HMHub(hass, homematic, hub_name))
def _hm_service_virtualkey(service):
"""Service to handle virtualkey servicecalls."""
address = service.data.get(ATTR_ADDRESS)
channel = service.data.get(ATTR_CHANNEL)
param = service.data.get(ATTR_PARAM)
# Device not found
hmdevice = _device_from_servicecall(hass, service)
if hmdevice is None:
_LOGGER.error("%s not found for service virtualkey!", address)
return
# Parameter doesn't exist for device
if param not in hmdevice.ACTIONNODE:
_LOGGER.error("%s not datapoint in hm device %s", param, address)
return
# Channel doesn't exist for device
if channel not in hmdevice.ACTIONNODE[param]:
_LOGGER.error("%i is not a channel in hm device %s", channel, address)
return
# Call parameter
hmdevice.actionNodeData(param, True, channel)
hass.services.register(
DOMAIN,
SERVICE_VIRTUALKEY,
_hm_service_virtualkey,
schema=SCHEMA_SERVICE_VIRTUALKEY,
)
def _service_handle_value(service):
"""Service to call setValue method for HomeMatic system variable."""
entity_ids = service.data.get(ATTR_ENTITY_ID)
name = service.data[ATTR_NAME]
value = service.data[ATTR_VALUE]
if entity_ids:
entities = [
entity for entity in entity_hubs if entity.entity_id in entity_ids
]
else:
entities = entity_hubs
if not entities:
_LOGGER.error("No HomeMatic hubs available")
return
for hub in entities:
hub.hm_set_variable(name, value)
hass.services.register(
DOMAIN,
SERVICE_SET_VARIABLE_VALUE,
_service_handle_value,
schema=SCHEMA_SERVICE_SET_VARIABLE_VALUE,
)
def _service_handle_reconnect(service):
"""Service to reconnect all HomeMatic hubs."""
homematic.reconnect()
hass.services.register(
DOMAIN,
SERVICE_RECONNECT,
_service_handle_reconnect,
schema=SCHEMA_SERVICE_RECONNECT,
)
def _service_handle_device(service):
"""Service to call setValue method for HomeMatic devices."""
address = service.data.get(ATTR_ADDRESS)
channel = service.data.get(ATTR_CHANNEL)
param = service.data.get(ATTR_PARAM)
value = service.data.get(ATTR_VALUE)
value_type = service.data.get(ATTR_VALUE_TYPE)
# Convert value into correct XML-RPC Type.
# https://docs.python.org/3/library/xmlrpc.client.html#xmlrpc.client.ServerProxy
if value_type:
if value_type == "int":
value = int(value)
elif value_type == "double":
value = float(value)
elif value_type == "boolean":
value = bool(value)
elif value_type == "dateTime.iso8601":
value = datetime.strptime(value, "%Y%m%dT%H:%M:%S")
else:
# Default is 'string'
value = str(value)
# Device not found
hmdevice = _device_from_servicecall(hass, service)
if hmdevice is None:
_LOGGER.error("%s not found!", address)
return
hmdevice.setValue(param, value, channel)
hass.services.register(
DOMAIN,
SERVICE_SET_DEVICE_VALUE,
_service_handle_device,
schema=SCHEMA_SERVICE_SET_DEVICE_VALUE,
)
def _service_handle_install_mode(service):
"""Service to set interface into install mode."""
interface = service.data.get(ATTR_INTERFACE)
mode = service.data.get(ATTR_MODE)
time = service.data.get(ATTR_TIME)
address = service.data.get(ATTR_ADDRESS)
homematic.setInstallMode(interface, t=time, mode=mode, address=address)
hass.services.register(
DOMAIN,
SERVICE_SET_INSTALL_MODE,
_service_handle_install_mode,
schema=SCHEMA_SERVICE_SET_INSTALL_MODE,
)
def _service_put_paramset(service):
"""Service to call the putParamset method on a HomeMatic connection."""
interface = service.data.get(ATTR_INTERFACE)
address = service.data.get(ATTR_ADDRESS)
paramset_key = service.data.get(ATTR_PARAMSET_KEY)
# When passing in the paramset from a YAML file we get an OrderedDict
# here instead of a dict, so add this explicit cast.
# The service schema makes sure that this cast works.
paramset = dict(service.data.get(ATTR_PARAMSET))
rx_mode = service.data.get(ATTR_RX_MODE)
_LOGGER.debug(
"Calling putParamset: %s, %s, %s, %s, %s",
interface,
address,
paramset_key,
paramset,
rx_mode,
)
homematic.putParamset(interface, address, paramset_key, paramset, rx_mode)
hass.services.register(
DOMAIN,
SERVICE_PUT_PARAMSET,
_service_put_paramset,
schema=SCHEMA_SERVICE_PUT_PARAMSET,
)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"conf",
"=",
"config",
"[",
"DOMAIN",
"]",
"hass",
".",
"data",
"[",
"DATA_CONF",
"]",
"=",
"remotes",
"=",
"{",
"}",
"hass",
".",
"data",
"[",
"DATA_STORE",
"]",
"=",
"set",
"(",
")",
"# Create hosts-dictionary for pyhomematic",
"for",
"rname",
",",
"rconfig",
"in",
"conf",
"[",
"CONF_INTERFACES",
"]",
".",
"items",
"(",
")",
":",
"remotes",
"[",
"rname",
"]",
"=",
"{",
"\"ip\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_HOST",
")",
",",
"\"port\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_PORT",
")",
",",
"\"path\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_PATH",
")",
",",
"\"resolvenames\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_RESOLVENAMES",
")",
",",
"\"jsonport\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_JSONPORT",
")",
",",
"\"username\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_USERNAME",
")",
",",
"\"password\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_PASSWORD",
")",
",",
"\"callbackip\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_CALLBACK_IP",
")",
",",
"\"callbackport\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_CALLBACK_PORT",
")",
",",
"\"ssl\"",
":",
"rconfig",
"[",
"CONF_SSL",
"]",
",",
"\"verify_ssl\"",
":",
"rconfig",
".",
"get",
"(",
"CONF_VERIFY_SSL",
")",
",",
"\"connect\"",
":",
"True",
",",
"}",
"for",
"sname",
",",
"sconfig",
"in",
"conf",
"[",
"CONF_HOSTS",
"]",
".",
"items",
"(",
")",
":",
"remotes",
"[",
"sname",
"]",
"=",
"{",
"\"ip\"",
":",
"sconfig",
".",
"get",
"(",
"CONF_HOST",
")",
",",
"\"port\"",
":",
"sconfig",
"[",
"CONF_PORT",
"]",
",",
"\"username\"",
":",
"sconfig",
".",
"get",
"(",
"CONF_USERNAME",
")",
",",
"\"password\"",
":",
"sconfig",
".",
"get",
"(",
"CONF_PASSWORD",
")",
",",
"\"connect\"",
":",
"False",
",",
"}",
"# Create server thread",
"bound_system_callback",
"=",
"partial",
"(",
"_system_callback_handler",
",",
"hass",
",",
"config",
")",
"hass",
".",
"data",
"[",
"DATA_HOMEMATIC",
"]",
"=",
"homematic",
"=",
"HMConnection",
"(",
"local",
"=",
"config",
"[",
"DOMAIN",
"]",
".",
"get",
"(",
"CONF_LOCAL_IP",
")",
",",
"localport",
"=",
"config",
"[",
"DOMAIN",
"]",
".",
"get",
"(",
"CONF_LOCAL_PORT",
",",
"DEFAULT_LOCAL_PORT",
")",
",",
"remotes",
"=",
"remotes",
",",
"systemcallback",
"=",
"bound_system_callback",
",",
"interface_id",
"=",
"\"homeassistant\"",
",",
")",
"# Start server thread, connect to hosts, initialize to receive events",
"homematic",
".",
"start",
"(",
")",
"# Stops server when Home Assistant is shutting down",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"hass",
".",
"data",
"[",
"DATA_HOMEMATIC",
"]",
".",
"stop",
")",
"# Init homematic hubs",
"entity_hubs",
"=",
"[",
"]",
"for",
"hub_name",
"in",
"conf",
"[",
"CONF_HOSTS",
"]",
":",
"entity_hubs",
".",
"append",
"(",
"HMHub",
"(",
"hass",
",",
"homematic",
",",
"hub_name",
")",
")",
"def",
"_hm_service_virtualkey",
"(",
"service",
")",
":",
"\"\"\"Service to handle virtualkey servicecalls.\"\"\"",
"address",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ADDRESS",
")",
"channel",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_CHANNEL",
")",
"param",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_PARAM",
")",
"# Device not found",
"hmdevice",
"=",
"_device_from_servicecall",
"(",
"hass",
",",
"service",
")",
"if",
"hmdevice",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"%s not found for service virtualkey!\"",
",",
"address",
")",
"return",
"# Parameter doesn't exist for device",
"if",
"param",
"not",
"in",
"hmdevice",
".",
"ACTIONNODE",
":",
"_LOGGER",
".",
"error",
"(",
"\"%s not datapoint in hm device %s\"",
",",
"param",
",",
"address",
")",
"return",
"# Channel doesn't exist for device",
"if",
"channel",
"not",
"in",
"hmdevice",
".",
"ACTIONNODE",
"[",
"param",
"]",
":",
"_LOGGER",
".",
"error",
"(",
"\"%i is not a channel in hm device %s\"",
",",
"channel",
",",
"address",
")",
"return",
"# Call parameter",
"hmdevice",
".",
"actionNodeData",
"(",
"param",
",",
"True",
",",
"channel",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_VIRTUALKEY",
",",
"_hm_service_virtualkey",
",",
"schema",
"=",
"SCHEMA_SERVICE_VIRTUALKEY",
",",
")",
"def",
"_service_handle_value",
"(",
"service",
")",
":",
"\"\"\"Service to call setValue method for HomeMatic system variable.\"\"\"",
"entity_ids",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ENTITY_ID",
")",
"name",
"=",
"service",
".",
"data",
"[",
"ATTR_NAME",
"]",
"value",
"=",
"service",
".",
"data",
"[",
"ATTR_VALUE",
"]",
"if",
"entity_ids",
":",
"entities",
"=",
"[",
"entity",
"for",
"entity",
"in",
"entity_hubs",
"if",
"entity",
".",
"entity_id",
"in",
"entity_ids",
"]",
"else",
":",
"entities",
"=",
"entity_hubs",
"if",
"not",
"entities",
":",
"_LOGGER",
".",
"error",
"(",
"\"No HomeMatic hubs available\"",
")",
"return",
"for",
"hub",
"in",
"entities",
":",
"hub",
".",
"hm_set_variable",
"(",
"name",
",",
"value",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_VARIABLE_VALUE",
",",
"_service_handle_value",
",",
"schema",
"=",
"SCHEMA_SERVICE_SET_VARIABLE_VALUE",
",",
")",
"def",
"_service_handle_reconnect",
"(",
"service",
")",
":",
"\"\"\"Service to reconnect all HomeMatic hubs.\"\"\"",
"homematic",
".",
"reconnect",
"(",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_RECONNECT",
",",
"_service_handle_reconnect",
",",
"schema",
"=",
"SCHEMA_SERVICE_RECONNECT",
",",
")",
"def",
"_service_handle_device",
"(",
"service",
")",
":",
"\"\"\"Service to call setValue method for HomeMatic devices.\"\"\"",
"address",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ADDRESS",
")",
"channel",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_CHANNEL",
")",
"param",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_PARAM",
")",
"value",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_VALUE",
")",
"value_type",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_VALUE_TYPE",
")",
"# Convert value into correct XML-RPC Type.",
"# https://docs.python.org/3/library/xmlrpc.client.html#xmlrpc.client.ServerProxy",
"if",
"value_type",
":",
"if",
"value_type",
"==",
"\"int\"",
":",
"value",
"=",
"int",
"(",
"value",
")",
"elif",
"value_type",
"==",
"\"double\"",
":",
"value",
"=",
"float",
"(",
"value",
")",
"elif",
"value_type",
"==",
"\"boolean\"",
":",
"value",
"=",
"bool",
"(",
"value",
")",
"elif",
"value_type",
"==",
"\"dateTime.iso8601\"",
":",
"value",
"=",
"datetime",
".",
"strptime",
"(",
"value",
",",
"\"%Y%m%dT%H:%M:%S\"",
")",
"else",
":",
"# Default is 'string'",
"value",
"=",
"str",
"(",
"value",
")",
"# Device not found",
"hmdevice",
"=",
"_device_from_servicecall",
"(",
"hass",
",",
"service",
")",
"if",
"hmdevice",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"%s not found!\"",
",",
"address",
")",
"return",
"hmdevice",
".",
"setValue",
"(",
"param",
",",
"value",
",",
"channel",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_DEVICE_VALUE",
",",
"_service_handle_device",
",",
"schema",
"=",
"SCHEMA_SERVICE_SET_DEVICE_VALUE",
",",
")",
"def",
"_service_handle_install_mode",
"(",
"service",
")",
":",
"\"\"\"Service to set interface into install mode.\"\"\"",
"interface",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_INTERFACE",
")",
"mode",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_MODE",
")",
"time",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_TIME",
")",
"address",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ADDRESS",
")",
"homematic",
".",
"setInstallMode",
"(",
"interface",
",",
"t",
"=",
"time",
",",
"mode",
"=",
"mode",
",",
"address",
"=",
"address",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_INSTALL_MODE",
",",
"_service_handle_install_mode",
",",
"schema",
"=",
"SCHEMA_SERVICE_SET_INSTALL_MODE",
",",
")",
"def",
"_service_put_paramset",
"(",
"service",
")",
":",
"\"\"\"Service to call the putParamset method on a HomeMatic connection.\"\"\"",
"interface",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_INTERFACE",
")",
"address",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ADDRESS",
")",
"paramset_key",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_PARAMSET_KEY",
")",
"# When passing in the paramset from a YAML file we get an OrderedDict",
"# here instead of a dict, so add this explicit cast.",
"# The service schema makes sure that this cast works.",
"paramset",
"=",
"dict",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_PARAMSET",
")",
")",
"rx_mode",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_RX_MODE",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Calling putParamset: %s, %s, %s, %s, %s\"",
",",
"interface",
",",
"address",
",",
"paramset_key",
",",
"paramset",
",",
"rx_mode",
",",
")",
"homematic",
".",
"putParamset",
"(",
"interface",
",",
"address",
",",
"paramset_key",
",",
"paramset",
",",
"rx_mode",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_PUT_PARAMSET",
",",
"_service_put_paramset",
",",
"schema",
"=",
"SCHEMA_SERVICE_PUT_PARAMSET",
",",
")",
"return",
"True"
] | [
209,
0
] | [
415,
15
] | python | en | ['en', 'en', 'en'] | True |
_system_callback_handler | (hass, config, src, *args) | System callback handler. | System callback handler. | def _system_callback_handler(hass, config, src, *args):
"""System callback handler."""
# New devices available at hub
if src == "newDevices":
(interface_id, dev_descriptions) = args
interface = interface_id.split("-")[-1]
# Device support active?
if not hass.data[DATA_CONF][interface]["connect"]:
return
addresses = []
for dev in dev_descriptions:
address = dev["ADDRESS"].split(":")[0]
if address not in hass.data[DATA_STORE]:
hass.data[DATA_STORE].add(address)
addresses.append(address)
# Register EVENTS
# Search all devices with an EVENTNODE that includes data
bound_event_callback = partial(_hm_event_handler, hass, interface)
for dev in addresses:
hmdevice = hass.data[DATA_HOMEMATIC].devices[interface].get(dev)
if hmdevice.EVENTNODE:
hmdevice.setEventCallback(callback=bound_event_callback, bequeath=True)
# Create Home Assistant entities
if addresses:
for component_name, discovery_type in (
("switch", DISCOVER_SWITCHES),
("light", DISCOVER_LIGHTS),
("cover", DISCOVER_COVER),
("binary_sensor", DISCOVER_BINARY_SENSORS),
("sensor", DISCOVER_SENSORS),
("climate", DISCOVER_CLIMATE),
("lock", DISCOVER_LOCKS),
("binary_sensor", DISCOVER_BATTERY),
):
# Get all devices of a specific type
found_devices = _get_devices(hass, discovery_type, addresses, interface)
# When devices of this type are found
# they are setup in Home Assistant and a discovery event is fired
if found_devices:
discovery.load_platform(
hass,
component_name,
DOMAIN,
{
ATTR_DISCOVER_DEVICES: found_devices,
ATTR_DISCOVERY_TYPE: discovery_type,
},
config,
)
# Homegear error message
elif src == "error":
_LOGGER.error("Error: %s", args)
(interface_id, errorcode, message) = args
hass.bus.fire(EVENT_ERROR, {ATTR_ERRORCODE: errorcode, ATTR_MESSAGE: message}) | [
"def",
"_system_callback_handler",
"(",
"hass",
",",
"config",
",",
"src",
",",
"*",
"args",
")",
":",
"# New devices available at hub",
"if",
"src",
"==",
"\"newDevices\"",
":",
"(",
"interface_id",
",",
"dev_descriptions",
")",
"=",
"args",
"interface",
"=",
"interface_id",
".",
"split",
"(",
"\"-\"",
")",
"[",
"-",
"1",
"]",
"# Device support active?",
"if",
"not",
"hass",
".",
"data",
"[",
"DATA_CONF",
"]",
"[",
"interface",
"]",
"[",
"\"connect\"",
"]",
":",
"return",
"addresses",
"=",
"[",
"]",
"for",
"dev",
"in",
"dev_descriptions",
":",
"address",
"=",
"dev",
"[",
"\"ADDRESS\"",
"]",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"if",
"address",
"not",
"in",
"hass",
".",
"data",
"[",
"DATA_STORE",
"]",
":",
"hass",
".",
"data",
"[",
"DATA_STORE",
"]",
".",
"add",
"(",
"address",
")",
"addresses",
".",
"append",
"(",
"address",
")",
"# Register EVENTS",
"# Search all devices with an EVENTNODE that includes data",
"bound_event_callback",
"=",
"partial",
"(",
"_hm_event_handler",
",",
"hass",
",",
"interface",
")",
"for",
"dev",
"in",
"addresses",
":",
"hmdevice",
"=",
"hass",
".",
"data",
"[",
"DATA_HOMEMATIC",
"]",
".",
"devices",
"[",
"interface",
"]",
".",
"get",
"(",
"dev",
")",
"if",
"hmdevice",
".",
"EVENTNODE",
":",
"hmdevice",
".",
"setEventCallback",
"(",
"callback",
"=",
"bound_event_callback",
",",
"bequeath",
"=",
"True",
")",
"# Create Home Assistant entities",
"if",
"addresses",
":",
"for",
"component_name",
",",
"discovery_type",
"in",
"(",
"(",
"\"switch\"",
",",
"DISCOVER_SWITCHES",
")",
",",
"(",
"\"light\"",
",",
"DISCOVER_LIGHTS",
")",
",",
"(",
"\"cover\"",
",",
"DISCOVER_COVER",
")",
",",
"(",
"\"binary_sensor\"",
",",
"DISCOVER_BINARY_SENSORS",
")",
",",
"(",
"\"sensor\"",
",",
"DISCOVER_SENSORS",
")",
",",
"(",
"\"climate\"",
",",
"DISCOVER_CLIMATE",
")",
",",
"(",
"\"lock\"",
",",
"DISCOVER_LOCKS",
")",
",",
"(",
"\"binary_sensor\"",
",",
"DISCOVER_BATTERY",
")",
",",
")",
":",
"# Get all devices of a specific type",
"found_devices",
"=",
"_get_devices",
"(",
"hass",
",",
"discovery_type",
",",
"addresses",
",",
"interface",
")",
"# When devices of this type are found",
"# they are setup in Home Assistant and a discovery event is fired",
"if",
"found_devices",
":",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"component_name",
",",
"DOMAIN",
",",
"{",
"ATTR_DISCOVER_DEVICES",
":",
"found_devices",
",",
"ATTR_DISCOVERY_TYPE",
":",
"discovery_type",
",",
"}",
",",
"config",
",",
")",
"# Homegear error message",
"elif",
"src",
"==",
"\"error\"",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error: %s\"",
",",
"args",
")",
"(",
"interface_id",
",",
"errorcode",
",",
"message",
")",
"=",
"args",
"hass",
".",
"bus",
".",
"fire",
"(",
"EVENT_ERROR",
",",
"{",
"ATTR_ERRORCODE",
":",
"errorcode",
",",
"ATTR_MESSAGE",
":",
"message",
"}",
")"
] | [
418,
0
] | [
478,
86
] | python | en | ['en', 'da', 'en'] | True |
_get_devices | (hass, discovery_type, keys, interface) | Get the HomeMatic devices for given discovery_type. | Get the HomeMatic devices for given discovery_type. | def _get_devices(hass, discovery_type, keys, interface):
"""Get the HomeMatic devices for given discovery_type."""
device_arr = []
for key in keys:
device = hass.data[DATA_HOMEMATIC].devices[interface][key]
class_name = device.__class__.__name__
metadata = {}
# Class not supported by discovery type
if (
discovery_type != DISCOVER_BATTERY
and class_name not in HM_DEVICE_TYPES[discovery_type]
):
continue
# Load metadata needed to generate a parameter list
if discovery_type == DISCOVER_SENSORS:
metadata.update(device.SENSORNODE)
elif discovery_type == DISCOVER_BINARY_SENSORS:
metadata.update(device.BINARYNODE)
elif discovery_type == DISCOVER_BATTERY:
if ATTR_LOWBAT in device.ATTRIBUTENODE:
metadata.update({ATTR_LOWBAT: device.ATTRIBUTENODE[ATTR_LOWBAT]})
elif ATTR_LOW_BAT in device.ATTRIBUTENODE:
metadata.update({ATTR_LOW_BAT: device.ATTRIBUTENODE[ATTR_LOW_BAT]})
else:
continue
else:
metadata.update({None: device.ELEMENT})
# Generate options for 1...n elements with 1...n parameters
for param, channels in metadata.items():
if (
param in HM_IGNORE_DISCOVERY_NODE
and class_name not in HM_IGNORE_DISCOVERY_NODE_EXCEPTIONS.get(param, [])
):
continue
if discovery_type == DISCOVER_SWITCHES and class_name == "IPKeySwitchLevel":
channels.remove(8)
channels.remove(12)
if discovery_type == DISCOVER_LIGHTS and class_name == "IPKeySwitchLevel":
channels.remove(4)
# Add devices
_LOGGER.debug(
"%s: Handling %s: %s: %s", discovery_type, key, param, channels
)
for channel in channels:
name = _create_ha_id(
name=device.NAME, channel=channel, param=param, count=len(channels)
)
unique_id = _create_ha_id(
name=key, channel=channel, param=param, count=len(channels)
)
device_dict = {
CONF_PLATFORM: "homematic",
ATTR_ADDRESS: key,
ATTR_INTERFACE: interface,
ATTR_NAME: name,
ATTR_DEVICE_TYPE: class_name,
ATTR_CHANNEL: channel,
ATTR_UNIQUE_ID: unique_id,
}
if param is not None:
device_dict[ATTR_PARAM] = param
# Add new device
try:
DEVICE_SCHEMA(device_dict)
device_arr.append(device_dict)
except vol.MultipleInvalid as err:
_LOGGER.error("Invalid device config: %s", str(err))
return device_arr | [
"def",
"_get_devices",
"(",
"hass",
",",
"discovery_type",
",",
"keys",
",",
"interface",
")",
":",
"device_arr",
"=",
"[",
"]",
"for",
"key",
"in",
"keys",
":",
"device",
"=",
"hass",
".",
"data",
"[",
"DATA_HOMEMATIC",
"]",
".",
"devices",
"[",
"interface",
"]",
"[",
"key",
"]",
"class_name",
"=",
"device",
".",
"__class__",
".",
"__name__",
"metadata",
"=",
"{",
"}",
"# Class not supported by discovery type",
"if",
"(",
"discovery_type",
"!=",
"DISCOVER_BATTERY",
"and",
"class_name",
"not",
"in",
"HM_DEVICE_TYPES",
"[",
"discovery_type",
"]",
")",
":",
"continue",
"# Load metadata needed to generate a parameter list",
"if",
"discovery_type",
"==",
"DISCOVER_SENSORS",
":",
"metadata",
".",
"update",
"(",
"device",
".",
"SENSORNODE",
")",
"elif",
"discovery_type",
"==",
"DISCOVER_BINARY_SENSORS",
":",
"metadata",
".",
"update",
"(",
"device",
".",
"BINARYNODE",
")",
"elif",
"discovery_type",
"==",
"DISCOVER_BATTERY",
":",
"if",
"ATTR_LOWBAT",
"in",
"device",
".",
"ATTRIBUTENODE",
":",
"metadata",
".",
"update",
"(",
"{",
"ATTR_LOWBAT",
":",
"device",
".",
"ATTRIBUTENODE",
"[",
"ATTR_LOWBAT",
"]",
"}",
")",
"elif",
"ATTR_LOW_BAT",
"in",
"device",
".",
"ATTRIBUTENODE",
":",
"metadata",
".",
"update",
"(",
"{",
"ATTR_LOW_BAT",
":",
"device",
".",
"ATTRIBUTENODE",
"[",
"ATTR_LOW_BAT",
"]",
"}",
")",
"else",
":",
"continue",
"else",
":",
"metadata",
".",
"update",
"(",
"{",
"None",
":",
"device",
".",
"ELEMENT",
"}",
")",
"# Generate options for 1...n elements with 1...n parameters",
"for",
"param",
",",
"channels",
"in",
"metadata",
".",
"items",
"(",
")",
":",
"if",
"(",
"param",
"in",
"HM_IGNORE_DISCOVERY_NODE",
"and",
"class_name",
"not",
"in",
"HM_IGNORE_DISCOVERY_NODE_EXCEPTIONS",
".",
"get",
"(",
"param",
",",
"[",
"]",
")",
")",
":",
"continue",
"if",
"discovery_type",
"==",
"DISCOVER_SWITCHES",
"and",
"class_name",
"==",
"\"IPKeySwitchLevel\"",
":",
"channels",
".",
"remove",
"(",
"8",
")",
"channels",
".",
"remove",
"(",
"12",
")",
"if",
"discovery_type",
"==",
"DISCOVER_LIGHTS",
"and",
"class_name",
"==",
"\"IPKeySwitchLevel\"",
":",
"channels",
".",
"remove",
"(",
"4",
")",
"# Add devices",
"_LOGGER",
".",
"debug",
"(",
"\"%s: Handling %s: %s: %s\"",
",",
"discovery_type",
",",
"key",
",",
"param",
",",
"channels",
")",
"for",
"channel",
"in",
"channels",
":",
"name",
"=",
"_create_ha_id",
"(",
"name",
"=",
"device",
".",
"NAME",
",",
"channel",
"=",
"channel",
",",
"param",
"=",
"param",
",",
"count",
"=",
"len",
"(",
"channels",
")",
")",
"unique_id",
"=",
"_create_ha_id",
"(",
"name",
"=",
"key",
",",
"channel",
"=",
"channel",
",",
"param",
"=",
"param",
",",
"count",
"=",
"len",
"(",
"channels",
")",
")",
"device_dict",
"=",
"{",
"CONF_PLATFORM",
":",
"\"homematic\"",
",",
"ATTR_ADDRESS",
":",
"key",
",",
"ATTR_INTERFACE",
":",
"interface",
",",
"ATTR_NAME",
":",
"name",
",",
"ATTR_DEVICE_TYPE",
":",
"class_name",
",",
"ATTR_CHANNEL",
":",
"channel",
",",
"ATTR_UNIQUE_ID",
":",
"unique_id",
",",
"}",
"if",
"param",
"is",
"not",
"None",
":",
"device_dict",
"[",
"ATTR_PARAM",
"]",
"=",
"param",
"# Add new device",
"try",
":",
"DEVICE_SCHEMA",
"(",
"device_dict",
")",
"device_arr",
".",
"append",
"(",
"device_dict",
")",
"except",
"vol",
".",
"MultipleInvalid",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Invalid device config: %s\"",
",",
"str",
"(",
"err",
")",
")",
"return",
"device_arr"
] | [
481,
0
] | [
554,
21
] | python | en | ['en', 'en', 'en'] | True |
_create_ha_id | (name, channel, param, count) | Generate a unique entity id. | Generate a unique entity id. | def _create_ha_id(name, channel, param, count):
"""Generate a unique entity id."""
# HMDevice is a simple device
if count == 1 and param is None:
return name
# Has multiple elements/channels
if count > 1 and param is None:
return f"{name} {channel}"
# With multiple parameters on first channel
if count == 1 and param is not None:
return f"{name} {param}"
# Multiple parameters with multiple channels
if count > 1 and param is not None:
return f"{name} {channel} {param}" | [
"def",
"_create_ha_id",
"(",
"name",
",",
"channel",
",",
"param",
",",
"count",
")",
":",
"# HMDevice is a simple device",
"if",
"count",
"==",
"1",
"and",
"param",
"is",
"None",
":",
"return",
"name",
"# Has multiple elements/channels",
"if",
"count",
">",
"1",
"and",
"param",
"is",
"None",
":",
"return",
"f\"{name} {channel}\"",
"# With multiple parameters on first channel",
"if",
"count",
"==",
"1",
"and",
"param",
"is",
"not",
"None",
":",
"return",
"f\"{name} {param}\"",
"# Multiple parameters with multiple channels",
"if",
"count",
">",
"1",
"and",
"param",
"is",
"not",
"None",
":",
"return",
"f\"{name} {channel} {param}\""
] | [
557,
0
] | [
573,
42
] | python | it | ['fr', 'it', 'it'] | True |
_hm_event_handler | (hass, interface, device, caller, attribute, value) | Handle all pyhomematic device events. | Handle all pyhomematic device events. | def _hm_event_handler(hass, interface, device, caller, attribute, value):
"""Handle all pyhomematic device events."""
try:
channel = int(device.split(":")[1])
address = device.split(":")[0]
hmdevice = hass.data[DATA_HOMEMATIC].devices[interface].get(address)
except (TypeError, ValueError):
_LOGGER.error("Event handling channel convert error!")
return
# Return if not an event supported by device
if attribute not in hmdevice.EVENTNODE:
return
_LOGGER.debug("Event %s for %s channel %i", attribute, hmdevice.NAME, channel)
# Keypress event
if attribute in HM_PRESS_EVENTS:
hass.bus.fire(
EVENT_KEYPRESS,
{ATTR_NAME: hmdevice.NAME, ATTR_PARAM: attribute, ATTR_CHANNEL: channel},
)
return
# Impulse event
if attribute in HM_IMPULSE_EVENTS:
hass.bus.fire(EVENT_IMPULSE, {ATTR_NAME: hmdevice.NAME, ATTR_CHANNEL: channel})
return
_LOGGER.warning("Event is unknown and not forwarded") | [
"def",
"_hm_event_handler",
"(",
"hass",
",",
"interface",
",",
"device",
",",
"caller",
",",
"attribute",
",",
"value",
")",
":",
"try",
":",
"channel",
"=",
"int",
"(",
"device",
".",
"split",
"(",
"\":\"",
")",
"[",
"1",
"]",
")",
"address",
"=",
"device",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"hmdevice",
"=",
"hass",
".",
"data",
"[",
"DATA_HOMEMATIC",
"]",
".",
"devices",
"[",
"interface",
"]",
".",
"get",
"(",
"address",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Event handling channel convert error!\"",
")",
"return",
"# Return if not an event supported by device",
"if",
"attribute",
"not",
"in",
"hmdevice",
".",
"EVENTNODE",
":",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Event %s for %s channel %i\"",
",",
"attribute",
",",
"hmdevice",
".",
"NAME",
",",
"channel",
")",
"# Keypress event",
"if",
"attribute",
"in",
"HM_PRESS_EVENTS",
":",
"hass",
".",
"bus",
".",
"fire",
"(",
"EVENT_KEYPRESS",
",",
"{",
"ATTR_NAME",
":",
"hmdevice",
".",
"NAME",
",",
"ATTR_PARAM",
":",
"attribute",
",",
"ATTR_CHANNEL",
":",
"channel",
"}",
",",
")",
"return",
"# Impulse event",
"if",
"attribute",
"in",
"HM_IMPULSE_EVENTS",
":",
"hass",
".",
"bus",
".",
"fire",
"(",
"EVENT_IMPULSE",
",",
"{",
"ATTR_NAME",
":",
"hmdevice",
".",
"NAME",
",",
"ATTR_CHANNEL",
":",
"channel",
"}",
")",
"return",
"_LOGGER",
".",
"warning",
"(",
"\"Event is unknown and not forwarded\"",
")"
] | [
576,
0
] | [
605,
57
] | python | en | ['en', 'en', 'en'] | True |
_device_from_servicecall | (hass, service) | Extract HomeMatic device from service call. | Extract HomeMatic device from service call. | def _device_from_servicecall(hass, service):
"""Extract HomeMatic device from service call."""
address = service.data.get(ATTR_ADDRESS)
interface = service.data.get(ATTR_INTERFACE)
if address == "BIDCOS-RF":
address = "BidCoS-RF"
if interface:
return hass.data[DATA_HOMEMATIC].devices[interface].get(address)
for devices in hass.data[DATA_HOMEMATIC].devices.values():
if address in devices:
return devices[address] | [
"def",
"_device_from_servicecall",
"(",
"hass",
",",
"service",
")",
":",
"address",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ADDRESS",
")",
"interface",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_INTERFACE",
")",
"if",
"address",
"==",
"\"BIDCOS-RF\"",
":",
"address",
"=",
"\"BidCoS-RF\"",
"if",
"interface",
":",
"return",
"hass",
".",
"data",
"[",
"DATA_HOMEMATIC",
"]",
".",
"devices",
"[",
"interface",
"]",
".",
"get",
"(",
"address",
")",
"for",
"devices",
"in",
"hass",
".",
"data",
"[",
"DATA_HOMEMATIC",
"]",
".",
"devices",
".",
"values",
"(",
")",
":",
"if",
"address",
"in",
"devices",
":",
"return",
"devices",
"[",
"address",
"]"
] | [
608,
0
] | [
620,
35
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass: HomeAssistant, config: dict) | Set up the DoorBird component. | Set up the DoorBird component. | async def async_setup(hass: HomeAssistant, config: dict):
"""Set up the DoorBird component."""
hass.data.setdefault(DOMAIN, {})
# Provide an endpoint for the doorstations to call to trigger events
hass.http.register_view(DoorBirdRequestView)
if DOMAIN in config and CONF_DEVICES in config[DOMAIN]:
for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVICES]):
if CONF_NAME not in doorstation_config:
doorstation_config[CONF_NAME] = f"DoorBird {index + 1}"
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=doorstation_config
)
)
def _reset_device_favorites_handler(event):
"""Handle clearing favorites on device."""
token = event.data.get("token")
if token is None:
return
doorstation = get_doorstation_by_token(hass, token)
if doorstation is None:
_LOGGER.error("Device not found for provided token")
return
# Clear webhooks
favorites = doorstation.device.favorites()
for favorite_type in favorites:
for favorite_id in favorites[favorite_type]:
doorstation.device.delete_favorite(favorite_type, favorite_id)
hass.bus.async_listen(RESET_DEVICE_FAVORITES, _reset_device_favorites_handler)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
":",
"hass",
".",
"data",
".",
"setdefault",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"# Provide an endpoint for the doorstations to call to trigger events",
"hass",
".",
"http",
".",
"register_view",
"(",
"DoorBirdRequestView",
")",
"if",
"DOMAIN",
"in",
"config",
"and",
"CONF_DEVICES",
"in",
"config",
"[",
"DOMAIN",
"]",
":",
"for",
"index",
",",
"doorstation_config",
"in",
"enumerate",
"(",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_DEVICES",
"]",
")",
":",
"if",
"CONF_NAME",
"not",
"in",
"doorstation_config",
":",
"doorstation_config",
"[",
"CONF_NAME",
"]",
"=",
"f\"DoorBird {index + 1}\"",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"doorstation_config",
")",
")",
"def",
"_reset_device_favorites_handler",
"(",
"event",
")",
":",
"\"\"\"Handle clearing favorites on device.\"\"\"",
"token",
"=",
"event",
".",
"data",
".",
"get",
"(",
"\"token\"",
")",
"if",
"token",
"is",
"None",
":",
"return",
"doorstation",
"=",
"get_doorstation_by_token",
"(",
"hass",
",",
"token",
")",
"if",
"doorstation",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Device not found for provided token\"",
")",
"return",
"# Clear webhooks",
"favorites",
"=",
"doorstation",
".",
"device",
".",
"favorites",
"(",
")",
"for",
"favorite_type",
"in",
"favorites",
":",
"for",
"favorite_id",
"in",
"favorites",
"[",
"favorite_type",
"]",
":",
"doorstation",
".",
"device",
".",
"delete_favorite",
"(",
"favorite_type",
",",
"favorite_id",
")",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"RESET_DEVICE_FAVORITES",
",",
"_reset_device_favorites_handler",
")",
"return",
"True"
] | [
69,
0
] | [
109,
15
] | python | en | ['en', 'nl', 'en'] | True |
async_setup_entry | (hass: HomeAssistant, entry: ConfigEntry) | Set up DoorBird from a config entry. | Set up DoorBird from a config entry. | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Set up DoorBird from a config entry."""
_async_import_options_from_data_if_missing(hass, entry)
doorstation_config = entry.data
doorstation_options = entry.options
config_entry_id = entry.entry_id
device_ip = doorstation_config[CONF_HOST]
username = doorstation_config[CONF_USERNAME]
password = doorstation_config[CONF_PASSWORD]
device = DoorBird(device_ip, username, password)
try:
status = await hass.async_add_executor_job(device.ready)
info = await hass.async_add_executor_job(device.info)
except urllib.error.HTTPError as err:
if err.code == HTTP_UNAUTHORIZED:
_LOGGER.error(
"Authorization rejected by DoorBird for %s@%s", username, device_ip
)
return False
raise ConfigEntryNotReady from err
except OSError as oserr:
_LOGGER.error("Failed to setup doorbird at %s: %s", device_ip, oserr)
raise ConfigEntryNotReady from oserr
if not status[0]:
_LOGGER.error(
"Could not connect to DoorBird as %s@%s: Error %s",
username,
device_ip,
str(status[1]),
)
raise ConfigEntryNotReady
token = doorstation_config.get(CONF_TOKEN, config_entry_id)
custom_url = doorstation_config.get(CONF_CUSTOM_URL)
name = doorstation_config.get(CONF_NAME)
events = doorstation_options.get(CONF_EVENTS, [])
doorstation = ConfiguredDoorBird(device, name, events, custom_url, token)
# Subscribe to doorbell or motion events
if not await _async_register_events(hass, doorstation):
raise ConfigEntryNotReady
hass.data[DOMAIN][config_entry_id] = {
DOOR_STATION: doorstation,
DOOR_STATION_INFO: info,
}
entry.add_update_listener(_update_listener)
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"_async_import_options_from_data_if_missing",
"(",
"hass",
",",
"entry",
")",
"doorstation_config",
"=",
"entry",
".",
"data",
"doorstation_options",
"=",
"entry",
".",
"options",
"config_entry_id",
"=",
"entry",
".",
"entry_id",
"device_ip",
"=",
"doorstation_config",
"[",
"CONF_HOST",
"]",
"username",
"=",
"doorstation_config",
"[",
"CONF_USERNAME",
"]",
"password",
"=",
"doorstation_config",
"[",
"CONF_PASSWORD",
"]",
"device",
"=",
"DoorBird",
"(",
"device_ip",
",",
"username",
",",
"password",
")",
"try",
":",
"status",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"device",
".",
"ready",
")",
"info",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"device",
".",
"info",
")",
"except",
"urllib",
".",
"error",
".",
"HTTPError",
"as",
"err",
":",
"if",
"err",
".",
"code",
"==",
"HTTP_UNAUTHORIZED",
":",
"_LOGGER",
".",
"error",
"(",
"\"Authorization rejected by DoorBird for %s@%s\"",
",",
"username",
",",
"device_ip",
")",
"return",
"False",
"raise",
"ConfigEntryNotReady",
"from",
"err",
"except",
"OSError",
"as",
"oserr",
":",
"_LOGGER",
".",
"error",
"(",
"\"Failed to setup doorbird at %s: %s\"",
",",
"device_ip",
",",
"oserr",
")",
"raise",
"ConfigEntryNotReady",
"from",
"oserr",
"if",
"not",
"status",
"[",
"0",
"]",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not connect to DoorBird as %s@%s: Error %s\"",
",",
"username",
",",
"device_ip",
",",
"str",
"(",
"status",
"[",
"1",
"]",
")",
",",
")",
"raise",
"ConfigEntryNotReady",
"token",
"=",
"doorstation_config",
".",
"get",
"(",
"CONF_TOKEN",
",",
"config_entry_id",
")",
"custom_url",
"=",
"doorstation_config",
".",
"get",
"(",
"CONF_CUSTOM_URL",
")",
"name",
"=",
"doorstation_config",
".",
"get",
"(",
"CONF_NAME",
")",
"events",
"=",
"doorstation_options",
".",
"get",
"(",
"CONF_EVENTS",
",",
"[",
"]",
")",
"doorstation",
"=",
"ConfiguredDoorBird",
"(",
"device",
",",
"name",
",",
"events",
",",
"custom_url",
",",
"token",
")",
"# Subscribe to doorbell or motion events",
"if",
"not",
"await",
"_async_register_events",
"(",
"hass",
",",
"doorstation",
")",
":",
"raise",
"ConfigEntryNotReady",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry_id",
"]",
"=",
"{",
"DOOR_STATION",
":",
"doorstation",
",",
"DOOR_STATION_INFO",
":",
"info",
",",
"}",
"entry",
".",
"add_update_listener",
"(",
"_update_listener",
")",
"for",
"component",
"in",
"PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"entry",
",",
"component",
")",
")",
"return",
"True"
] | [
112,
0
] | [
170,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass: HomeAssistant, entry: ConfigEntry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"unload_ok",
"=",
"all",
"(",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"entry",
",",
"component",
")",
"for",
"component",
"in",
"PLATFORMS",
"]",
")",
")",
"if",
"unload_ok",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"pop",
"(",
"entry",
".",
"entry_id",
")",
"return",
"unload_ok"
] | [
173,
0
] | [
187,
20
] | python | en | ['en', 'es', 'en'] | True |
_update_listener | (hass: HomeAssistant, entry: ConfigEntry) | Handle options update. | Handle options update. | async def _update_listener(hass: HomeAssistant, entry: ConfigEntry):
"""Handle options update."""
config_entry_id = entry.entry_id
doorstation = hass.data[DOMAIN][config_entry_id][DOOR_STATION]
doorstation.events = entry.options[CONF_EVENTS]
# Subscribe to doorbell or motion events
await _async_register_events(hass, doorstation) | [
"async",
"def",
"_update_listener",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
":",
"config_entry_id",
"=",
"entry",
".",
"entry_id",
"doorstation",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry_id",
"]",
"[",
"DOOR_STATION",
"]",
"doorstation",
".",
"events",
"=",
"entry",
".",
"options",
"[",
"CONF_EVENTS",
"]",
"# Subscribe to doorbell or motion events",
"await",
"_async_register_events",
"(",
"hass",
",",
"doorstation",
")"
] | [
207,
0
] | [
214,
51
] | python | en | ['en', 'nl', 'en'] | True |
ConfiguredDoorBird.__init__ | (self, device, name, events, custom_url, token) | Initialize configured device. | Initialize configured device. | def __init__(self, device, name, events, custom_url, token):
"""Initialize configured device."""
self._name = name
self._device = device
self._custom_url = custom_url
self.events = events
self.doorstation_events = [self._get_event_name(event) for event in self.events]
self._token = token | [
"def",
"__init__",
"(",
"self",
",",
"device",
",",
"name",
",",
"events",
",",
"custom_url",
",",
"token",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_device",
"=",
"device",
"self",
".",
"_custom_url",
"=",
"custom_url",
"self",
".",
"events",
"=",
"events",
"self",
".",
"doorstation_events",
"=",
"[",
"self",
".",
"_get_event_name",
"(",
"event",
")",
"for",
"event",
"in",
"self",
".",
"events",
"]",
"self",
".",
"_token",
"=",
"token"
] | [
233,
4
] | [
240,
27
] | python | en | ['en', 'en', 'en'] | True |
ConfiguredDoorBird.name | (self) | Get custom device name. | Get custom device name. | def name(self):
"""Get custom device name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
243,
4
] | [
245,
25
] | python | en | ['es', 'sl', 'en'] | False |
ConfiguredDoorBird.device | (self) | Get the configured device. | Get the configured device. | def device(self):
"""Get the configured device."""
return self._device | [
"def",
"device",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device"
] | [
248,
4
] | [
250,
27
] | python | en | ['en', 'en', 'en'] | True |
ConfiguredDoorBird.custom_url | (self) | Get custom url for device. | Get custom url for device. | def custom_url(self):
"""Get custom url for device."""
return self._custom_url | [
"def",
"custom_url",
"(",
"self",
")",
":",
"return",
"self",
".",
"_custom_url"
] | [
253,
4
] | [
255,
31
] | python | en | ['da', 'en', 'en'] | True |
ConfiguredDoorBird.token | (self) | Get token for device. | Get token for device. | def token(self):
"""Get token for device."""
return self._token | [
"def",
"token",
"(",
"self",
")",
":",
"return",
"self",
".",
"_token"
] | [
258,
4
] | [
260,
26
] | python | en | ['nl', 'en', 'en'] | True |
ConfiguredDoorBird.register_events | (self, hass) | Register events on device. | Register events on device. | def register_events(self, hass):
"""Register events on device."""
# Get the URL of this server
hass_url = get_url(hass)
# Override url if another is specified in the configuration
if self.custom_url is not None:
hass_url = self.custom_url
for event in self.doorstation_events:
self._register_event(hass_url, event)
_LOGGER.info("Successfully registered URL for %s on %s", event, self.name) | [
"def",
"register_events",
"(",
"self",
",",
"hass",
")",
":",
"# Get the URL of this server",
"hass_url",
"=",
"get_url",
"(",
"hass",
")",
"# Override url if another is specified in the configuration",
"if",
"self",
".",
"custom_url",
"is",
"not",
"None",
":",
"hass_url",
"=",
"self",
".",
"custom_url",
"for",
"event",
"in",
"self",
".",
"doorstation_events",
":",
"self",
".",
"_register_event",
"(",
"hass_url",
",",
"event",
")",
"_LOGGER",
".",
"info",
"(",
"\"Successfully registered URL for %s on %s\"",
",",
"event",
",",
"self",
".",
"name",
")"
] | [
262,
4
] | [
274,
86
] | python | en | ['en', 'en', 'en'] | True |
ConfiguredDoorBird.slug | (self) | Get device slug. | Get device slug. | def slug(self):
"""Get device slug."""
return slugify(self._name) | [
"def",
"slug",
"(",
"self",
")",
":",
"return",
"slugify",
"(",
"self",
".",
"_name",
")"
] | [
277,
4
] | [
279,
34
] | python | bs | ['fr', 'bs', 'en'] | False |
ConfiguredDoorBird._register_event | (self, hass_url, event) | Add a schedule entry in the device for a sensor. | Add a schedule entry in the device for a sensor. | def _register_event(self, hass_url, event):
"""Add a schedule entry in the device for a sensor."""
url = f"{hass_url}{API_URL}/{event}?token={self._token}"
# Register HA URL as webhook if not already, then get the ID
if not self.webhook_is_registered(url):
self.device.change_favorite("http", f"Home Assistant ({event})", url)
fav_id = self.get_webhook_id(url)
if not fav_id:
_LOGGER.warning(
'Could not find favorite for URL "%s". ' 'Skipping sensor "%s"',
url,
event,
)
return | [
"def",
"_register_event",
"(",
"self",
",",
"hass_url",
",",
"event",
")",
":",
"url",
"=",
"f\"{hass_url}{API_URL}/{event}?token={self._token}\"",
"# Register HA URL as webhook if not already, then get the ID",
"if",
"not",
"self",
".",
"webhook_is_registered",
"(",
"url",
")",
":",
"self",
".",
"device",
".",
"change_favorite",
"(",
"\"http\"",
",",
"f\"Home Assistant ({event})\"",
",",
"url",
")",
"fav_id",
"=",
"self",
".",
"get_webhook_id",
"(",
"url",
")",
"if",
"not",
"fav_id",
":",
"_LOGGER",
".",
"warning",
"(",
"'Could not find favorite for URL \"%s\". '",
"'Skipping sensor \"%s\"'",
",",
"url",
",",
"event",
",",
")",
"return"
] | [
284,
4
] | [
300,
18
] | python | en | ['en', 'en', 'en'] | True |
ConfiguredDoorBird.webhook_is_registered | (self, url, favs=None) | Return whether the given URL is registered as a device favorite. | Return whether the given URL is registered as a device favorite. | def webhook_is_registered(self, url, favs=None) -> bool:
"""Return whether the given URL is registered as a device favorite."""
favs = favs if favs else self.device.favorites()
if "http" not in favs:
return False
for fav in favs["http"].values():
if fav["value"] == url:
return True
return False | [
"def",
"webhook_is_registered",
"(",
"self",
",",
"url",
",",
"favs",
"=",
"None",
")",
"->",
"bool",
":",
"favs",
"=",
"favs",
"if",
"favs",
"else",
"self",
".",
"device",
".",
"favorites",
"(",
")",
"if",
"\"http\"",
"not",
"in",
"favs",
":",
"return",
"False",
"for",
"fav",
"in",
"favs",
"[",
"\"http\"",
"]",
".",
"values",
"(",
")",
":",
"if",
"fav",
"[",
"\"value\"",
"]",
"==",
"url",
":",
"return",
"True",
"return",
"False"
] | [
302,
4
] | [
313,
20
] | python | en | ['en', 'en', 'en'] | True |
ConfiguredDoorBird.get_webhook_id | (self, url, favs=None) |
Return the device favorite ID for the given URL.
The favorite must exist or there will be problems.
|
Return the device favorite ID for the given URL. | def get_webhook_id(self, url, favs=None) -> str or None:
"""
Return the device favorite ID for the given URL.
The favorite must exist or there will be problems.
"""
favs = favs if favs else self.device.favorites()
if "http" not in favs:
return None
for fav_id in favs["http"]:
if favs["http"][fav_id]["value"] == url:
return fav_id
return None | [
"def",
"get_webhook_id",
"(",
"self",
",",
"url",
",",
"favs",
"=",
"None",
")",
"->",
"str",
"or",
"None",
":",
"favs",
"=",
"favs",
"if",
"favs",
"else",
"self",
".",
"device",
".",
"favorites",
"(",
")",
"if",
"\"http\"",
"not",
"in",
"favs",
":",
"return",
"None",
"for",
"fav_id",
"in",
"favs",
"[",
"\"http\"",
"]",
":",
"if",
"favs",
"[",
"\"http\"",
"]",
"[",
"fav_id",
"]",
"[",
"\"value\"",
"]",
"==",
"url",
":",
"return",
"fav_id",
"return",
"None"
] | [
315,
4
] | [
330,
19
] | python | en | ['en', 'error', 'th'] | False |
ConfiguredDoorBird.get_event_data | (self) | Get data to pass along with HA event. | Get data to pass along with HA event. | def get_event_data(self):
"""Get data to pass along with HA event."""
return {
"timestamp": dt_util.utcnow().isoformat(),
"live_video_url": self._device.live_video_url,
"live_image_url": self._device.live_image_url,
"rtsp_live_video_url": self._device.rtsp_live_video_url,
"html5_viewer_url": self._device.html5_viewer_url,
} | [
"def",
"get_event_data",
"(",
"self",
")",
":",
"return",
"{",
"\"timestamp\"",
":",
"dt_util",
".",
"utcnow",
"(",
")",
".",
"isoformat",
"(",
")",
",",
"\"live_video_url\"",
":",
"self",
".",
"_device",
".",
"live_video_url",
",",
"\"live_image_url\"",
":",
"self",
".",
"_device",
".",
"live_image_url",
",",
"\"rtsp_live_video_url\"",
":",
"self",
".",
"_device",
".",
"rtsp_live_video_url",
",",
"\"html5_viewer_url\"",
":",
"self",
".",
"_device",
".",
"html5_viewer_url",
",",
"}"
] | [
332,
4
] | [
340,
9
] | python | en | ['en', 'en', 'en'] | True |
DoorBirdRequestView.get | (self, request, event) | Respond to requests from the device. | Respond to requests from the device. | async def get(self, request, event):
"""Respond to requests from the device."""
hass = request.app["hass"]
token = request.query.get("token")
device = get_doorstation_by_token(hass, token)
if device is None:
return web.Response(
status=HTTP_UNAUTHORIZED, text="Invalid token provided."
)
if device:
event_data = device.get_event_data()
else:
event_data = {}
if event == "clear":
hass.bus.async_fire(RESET_DEVICE_FAVORITES, {"token": token})
message = f"HTTP Favorites cleared for {device.slug}"
return web.Response(status=HTTP_OK, text=message)
event_data[ATTR_ENTITY_ID] = hass.data[DOMAIN][
DOOR_STATION_EVENT_ENTITY_IDS
].get(event)
hass.bus.async_fire(f"{DOMAIN}_{event}", event_data)
return web.Response(status=HTTP_OK, text="OK") | [
"async",
"def",
"get",
"(",
"self",
",",
"request",
",",
"event",
")",
":",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"token",
"=",
"request",
".",
"query",
".",
"get",
"(",
"\"token\"",
")",
"device",
"=",
"get_doorstation_by_token",
"(",
"hass",
",",
"token",
")",
"if",
"device",
"is",
"None",
":",
"return",
"web",
".",
"Response",
"(",
"status",
"=",
"HTTP_UNAUTHORIZED",
",",
"text",
"=",
"\"Invalid token provided.\"",
")",
"if",
"device",
":",
"event_data",
"=",
"device",
".",
"get_event_data",
"(",
")",
"else",
":",
"event_data",
"=",
"{",
"}",
"if",
"event",
"==",
"\"clear\"",
":",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"RESET_DEVICE_FAVORITES",
",",
"{",
"\"token\"",
":",
"token",
"}",
")",
"message",
"=",
"f\"HTTP Favorites cleared for {device.slug}\"",
"return",
"web",
".",
"Response",
"(",
"status",
"=",
"HTTP_OK",
",",
"text",
"=",
"message",
")",
"event_data",
"[",
"ATTR_ENTITY_ID",
"]",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"DOOR_STATION_EVENT_ENTITY_IDS",
"]",
".",
"get",
"(",
"event",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"f\"{DOMAIN}_{event}\"",
",",
"event_data",
")",
"return",
"web",
".",
"Response",
"(",
"status",
"=",
"HTTP_OK",
",",
"text",
"=",
"\"OK\"",
")"
] | [
351,
4
] | [
381,
54
] | python | en | ['en', 'en', 'en'] | True |
client | (hass, hass_ws_client) | Fixture that can interact with the config manager API. | Fixture that can interact with the config manager API. | def client(hass, hass_ws_client):
"""Fixture that can interact with the config manager API."""
hass.loop.run_until_complete(device_registry.async_setup(hass))
yield hass.loop.run_until_complete(hass_ws_client(hass)) | [
"def",
"client",
"(",
"hass",
",",
"hass_ws_client",
")",
":",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"device_registry",
".",
"async_setup",
"(",
"hass",
")",
")",
"yield",
"hass",
".",
"loop",
".",
"run_until_complete",
"(",
"hass_ws_client",
"(",
"hass",
")",
")"
] | [
9,
0
] | [
12,
60
] | python | en | ['en', 'en', 'en'] | True |
registry | (hass) | Return an empty, loaded, registry. | Return an empty, loaded, registry. | def registry(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass) | [
"def",
"registry",
"(",
"hass",
")",
":",
"return",
"mock_device_registry",
"(",
"hass",
")"
] | [
16,
0
] | [
18,
37
] | python | en | ['en', 'fy', 'en'] | True |
test_list_devices | (hass, client, registry) | Test list entries. | Test list entries. | async def test_list_devices(hass, client, registry):
"""Test list entries."""
registry.async_get_or_create(
config_entry_id="1234",
connections={("ethernet", "12:34:56:78:90:AB:CD:EF")},
identifiers={("bridgeid", "0123")},
manufacturer="manufacturer",
model="model",
)
registry.async_get_or_create(
config_entry_id="1234",
identifiers={("bridgeid", "1234")},
manufacturer="manufacturer",
model="model",
via_device=("bridgeid", "0123"),
entry_type="service",
)
await client.send_json({"id": 5, "type": "config/device_registry/list"})
msg = await client.receive_json()
dev1, dev2 = [entry.pop("id") for entry in msg["result"]]
assert msg["result"] == [
{
"config_entries": ["1234"],
"connections": [["ethernet", "12:34:56:78:90:AB:CD:EF"]],
"identifiers": [["bridgeid", "0123"]],
"manufacturer": "manufacturer",
"model": "model",
"name": None,
"sw_version": None,
"entry_type": None,
"via_device_id": None,
"area_id": None,
"name_by_user": None,
},
{
"config_entries": ["1234"],
"connections": [],
"identifiers": [["bridgeid", "1234"]],
"manufacturer": "manufacturer",
"model": "model",
"name": None,
"sw_version": None,
"entry_type": "service",
"via_device_id": dev1,
"area_id": None,
"name_by_user": None,
},
] | [
"async",
"def",
"test_list_devices",
"(",
"hass",
",",
"client",
",",
"registry",
")",
":",
"registry",
".",
"async_get_or_create",
"(",
"config_entry_id",
"=",
"\"1234\"",
",",
"connections",
"=",
"{",
"(",
"\"ethernet\"",
",",
"\"12:34:56:78:90:AB:CD:EF\"",
")",
"}",
",",
"identifiers",
"=",
"{",
"(",
"\"bridgeid\"",
",",
"\"0123\"",
")",
"}",
",",
"manufacturer",
"=",
"\"manufacturer\"",
",",
"model",
"=",
"\"model\"",
",",
")",
"registry",
".",
"async_get_or_create",
"(",
"config_entry_id",
"=",
"\"1234\"",
",",
"identifiers",
"=",
"{",
"(",
"\"bridgeid\"",
",",
"\"1234\"",
")",
"}",
",",
"manufacturer",
"=",
"\"manufacturer\"",
",",
"model",
"=",
"\"model\"",
",",
"via_device",
"=",
"(",
"\"bridgeid\"",
",",
"\"0123\"",
")",
",",
"entry_type",
"=",
"\"service\"",
",",
")",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"5",
",",
"\"type\"",
":",
"\"config/device_registry/list\"",
"}",
")",
"msg",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"dev1",
",",
"dev2",
"=",
"[",
"entry",
".",
"pop",
"(",
"\"id\"",
")",
"for",
"entry",
"in",
"msg",
"[",
"\"result\"",
"]",
"]",
"assert",
"msg",
"[",
"\"result\"",
"]",
"==",
"[",
"{",
"\"config_entries\"",
":",
"[",
"\"1234\"",
"]",
",",
"\"connections\"",
":",
"[",
"[",
"\"ethernet\"",
",",
"\"12:34:56:78:90:AB:CD:EF\"",
"]",
"]",
",",
"\"identifiers\"",
":",
"[",
"[",
"\"bridgeid\"",
",",
"\"0123\"",
"]",
"]",
",",
"\"manufacturer\"",
":",
"\"manufacturer\"",
",",
"\"model\"",
":",
"\"model\"",
",",
"\"name\"",
":",
"None",
",",
"\"sw_version\"",
":",
"None",
",",
"\"entry_type\"",
":",
"None",
",",
"\"via_device_id\"",
":",
"None",
",",
"\"area_id\"",
":",
"None",
",",
"\"name_by_user\"",
":",
"None",
",",
"}",
",",
"{",
"\"config_entries\"",
":",
"[",
"\"1234\"",
"]",
",",
"\"connections\"",
":",
"[",
"]",
",",
"\"identifiers\"",
":",
"[",
"[",
"\"bridgeid\"",
",",
"\"1234\"",
"]",
"]",
",",
"\"manufacturer\"",
":",
"\"manufacturer\"",
",",
"\"model\"",
":",
"\"model\"",
",",
"\"name\"",
":",
"None",
",",
"\"sw_version\"",
":",
"None",
",",
"\"entry_type\"",
":",
"\"service\"",
",",
"\"via_device_id\"",
":",
"dev1",
",",
"\"area_id\"",
":",
"None",
",",
"\"name_by_user\"",
":",
"None",
",",
"}",
",",
"]"
] | [
21,
0
] | [
71,
5
] | python | en | ['fr', 'gd', 'en'] | False |
test_update_device | (hass, client, registry) | Test update entry. | Test update entry. | async def test_update_device(hass, client, registry):
"""Test update entry."""
device = registry.async_get_or_create(
config_entry_id="1234",
connections={("ethernet", "12:34:56:78:90:AB:CD:EF")},
identifiers={("bridgeid", "0123")},
manufacturer="manufacturer",
model="model",
)
assert not device.area_id
assert not device.name_by_user
await client.send_json(
{
"id": 1,
"device_id": device.id,
"area_id": "12345A",
"name_by_user": "Test Friendly Name",
"type": "config/device_registry/update",
}
)
msg = await client.receive_json()
assert msg["result"]["id"] == device.id
assert msg["result"]["area_id"] == "12345A"
assert msg["result"]["name_by_user"] == "Test Friendly Name"
assert len(registry.devices) == 1 | [
"async",
"def",
"test_update_device",
"(",
"hass",
",",
"client",
",",
"registry",
")",
":",
"device",
"=",
"registry",
".",
"async_get_or_create",
"(",
"config_entry_id",
"=",
"\"1234\"",
",",
"connections",
"=",
"{",
"(",
"\"ethernet\"",
",",
"\"12:34:56:78:90:AB:CD:EF\"",
")",
"}",
",",
"identifiers",
"=",
"{",
"(",
"\"bridgeid\"",
",",
"\"0123\"",
")",
"}",
",",
"manufacturer",
"=",
"\"manufacturer\"",
",",
"model",
"=",
"\"model\"",
",",
")",
"assert",
"not",
"device",
".",
"area_id",
"assert",
"not",
"device",
".",
"name_by_user",
"await",
"client",
".",
"send_json",
"(",
"{",
"\"id\"",
":",
"1",
",",
"\"device_id\"",
":",
"device",
".",
"id",
",",
"\"area_id\"",
":",
"\"12345A\"",
",",
"\"name_by_user\"",
":",
"\"Test Friendly Name\"",
",",
"\"type\"",
":",
"\"config/device_registry/update\"",
",",
"}",
")",
"msg",
"=",
"await",
"client",
".",
"receive_json",
"(",
")",
"assert",
"msg",
"[",
"\"result\"",
"]",
"[",
"\"id\"",
"]",
"==",
"device",
".",
"id",
"assert",
"msg",
"[",
"\"result\"",
"]",
"[",
"\"area_id\"",
"]",
"==",
"\"12345A\"",
"assert",
"msg",
"[",
"\"result\"",
"]",
"[",
"\"name_by_user\"",
"]",
"==",
"\"Test Friendly Name\"",
"assert",
"len",
"(",
"registry",
".",
"devices",
")",
"==",
"1"
] | [
74,
0
] | [
102,
37
] | python | en | ['es', 'en', 'en'] | True |
test_events_http_api | (hass, hass_client) | Test the calendar demo view. | Test the calendar demo view. | async def test_events_http_api(hass, hass_client):
"""Test the calendar demo view."""
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})
await hass.async_block_till_done()
client = await hass_client()
response = await client.get("/api/calendars/calendar.calendar_2")
assert response.status == 400
start = dt_util.now()
end = start + timedelta(days=1)
response = await client.get(
"/api/calendars/calendar.calendar_1?start={}&end={}".format(
start.isoformat(), end.isoformat()
)
)
assert response.status == 200
events = await response.json()
assert events[0]["summary"] == "Future Event"
assert events[0]["title"] == "Future Event" | [
"async",
"def",
"test_events_http_api",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"calendar\"",
",",
"{",
"\"calendar\"",
":",
"{",
"\"platform\"",
":",
"\"demo\"",
"}",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"\"/api/calendars/calendar.calendar_2\"",
")",
"assert",
"response",
".",
"status",
"==",
"400",
"start",
"=",
"dt_util",
".",
"now",
"(",
")",
"end",
"=",
"start",
"+",
"timedelta",
"(",
"days",
"=",
"1",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"\"/api/calendars/calendar.calendar_1?start={}&end={}\"",
".",
"format",
"(",
"start",
".",
"isoformat",
"(",
")",
",",
"end",
".",
"isoformat",
"(",
")",
")",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"events",
"=",
"await",
"response",
".",
"json",
"(",
")",
"assert",
"events",
"[",
"0",
"]",
"[",
"\"summary\"",
"]",
"==",
"\"Future Event\"",
"assert",
"events",
"[",
"0",
"]",
"[",
"\"title\"",
"]",
"==",
"\"Future Event\""
] | [
7,
0
] | [
24,
47
] | python | en | ['en', 'pt', 'en'] | True |
test_calendars_http_api | (hass, hass_client) | Test the calendar demo view. | Test the calendar demo view. | async def test_calendars_http_api(hass, hass_client):
"""Test the calendar demo view."""
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})
await hass.async_block_till_done()
client = await hass_client()
response = await client.get("/api/calendars")
assert response.status == 200
data = await response.json()
assert data == [
{"entity_id": "calendar.calendar_1", "name": "Calendar 1"},
{"entity_id": "calendar.calendar_2", "name": "Calendar 2"},
] | [
"async",
"def",
"test_calendars_http_api",
"(",
"hass",
",",
"hass_client",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"calendar\"",
",",
"{",
"\"calendar\"",
":",
"{",
"\"platform\"",
":",
"\"demo\"",
"}",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"response",
"=",
"await",
"client",
".",
"get",
"(",
"\"/api/calendars\"",
")",
"assert",
"response",
".",
"status",
"==",
"200",
"data",
"=",
"await",
"response",
".",
"json",
"(",
")",
"assert",
"data",
"==",
"[",
"{",
"\"entity_id\"",
":",
"\"calendar.calendar_1\"",
",",
"\"name\"",
":",
"\"Calendar 1\"",
"}",
",",
"{",
"\"entity_id\"",
":",
"\"calendar.calendar_2\"",
",",
"\"name\"",
":",
"\"Calendar 2\"",
"}",
",",
"]"
] | [
27,
0
] | [
38,
5
] | python | en | ['en', 'pt', 'en'] | True |
NumatoModuleMock.__init__ | (self) | Initialize the numato_gpio module mockup class. | Initialize the numato_gpio module mockup class. | def __init__(self):
"""Initialize the numato_gpio module mockup class."""
self.devices = {} | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"devices",
"=",
"{",
"}"
] | [
9,
4
] | [
11,
25
] | python | en | ['en', 'ro', 'en'] | True |
NumatoModuleMock.discover | (self, _=None) | Mockup for the numato device discovery.
Ignore the device list argument, mock discovers /dev/ttyACM0.
| Mockup for the numato device discovery. | def discover(self, _=None):
"""Mockup for the numato device discovery.
Ignore the device list argument, mock discovers /dev/ttyACM0.
"""
self.devices[0] = NumatoModuleMock.NumatoDeviceMock("/dev/ttyACM0") | [
"def",
"discover",
"(",
"self",
",",
"_",
"=",
"None",
")",
":",
"self",
".",
"devices",
"[",
"0",
"]",
"=",
"NumatoModuleMock",
".",
"NumatoDeviceMock",
"(",
"\"/dev/ttyACM0\"",
")"
] | [
58,
4
] | [
63,
75
] | python | en | ['en', 'en', 'en'] | True |
NumatoModuleMock.cleanup | (self) | Mockup for the numato device cleanup. | Mockup for the numato device cleanup. | def cleanup(self):
"""Mockup for the numato device cleanup."""
self.devices.clear() | [
"def",
"cleanup",
"(",
"self",
")",
":",
"self",
".",
"devices",
".",
"clear",
"(",
")"
] | [
65,
4
] | [
67,
28
] | python | en | ['en', 'en', 'en'] | True |
filter_markdown | (md, **kwargs) |
Remove the link to the dev portal from the readme and replace it with
a link to the repo (since we're in the dev portal already).
|
Remove the link to the dev portal from the readme and replace it with
a link to the repo (since we're in the dev portal already).
| def filter_markdown(md, **kwargs):
"""
Remove the link to the dev portal from the readme and replace it with
a link to the repo (since we're in the dev portal already).
"""
REMOVE = """## [➡️ XRP API Reference Documentation](https://xrpl.org/xrp-api.html)
See the full reference documentation on the XRP Ledger Dev Portal."""
REPLACEMENT = """[[Source]](https://github.com/xpring-eng/xrp-api "Source")"""
return md.replace(REMOVE, REPLACEMENT) | [
"def",
"filter_markdown",
"(",
"md",
",",
"*",
"*",
"kwargs",
")",
":",
"REMOVE",
"=",
"\"\"\"## [➡️ XRP API Reference Documentation](https://xrpl.org/xrp-api.html)\n\nSee the full reference documentation on the XRP Ledger Dev Portal.\"\"\"",
"REPLACEMENT",
"=",
"\"\"\"[[Source]](https://github.com/xpring-eng/xrp-api \"Source\")\"\"\"",
"return",
"md",
".",
"replace",
"(",
"REMOVE",
",",
"REPLACEMENT",
")"
] | [
0,
0
] | [
12,
42
] | python | en | ['en', 'error', 'th'] | False |
async_setup_entry | (hass, entry, async_add_entities) | Set up the Tibber sensor. | Set up the Tibber sensor. | async def async_setup_entry(hass, entry, async_add_entities):
"""Set up the Tibber sensor."""
tibber_connection = hass.data.get(TIBBER_DOMAIN)
dev = []
for home in tibber_connection.get_homes(only_active=False):
try:
await home.update_info()
except asyncio.TimeoutError as err:
_LOGGER.error("Timeout connecting to Tibber home: %s ", err)
raise PlatformNotReady() from err
except aiohttp.ClientError as err:
_LOGGER.error("Error connecting to Tibber home: %s ", err)
raise PlatformNotReady() from err
if home.has_active_subscription:
dev.append(TibberSensorElPrice(home))
if home.has_real_time_consumption:
dev.append(TibberSensorRT(home))
async_add_entities(dev, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
",",
"async_add_entities",
")",
":",
"tibber_connection",
"=",
"hass",
".",
"data",
".",
"get",
"(",
"TIBBER_DOMAIN",
")",
"dev",
"=",
"[",
"]",
"for",
"home",
"in",
"tibber_connection",
".",
"get_homes",
"(",
"only_active",
"=",
"False",
")",
":",
"try",
":",
"await",
"home",
".",
"update_info",
"(",
")",
"except",
"asyncio",
".",
"TimeoutError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Timeout connecting to Tibber home: %s \"",
",",
"err",
")",
"raise",
"PlatformNotReady",
"(",
")",
"from",
"err",
"except",
"aiohttp",
".",
"ClientError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error connecting to Tibber home: %s \"",
",",
"err",
")",
"raise",
"PlatformNotReady",
"(",
")",
"from",
"err",
"if",
"home",
".",
"has_active_subscription",
":",
"dev",
".",
"append",
"(",
"TibberSensorElPrice",
"(",
"home",
")",
")",
"if",
"home",
".",
"has_real_time_consumption",
":",
"dev",
".",
"append",
"(",
"TibberSensorRT",
"(",
"home",
")",
")",
"async_add_entities",
"(",
"dev",
",",
"True",
")"
] | [
24,
0
] | [
44,
33
] | python | en | ['en', 'da', 'en'] | True |
TibberSensor.__init__ | (self, tibber_home) | Initialize the sensor. | Initialize the sensor. | def __init__(self, tibber_home):
"""Initialize the sensor."""
self._tibber_home = tibber_home
self._last_updated = None
self._state = None
self._is_available = False
self._device_state_attributes = {}
self._name = tibber_home.info["viewer"]["home"]["appNickname"]
if self._name is None:
self._name = tibber_home.info["viewer"]["home"]["address"].get(
"address1", ""
)
self._spread_load_constant = randrange(3600) | [
"def",
"__init__",
"(",
"self",
",",
"tibber_home",
")",
":",
"self",
".",
"_tibber_home",
"=",
"tibber_home",
"self",
".",
"_last_updated",
"=",
"None",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_is_available",
"=",
"False",
"self",
".",
"_device_state_attributes",
"=",
"{",
"}",
"self",
".",
"_name",
"=",
"tibber_home",
".",
"info",
"[",
"\"viewer\"",
"]",
"[",
"\"home\"",
"]",
"[",
"\"appNickname\"",
"]",
"if",
"self",
".",
"_name",
"is",
"None",
":",
"self",
".",
"_name",
"=",
"tibber_home",
".",
"info",
"[",
"\"viewer\"",
"]",
"[",
"\"home\"",
"]",
"[",
"\"address\"",
"]",
".",
"get",
"(",
"\"address1\"",
",",
"\"\"",
")",
"self",
".",
"_spread_load_constant",
"=",
"randrange",
"(",
"3600",
")"
] | [
50,
4
] | [
62,
52
] | python | en | ['en', 'en', 'en'] | True |
TibberSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return self._device_state_attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_state_attributes"
] | [
65,
4
] | [
67,
44
] | python | en | ['en', 'en', 'en'] | True |
TibberSensor.model | (self) | Return the model of the sensor. | Return the model of the sensor. | def model(self):
"""Return the model of the sensor."""
return None | [
"def",
"model",
"(",
"self",
")",
":",
"return",
"None"
] | [
70,
4
] | [
72,
19
] | python | en | ['en', 'no', 'en'] | True |
TibberSensor.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
75,
4
] | [
77,
26
] | python | en | ['en', 'en', 'en'] | True |
TibberSensor.device_id | (self) | Return the ID of the physical device this sensor is part of. | Return the ID of the physical device this sensor is part of. | def device_id(self):
"""Return the ID of the physical device this sensor is part of."""
home = self._tibber_home.info["viewer"]["home"]
return home["meteringPointData"]["consumptionEan"] | [
"def",
"device_id",
"(",
"self",
")",
":",
"home",
"=",
"self",
".",
"_tibber_home",
".",
"info",
"[",
"\"viewer\"",
"]",
"[",
"\"home\"",
"]",
"return",
"home",
"[",
"\"meteringPointData\"",
"]",
"[",
"\"consumptionEan\"",
"]"
] | [
80,
4
] | [
83,
58
] | python | en | ['en', 'en', 'en'] | True |
TibberSensor.device_info | (self) | Return the device_info of the device. | Return the device_info of the device. | def device_info(self):
"""Return the device_info of the device."""
device_info = {
"identifiers": {(TIBBER_DOMAIN, self.device_id)},
"name": self.name,
"manufacturer": MANUFACTURER,
}
if self.model is not None:
device_info["model"] = self.model
return device_info | [
"def",
"device_info",
"(",
"self",
")",
":",
"device_info",
"=",
"{",
"\"identifiers\"",
":",
"{",
"(",
"TIBBER_DOMAIN",
",",
"self",
".",
"device_id",
")",
"}",
",",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"manufacturer\"",
":",
"MANUFACTURER",
",",
"}",
"if",
"self",
".",
"model",
"is",
"not",
"None",
":",
"device_info",
"[",
"\"model\"",
"]",
"=",
"self",
".",
"model",
"return",
"device_info"
] | [
86,
4
] | [
95,
26
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorElPrice.async_update | (self) | Get the latest data and updates the states. | Get the latest data and updates the states. | async def async_update(self):
"""Get the latest data and updates the states."""
now = dt_util.now()
if (
self._tibber_home.current_price_total
and self._last_updated
and self._last_updated.hour == now.hour
and self._tibber_home.last_data_timestamp
):
return
if (
not self._tibber_home.last_data_timestamp
or (self._tibber_home.last_data_timestamp - now).total_seconds()
< 5 * 3600 + self._spread_load_constant
or not self._is_available
):
_LOGGER.debug("Asking for new data")
await self._fetch_data()
res = self._tibber_home.current_price_data()
self._state, price_level, self._last_updated = res
self._device_state_attributes["price_level"] = price_level
attrs = self._tibber_home.current_attributes()
self._device_state_attributes.update(attrs)
self._is_available = self._state is not None | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"now",
"=",
"dt_util",
".",
"now",
"(",
")",
"if",
"(",
"self",
".",
"_tibber_home",
".",
"current_price_total",
"and",
"self",
".",
"_last_updated",
"and",
"self",
".",
"_last_updated",
".",
"hour",
"==",
"now",
".",
"hour",
"and",
"self",
".",
"_tibber_home",
".",
"last_data_timestamp",
")",
":",
"return",
"if",
"(",
"not",
"self",
".",
"_tibber_home",
".",
"last_data_timestamp",
"or",
"(",
"self",
".",
"_tibber_home",
".",
"last_data_timestamp",
"-",
"now",
")",
".",
"total_seconds",
"(",
")",
"<",
"5",
"*",
"3600",
"+",
"self",
".",
"_spread_load_constant",
"or",
"not",
"self",
".",
"_is_available",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Asking for new data\"",
")",
"await",
"self",
".",
"_fetch_data",
"(",
")",
"res",
"=",
"self",
".",
"_tibber_home",
".",
"current_price_data",
"(",
")",
"self",
".",
"_state",
",",
"price_level",
",",
"self",
".",
"_last_updated",
"=",
"res",
"self",
".",
"_device_state_attributes",
"[",
"\"price_level\"",
"]",
"=",
"price_level",
"attrs",
"=",
"self",
".",
"_tibber_home",
".",
"current_attributes",
"(",
")",
"self",
".",
"_device_state_attributes",
".",
"update",
"(",
"attrs",
")",
"self",
".",
"_is_available",
"=",
"self",
".",
"_state",
"is",
"not",
"None"
] | [
101,
4
] | [
127,
52
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorElPrice.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self):
"""Return True if entity is available."""
return self._is_available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_is_available"
] | [
130,
4
] | [
132,
33
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorElPrice.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return f"Electricity price {self._name}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"Electricity price {self._name}\""
] | [
135,
4
] | [
137,
48
] | python | en | ['en', 'mi', 'en'] | True |
TibberSensorElPrice.model | (self) | Return the model of the sensor. | Return the model of the sensor. | def model(self):
"""Return the model of the sensor."""
return "Price Sensor" | [
"def",
"model",
"(",
"self",
")",
":",
"return",
"\"Price Sensor\""
] | [
140,
4
] | [
142,
29
] | python | en | ['en', 'no', 'en'] | True |
TibberSensorElPrice.icon | (self) | Return the icon to use in the frontend. | Return the icon to use in the frontend. | def icon(self):
"""Return the icon to use in the frontend."""
return ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"ICON"
] | [
145,
4
] | [
147,
19
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorElPrice.unit_of_measurement | (self) | Return the unit of measurement of this entity. | Return the unit of measurement of this entity. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity."""
return self._tibber_home.price_unit | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tibber_home",
".",
"price_unit"
] | [
150,
4
] | [
152,
43
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorElPrice.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self):
"""Return a unique ID."""
return self.device_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"device_id"
] | [
155,
4
] | [
157,
29
] | python | ca | ['fr', 'ca', 'en'] | False |
TibberSensorRT.async_added_to_hass | (self) | Start listen for real time data. | Start listen for real time data. | async def async_added_to_hass(self):
"""Start listen for real time data."""
await self._tibber_home.rt_subscribe(self.hass.loop, self._async_callback) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"await",
"self",
".",
"_tibber_home",
".",
"rt_subscribe",
"(",
"self",
".",
"hass",
".",
"loop",
",",
"self",
".",
"_async_callback",
")"
] | [
179,
4
] | [
181,
82
] | python | en | ['en', 'no', 'en'] | True |
TibberSensorRT._async_callback | (self, payload) | Handle received data. | Handle received data. | async def _async_callback(self, payload):
"""Handle received data."""
errors = payload.get("errors")
if errors:
_LOGGER.error(errors[0])
return
data = payload.get("data")
if data is None:
return
live_measurement = data.get("liveMeasurement")
if live_measurement is None:
return
self._state = live_measurement.pop("power", None)
for key, value in live_measurement.items():
if value is None:
continue
self._device_state_attributes[key] = value
self.async_write_ha_state() | [
"async",
"def",
"_async_callback",
"(",
"self",
",",
"payload",
")",
":",
"errors",
"=",
"payload",
".",
"get",
"(",
"\"errors\"",
")",
"if",
"errors",
":",
"_LOGGER",
".",
"error",
"(",
"errors",
"[",
"0",
"]",
")",
"return",
"data",
"=",
"payload",
".",
"get",
"(",
"\"data\"",
")",
"if",
"data",
"is",
"None",
":",
"return",
"live_measurement",
"=",
"data",
".",
"get",
"(",
"\"liveMeasurement\"",
")",
"if",
"live_measurement",
"is",
"None",
":",
"return",
"self",
".",
"_state",
"=",
"live_measurement",
".",
"pop",
"(",
"\"power\"",
",",
"None",
")",
"for",
"key",
",",
"value",
"in",
"live_measurement",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"continue",
"self",
".",
"_device_state_attributes",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"async_write_ha_state",
"(",
")"
] | [
183,
4
] | [
201,
35
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorRT.available | (self) | Return True if entity is available. | Return True if entity is available. | def available(self):
"""Return True if entity is available."""
return self._tibber_home.rt_subscription_running | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tibber_home",
".",
"rt_subscription_running"
] | [
204,
4
] | [
206,
56
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorRT.model | (self) | Return the model of the sensor. | Return the model of the sensor. | def model(self):
"""Return the model of the sensor."""
return "Tibber Pulse" | [
"def",
"model",
"(",
"self",
")",
":",
"return",
"\"Tibber Pulse\""
] | [
209,
4
] | [
211,
29
] | python | en | ['en', 'no', 'en'] | True |
TibberSensorRT.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return f"Real time consumption {self._name}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"Real time consumption {self._name}\""
] | [
214,
4
] | [
216,
52
] | python | en | ['en', 'mi', 'en'] | True |
TibberSensorRT.should_poll | (self) | Return the polling state. | Return the polling state. | def should_poll(self):
"""Return the polling state."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
219,
4
] | [
221,
20
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorRT.unit_of_measurement | (self) | Return the unit of measurement of this entity. | Return the unit of measurement of this entity. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity."""
return POWER_WATT | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"POWER_WATT"
] | [
224,
4
] | [
226,
25
] | python | en | ['en', 'en', 'en'] | True |
TibberSensorRT.unique_id | (self) | Return a unique ID. | Return a unique ID. | def unique_id(self):
"""Return a unique ID."""
return f"{self.device_id}_rt_consumption" | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"f\"{self.device_id}_rt_consumption\""
] | [
229,
4
] | [
231,
49
] | python | ca | ['fr', 'ca', 'en'] | False |
TibberSensorRT.device_class | (self) | Return the device class of the sensor. | Return the device class of the sensor. | def device_class(self):
"""Return the device class of the sensor."""
return DEVICE_CLASS_POWER | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"DEVICE_CLASS_POWER"
] | [
234,
4
] | [
236,
33
] | python | en | ['en', 'en', 'en'] | True |
test_unload_entry | (hass, cfupdate) | Test successful unload of entry. | Test successful unload of entry. | async def test_unload_entry(hass, cfupdate):
"""Test successful unload of entry."""
entry = await init_integration(hass)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert entry.state == ENTRY_STATE_LOADED
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state == ENTRY_STATE_NOT_LOADED
assert not hass.data.get(DOMAIN) | [
"async",
"def",
"test_unload_entry",
"(",
"hass",
",",
"cfupdate",
")",
":",
"entry",
"=",
"await",
"init_integration",
"(",
"hass",
")",
"assert",
"len",
"(",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
")",
"==",
"1",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_LOADED",
"assert",
"await",
"hass",
".",
"config_entries",
".",
"async_unload",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_NOT_LOADED",
"assert",
"not",
"hass",
".",
"data",
".",
"get",
"(",
"DOMAIN",
")"
] | [
15,
0
] | [
26,
36
] | python | en | ['en', 'en', 'en'] | True |
test_async_setup_raises_entry_not_ready | (hass, cfupdate) | Test that it throws ConfigEntryNotReady when exception occurs during setup. | Test that it throws ConfigEntryNotReady when exception occurs during setup. | async def test_async_setup_raises_entry_not_ready(hass, cfupdate):
"""Test that it throws ConfigEntryNotReady when exception occurs during setup."""
instance = cfupdate.return_value
entry = MockConfigEntry(domain=DOMAIN, data=ENTRY_CONFIG)
entry.add_to_hass(hass)
instance.get_zone_id.side_effect = CloudflareConnectionException()
await hass.config_entries.async_setup(entry.entry_id)
assert entry.state == ENTRY_STATE_SETUP_RETRY | [
"async",
"def",
"test_async_setup_raises_entry_not_ready",
"(",
"hass",
",",
"cfupdate",
")",
":",
"instance",
"=",
"cfupdate",
".",
"return_value",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"data",
"=",
"ENTRY_CONFIG",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"instance",
".",
"get_zone_id",
".",
"side_effect",
"=",
"CloudflareConnectionException",
"(",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_SETUP_RETRY"
] | [
29,
0
] | [
39,
49
] | python | en | ['en', 'en', 'en'] | True |
test_integration_services | (hass, cfupdate) | Test integration services. | Test integration services. | async def test_integration_services(hass, cfupdate):
"""Test integration services."""
instance = cfupdate.return_value
entry = await init_integration(hass)
assert entry.state == ENTRY_STATE_LOADED
await hass.services.async_call(
DOMAIN,
SERVICE_UPDATE_RECORDS,
{},
blocking=True,
)
await hass.async_block_till_done()
instance.update_records.assert_called_once() | [
"async",
"def",
"test_integration_services",
"(",
"hass",
",",
"cfupdate",
")",
":",
"instance",
"=",
"cfupdate",
".",
"return_value",
"entry",
"=",
"await",
"init_integration",
"(",
"hass",
")",
"assert",
"entry",
".",
"state",
"==",
"ENTRY_STATE_LOADED",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"DOMAIN",
",",
"SERVICE_UPDATE_RECORDS",
",",
"{",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"instance",
".",
"update_records",
".",
"assert_called_once",
"(",
")"
] | [
42,
0
] | [
57,
48
] | python | en | ['en', 'da', 'en'] | True |
mock_login | () | Mock pymelcloud login. | Mock pymelcloud login. | def mock_login():
"""Mock pymelcloud login."""
with patch(
"homeassistant.components.melcloud.config_flow.pymelcloud.login"
) as mock:
mock.return_value = "test-token"
yield mock | [
"def",
"mock_login",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.melcloud.config_flow.pymelcloud.login\"",
")",
"as",
"mock",
":",
"mock",
".",
"return_value",
"=",
"\"test-token\"",
"yield",
"mock"
] | [
16,
0
] | [
22,
18
] | python | en | ['nl', 'ht', 'en'] | False |
mock_get_devices | () | Mock pymelcloud get_devices. | Mock pymelcloud get_devices. | def mock_get_devices():
"""Mock pymelcloud get_devices."""
with patch(
"homeassistant.components.melcloud.config_flow.pymelcloud.get_devices"
) as mock:
mock.return_value = {
pymelcloud.DEVICE_TYPE_ATA: [],
pymelcloud.DEVICE_TYPE_ATW: [],
}
yield mock | [
"def",
"mock_get_devices",
"(",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.melcloud.config_flow.pymelcloud.get_devices\"",
")",
"as",
"mock",
":",
"mock",
".",
"return_value",
"=",
"{",
"pymelcloud",
".",
"DEVICE_TYPE_ATA",
":",
"[",
"]",
",",
"pymelcloud",
".",
"DEVICE_TYPE_ATW",
":",
"[",
"]",
",",
"}",
"yield",
"mock"
] | [
26,
0
] | [
35,
18
] | python | en | ['nl', 'en', 'en'] | True |
mock_request_info | () | Mock RequestInfo to create ClientResponseErrors. | Mock RequestInfo to create ClientResponseErrors. | def mock_request_info():
"""Mock RequestInfo to create ClientResponseErrors."""
with patch("aiohttp.RequestInfo") as mock_ri:
mock_ri.return_value.real_url.return_value = ""
yield mock_ri | [
"def",
"mock_request_info",
"(",
")",
":",
"with",
"patch",
"(",
"\"aiohttp.RequestInfo\"",
")",
"as",
"mock_ri",
":",
"mock_ri",
".",
"return_value",
".",
"real_url",
".",
"return_value",
"=",
"\"\"",
"yield",
"mock_ri"
] | [
39,
0
] | [
43,
21
] | python | en | ['en', 'sr', 'en'] | True |
test_form | (hass, mock_login, mock_get_devices) | Test we get the form. | Test we get the form. | async def test_form(hass, mock_login, mock_get_devices):
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] is None
with patch(
"homeassistant.components.melcloud.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.melcloud.async_setup_entry", return_value=True
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"username": "[email protected]", "password": "test-password"},
)
await hass.async_block_till_done()
assert result2["type"] == "create_entry"
assert result2["title"] == "[email protected]"
assert result2["data"] == {
"username": "[email protected]",
"token": "test-token",
}
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_form",
"(",
"hass",
",",
"mock_login",
",",
"mock_get_devices",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"is",
"None",
"with",
"patch",
"(",
"\"homeassistant.components.melcloud.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.melcloud.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup_entry",
":",
"result2",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"{",
"\"username\"",
":",
"\"[email protected]\"",
",",
"\"password\"",
":",
"\"test-password\"",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result2",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result2",
"[",
"\"title\"",
"]",
"==",
"\"[email protected]\"",
"assert",
"result2",
"[",
"\"data\"",
"]",
"==",
"{",
"\"username\"",
":",
"\"[email protected]\"",
",",
"\"token\"",
":",
"\"test-token\"",
",",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
46,
0
] | [
72,
48
] | python | en | ['en', 'en', 'en'] | True |
test_form_errors | (hass, mock_login, mock_get_devices, error, reason) | Test we handle cannot connect error. | Test we handle cannot connect error. | async def test_form_errors(hass, mock_login, mock_get_devices, error, reason):
"""Test we handle cannot connect error."""
mock_login.side_effect = error
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={"username": "[email protected]", "password": "test-password"},
)
assert len(mock_login.mock_calls) == 1
assert result["type"] == "abort"
assert result["reason"] == reason | [
"async",
"def",
"test_form_errors",
"(",
"hass",
",",
"mock_login",
",",
"mock_get_devices",
",",
"error",
",",
"reason",
")",
":",
"mock_login",
".",
"side_effect",
"=",
"error",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"\"username\"",
":",
"\"[email protected]\"",
",",
"\"password\"",
":",
"\"test-password\"",
"}",
",",
")",
"assert",
"len",
"(",
"mock_login",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"abort\"",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"reason"
] | [
79,
0
] | [
91,
37
] | python | en | ['en', 'en', 'en'] | True |
test_form_response_errors | (
hass, mock_login, mock_get_devices, mock_request_info, error, message
) | Test we handle response errors. | Test we handle response errors. | async def test_form_response_errors(
hass, mock_login, mock_get_devices, mock_request_info, error, message
):
"""Test we handle response errors."""
mock_login.side_effect = ClientResponseError(mock_request_info(), (), status=error)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={"username": "[email protected]", "password": "test-password"},
)
assert result["type"] == "abort"
assert result["reason"] == message | [
"async",
"def",
"test_form_response_errors",
"(",
"hass",
",",
"mock_login",
",",
"mock_get_devices",
",",
"mock_request_info",
",",
"error",
",",
"message",
")",
":",
"mock_login",
".",
"side_effect",
"=",
"ClientResponseError",
"(",
"mock_request_info",
"(",
")",
",",
"(",
")",
",",
"status",
"=",
"error",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"\"username\"",
":",
"\"[email protected]\"",
",",
"\"password\"",
":",
"\"test-password\"",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"abort\"",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"message"
] | [
102,
0
] | [
115,
38
] | python | de | ['de', 'sr', 'en'] | False |
test_import_with_token | (hass, mock_login, mock_get_devices) | Test successful import. | Test successful import. | async def test_import_with_token(hass, mock_login, mock_get_devices):
"""Test successful import."""
with patch(
"homeassistant.components.melcloud.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.melcloud.async_setup_entry", return_value=True
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={"username": "[email protected]", "token": "test-token"},
)
await hass.async_block_till_done()
assert result["type"] == "create_entry"
assert result["title"] == "[email protected]"
assert result["data"] == {
"username": "[email protected]",
"token": "test-token",
}
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_import_with_token",
"(",
"hass",
",",
"mock_login",
",",
"mock_get_devices",
")",
":",
"with",
"patch",
"(",
"\"homeassistant.components.melcloud.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.melcloud.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup_entry",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"{",
"\"username\"",
":",
"\"[email protected]\"",
",",
"\"token\"",
":",
"\"test-token\"",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"[email protected]\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"\"username\"",
":",
"\"[email protected]\"",
",",
"\"token\"",
":",
"\"test-token\"",
",",
"}",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"1",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
118,
0
] | [
139,
48
] | python | en | ['en', 'la', 'en'] | True |
test_token_refresh | (hass, mock_login, mock_get_devices) | Re-configuration with existing username should refresh token. | Re-configuration with existing username should refresh token. | async def test_token_refresh(hass, mock_login, mock_get_devices):
"""Re-configuration with existing username should refresh token."""
mock_entry = MockConfigEntry(
domain=DOMAIN,
data={"username": "[email protected]", "token": "test-original-token"},
unique_id="[email protected]",
)
mock_entry.add_to_hass(hass)
with patch(
"homeassistant.components.melcloud.async_setup", return_value=True
) as mock_setup, patch(
"homeassistant.components.melcloud.async_setup_entry", return_value=True
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={
"username": "[email protected]",
"password": "test-password",
},
)
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 0
assert len(mock_setup_entry.mock_calls) == 0
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
entry = entries[0]
assert entry.data["username"] == "[email protected]"
assert entry.data["token"] == "test-token" | [
"async",
"def",
"test_token_refresh",
"(",
"hass",
",",
"mock_login",
",",
"mock_get_devices",
")",
":",
"mock_entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"data",
"=",
"{",
"\"username\"",
":",
"\"[email protected]\"",
",",
"\"token\"",
":",
"\"test-original-token\"",
"}",
",",
"unique_id",
"=",
"\"[email protected]\"",
",",
")",
"mock_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"with",
"patch",
"(",
"\"homeassistant.components.melcloud.async_setup\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup",
",",
"patch",
"(",
"\"homeassistant.components.melcloud.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
"as",
"mock_setup_entry",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"\"username\"",
":",
"\"[email protected]\"",
",",
"\"password\"",
":",
"\"test-password\"",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"abort\"",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\"",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"mock_setup",
".",
"mock_calls",
")",
"==",
"0",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"0",
"entries",
"=",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
"assert",
"len",
"(",
"entries",
")",
"==",
"1",
"entry",
"=",
"entries",
"[",
"0",
"]",
"assert",
"entry",
".",
"data",
"[",
"\"username\"",
"]",
"==",
"\"[email protected]\"",
"assert",
"entry",
".",
"data",
"[",
"\"token\"",
"]",
"==",
"\"test-token\""
] | [
142,
0
] | [
176,
46
] | python | en | ['en', 'en', 'en'] | True |
auth_provider_from_config | (
hass: HomeAssistant, store: AuthStore, config: Dict[str, Any]
) | Initialize an auth provider from a config. | Initialize an auth provider from a config. | async def auth_provider_from_config(
hass: HomeAssistant, store: AuthStore, config: Dict[str, Any]
) -> AuthProvider:
"""Initialize an auth provider from a config."""
provider_name = config[CONF_TYPE]
module = await load_auth_provider_module(hass, provider_name)
try:
config = module.CONFIG_SCHEMA(config) # type: ignore
except vol.Invalid as err:
_LOGGER.error(
"Invalid configuration for auth provider %s: %s",
provider_name,
humanize_error(config, err),
)
raise
return AUTH_PROVIDERS[provider_name](hass, store, config) | [
"async",
"def",
"auth_provider_from_config",
"(",
"hass",
":",
"HomeAssistant",
",",
"store",
":",
"AuthStore",
",",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"AuthProvider",
":",
"provider_name",
"=",
"config",
"[",
"CONF_TYPE",
"]",
"module",
"=",
"await",
"load_auth_provider_module",
"(",
"hass",
",",
"provider_name",
")",
"try",
":",
"config",
"=",
"module",
".",
"CONFIG_SCHEMA",
"(",
"config",
")",
"# type: ignore",
"except",
"vol",
".",
"Invalid",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Invalid configuration for auth provider %s: %s\"",
",",
"provider_name",
",",
"humanize_error",
"(",
"config",
",",
"err",
")",
",",
")",
"raise",
"return",
"AUTH_PROVIDERS",
"[",
"provider_name",
"]",
"(",
"hass",
",",
"store",
",",
"config",
")"
] | [
120,
0
] | [
137,
61
] | python | en | ['en', 'en', 'en'] | True |
load_auth_provider_module | (
hass: HomeAssistant, provider: str
) | Load an auth provider. | Load an auth provider. | async def load_auth_provider_module(
hass: HomeAssistant, provider: str
) -> types.ModuleType:
"""Load an auth provider."""
try:
module = importlib.import_module(f"homeassistant.auth.providers.{provider}")
except ImportError as err:
_LOGGER.error("Unable to load auth provider %s: %s", provider, err)
raise HomeAssistantError(
f"Unable to load auth provider {provider}: {err}"
) from err
if hass.config.skip_pip or not hasattr(module, "REQUIREMENTS"):
return module
processed = hass.data.get(DATA_REQS)
if processed is None:
processed = hass.data[DATA_REQS] = set()
elif provider in processed:
return module
# https://github.com/python/mypy/issues/1424
reqs = module.REQUIREMENTS # type: ignore
await requirements.async_process_requirements(
hass, f"auth provider {provider}", reqs
)
processed.add(provider)
return module | [
"async",
"def",
"load_auth_provider_module",
"(",
"hass",
":",
"HomeAssistant",
",",
"provider",
":",
"str",
")",
"->",
"types",
".",
"ModuleType",
":",
"try",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"f\"homeassistant.auth.providers.{provider}\"",
")",
"except",
"ImportError",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to load auth provider %s: %s\"",
",",
"provider",
",",
"err",
")",
"raise",
"HomeAssistantError",
"(",
"f\"Unable to load auth provider {provider}: {err}\"",
")",
"from",
"err",
"if",
"hass",
".",
"config",
".",
"skip_pip",
"or",
"not",
"hasattr",
"(",
"module",
",",
"\"REQUIREMENTS\"",
")",
":",
"return",
"module",
"processed",
"=",
"hass",
".",
"data",
".",
"get",
"(",
"DATA_REQS",
")",
"if",
"processed",
"is",
"None",
":",
"processed",
"=",
"hass",
".",
"data",
"[",
"DATA_REQS",
"]",
"=",
"set",
"(",
")",
"elif",
"provider",
"in",
"processed",
":",
"return",
"module",
"# https://github.com/python/mypy/issues/1424",
"reqs",
"=",
"module",
".",
"REQUIREMENTS",
"# type: ignore",
"await",
"requirements",
".",
"async_process_requirements",
"(",
"hass",
",",
"f\"auth provider {provider}\"",
",",
"reqs",
")",
"processed",
".",
"add",
"(",
"provider",
")",
"return",
"module"
] | [
140,
0
] | [
169,
17
] | python | en | ['de', 'en', 'en'] | True |
AuthProvider.__init__ | (
self, hass: HomeAssistant, store: AuthStore, config: Dict[str, Any]
) | Initialize an auth provider. | Initialize an auth provider. | def __init__(
self, hass: HomeAssistant, store: AuthStore, config: Dict[str, Any]
) -> None:
"""Initialize an auth provider."""
self.hass = hass
self.store = store
self.config = config | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistant",
",",
"store",
":",
"AuthStore",
",",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"store",
"=",
"store",
"self",
".",
"config",
"=",
"config"
] | [
41,
4
] | [
47,
28
] | python | en | ['de', 'en', 'en'] | True |
AuthProvider.id | (self) | Return id of the auth provider.
Optional, can be None.
| Return id of the auth provider. | def id(self) -> Optional[str]:
"""Return id of the auth provider.
Optional, can be None.
"""
return self.config.get(CONF_ID) | [
"def",
"id",
"(",
"self",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"return",
"self",
".",
"config",
".",
"get",
"(",
"CONF_ID",
")"
] | [
50,
4
] | [
55,
39
] | python | en | ['en', 'en', 'en'] | True |
AuthProvider.type | (self) | Return type of the provider. | Return type of the provider. | def type(self) -> str:
"""Return type of the provider."""
return self.config[CONF_TYPE] | [
"def",
"type",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"config",
"[",
"CONF_TYPE",
"]"
] | [
58,
4
] | [
60,
37
] | python | en | ['en', 'no', 'en'] | True |
AuthProvider.name | (self) | Return the name of the auth provider. | Return the name of the auth provider. | def name(self) -> str:
"""Return the name of the auth provider."""
return self.config.get(CONF_NAME, self.DEFAULT_TITLE) | [
"def",
"name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"config",
".",
"get",
"(",
"CONF_NAME",
",",
"self",
".",
"DEFAULT_TITLE",
")"
] | [
63,
4
] | [
65,
61
] | python | en | ['en', 'en', 'en'] | True |
AuthProvider.support_mfa | (self) | Return whether multi-factor auth supported by the auth provider. | Return whether multi-factor auth supported by the auth provider. | def support_mfa(self) -> bool:
"""Return whether multi-factor auth supported by the auth provider."""
return True | [
"def",
"support_mfa",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"True"
] | [
68,
4
] | [
70,
19
] | python | en | ['en', 'en', 'en'] | True |
AuthProvider.async_credentials | (self) | Return all credentials of this provider. | Return all credentials of this provider. | async def async_credentials(self) -> List[Credentials]:
"""Return all credentials of this provider."""
users = await self.store.async_get_users()
return [
credentials
for user in users
for credentials in user.credentials
if (
credentials.auth_provider_type == self.type
and credentials.auth_provider_id == self.id
)
] | [
"async",
"def",
"async_credentials",
"(",
"self",
")",
"->",
"List",
"[",
"Credentials",
"]",
":",
"users",
"=",
"await",
"self",
".",
"store",
".",
"async_get_users",
"(",
")",
"return",
"[",
"credentials",
"for",
"user",
"in",
"users",
"for",
"credentials",
"in",
"user",
".",
"credentials",
"if",
"(",
"credentials",
".",
"auth_provider_type",
"==",
"self",
".",
"type",
"and",
"credentials",
".",
"auth_provider_id",
"==",
"self",
".",
"id",
")",
"]"
] | [
72,
4
] | [
83,
9
] | python | en | ['en', 'en', 'en'] | True |
AuthProvider.async_create_credentials | (self, data: Dict[str, str]) | Create credentials. | Create credentials. | def async_create_credentials(self, data: Dict[str, str]) -> Credentials:
"""Create credentials."""
return Credentials(
auth_provider_type=self.type, auth_provider_id=self.id, data=data
) | [
"def",
"async_create_credentials",
"(",
"self",
",",
"data",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"Credentials",
":",
"return",
"Credentials",
"(",
"auth_provider_type",
"=",
"self",
".",
"type",
",",
"auth_provider_id",
"=",
"self",
".",
"id",
",",
"data",
"=",
"data",
")"
] | [
86,
4
] | [
90,
9
] | python | en | ['en', 'la', 'en'] | False |
AuthProvider.async_login_flow | (self, context: Optional[Dict]) | Return the data flow for logging in with auth provider.
Auth provider should extend LoginFlow and return an instance.
| Return the data flow for logging in with auth provider. | async def async_login_flow(self, context: Optional[Dict]) -> "LoginFlow":
"""Return the data flow for logging in with auth provider.
Auth provider should extend LoginFlow and return an instance.
"""
raise NotImplementedError | [
"async",
"def",
"async_login_flow",
"(",
"self",
",",
"context",
":",
"Optional",
"[",
"Dict",
"]",
")",
"->",
"\"LoginFlow\"",
":",
"raise",
"NotImplementedError"
] | [
94,
4
] | [
99,
33
] | python | en | ['en', 'en', 'en'] | True |
AuthProvider.async_get_or_create_credentials | (
self, flow_result: Dict[str, str]
) | Get credentials based on the flow result. | Get credentials based on the flow result. | async def async_get_or_create_credentials(
self, flow_result: Dict[str, str]
) -> Credentials:
"""Get credentials based on the flow result."""
raise NotImplementedError | [
"async",
"def",
"async_get_or_create_credentials",
"(",
"self",
",",
"flow_result",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
")",
"->",
"Credentials",
":",
"raise",
"NotImplementedError"
] | [
101,
4
] | [
105,
33
] | python | en | ['en', 'en', 'en'] | True |
AuthProvider.async_user_meta_for_credentials | (
self, credentials: Credentials
) | Return extra user metadata for credentials.
Will be used to populate info when creating a new user.
| Return extra user metadata for credentials. | async def async_user_meta_for_credentials(
self, credentials: Credentials
) -> UserMeta:
"""Return extra user metadata for credentials.
Will be used to populate info when creating a new user.
"""
raise NotImplementedError | [
"async",
"def",
"async_user_meta_for_credentials",
"(",
"self",
",",
"credentials",
":",
"Credentials",
")",
"->",
"UserMeta",
":",
"raise",
"NotImplementedError"
] | [
107,
4
] | [
114,
33
] | python | en | ['nb', 'la', 'en'] | False |
AuthProvider.async_initialize | (self) | Initialize the auth provider. | Initialize the auth provider. | async def async_initialize(self) -> None:
"""Initialize the auth provider.""" | [
"async",
"def",
"async_initialize",
"(",
"self",
")",
"->",
"None",
":"
] | [
116,
4
] | [
117,
43
] | python | en | ['en', 'en', 'en'] | True |
LoginFlow.__init__ | (self, auth_provider: AuthProvider) | Initialize the login flow. | Initialize the login flow. | def __init__(self, auth_provider: AuthProvider) -> None:
"""Initialize the login flow."""
self._auth_provider = auth_provider
self._auth_module_id: Optional[str] = None
self._auth_manager = auth_provider.hass.auth
self.available_mfa_modules: Dict[str, str] = {}
self.created_at = dt_util.utcnow()
self.invalid_mfa_times = 0
self.user: Optional[User] = None | [
"def",
"__init__",
"(",
"self",
",",
"auth_provider",
":",
"AuthProvider",
")",
"->",
"None",
":",
"self",
".",
"_auth_provider",
"=",
"auth_provider",
"self",
".",
"_auth_module_id",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
"self",
".",
"_auth_manager",
"=",
"auth_provider",
".",
"hass",
".",
"auth",
"self",
".",
"available_mfa_modules",
":",
"Dict",
"[",
"str",
",",
"str",
"]",
"=",
"{",
"}",
"self",
".",
"created_at",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"self",
".",
"invalid_mfa_times",
"=",
"0",
"self",
".",
"user",
":",
"Optional",
"[",
"User",
"]",
"=",
"None"
] | [
175,
4
] | [
183,
40
] | python | en | ['en', 'en', 'en'] | True |
LoginFlow.async_step_init | (
self, user_input: Optional[Dict[str, str]] = None
) | Handle the first step of login flow.
Return self.async_show_form(step_id='init') if user_input is None.
Return await self.async_finish(flow_result) if login init step pass.
| Handle the first step of login flow. | async def async_step_init(
self, user_input: Optional[Dict[str, str]] = None
) -> Dict[str, Any]:
"""Handle the first step of login flow.
Return self.async_show_form(step_id='init') if user_input is None.
Return await self.async_finish(flow_result) if login init step pass.
"""
raise NotImplementedError | [
"async",
"def",
"async_step_init",
"(",
"self",
",",
"user_input",
":",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"raise",
"NotImplementedError"
] | [
185,
4
] | [
193,
33
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.