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_user_ipp_version_error | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test we abort user flow on IPP version not supported error. | Test we abort user flow on IPP version not supported error. | async def test_user_ipp_version_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we abort user flow on IPP version not supported error."""
mock_connection(aioclient_mock, version_not_supported=True)
user_input = {**MOCK_USER_INPUT}
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=user_input,
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "ipp_version_error" | [
"async",
"def",
"test_user_ipp_version_error",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"mock_connection",
"(",
"aioclient_mock",
",",
"version_not_supported",
"=",
"True",
")",
"user_input",
"=",
"{",
"*",
"*",
"MOCK_USER_INPUT",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
"data",
"=",
"user_input",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"ipp_version_error\""
] | [
205,
0
] | [
219,
50
] | python | en | ['en', 'en', 'en'] | True |
test_zeroconf_ipp_version_error | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test we abort zeroconf flow on IPP version not supported error. | Test we abort zeroconf flow on IPP version not supported error. | async def test_zeroconf_ipp_version_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we abort zeroconf flow on IPP version not supported error."""
mock_connection(aioclient_mock, version_not_supported=True)
discovery_info = {**MOCK_ZEROCONF_IPP_SERVICE_INFO}
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "ipp_version_error" | [
"async",
"def",
"test_zeroconf_ipp_version_error",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"mock_connection",
"(",
"aioclient_mock",
",",
"version_not_supported",
"=",
"True",
")",
"discovery_info",
"=",
"{",
"*",
"*",
"MOCK_ZEROCONF_IPP_SERVICE_INFO",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
"data",
"=",
"discovery_info",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"ipp_version_error\""
] | [
222,
0
] | [
236,
50
] | python | en | ['en', 'de', 'en'] | True |
test_user_device_exists_abort | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test we abort user flow if printer already configured. | Test we abort user flow if printer already configured. | async def test_user_device_exists_abort(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we abort user flow if printer already configured."""
await init_integration(hass, aioclient_mock, skip_setup=True)
user_input = MOCK_USER_INPUT.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=user_input,
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" | [
"async",
"def",
"test_user_device_exists_abort",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"await",
"init_integration",
"(",
"hass",
",",
"aioclient_mock",
",",
"skip_setup",
"=",
"True",
")",
"user_input",
"=",
"MOCK_USER_INPUT",
".",
"copy",
"(",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
"data",
"=",
"user_input",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\""
] | [
239,
0
] | [
253,
51
] | python | en | ['en', 'de', 'en'] | True |
test_zeroconf_device_exists_abort | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test we abort zeroconf flow if printer already configured. | Test we abort zeroconf flow if printer already configured. | async def test_zeroconf_device_exists_abort(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we abort zeroconf flow if printer already configured."""
await init_integration(hass, aioclient_mock, skip_setup=True)
discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" | [
"async",
"def",
"test_zeroconf_device_exists_abort",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"await",
"init_integration",
"(",
"hass",
",",
"aioclient_mock",
",",
"skip_setup",
"=",
"True",
")",
"discovery_info",
"=",
"MOCK_ZEROCONF_IPP_SERVICE_INFO",
".",
"copy",
"(",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
"data",
"=",
"discovery_info",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\""
] | [
256,
0
] | [
270,
51
] | python | de | ['de', 'de', 'en'] | True |
test_zeroconf_with_uuid_device_exists_abort | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test we abort zeroconf flow if printer already configured. | Test we abort zeroconf flow if printer already configured. | async def test_zeroconf_with_uuid_device_exists_abort(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we abort zeroconf flow if printer already configured."""
await init_integration(hass, aioclient_mock, skip_setup=True)
discovery_info = {
**MOCK_ZEROCONF_IPP_SERVICE_INFO,
"properties": {
**MOCK_ZEROCONF_IPP_SERVICE_INFO["properties"],
"UUID": "cfe92100-67c4-11d4-a45f-f8d027761251",
},
}
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" | [
"async",
"def",
"test_zeroconf_with_uuid_device_exists_abort",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"await",
"init_integration",
"(",
"hass",
",",
"aioclient_mock",
",",
"skip_setup",
"=",
"True",
")",
"discovery_info",
"=",
"{",
"*",
"*",
"MOCK_ZEROCONF_IPP_SERVICE_INFO",
",",
"\"properties\"",
":",
"{",
"*",
"*",
"MOCK_ZEROCONF_IPP_SERVICE_INFO",
"[",
"\"properties\"",
"]",
",",
"\"UUID\"",
":",
"\"cfe92100-67c4-11d4-a45f-f8d027761251\"",
",",
"}",
",",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
"data",
"=",
"discovery_info",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\""
] | [
273,
0
] | [
293,
51
] | python | de | ['de', 'de', 'en'] | True |
test_zeroconf_empty_unique_id | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test zeroconf flow if printer lacks (empty) unique identification. | Test zeroconf flow if printer lacks (empty) unique identification. | async def test_zeroconf_empty_unique_id(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test zeroconf flow if printer lacks (empty) unique identification."""
mock_connection(aioclient_mock, no_unique_id=True)
discovery_info = {
**MOCK_ZEROCONF_IPP_SERVICE_INFO,
"properties": {**MOCK_ZEROCONF_IPP_SERVICE_INFO["properties"], "UUID": ""},
}
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["type"] == RESULT_TYPE_FORM | [
"async",
"def",
"test_zeroconf_empty_unique_id",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"mock_connection",
"(",
"aioclient_mock",
",",
"no_unique_id",
"=",
"True",
")",
"discovery_info",
"=",
"{",
"*",
"*",
"MOCK_ZEROCONF_IPP_SERVICE_INFO",
",",
"\"properties\"",
":",
"{",
"*",
"*",
"MOCK_ZEROCONF_IPP_SERVICE_INFO",
"[",
"\"properties\"",
"]",
",",
"\"UUID\"",
":",
"\"\"",
"}",
",",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
"data",
"=",
"discovery_info",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM"
] | [
296,
0
] | [
312,
45
] | python | fr | ['fr', 'fr', 'en'] | True |
test_zeroconf_no_unique_id | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test zeroconf flow if printer lacks unique identification. | Test zeroconf flow if printer lacks unique identification. | async def test_zeroconf_no_unique_id(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test zeroconf flow if printer lacks unique identification."""
mock_connection(aioclient_mock, no_unique_id=True)
discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["type"] == RESULT_TYPE_FORM | [
"async",
"def",
"test_zeroconf_no_unique_id",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"mock_connection",
"(",
"aioclient_mock",
",",
"no_unique_id",
"=",
"True",
")",
"discovery_info",
"=",
"MOCK_ZEROCONF_IPP_SERVICE_INFO",
".",
"copy",
"(",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
"data",
"=",
"discovery_info",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM"
] | [
315,
0
] | [
328,
45
] | python | fr | ['fr', 'fr', 'en'] | True |
test_full_user_flow_implementation | (
hass: HomeAssistant, aioclient_mock
) | Test the full manual user flow from start to finish. | Test the full manual user flow from start to finish. | async def test_full_user_flow_implementation(
hass: HomeAssistant, aioclient_mock
) -> None:
"""Test the full manual user flow from start to finish."""
mock_connection(aioclient_mock)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["step_id"] == "user"
assert result["type"] == RESULT_TYPE_FORM
with patch(
"homeassistant.components.ipp.async_setup_entry", return_value=True
), patch("homeassistant.components.ipp.async_setup", return_value=True):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.31", CONF_BASE_PATH: "/ipp/print"},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "192.168.1.31"
assert result["data"]
assert result["data"][CONF_HOST] == "192.168.1.31"
assert result["data"][CONF_UUID] == "cfe92100-67c4-11d4-a45f-f8d027761251"
assert result["result"]
assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" | [
"async",
"def",
"test_full_user_flow_implementation",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
")",
"->",
"None",
":",
"mock_connection",
"(",
"aioclient_mock",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
",",
")",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"with",
"patch",
"(",
"\"homeassistant.components.ipp.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
",",
"patch",
"(",
"\"homeassistant.components.ipp.async_setup\"",
",",
"return_value",
"=",
"True",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"192.168.1.31\"",
",",
"CONF_BASE_PATH",
":",
"\"/ipp/print\"",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"192.168.1.31\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"\"192.168.1.31\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_UUID",
"]",
"==",
"\"cfe92100-67c4-11d4-a45f-f8d027761251\"",
"assert",
"result",
"[",
"\"result\"",
"]",
"assert",
"result",
"[",
"\"result\"",
"]",
".",
"unique_id",
"==",
"\"cfe92100-67c4-11d4-a45f-f8d027761251\""
] | [
331,
0
] | [
361,
79
] | python | en | ['en', 'en', 'en'] | True |
test_full_zeroconf_flow_implementation | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test the full manual user flow from start to finish. | Test the full manual user flow from start to finish. | async def test_full_zeroconf_flow_implementation(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the full manual user flow from start to finish."""
mock_connection(aioclient_mock)
discovery_info = MOCK_ZEROCONF_IPP_SERVICE_INFO.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["step_id"] == "zeroconf_confirm"
assert result["type"] == RESULT_TYPE_FORM
with patch(
"homeassistant.components.ipp.async_setup_entry", return_value=True
), patch("homeassistant.components.ipp.async_setup", return_value=True):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "EPSON XP-6000 Series"
assert result["data"]
assert result["data"][CONF_HOST] == "192.168.1.31"
assert result["data"][CONF_NAME] == "EPSON XP-6000 Series"
assert result["data"][CONF_UUID] == "cfe92100-67c4-11d4-a45f-f8d027761251"
assert not result["data"][CONF_SSL]
assert result["result"]
assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" | [
"async",
"def",
"test_full_zeroconf_flow_implementation",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"mock_connection",
"(",
"aioclient_mock",
")",
"discovery_info",
"=",
"MOCK_ZEROCONF_IPP_SERVICE_INFO",
".",
"copy",
"(",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
"data",
"=",
"discovery_info",
",",
")",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"zeroconf_confirm\"",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"with",
"patch",
"(",
"\"homeassistant.components.ipp.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
",",
"patch",
"(",
"\"homeassistant.components.ipp.async_setup\"",
",",
"return_value",
"=",
"True",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"EPSON XP-6000 Series\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"\"192.168.1.31\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"\"EPSON XP-6000 Series\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_UUID",
"]",
"==",
"\"cfe92100-67c4-11d4-a45f-f8d027761251\"",
"assert",
"not",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_SSL",
"]",
"assert",
"result",
"[",
"\"result\"",
"]",
"assert",
"result",
"[",
"\"result\"",
"]",
".",
"unique_id",
"==",
"\"cfe92100-67c4-11d4-a45f-f8d027761251\""
] | [
364,
0
] | [
397,
79
] | python | en | ['en', 'en', 'en'] | True |
test_full_zeroconf_tls_flow_implementation | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test the full manual user flow from start to finish. | Test the full manual user flow from start to finish. | async def test_full_zeroconf_tls_flow_implementation(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the full manual user flow from start to finish."""
mock_connection(aioclient_mock, ssl=True)
discovery_info = MOCK_ZEROCONF_IPPS_SERVICE_INFO.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["step_id"] == "zeroconf_confirm"
assert result["type"] == RESULT_TYPE_FORM
assert result["description_placeholders"] == {CONF_NAME: "EPSON XP-6000 Series"}
with patch(
"homeassistant.components.ipp.async_setup_entry", return_value=True
), patch("homeassistant.components.ipp.async_setup", return_value=True):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "EPSON XP-6000 Series"
assert result["data"]
assert result["data"][CONF_HOST] == "192.168.1.31"
assert result["data"][CONF_NAME] == "EPSON XP-6000 Series"
assert result["data"][CONF_UUID] == "cfe92100-67c4-11d4-a45f-f8d027761251"
assert result["data"][CONF_SSL]
assert result["result"]
assert result["result"].unique_id == "cfe92100-67c4-11d4-a45f-f8d027761251" | [
"async",
"def",
"test_full_zeroconf_tls_flow_implementation",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"mock_connection",
"(",
"aioclient_mock",
",",
"ssl",
"=",
"True",
")",
"discovery_info",
"=",
"MOCK_ZEROCONF_IPPS_SERVICE_INFO",
".",
"copy",
"(",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
"data",
"=",
"discovery_info",
",",
")",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"zeroconf_confirm\"",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"description_placeholders\"",
"]",
"==",
"{",
"CONF_NAME",
":",
"\"EPSON XP-6000 Series\"",
"}",
"with",
"patch",
"(",
"\"homeassistant.components.ipp.async_setup_entry\"",
",",
"return_value",
"=",
"True",
")",
",",
"patch",
"(",
"\"homeassistant.components.ipp.async_setup\"",
",",
"return_value",
"=",
"True",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"\"EPSON XP-6000 Series\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_HOST",
"]",
"==",
"\"192.168.1.31\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"\"EPSON XP-6000 Series\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_UUID",
"]",
"==",
"\"cfe92100-67c4-11d4-a45f-f8d027761251\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_SSL",
"]",
"assert",
"result",
"[",
"\"result\"",
"]",
"assert",
"result",
"[",
"\"result\"",
"]",
".",
"unique_id",
"==",
"\"cfe92100-67c4-11d4-a45f-f8d027761251\""
] | [
400,
0
] | [
434,
79
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the Epson projector from a config entry. | Set up the Epson projector from a config entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the Epson projector from a config entry."""
unique_id = config_entry.entry_id
projector = hass.data[DOMAIN][unique_id]
projector_entity = EpsonProjectorMediaPlayer(
projector, config_entry.title, unique_id
)
async_add_entities([projector_entity], True)
platform = entity_platform.current_platform.get()
platform.async_register_entity_service(
SERVICE_SELECT_CMODE,
{vol.Required(ATTR_CMODE): vol.All(cv.string, vol.Any(*CMODE_LIST_SET))},
SERVICE_SELECT_CMODE,
) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"unique_id",
"=",
"config_entry",
".",
"entry_id",
"projector",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"unique_id",
"]",
"projector_entity",
"=",
"EpsonProjectorMediaPlayer",
"(",
"projector",
",",
"config_entry",
".",
"title",
",",
"unique_id",
")",
"async_add_entities",
"(",
"[",
"projector_entity",
"]",
",",
"True",
")",
"platform",
"=",
"entity_platform",
".",
"current_platform",
".",
"get",
"(",
")",
"platform",
".",
"async_register_entity_service",
"(",
"SERVICE_SELECT_CMODE",
",",
"{",
"vol",
".",
"Required",
"(",
"ATTR_CMODE",
")",
":",
"vol",
".",
"All",
"(",
"cv",
".",
"string",
",",
"vol",
".",
"Any",
"(",
"*",
"CMODE_LIST_SET",
")",
")",
"}",
",",
"SERVICE_SELECT_CMODE",
",",
")"
] | [
66,
0
] | [
79,
5
] | python | en | ['en', 'en', 'en'] | True |
async_setup_platform | (hass, config, async_add_entities, discovery_info=None) | Set up the Epson projector. | Set up the Epson projector. | async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Epson projector."""
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=config
)
) | [
"async",
"def",
"async_setup_platform",
"(",
"hass",
",",
"config",
",",
"async_add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_IMPORT",
"}",
",",
"data",
"=",
"config",
")",
")"
] | [
82,
0
] | [
88,
5
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.__init__ | (self, projector, name, unique_id) | Initialize entity to control Epson projector. | Initialize entity to control Epson projector. | def __init__(self, projector, name, unique_id):
"""Initialize entity to control Epson projector."""
self._name = name
self._projector = projector
self._available = False
self._cmode = None
self._source_list = list(DEFAULT_SOURCES.values())
self._source = None
self._volume = None
self._state = None
self._unique_id = unique_id | [
"def",
"__init__",
"(",
"self",
",",
"projector",
",",
"name",
",",
"unique_id",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_projector",
"=",
"projector",
"self",
".",
"_available",
"=",
"False",
"self",
".",
"_cmode",
"=",
"None",
"self",
".",
"_source_list",
"=",
"list",
"(",
"DEFAULT_SOURCES",
".",
"values",
"(",
")",
")",
"self",
".",
"_source",
"=",
"None",
"self",
".",
"_volume",
"=",
"None",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_unique_id",
"=",
"unique_id"
] | [
94,
4
] | [
104,
35
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.async_update | (self) | Update state of device. | Update state of device. | async def async_update(self):
"""Update state of device."""
power_state = await self._projector.get_property(POWER)
_LOGGER.debug("Projector status: %s", power_state)
if not power_state or power_state == EPSON_STATE_UNAVAILABLE:
self._available = False
return
self._available = True
if power_state == EPSON_CODES[POWER]:
self._state = STATE_ON
self._source_list = list(DEFAULT_SOURCES.values())
cmode = await self._projector.get_property(CMODE)
self._cmode = CMODE_LIST.get(cmode, self._cmode)
source = await self._projector.get_property(SOURCE)
self._source = SOURCE_LIST.get(source, self._source)
volume = await self._projector.get_property(VOLUME)
if volume:
self._volume = volume
elif power_state == BUSY:
self._state = STATE_ON
else:
self._state = STATE_OFF | [
"async",
"def",
"async_update",
"(",
"self",
")",
":",
"power_state",
"=",
"await",
"self",
".",
"_projector",
".",
"get_property",
"(",
"POWER",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Projector status: %s\"",
",",
"power_state",
")",
"if",
"not",
"power_state",
"or",
"power_state",
"==",
"EPSON_STATE_UNAVAILABLE",
":",
"self",
".",
"_available",
"=",
"False",
"return",
"self",
".",
"_available",
"=",
"True",
"if",
"power_state",
"==",
"EPSON_CODES",
"[",
"POWER",
"]",
":",
"self",
".",
"_state",
"=",
"STATE_ON",
"self",
".",
"_source_list",
"=",
"list",
"(",
"DEFAULT_SOURCES",
".",
"values",
"(",
")",
")",
"cmode",
"=",
"await",
"self",
".",
"_projector",
".",
"get_property",
"(",
"CMODE",
")",
"self",
".",
"_cmode",
"=",
"CMODE_LIST",
".",
"get",
"(",
"cmode",
",",
"self",
".",
"_cmode",
")",
"source",
"=",
"await",
"self",
".",
"_projector",
".",
"get_property",
"(",
"SOURCE",
")",
"self",
".",
"_source",
"=",
"SOURCE_LIST",
".",
"get",
"(",
"source",
",",
"self",
".",
"_source",
")",
"volume",
"=",
"await",
"self",
".",
"_projector",
".",
"get_property",
"(",
"VOLUME",
")",
"if",
"volume",
":",
"self",
".",
"_volume",
"=",
"volume",
"elif",
"power_state",
"==",
"BUSY",
":",
"self",
".",
"_state",
"=",
"STATE_ON",
"else",
":",
"self",
".",
"_state",
"=",
"STATE_OFF"
] | [
106,
4
] | [
127,
35
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
130,
4
] | [
132,
25
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.unique_id | (self) | Return unique ID. | Return unique ID. | def unique_id(self):
"""Return unique ID."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unique_id"
] | [
135,
4
] | [
137,
30
] | python | en | ['fr', 'la', 'en'] | False |
EpsonProjectorMediaPlayer.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"
] | [
140,
4
] | [
142,
26
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.available | (self) | Return if projector is available. | Return if projector is available. | def available(self):
"""Return if projector is available."""
return self._available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"_available"
] | [
145,
4
] | [
147,
30
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.supported_features | (self) | Flag media player features that are supported. | Flag media player features that are supported. | def supported_features(self):
"""Flag media player features that are supported."""
return SUPPORT_EPSON | [
"def",
"supported_features",
"(",
"self",
")",
":",
"return",
"SUPPORT_EPSON"
] | [
150,
4
] | [
152,
28
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.async_turn_on | (self) | Turn on epson. | Turn on epson. | async def async_turn_on(self):
"""Turn on epson."""
if self._state == STATE_OFF:
await self._projector.send_command(TURN_ON) | [
"async",
"def",
"async_turn_on",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"STATE_OFF",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"TURN_ON",
")"
] | [
154,
4
] | [
157,
55
] | python | en | ['en', 'et', 'en'] | True |
EpsonProjectorMediaPlayer.async_turn_off | (self) | Turn off epson. | Turn off epson. | async def async_turn_off(self):
"""Turn off epson."""
if self._state == STATE_ON:
await self._projector.send_command(TURN_OFF) | [
"async",
"def",
"async_turn_off",
"(",
"self",
")",
":",
"if",
"self",
".",
"_state",
"==",
"STATE_ON",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"TURN_OFF",
")"
] | [
159,
4
] | [
162,
56
] | python | en | ['en', 'ja', 'en'] | True |
EpsonProjectorMediaPlayer.source_list | (self) | List of available input sources. | List of available input sources. | def source_list(self):
"""List of available input sources."""
return self._source_list | [
"def",
"source_list",
"(",
"self",
")",
":",
"return",
"self",
".",
"_source_list"
] | [
165,
4
] | [
167,
32
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.source | (self) | Get current input sources. | Get current input sources. | def source(self):
"""Get current input sources."""
return self._source | [
"def",
"source",
"(",
"self",
")",
":",
"return",
"self",
".",
"_source"
] | [
170,
4
] | [
172,
27
] | python | en | ['fr', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.volume_level | (self) | Return the volume level of the media player (0..1). | Return the volume level of the media player (0..1). | def volume_level(self):
"""Return the volume level of the media player (0..1)."""
return self._volume | [
"def",
"volume_level",
"(",
"self",
")",
":",
"return",
"self",
".",
"_volume"
] | [
175,
4
] | [
177,
27
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.select_cmode | (self, cmode) | Set color mode in Epson. | Set color mode in Epson. | async def select_cmode(self, cmode):
"""Set color mode in Epson."""
await self._projector.send_command(CMODE_LIST_SET[cmode]) | [
"async",
"def",
"select_cmode",
"(",
"self",
",",
"cmode",
")",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"CMODE_LIST_SET",
"[",
"cmode",
"]",
")"
] | [
179,
4
] | [
181,
65
] | python | en | ['en', 'en', 'en'] | True |
EpsonProjectorMediaPlayer.async_select_source | (self, source) | Select input source. | Select input source. | async def async_select_source(self, source):
"""Select input source."""
selected_source = INV_SOURCES[source]
await self._projector.send_command(selected_source) | [
"async",
"def",
"async_select_source",
"(",
"self",
",",
"source",
")",
":",
"selected_source",
"=",
"INV_SOURCES",
"[",
"source",
"]",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"selected_source",
")"
] | [
183,
4
] | [
186,
59
] | python | en | ['fr', 'su', 'en'] | False |
EpsonProjectorMediaPlayer.async_mute_volume | (self, mute) | Mute (true) or unmute (false) sound. | Mute (true) or unmute (false) sound. | async def async_mute_volume(self, mute):
"""Mute (true) or unmute (false) sound."""
await self._projector.send_command(MUTE) | [
"async",
"def",
"async_mute_volume",
"(",
"self",
",",
"mute",
")",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"MUTE",
")"
] | [
188,
4
] | [
190,
48
] | python | en | ['en', 'la', 'en'] | True |
EpsonProjectorMediaPlayer.async_volume_up | (self) | Increase volume. | Increase volume. | async def async_volume_up(self):
"""Increase volume."""
await self._projector.send_command(VOL_UP) | [
"async",
"def",
"async_volume_up",
"(",
"self",
")",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"VOL_UP",
")"
] | [
192,
4
] | [
194,
50
] | python | en | ['en', 'af', 'en'] | False |
EpsonProjectorMediaPlayer.async_volume_down | (self) | Decrease volume. | Decrease volume. | async def async_volume_down(self):
"""Decrease volume."""
await self._projector.send_command(VOL_DOWN) | [
"async",
"def",
"async_volume_down",
"(",
"self",
")",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"VOL_DOWN",
")"
] | [
196,
4
] | [
198,
52
] | python | en | ['en', 'de', 'en'] | False |
EpsonProjectorMediaPlayer.async_media_play | (self) | Play media via Epson. | Play media via Epson. | async def async_media_play(self):
"""Play media via Epson."""
await self._projector.send_command(PLAY) | [
"async",
"def",
"async_media_play",
"(",
"self",
")",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"PLAY",
")"
] | [
200,
4
] | [
202,
48
] | python | en | ['en', 'sk', 'it'] | False |
EpsonProjectorMediaPlayer.async_media_pause | (self) | Pause media via Epson. | Pause media via Epson. | async def async_media_pause(self):
"""Pause media via Epson."""
await self._projector.send_command(PAUSE) | [
"async",
"def",
"async_media_pause",
"(",
"self",
")",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"PAUSE",
")"
] | [
204,
4
] | [
206,
49
] | python | de | ['de', 'sk', 'it'] | False |
EpsonProjectorMediaPlayer.async_media_next_track | (self) | Skip to next. | Skip to next. | async def async_media_next_track(self):
"""Skip to next."""
await self._projector.send_command(FAST) | [
"async",
"def",
"async_media_next_track",
"(",
"self",
")",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"FAST",
")"
] | [
208,
4
] | [
210,
48
] | python | en | ['en', 'bg-Latn', 'en'] | True |
EpsonProjectorMediaPlayer.async_media_previous_track | (self) | Skip to previous. | Skip to previous. | async def async_media_previous_track(self):
"""Skip to previous."""
await self._projector.send_command(BACK) | [
"async",
"def",
"async_media_previous_track",
"(",
"self",
")",
":",
"await",
"self",
".",
"_projector",
".",
"send_command",
"(",
"BACK",
")"
] | [
212,
4
] | [
214,
48
] | python | en | ['en', 'el-Latn', 'en'] | True |
EpsonProjectorMediaPlayer.device_state_attributes | (self) | Return device specific state attributes. | Return device specific state attributes. | def device_state_attributes(self):
"""Return device specific state attributes."""
if self._cmode is None:
return {}
return {ATTR_CMODE: self._cmode} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cmode",
"is",
"None",
":",
"return",
"{",
"}",
"return",
"{",
"ATTR_CMODE",
":",
"self",
".",
"_cmode",
"}"
] | [
217,
4
] | [
221,
40
] | python | en | ['fr', 'en', 'en'] | True |
get_domains | (device_type) | Return the domains available for a device type. | Return the domains available for a device type. | def get_domains(device_type):
"""Return the domains available for a device type."""
return {domain for domain, types in DOMAINS_AND_TYPES if device_type in types} | [
"def",
"get_domains",
"(",
"device_type",
")",
":",
"return",
"{",
"domain",
"for",
"domain",
",",
"types",
"in",
"DOMAINS_AND_TYPES",
"if",
"device_type",
"in",
"types",
"}"
] | [
24,
0
] | [
26,
82
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice.__init__ | (self, hass, config) | Initialize the device. | Initialize the device. | def __init__(self, hass, config):
"""Initialize the device."""
self.hass = hass
self.config = config
self.api = None
self.update_manager = None
self.fw_version = None
self.authorized = None
self.reset_jobs = [] | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"config",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"config",
"=",
"config",
"self",
".",
"api",
"=",
"None",
"self",
".",
"update_manager",
"=",
"None",
"self",
".",
"fw_version",
"=",
"None",
"self",
".",
"authorized",
"=",
"None",
"self",
".",
"reset_jobs",
"=",
"[",
"]"
] | [
32,
4
] | [
40,
28
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return self.config.title | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"config",
".",
"title"
] | [
43,
4
] | [
45,
32
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice.unique_id | (self) | Return the unique id of the device. | Return the unique id of the device. | def unique_id(self):
"""Return the unique id of the device."""
return self.config.unique_id | [
"def",
"unique_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"config",
".",
"unique_id"
] | [
48,
4
] | [
50,
36
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice.async_update | (hass, entry) | Update the device and related entities.
Triggered when the device is renamed on the frontend.
| Update the device and related entities. | async def async_update(hass, entry):
"""Update the device and related entities.
Triggered when the device is renamed on the frontend.
"""
device_registry = await dr.async_get_registry(hass)
device_entry = device_registry.async_get_device(
{(DOMAIN, entry.unique_id)}, set()
)
device_registry.async_update_device(device_entry.id, name=entry.title)
await hass.config_entries.async_reload(entry.entry_id) | [
"async",
"def",
"async_update",
"(",
"hass",
",",
"entry",
")",
":",
"device_registry",
"=",
"await",
"dr",
".",
"async_get_registry",
"(",
"hass",
")",
"device_entry",
"=",
"device_registry",
".",
"async_get_device",
"(",
"{",
"(",
"DOMAIN",
",",
"entry",
".",
"unique_id",
")",
"}",
",",
"set",
"(",
")",
")",
"device_registry",
".",
"async_update_device",
"(",
"device_entry",
".",
"id",
",",
"name",
"=",
"entry",
".",
"title",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_reload",
"(",
"entry",
".",
"entry_id",
")"
] | [
53,
4
] | [
63,
62
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice.async_setup | (self) | Set up the device and related entities. | Set up the device and related entities. | async def async_setup(self):
"""Set up the device and related entities."""
config = self.config
api = blk.gendevice(
config.data[CONF_TYPE],
(config.data[CONF_HOST], DEFAULT_PORT),
bytes.fromhex(config.data[CONF_MAC]),
name=config.title,
)
api.timeout = config.data[CONF_TIMEOUT]
self.api = api
try:
await self.hass.async_add_executor_job(api.auth)
except AuthenticationError:
await self._async_handle_auth_error()
return False
except (NetworkTimeoutError, OSError) as err:
raise ConfigEntryNotReady from err
except BroadlinkException as err:
_LOGGER.error(
"Failed to authenticate to the device at %s: %s", api.host[0], err
)
return False
self.authorized = True
update_manager = get_update_manager(self)
coordinator = update_manager.coordinator
await coordinator.async_refresh()
if not coordinator.last_update_success:
raise ConfigEntryNotReady()
self.update_manager = update_manager
self.hass.data[DOMAIN].devices[config.entry_id] = self
self.reset_jobs.append(config.add_update_listener(self.async_update))
try:
self.fw_version = await self.hass.async_add_executor_job(api.get_fwversion)
except (BroadlinkException, OSError):
pass
# Forward entry setup to related domains.
tasks = (
self.hass.config_entries.async_forward_entry_setup(config, domain)
for domain in get_domains(self.api.type)
)
for entry_setup in tasks:
self.hass.async_create_task(entry_setup)
return True | [
"async",
"def",
"async_setup",
"(",
"self",
")",
":",
"config",
"=",
"self",
".",
"config",
"api",
"=",
"blk",
".",
"gendevice",
"(",
"config",
".",
"data",
"[",
"CONF_TYPE",
"]",
",",
"(",
"config",
".",
"data",
"[",
"CONF_HOST",
"]",
",",
"DEFAULT_PORT",
")",
",",
"bytes",
".",
"fromhex",
"(",
"config",
".",
"data",
"[",
"CONF_MAC",
"]",
")",
",",
"name",
"=",
"config",
".",
"title",
",",
")",
"api",
".",
"timeout",
"=",
"config",
".",
"data",
"[",
"CONF_TIMEOUT",
"]",
"self",
".",
"api",
"=",
"api",
"try",
":",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"api",
".",
"auth",
")",
"except",
"AuthenticationError",
":",
"await",
"self",
".",
"_async_handle_auth_error",
"(",
")",
"return",
"False",
"except",
"(",
"NetworkTimeoutError",
",",
"OSError",
")",
"as",
"err",
":",
"raise",
"ConfigEntryNotReady",
"from",
"err",
"except",
"BroadlinkException",
"as",
"err",
":",
"_LOGGER",
".",
"error",
"(",
"\"Failed to authenticate to the device at %s: %s\"",
",",
"api",
".",
"host",
"[",
"0",
"]",
",",
"err",
")",
"return",
"False",
"self",
".",
"authorized",
"=",
"True",
"update_manager",
"=",
"get_update_manager",
"(",
"self",
")",
"coordinator",
"=",
"update_manager",
".",
"coordinator",
"await",
"coordinator",
".",
"async_refresh",
"(",
")",
"if",
"not",
"coordinator",
".",
"last_update_success",
":",
"raise",
"ConfigEntryNotReady",
"(",
")",
"self",
".",
"update_manager",
"=",
"update_manager",
"self",
".",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"devices",
"[",
"config",
".",
"entry_id",
"]",
"=",
"self",
"self",
".",
"reset_jobs",
".",
"append",
"(",
"config",
".",
"add_update_listener",
"(",
"self",
".",
"async_update",
")",
")",
"try",
":",
"self",
".",
"fw_version",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"api",
".",
"get_fwversion",
")",
"except",
"(",
"BroadlinkException",
",",
"OSError",
")",
":",
"pass",
"# Forward entry setup to related domains.",
"tasks",
"=",
"(",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"config",
",",
"domain",
")",
"for",
"domain",
"in",
"get_domains",
"(",
"self",
".",
"api",
".",
"type",
")",
")",
"for",
"entry_setup",
"in",
"tasks",
":",
"self",
".",
"hass",
".",
"async_create_task",
"(",
"entry_setup",
")",
"return",
"True"
] | [
65,
4
] | [
119,
19
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice.async_unload | (self) | Unload the device and related entities. | Unload the device and related entities. | async def async_unload(self):
"""Unload the device and related entities."""
if self.update_manager is None:
return True
while self.reset_jobs:
self.reset_jobs.pop()()
tasks = (
self.hass.config_entries.async_forward_entry_unload(self.config, domain)
for domain in get_domains(self.api.type)
)
results = await asyncio.gather(*tasks)
return all(results) | [
"async",
"def",
"async_unload",
"(",
"self",
")",
":",
"if",
"self",
".",
"update_manager",
"is",
"None",
":",
"return",
"True",
"while",
"self",
".",
"reset_jobs",
":",
"self",
".",
"reset_jobs",
".",
"pop",
"(",
")",
"(",
")",
"tasks",
"=",
"(",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"self",
".",
"config",
",",
"domain",
")",
"for",
"domain",
"in",
"get_domains",
"(",
"self",
".",
"api",
".",
"type",
")",
")",
"results",
"=",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
")",
"return",
"all",
"(",
"results",
")"
] | [
121,
4
] | [
134,
27
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice.async_auth | (self) | Authenticate to the device. | Authenticate to the device. | async def async_auth(self):
"""Authenticate to the device."""
try:
await self.hass.async_add_executor_job(self.api.auth)
except (BroadlinkException, OSError) as err:
_LOGGER.debug(
"Failed to authenticate to the device at %s: %s", self.api.host[0], err
)
if isinstance(err, AuthenticationError):
await self._async_handle_auth_error()
return False
return True | [
"async",
"def",
"async_auth",
"(",
"self",
")",
":",
"try",
":",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"api",
".",
"auth",
")",
"except",
"(",
"BroadlinkException",
",",
"OSError",
")",
"as",
"err",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Failed to authenticate to the device at %s: %s\"",
",",
"self",
".",
"api",
".",
"host",
"[",
"0",
"]",
",",
"err",
")",
"if",
"isinstance",
"(",
"err",
",",
"AuthenticationError",
")",
":",
"await",
"self",
".",
"_async_handle_auth_error",
"(",
")",
"return",
"False",
"return",
"True"
] | [
136,
4
] | [
147,
19
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice.async_request | (self, function, *args, **kwargs) | Send a request to the device. | Send a request to the device. | async def async_request(self, function, *args, **kwargs):
"""Send a request to the device."""
request = partial(function, *args, **kwargs)
try:
return await self.hass.async_add_executor_job(request)
except (AuthorizationError, ConnectionClosedError):
if not await self.async_auth():
raise
return await self.hass.async_add_executor_job(request) | [
"async",
"def",
"async_request",
"(",
"self",
",",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"request",
"=",
"partial",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"return",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"request",
")",
"except",
"(",
"AuthorizationError",
",",
"ConnectionClosedError",
")",
":",
"if",
"not",
"await",
"self",
".",
"async_auth",
"(",
")",
":",
"raise",
"return",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"request",
")"
] | [
149,
4
] | [
157,
66
] | python | en | ['en', 'en', 'en'] | True |
BroadlinkDevice._async_handle_auth_error | (self) | Handle an authentication error. | Handle an authentication error. | async def _async_handle_auth_error(self):
"""Handle an authentication error."""
if self.authorized is False:
return
self.authorized = False
_LOGGER.error(
"%s (%s at %s) is locked. Click Configuration in the sidebar, "
"click Integrations, click Configure on the device and follow "
"the instructions to unlock it",
self.name,
self.api.model,
self.api.host[0],
)
self.hass.async_create_task(
self.hass.config_entries.flow.async_init(
DOMAIN,
context={"source": "reauth"},
data={CONF_NAME: self.name, **self.config.data},
)
) | [
"async",
"def",
"_async_handle_auth_error",
"(",
"self",
")",
":",
"if",
"self",
".",
"authorized",
"is",
"False",
":",
"return",
"self",
".",
"authorized",
"=",
"False",
"_LOGGER",
".",
"error",
"(",
"\"%s (%s at %s) is locked. Click Configuration in the sidebar, \"",
"\"click Integrations, click Configure on the device and follow \"",
"\"the instructions to unlock it\"",
",",
"self",
".",
"name",
",",
"self",
".",
"api",
".",
"model",
",",
"self",
".",
"api",
".",
"host",
"[",
"0",
"]",
",",
")",
"self",
".",
"hass",
".",
"async_create_task",
"(",
"self",
".",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"\"reauth\"",
"}",
",",
"data",
"=",
"{",
"CONF_NAME",
":",
"self",
".",
"name",
",",
"*",
"*",
"self",
".",
"config",
".",
"data",
"}",
",",
")",
")"
] | [
159,
4
] | [
181,
9
] | python | de | ['de', 'fr', 'en'] | False |
test_flow_manual_configuration | (hass) | Test that config flow works. | Test that config flow works. | async def test_flow_manual_configuration(hass):
"""Test that config flow works."""
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
with patch("axis.vapix.Vapix.request", new=vapix_request):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == f"M1065-LW - {MAC}"
assert result["data"] == {
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
CONF_MAC: MAC,
CONF_MODEL: "M1065-LW",
CONF_NAME: "M1065-LW 0",
} | [
"async",
"def",
"test_flow_manual_configuration",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"SOURCE_USER",
"with",
"patch",
"(",
"\"axis.vapix.Vapix.request\"",
",",
"new",
"=",
"vapix_request",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"f\"M1065-LW - {MAC}\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"CONF_MAC",
":",
"MAC",
",",
"CONF_MODEL",
":",
"\"M1065-LW\"",
",",
"CONF_NAME",
":",
"\"M1065-LW 0\"",
",",
"}"
] | [
31,
0
] | [
61,
5
] | python | en | ['en', 'en', 'en'] | True |
test_manual_configuration_update_configuration | (hass) | Test that config flow fails on already configured device. | Test that config flow fails on already configured device. | async def test_manual_configuration_update_configuration(hass):
"""Test that config flow fails on already configured device."""
config_entry = await setup_axis_integration(hass)
device = hass.data[AXIS_DOMAIN][config_entry.unique_id]
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
with patch(
"homeassistant.components.axis.async_setup_entry",
return_value=True,
) as mock_setup_entry, patch("axis.vapix.Vapix.request", new=vapix_request):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "2.3.4.5",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
assert device.host == "2.3.4.5"
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_manual_configuration_update_configuration",
"(",
"hass",
")",
":",
"config_entry",
"=",
"await",
"setup_axis_integration",
"(",
"hass",
")",
"device",
"=",
"hass",
".",
"data",
"[",
"AXIS_DOMAIN",
"]",
"[",
"config_entry",
".",
"unique_id",
"]",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"SOURCE_USER",
"with",
"patch",
"(",
"\"homeassistant.components.axis.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_setup_entry",
",",
"patch",
"(",
"\"axis.vapix.Vapix.request\"",
",",
"new",
"=",
"vapix_request",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"2.3.4.5\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\"",
"assert",
"device",
".",
"host",
"==",
"\"2.3.4.5\"",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
64,
0
] | [
94,
48
] | python | en | ['en', 'en', 'en'] | True |
test_flow_fails_already_configured | (hass) | Test that config flow fails on already configured device. | Test that config flow fails on already configured device. | async def test_flow_fails_already_configured(hass):
"""Test that config flow fails on already configured device."""
await setup_axis_integration(hass)
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
with patch("axis.vapix.Vapix.request", new=vapix_request):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" | [
"async",
"def",
"test_flow_fails_already_configured",
"(",
"hass",
")",
":",
"await",
"setup_axis_integration",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"SOURCE_USER",
"with",
"patch",
"(",
"\"axis.vapix.Vapix.request\"",
",",
"new",
"=",
"vapix_request",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\""
] | [
97,
0
] | [
120,
51
] | python | en | ['en', 'en', 'en'] | True |
test_flow_fails_faulty_credentials | (hass) | Test that config flow fails on faulty credentials. | Test that config flow fails on faulty credentials. | async def test_flow_fails_faulty_credentials(hass):
"""Test that config flow fails on faulty credentials."""
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
with patch(
"homeassistant.components.axis.config_flow.get_device",
side_effect=config_flow.AuthenticationRequired,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
},
)
assert result["errors"] == {"base": "invalid_auth"} | [
"async",
"def",
"test_flow_fails_faulty_credentials",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"SOURCE_USER",
"with",
"patch",
"(",
"\"homeassistant.components.axis.config_flow.get_device\"",
",",
"side_effect",
"=",
"config_flow",
".",
"AuthenticationRequired",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"invalid_auth\"",
"}"
] | [
123,
0
] | [
146,
55
] | python | en | ['en', 'en', 'en'] | True |
test_flow_fails_cannot_connect | (hass) | Test that config flow fails on cannot connect. | Test that config flow fails on cannot connect. | async def test_flow_fails_cannot_connect(hass):
"""Test that config flow fails on cannot connect."""
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
with patch(
"homeassistant.components.axis.config_flow.get_device",
side_effect=config_flow.CannotConnect,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
},
)
assert result["errors"] == {"base": "cannot_connect"} | [
"async",
"def",
"test_flow_fails_cannot_connect",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"SOURCE_USER",
"with",
"patch",
"(",
"\"homeassistant.components.axis.config_flow.get_device\"",
",",
"side_effect",
"=",
"config_flow",
".",
"CannotConnect",
",",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
149,
0
] | [
172,
57
] | python | en | ['en', 'en', 'en'] | True |
test_flow_create_entry_multiple_existing_entries_of_same_model | (hass) | Test that create entry can generate a name with other entries. | Test that create entry can generate a name with other entries. | async def test_flow_create_entry_multiple_existing_entries_of_same_model(hass):
"""Test that create entry can generate a name with other entries."""
entry = MockConfigEntry(
domain=AXIS_DOMAIN,
data={CONF_NAME: "M1065-LW 0", CONF_MODEL: "M1065-LW"},
)
entry.add_to_hass(hass)
entry2 = MockConfigEntry(
domain=AXIS_DOMAIN,
data={CONF_NAME: "M1065-LW 1", CONF_MODEL: "M1065-LW"},
)
entry2.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
with patch("axis.vapix.Vapix.request", new=vapix_request):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == f"M1065-LW - {MAC}"
assert result["data"] == {
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
CONF_MAC: MAC,
CONF_MODEL: "M1065-LW",
CONF_NAME: "M1065-LW 2",
}
assert result["data"][CONF_NAME] == "M1065-LW 2" | [
"async",
"def",
"test_flow_create_entry_multiple_existing_entries_of_same_model",
"(",
"hass",
")",
":",
"entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"AXIS_DOMAIN",
",",
"data",
"=",
"{",
"CONF_NAME",
":",
"\"M1065-LW 0\"",
",",
"CONF_MODEL",
":",
"\"M1065-LW\"",
"}",
",",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"entry2",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"AXIS_DOMAIN",
",",
"data",
"=",
"{",
"CONF_NAME",
":",
"\"M1065-LW 1\"",
",",
"CONF_MODEL",
":",
"\"M1065-LW\"",
"}",
",",
")",
"entry2",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_USER",
"}",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"SOURCE_USER",
"with",
"patch",
"(",
"\"axis.vapix.Vapix.request\"",
",",
"new",
"=",
"vapix_request",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"f\"M1065-LW - {MAC}\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"CONF_MAC",
":",
"MAC",
",",
"CONF_MODEL",
":",
"\"M1065-LW\"",
",",
"CONF_NAME",
":",
"\"M1065-LW 2\"",
",",
"}",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"\"M1065-LW 2\""
] | [
175,
0
] | [
218,
52
] | python | en | ['en', 'en', 'en'] | True |
test_zeroconf_flow | (hass) | Test that zeroconf discovery for new devices work. | Test that zeroconf discovery for new devices work. | async def test_zeroconf_flow(hass):
"""Test that zeroconf discovery for new devices work."""
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN,
data={
CONF_HOST: "1.2.3.4",
CONF_PORT: 80,
"hostname": "name",
"properties": {"macaddress": MAC},
},
context={"source": SOURCE_ZEROCONF},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == SOURCE_USER
with patch("axis.vapix.Vapix.request", new=vapix_request):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == f"M1065-LW - {MAC}"
assert result["data"] == {
CONF_HOST: "1.2.3.4",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_PORT: 80,
CONF_MAC: MAC,
CONF_MODEL: "M1065-LW",
CONF_NAME: "M1065-LW 0",
}
assert result["data"][CONF_NAME] == "M1065-LW 0" | [
"async",
"def",
"test_zeroconf_flow",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_PORT",
":",
"80",
",",
"\"hostname\"",
":",
"\"name\"",
",",
"\"properties\"",
":",
"{",
"\"macaddress\"",
":",
"MAC",
"}",
",",
"}",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"SOURCE_USER",
"with",
"patch",
"(",
"\"axis.vapix.Vapix.request\"",
",",
"new",
"=",
"vapix_request",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"f\"M1065-LW - {MAC}\"",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_USERNAME",
":",
"\"user\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_PORT",
":",
"80",
",",
"CONF_MAC",
":",
"MAC",
",",
"CONF_MODEL",
":",
"\"M1065-LW\"",
",",
"CONF_NAME",
":",
"\"M1065-LW 0\"",
",",
"}",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"\"M1065-LW 0\""
] | [
221,
0
] | [
260,
52
] | python | en | ['en', 'en', 'en'] | True |
test_zeroconf_flow_already_configured | (hass) | Test that zeroconf doesn't setup already configured devices. | Test that zeroconf doesn't setup already configured devices. | async def test_zeroconf_flow_already_configured(hass):
"""Test that zeroconf doesn't setup already configured devices."""
config_entry = await setup_axis_integration(hass)
device = hass.data[AXIS_DOMAIN][config_entry.unique_id]
assert device.host == "1.2.3.4"
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN,
data={
CONF_HOST: "1.2.3.4",
CONF_PORT: 80,
"hostname": "name",
"properties": {"macaddress": MAC},
},
context={"source": SOURCE_ZEROCONF},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
assert device.host == "1.2.3.4" | [
"async",
"def",
"test_zeroconf_flow_already_configured",
"(",
"hass",
")",
":",
"config_entry",
"=",
"await",
"setup_axis_integration",
"(",
"hass",
")",
"device",
"=",
"hass",
".",
"data",
"[",
"AXIS_DOMAIN",
"]",
"[",
"config_entry",
".",
"unique_id",
"]",
"assert",
"device",
".",
"host",
"==",
"\"1.2.3.4\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_PORT",
":",
"80",
",",
"\"hostname\"",
":",
"\"name\"",
",",
"\"properties\"",
":",
"{",
"\"macaddress\"",
":",
"MAC",
"}",
",",
"}",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\"",
"assert",
"device",
".",
"host",
"==",
"\"1.2.3.4\""
] | [
263,
0
] | [
282,
35
] | python | en | ['en', 'en', 'en'] | True |
test_zeroconf_flow_updated_configuration | (hass) | Test that zeroconf update configuration with new parameters. | Test that zeroconf update configuration with new parameters. | async def test_zeroconf_flow_updated_configuration(hass):
"""Test that zeroconf update configuration with new parameters."""
config_entry = await setup_axis_integration(hass)
device = hass.data[AXIS_DOMAIN][config_entry.unique_id]
assert device.host == "1.2.3.4"
assert device.config_entry.data == {
CONF_HOST: "1.2.3.4",
CONF_PORT: 80,
CONF_USERNAME: "root",
CONF_PASSWORD: "pass",
CONF_MAC: MAC,
CONF_MODEL: MODEL,
CONF_NAME: NAME,
}
with patch(
"homeassistant.components.axis.async_setup_entry",
return_value=True,
) as mock_setup_entry, patch("axis.vapix.Vapix.request", new=vapix_request):
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN,
data={
CONF_HOST: "2.3.4.5",
CONF_PORT: 8080,
"hostname": "name",
"properties": {"macaddress": MAC},
},
context={"source": SOURCE_ZEROCONF},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
assert device.config_entry.data == {
CONF_HOST: "2.3.4.5",
CONF_PORT: 8080,
CONF_USERNAME: "root",
CONF_PASSWORD: "pass",
CONF_MAC: MAC,
CONF_MODEL: MODEL,
CONF_NAME: NAME,
}
assert len(mock_setup_entry.mock_calls) == 1 | [
"async",
"def",
"test_zeroconf_flow_updated_configuration",
"(",
"hass",
")",
":",
"config_entry",
"=",
"await",
"setup_axis_integration",
"(",
"hass",
")",
"device",
"=",
"hass",
".",
"data",
"[",
"AXIS_DOMAIN",
"]",
"[",
"config_entry",
".",
"unique_id",
"]",
"assert",
"device",
".",
"host",
"==",
"\"1.2.3.4\"",
"assert",
"device",
".",
"config_entry",
".",
"data",
"==",
"{",
"CONF_HOST",
":",
"\"1.2.3.4\"",
",",
"CONF_PORT",
":",
"80",
",",
"CONF_USERNAME",
":",
"\"root\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_MAC",
":",
"MAC",
",",
"CONF_MODEL",
":",
"MODEL",
",",
"CONF_NAME",
":",
"NAME",
",",
"}",
"with",
"patch",
"(",
"\"homeassistant.components.axis.async_setup_entry\"",
",",
"return_value",
"=",
"True",
",",
")",
"as",
"mock_setup_entry",
",",
"patch",
"(",
"\"axis.vapix.Vapix.request\"",
",",
"new",
"=",
"vapix_request",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"\"2.3.4.5\"",
",",
"CONF_PORT",
":",
"8080",
",",
"\"hostname\"",
":",
"\"name\"",
",",
"\"properties\"",
":",
"{",
"\"macaddress\"",
":",
"MAC",
"}",
",",
"}",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\"",
"assert",
"device",
".",
"config_entry",
".",
"data",
"==",
"{",
"CONF_HOST",
":",
"\"2.3.4.5\"",
",",
"CONF_PORT",
":",
"8080",
",",
"CONF_USERNAME",
":",
"\"root\"",
",",
"CONF_PASSWORD",
":",
"\"pass\"",
",",
"CONF_MAC",
":",
"MAC",
",",
"CONF_MODEL",
":",
"MODEL",
",",
"CONF_NAME",
":",
"NAME",
",",
"}",
"assert",
"len",
"(",
"mock_setup_entry",
".",
"mock_calls",
")",
"==",
"1"
] | [
285,
0
] | [
327,
48
] | python | en | ['en', 'en', 'en'] | True |
test_zeroconf_flow_ignore_non_axis_device | (hass) | Test that zeroconf doesn't setup devices with link local addresses. | Test that zeroconf doesn't setup devices with link local addresses. | async def test_zeroconf_flow_ignore_non_axis_device(hass):
"""Test that zeroconf doesn't setup devices with link local addresses."""
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN,
data={CONF_HOST: "169.254.3.4", "properties": {"macaddress": "01234567890"}},
context={"source": SOURCE_ZEROCONF},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "not_axis_device" | [
"async",
"def",
"test_zeroconf_flow_ignore_non_axis_device",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"\"169.254.3.4\"",
",",
"\"properties\"",
":",
"{",
"\"macaddress\"",
":",
"\"01234567890\"",
"}",
"}",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"not_axis_device\""
] | [
330,
0
] | [
339,
48
] | python | en | ['en', 'en', 'en'] | True |
test_zeroconf_flow_ignore_link_local_address | (hass) | Test that zeroconf doesn't setup devices with link local addresses. | Test that zeroconf doesn't setup devices with link local addresses. | async def test_zeroconf_flow_ignore_link_local_address(hass):
"""Test that zeroconf doesn't setup devices with link local addresses."""
result = await hass.config_entries.flow.async_init(
AXIS_DOMAIN,
data={CONF_HOST: "169.254.3.4", "properties": {"macaddress": MAC}},
context={"source": SOURCE_ZEROCONF},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "link_local_address" | [
"async",
"def",
"test_zeroconf_flow_ignore_link_local_address",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"AXIS_DOMAIN",
",",
"data",
"=",
"{",
"CONF_HOST",
":",
"\"169.254.3.4\"",
",",
"\"properties\"",
":",
"{",
"\"macaddress\"",
":",
"MAC",
"}",
"}",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_ZEROCONF",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"link_local_address\""
] | [
342,
0
] | [
351,
51
] | python | en | ['en', 'en', 'en'] | True |
test_option_flow | (hass) | Test config flow options. | Test config flow options. | async def test_option_flow(hass):
"""Test config flow options."""
config_entry = await setup_axis_integration(hass)
device = hass.data[AXIS_DOMAIN][config_entry.unique_id]
assert device.option_stream_profile == DEFAULT_STREAM_PROFILE
result = await hass.config_entries.options.async_init(device.config_entry.entry_id)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "configure_stream"
assert set(result["data_schema"].schema[CONF_STREAM_PROFILE].container) == {
DEFAULT_STREAM_PROFILE,
"profile_1",
"profile_2",
}
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={CONF_STREAM_PROFILE: "profile_1"},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"] == {
CONF_EVENTS: True,
CONF_STREAM_PROFILE: "profile_1",
}
assert device.option_stream_profile == "profile_1" | [
"async",
"def",
"test_option_flow",
"(",
"hass",
")",
":",
"config_entry",
"=",
"await",
"setup_axis_integration",
"(",
"hass",
")",
"device",
"=",
"hass",
".",
"data",
"[",
"AXIS_DOMAIN",
"]",
"[",
"config_entry",
".",
"unique_id",
"]",
"assert",
"device",
".",
"option_stream_profile",
"==",
"DEFAULT_STREAM_PROFILE",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"options",
".",
"async_init",
"(",
"device",
".",
"config_entry",
".",
"entry_id",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"configure_stream\"",
"assert",
"set",
"(",
"result",
"[",
"\"data_schema\"",
"]",
".",
"schema",
"[",
"CONF_STREAM_PROFILE",
"]",
".",
"container",
")",
"==",
"{",
"DEFAULT_STREAM_PROFILE",
",",
"\"profile_1\"",
",",
"\"profile_2\"",
",",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"options",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_STREAM_PROFILE",
":",
"\"profile_1\"",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"{",
"CONF_EVENTS",
":",
"True",
",",
"CONF_STREAM_PROFILE",
":",
"\"profile_1\"",
",",
"}",
"assert",
"device",
".",
"option_stream_profile",
"==",
"\"profile_1\""
] | [
354,
0
] | [
380,
54
] | python | en | ['en', 'fr', 'en'] | True |
BinaryMeta.events | (self) | List[Event]: Events definition. | List[Event]: Events definition. | def events(self) -> List[Event]:
"""List[Event]: Events definition."""
return self._events | [
"def",
"events",
"(",
"self",
")",
"->",
"List",
"[",
"Event",
"]",
":",
"return",
"self",
".",
"_events"
] | [
65,
4
] | [
67,
27
] | python | en | ['fr', 'en', 'en'] | True |
BinaryMeta.default_event_name | (self) | str: Default event name, if no value matched. | str: Default event name, if no value matched. | def default_event_name(self) -> str:
"""str: Default event name, if no value matched."""
return self._default_event_name | [
"def",
"default_event_name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_default_event_name"
] | [
70,
4
] | [
72,
39
] | python | ca | ['ca', 'da', 'en'] | False |
BinaryMeta.event_attr_name | (self) | str: Event attribute name. | str: Event attribute name. | def event_attr_name(self) -> str:
"""str: Event attribute name."""
return self._event_attr_name | [
"def",
"event_attr_name",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_event_attr_name"
] | [
75,
4
] | [
77,
36
] | python | en | ['en', 'en', 'en'] | True |
BinaryMeta.time_zone | (self) | Time zone of this meta, used to correct timestamp. | Time zone of this meta, used to correct timestamp. | def time_zone(self):
"""Time zone of this meta, used to correct timestamp."""
return self._tzone | [
"def",
"time_zone",
"(",
"self",
")",
":",
"return",
"self",
".",
"_tzone"
] | [
80,
4
] | [
82,
26
] | python | en | ['en', 'en', 'en'] | True |
BinaryMeta.item_size | (self) | int: Item binary size (in bytes). | int: Item binary size (in bytes). | def item_size(self) -> int:
"""int: Item binary size (in bytes)."""
return self._item_struct.size | [
"def",
"item_size",
"(",
"self",
")",
"->",
"int",
":",
"return",
"self",
".",
"_item_struct",
".",
"size"
] | [
85,
4
] | [
87,
37
] | python | en | ['en', 'en', 'en'] | True |
BinaryMeta.columns | (self) | dict: Columns to extract. | dict: Columns to extract. | def columns(self) -> dict:
"""dict: Columns to extract."""
return {a.name: a.raw_name for a in self._attrs} | [
"def",
"columns",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"a",
".",
"name",
":",
"a",
".",
"raw_name",
"for",
"a",
"in",
"self",
".",
"_attrs",
"}"
] | [
90,
4
] | [
92,
56
] | python | en | ['en', 'en', 'en'] | True |
BinaryMeta.items | (self) | dict: Attribute items. | dict: Attribute items. | def items(self) -> dict:
"""dict: Attribute items."""
return {a.name: a.dtype for a in self._attrs} | [
"def",
"items",
"(",
"self",
")",
"->",
"dict",
":",
"return",
"{",
"a",
".",
"name",
":",
"a",
".",
"dtype",
"for",
"a",
"in",
"self",
".",
"_attrs",
"}"
] | [
94,
4
] | [
96,
53
] | python | en | ['en', 'la', 'en'] | True |
BinaryMeta.from_file | (self, file: str) | Read meta from yaml file. | Read meta from yaml file. | def from_file(self, file: str):
"""Read meta from yaml file."""
assert os.path.exists(file)
with open(file, "rt") as fp:
conf = safe_load(fp)
self._validate(conf)
self._build_item_struct() | [
"def",
"from_file",
"(",
"self",
",",
"file",
":",
"str",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"file",
")",
"with",
"open",
"(",
"file",
",",
"\"rt\"",
")",
"as",
"fp",
":",
"conf",
"=",
"safe_load",
"(",
"fp",
")",
"self",
".",
"_validate",
"(",
"conf",
")",
"self",
".",
"_build_item_struct",
"(",
")"
] | [
98,
4
] | [
107,
37
] | python | en | ['en', 'yo', 'en'] | True |
BinaryMeta.from_bytes | (self, meta_bytes: Union[bytes, bytearray, memoryview]) | Construct meta from bytes.
Args:
meta_bytes (Union[bytes, bytearray, memoryview]): Bytes content of meta.
| Construct meta from bytes. | def from_bytes(self, meta_bytes: Union[bytes, bytearray, memoryview]):
"""Construct meta from bytes.
Args:
meta_bytes (Union[bytes, bytearray, memoryview]): Bytes content of meta.
"""
assert meta_bytes is not None
self._events.clear()
self._attrs.clear()
self._raw_cols.clear()
conf = safe_load(meta_bytes[:].decode())
# NOTE: this methods used to load meta bytes from converted binary,
# which is our processed format, so we do not need validate here
self._events.extend(conf.get("events", []))
self._attrs.extend(conf.get("attributes", []))
self._event_attr_name = conf.get("event_attr_name", None)
self._default_event_name = conf.get("default_event_name", None)
self._raw_cols = [(a.raw_name, a.dtype) for a in self._attrs]
self._adjust_attrs = {i: a.adjust_ratio for i, a, in enumerate(
self._attrs) if a.adjust_ratio is not None}
self._build_item_struct() | [
"def",
"from_bytes",
"(",
"self",
",",
"meta_bytes",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
",",
"memoryview",
"]",
")",
":",
"assert",
"meta_bytes",
"is",
"not",
"None",
"self",
".",
"_events",
".",
"clear",
"(",
")",
"self",
".",
"_attrs",
".",
"clear",
"(",
")",
"self",
".",
"_raw_cols",
".",
"clear",
"(",
")",
"conf",
"=",
"safe_load",
"(",
"meta_bytes",
"[",
":",
"]",
".",
"decode",
"(",
")",
")",
"# NOTE: this methods used to load meta bytes from converted binary,",
"# which is our processed format, so we do not need validate here",
"self",
".",
"_events",
".",
"extend",
"(",
"conf",
".",
"get",
"(",
"\"events\"",
",",
"[",
"]",
")",
")",
"self",
".",
"_attrs",
".",
"extend",
"(",
"conf",
".",
"get",
"(",
"\"attributes\"",
",",
"[",
"]",
")",
")",
"self",
".",
"_event_attr_name",
"=",
"conf",
".",
"get",
"(",
"\"event_attr_name\"",
",",
"None",
")",
"self",
".",
"_default_event_name",
"=",
"conf",
".",
"get",
"(",
"\"default_event_name\"",
",",
"None",
")",
"self",
".",
"_raw_cols",
"=",
"[",
"(",
"a",
".",
"raw_name",
",",
"a",
".",
"dtype",
")",
"for",
"a",
"in",
"self",
".",
"_attrs",
"]",
"self",
".",
"_adjust_attrs",
"=",
"{",
"i",
":",
"a",
".",
"adjust_ratio",
"for",
"i",
",",
"a",
",",
"in",
"enumerate",
"(",
"self",
".",
"_attrs",
")",
"if",
"a",
".",
"adjust_ratio",
"is",
"not",
"None",
"}",
"self",
".",
"_build_item_struct",
"(",
")"
] | [
109,
4
] | [
137,
33
] | python | en | ['en', 'en', 'en'] | True |
BinaryMeta.from_dict | (self, meta_dict: dict) | Construct meta from dictionary.
Args:
meta_dict (dict): Meta dictionary.
| Construct meta from dictionary. | def from_dict(self, meta_dict: dict):
"""Construct meta from dictionary.
Args:
meta_dict (dict): Meta dictionary.
"""
self._validate(meta_dict)
self._build_item_struct() | [
"def",
"from_dict",
"(",
"self",
",",
"meta_dict",
":",
"dict",
")",
":",
"self",
".",
"_validate",
"(",
"meta_dict",
")",
"self",
".",
"_build_item_struct",
"(",
")"
] | [
139,
4
] | [
147,
33
] | python | en | ['en', 'en', 'en'] | True |
BinaryMeta.to_bytes | (self) | Convert meta into bytes.
Returns:
bytes: Bytes content of current meta.
| Convert meta into bytes. | def to_bytes(self):
"""Convert meta into bytes.
Returns:
bytes: Bytes content of current meta.
"""
return safe_dump(
{
"events": self._events,
"attributes": self._attrs,
"default_event_name": self._default_event_name,
"event_attr_name": self._event_attr_name
},
).encode() | [
"def",
"to_bytes",
"(",
"self",
")",
":",
"return",
"safe_dump",
"(",
"{",
"\"events\"",
":",
"self",
".",
"_events",
",",
"\"attributes\"",
":",
"self",
".",
"_attrs",
",",
"\"default_event_name\"",
":",
"self",
".",
"_default_event_name",
",",
"\"event_attr_name\"",
":",
"self",
".",
"_event_attr_name",
"}",
",",
")",
".",
"encode",
"(",
")"
] | [
149,
4
] | [
162,
18
] | python | en | ['en', 'sr', 'en'] | True |
BinaryMeta.get_item_values | (self, row: dict) | Retrieve value for item.
Args:
row (dict): A row that from a csv file.
Returns:
Union[list, tuple]: Get value for configured attributes from dict.
| Retrieve value for item. | def get_item_values(self, row: dict) -> Union[list, tuple]:
"""Retrieve value for item.
Args:
row (dict): A row that from a csv file.
Returns:
Union[list, tuple]: Get value for configured attributes from dict.
"""
# NOTE: keep the order
return (row[col] for col in self._raw_cols) | [
"def",
"get_item_values",
"(",
"self",
",",
"row",
":",
"dict",
")",
"->",
"Union",
"[",
"list",
",",
"tuple",
"]",
":",
"# NOTE: keep the order",
"return",
"(",
"row",
"[",
"col",
"]",
"for",
"col",
"in",
"self",
".",
"_raw_cols",
")"
] | [
164,
4
] | [
174,
51
] | python | en | ['en', 'pt', 'en'] | True |
BinaryMeta.item_to_bytes | (self, item_values: Union[tuple, list], out_bytes: Union[memoryview, bytearray]) | Convert item into bytes.
Args:
item_values (Union[tuple, list]): Value of attributes used to construct item.
out_bytes (Union[memoryview, bytearray]): Item bytes content.
Returns:
int: Result item size.
| Convert item into bytes. | def item_to_bytes(self, item_values: Union[tuple, list], out_bytes: Union[memoryview, bytearray]) -> int:
"""Convert item into bytes.
Args:
item_values (Union[tuple, list]): Value of attributes used to construct item.
out_bytes (Union[memoryview, bytearray]): Item bytes content.
Returns:
int: Result item size.
"""
self._item_struct.pack_into(out_bytes, 0, *item_values)
return self.item_size | [
"def",
"item_to_bytes",
"(",
"self",
",",
"item_values",
":",
"Union",
"[",
"tuple",
",",
"list",
"]",
",",
"out_bytes",
":",
"Union",
"[",
"memoryview",
",",
"bytearray",
"]",
")",
"->",
"int",
":",
"self",
".",
"_item_struct",
".",
"pack_into",
"(",
"out_bytes",
",",
"0",
",",
"*",
"item_values",
")",
"return",
"self",
".",
"item_size"
] | [
176,
4
] | [
188,
29
] | python | en | ['en', 'hu', 'en'] | True |
BinaryMeta.item_from_bytes | (self, item_bytes: Union[bytes, bytearray, memoryview], adjust_value: bool = False) | Convert bytes into item (namedtuple).
Args:
item_bytes (Union[bytes, bytearray, memoryview]): Item byte content.
adjust_value (bool): If need to adjust value for attributes that enabled this feature.
Returns:
namedtuple: Result item tuple.
| Convert bytes into item (namedtuple). | def item_from_bytes(self, item_bytes: Union[bytes, bytearray, memoryview], adjust_value: bool = False):
"""Convert bytes into item (namedtuple).
Args:
item_bytes (Union[bytes, bytearray, memoryview]): Item byte content.
adjust_value (bool): If need to adjust value for attributes that enabled this feature.
Returns:
namedtuple: Result item tuple.
"""
item_tuple = self._item_struct.unpack_from(item_bytes, 0)
if adjust_value:
# convert it into list to that we can change the value
item_tuple = list(item_tuple)
for index, ratio in self._adjust_attrs.items():
# make it percentage
item_tuple[index] += random.randrange(int(ratio[0]), int(ratio[1])) * 0.01 * item_tuple[index]
return self._item_nt._make(item_tuple) | [
"def",
"item_from_bytes",
"(",
"self",
",",
"item_bytes",
":",
"Union",
"[",
"bytes",
",",
"bytearray",
",",
"memoryview",
"]",
",",
"adjust_value",
":",
"bool",
"=",
"False",
")",
":",
"item_tuple",
"=",
"self",
".",
"_item_struct",
".",
"unpack_from",
"(",
"item_bytes",
",",
"0",
")",
"if",
"adjust_value",
":",
"# convert it into list to that we can change the value",
"item_tuple",
"=",
"list",
"(",
"item_tuple",
")",
"for",
"index",
",",
"ratio",
"in",
"self",
".",
"_adjust_attrs",
".",
"items",
"(",
")",
":",
"# make it percentage",
"item_tuple",
"[",
"index",
"]",
"+=",
"random",
".",
"randrange",
"(",
"int",
"(",
"ratio",
"[",
"0",
"]",
")",
",",
"int",
"(",
"ratio",
"[",
"1",
"]",
")",
")",
"*",
"0.01",
"*",
"item_tuple",
"[",
"index",
"]",
"return",
"self",
".",
"_item_nt",
".",
"_make",
"(",
"item_tuple",
")"
] | [
190,
4
] | [
210,
46
] | python | en | ['en', 'hu', 'en'] | True |
BinaryMeta._build_item_struct | (self) | Build item struct use field name in meta. | Build item struct use field name in meta. | def _build_item_struct(self):
"""Build item struct use field name in meta."""
self._item_nt = namedtuple("Item", [a.name for a in self._attrs])
fmt: str = "<" + "".join([dtype_pack_map[a.dtype] for a in self._attrs])
self._item_struct = Struct(fmt) | [
"def",
"_build_item_struct",
"(",
"self",
")",
":",
"self",
".",
"_item_nt",
"=",
"namedtuple",
"(",
"\"Item\"",
",",
"[",
"a",
".",
"name",
"for",
"a",
"in",
"self",
".",
"_attrs",
"]",
")",
"fmt",
":",
"str",
"=",
"\"<\"",
"+",
"\"\"",
".",
"join",
"(",
"[",
"dtype_pack_map",
"[",
"a",
".",
"dtype",
"]",
"for",
"a",
"in",
"self",
".",
"_attrs",
"]",
")",
"self",
".",
"_item_struct",
"=",
"Struct",
"(",
"fmt",
")"
] | [
212,
4
] | [
218,
39
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the available Danfoss Air sensors etc. | Set up the available Danfoss Air sensors etc. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the available Danfoss Air sensors etc."""
data = hass.data[DANFOSS_AIR_DOMAIN]
sensors = [
[
"Danfoss Air Exhaust Temperature",
TEMP_CELSIUS,
ReadCommand.exhaustTemperature,
DEVICE_CLASS_TEMPERATURE,
],
[
"Danfoss Air Outdoor Temperature",
TEMP_CELSIUS,
ReadCommand.outdoorTemperature,
DEVICE_CLASS_TEMPERATURE,
],
[
"Danfoss Air Supply Temperature",
TEMP_CELSIUS,
ReadCommand.supplyTemperature,
DEVICE_CLASS_TEMPERATURE,
],
[
"Danfoss Air Extract Temperature",
TEMP_CELSIUS,
ReadCommand.extractTemperature,
DEVICE_CLASS_TEMPERATURE,
],
[
"Danfoss Air Remaining Filter",
PERCENTAGE,
ReadCommand.filterPercent,
None,
],
[
"Danfoss Air Humidity",
PERCENTAGE,
ReadCommand.humidity,
DEVICE_CLASS_HUMIDITY,
],
["Danfoss Air Fan Step", PERCENTAGE, ReadCommand.fan_step, None],
["Danfoss Air Exhaust Fan Speed", "RPM", ReadCommand.exhaust_fan_speed, None],
["Danfoss Air Supply Fan Speed", "RPM", ReadCommand.supply_fan_speed, None],
[
"Danfoss Air Dial Battery",
PERCENTAGE,
ReadCommand.battery_percent,
DEVICE_CLASS_BATTERY,
],
]
dev = []
for sensor in sensors:
dev.append(DanfossAir(data, sensor[0], sensor[1], sensor[2], sensor[3]))
add_entities(dev, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"data",
"=",
"hass",
".",
"data",
"[",
"DANFOSS_AIR_DOMAIN",
"]",
"sensors",
"=",
"[",
"[",
"\"Danfoss Air Exhaust Temperature\"",
",",
"TEMP_CELSIUS",
",",
"ReadCommand",
".",
"exhaustTemperature",
",",
"DEVICE_CLASS_TEMPERATURE",
",",
"]",
",",
"[",
"\"Danfoss Air Outdoor Temperature\"",
",",
"TEMP_CELSIUS",
",",
"ReadCommand",
".",
"outdoorTemperature",
",",
"DEVICE_CLASS_TEMPERATURE",
",",
"]",
",",
"[",
"\"Danfoss Air Supply Temperature\"",
",",
"TEMP_CELSIUS",
",",
"ReadCommand",
".",
"supplyTemperature",
",",
"DEVICE_CLASS_TEMPERATURE",
",",
"]",
",",
"[",
"\"Danfoss Air Extract Temperature\"",
",",
"TEMP_CELSIUS",
",",
"ReadCommand",
".",
"extractTemperature",
",",
"DEVICE_CLASS_TEMPERATURE",
",",
"]",
",",
"[",
"\"Danfoss Air Remaining Filter\"",
",",
"PERCENTAGE",
",",
"ReadCommand",
".",
"filterPercent",
",",
"None",
",",
"]",
",",
"[",
"\"Danfoss Air Humidity\"",
",",
"PERCENTAGE",
",",
"ReadCommand",
".",
"humidity",
",",
"DEVICE_CLASS_HUMIDITY",
",",
"]",
",",
"[",
"\"Danfoss Air Fan Step\"",
",",
"PERCENTAGE",
",",
"ReadCommand",
".",
"fan_step",
",",
"None",
"]",
",",
"[",
"\"Danfoss Air Exhaust Fan Speed\"",
",",
"\"RPM\"",
",",
"ReadCommand",
".",
"exhaust_fan_speed",
",",
"None",
"]",
",",
"[",
"\"Danfoss Air Supply Fan Speed\"",
",",
"\"RPM\"",
",",
"ReadCommand",
".",
"supply_fan_speed",
",",
"None",
"]",
",",
"[",
"\"Danfoss Air Dial Battery\"",
",",
"PERCENTAGE",
",",
"ReadCommand",
".",
"battery_percent",
",",
"DEVICE_CLASS_BATTERY",
",",
"]",
",",
"]",
"dev",
"=",
"[",
"]",
"for",
"sensor",
"in",
"sensors",
":",
"dev",
".",
"append",
"(",
"DanfossAir",
"(",
"data",
",",
"sensor",
"[",
"0",
"]",
",",
"sensor",
"[",
"1",
"]",
",",
"sensor",
"[",
"2",
"]",
",",
"sensor",
"[",
"3",
"]",
")",
")",
"add_entities",
"(",
"dev",
",",
"True",
")"
] | [
19,
0
] | [
76,
27
] | python | en | ['en', 'su', 'en'] | True |
DanfossAir.__init__ | (self, data, name, sensor_unit, sensor_type, device_class) | Initialize the sensor. | Initialize the sensor. | def __init__(self, data, name, sensor_unit, sensor_type, device_class):
"""Initialize the sensor."""
self._data = data
self._name = name
self._state = None
self._type = sensor_type
self._unit = sensor_unit
self._device_class = device_class | [
"def",
"__init__",
"(",
"self",
",",
"data",
",",
"name",
",",
"sensor_unit",
",",
"sensor_type",
",",
"device_class",
")",
":",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"_state",
"=",
"None",
"self",
".",
"_type",
"=",
"sensor_type",
"self",
".",
"_unit",
"=",
"sensor_unit",
"self",
".",
"_device_class",
"=",
"device_class"
] | [
82,
4
] | [
89,
41
] | python | en | ['en', 'en', 'en'] | True |
DanfossAir.name | (self) | Return the name of the sensor. | Return the name of the sensor. | def name(self):
"""Return the name of the sensor."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
92,
4
] | [
94,
25
] | python | en | ['en', 'mi', 'en'] | True |
DanfossAir.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 self._device_class | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"self",
".",
"_device_class"
] | [
97,
4
] | [
99,
33
] | python | en | ['en', 'en', 'en'] | True |
DanfossAir.state | (self) | Return the state of the sensor. | Return the state of the sensor. | def state(self):
"""Return the state of the sensor."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
102,
4
] | [
104,
26
] | python | en | ['en', 'en', 'en'] | True |
DanfossAir.unit_of_measurement | (self) | Return the unit of measurement. | Return the unit of measurement. | def unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit"
] | [
107,
4
] | [
109,
25
] | python | en | ['en', 'la', 'en'] | True |
DanfossAir.update | (self) | Update the new state of the sensor.
This is done through the DanfossAir object that does the actual
communication with the Air CCM.
| Update the new state of the sensor. | def update(self):
"""Update the new state of the sensor.
This is done through the DanfossAir object that does the actual
communication with the Air CCM.
"""
self._data.update()
self._state = self._data.get_value(self._type)
if self._state is None:
_LOGGER.debug("Could not get data for %s", self._type) | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_data",
".",
"update",
"(",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_data",
".",
"get_value",
"(",
"self",
".",
"_type",
")",
"if",
"self",
".",
"_state",
"is",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Could not get data for %s\"",
",",
"self",
".",
"_type",
")"
] | [
111,
4
] | [
121,
66
] | python | en | ['en', 'en', 'en'] | True |
MaIlpAgent.__init__ | (
self, ilp: CitiBikeILP, num_station: int, num_time_interval: int, ticks_per_interval: int, ma_window_size: int
) | An agent that make decisions by ILP in Citi Bike scenario.
Args:
ilp (CitiBikeILP): The ILP instance.
num_station (int): The number of stations in the target environment.
num_time_interval (int): The number of time intervals for which the agent need to provide future demand and
supply for the ILP. Also, the time interval in the agent indicates the number of environment ticks
between two decision points in the ILP.
ticks_per_interval (int): How many environment ticks in each time interval. It is same to the number of
ticks between two decision points in the ILP.
ma_window_size (int): The historical data maintain window size of the Moving Average Forecaster.
| An agent that make decisions by ILP in Citi Bike scenario. | def __init__(
self, ilp: CitiBikeILP, num_station: int, num_time_interval: int, ticks_per_interval: int, ma_window_size: int
):
"""An agent that make decisions by ILP in Citi Bike scenario.
Args:
ilp (CitiBikeILP): The ILP instance.
num_station (int): The number of stations in the target environment.
num_time_interval (int): The number of time intervals for which the agent need to provide future demand and
supply for the ILP. Also, the time interval in the agent indicates the number of environment ticks
between two decision points in the ILP.
ticks_per_interval (int): How many environment ticks in each time interval. It is same to the number of
ticks between two decision points in the ILP.
ma_window_size (int): The historical data maintain window size of the Moving Average Forecaster.
"""
self._ilp = ilp
self._num_station = num_station
self._num_time_interval = num_time_interval
self._ticks_per_interval = ticks_per_interval
if not PEEP_AND_USE_REAL_DATA:
self._demand_forecaster = [Forecaster(window_size=ma_window_size) for _ in range(self._num_station)]
self._supply_forecaster = [Forecaster(window_size=ma_window_size) for _ in range(self._num_station)]
self._num_recorded_interval = 0
self._next_event_idx = 0 | [
"def",
"__init__",
"(",
"self",
",",
"ilp",
":",
"CitiBikeILP",
",",
"num_station",
":",
"int",
",",
"num_time_interval",
":",
"int",
",",
"ticks_per_interval",
":",
"int",
",",
"ma_window_size",
":",
"int",
")",
":",
"self",
".",
"_ilp",
"=",
"ilp",
"self",
".",
"_num_station",
"=",
"num_station",
"self",
".",
"_num_time_interval",
"=",
"num_time_interval",
"self",
".",
"_ticks_per_interval",
"=",
"ticks_per_interval",
"if",
"not",
"PEEP_AND_USE_REAL_DATA",
":",
"self",
".",
"_demand_forecaster",
"=",
"[",
"Forecaster",
"(",
"window_size",
"=",
"ma_window_size",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_num_station",
")",
"]",
"self",
".",
"_supply_forecaster",
"=",
"[",
"Forecaster",
"(",
"window_size",
"=",
"ma_window_size",
")",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"_num_station",
")",
"]",
"self",
".",
"_num_recorded_interval",
"=",
"0",
"self",
".",
"_next_event_idx",
"=",
"0"
] | [
25,
4
] | [
48,
36
] | python | en | ['en', 'en', 'en'] | True |
MaIlpAgent._record_history | (self, env_tick: int, finished_events: List[Event]) |
Args:
env_tick (int): The current Env tick.
finished_events (List[Event]): The finished events got from the Env.
|
Args:
env_tick (int): The current Env tick.
finished_events (List[Event]): The finished events got from the Env.
| def _record_history(self, env_tick: int, finished_events: List[Event]):
"""
Args:
env_tick (int): The current Env tick.
finished_events (List[Event]): The finished events got from the Env.
"""
num_interval_to_record = (env_tick - 1) // self._ticks_per_interval - self._num_recorded_interval
if num_interval_to_record <= 0:
return
demand_history = np.zeros((num_interval_to_record, self._num_station), dtype=np.int16)
supply_history = np.zeros((num_interval_to_record, self._num_station), dtype=np.int16)
while self._next_event_idx < len(finished_events):
# Calculate the interval index of this finished event.
interval_idx = (
finished_events[self._next_event_idx].tick // self._ticks_per_interval - self._num_recorded_interval
)
assert interval_idx >= 0, "The finished events are not sorted by tick!"
if interval_idx >= num_interval_to_record:
break
# Check the event_type to get the historical demand and supply.
event_type = finished_events[self._next_event_idx].event_type
if event_type == CitiBikeEvents.RequireBike:
# TODO: Replace it with a pre-defined PayLoad.
payload = finished_events[self._next_event_idx].payload
demand_history[interval_idx, payload.src_station] += 1
elif event_type == CitiBikeEvents.ReturnBike:
payload: BikeReturnPayload = finished_events[self._next_event_idx].payload
supply_history[interval_idx, payload.to_station_idx] += payload.number
# Update the index to the finished event that has not been processed.
self._next_event_idx += 1
self._num_recorded_interval += num_interval_to_record
# Record to the forecasters.
for i in range(self._num_station):
self._demand_forecaster[i].record(demand_history[:, i])
self._supply_forecaster[i].record(supply_history[:, i]) | [
"def",
"_record_history",
"(",
"self",
",",
"env_tick",
":",
"int",
",",
"finished_events",
":",
"List",
"[",
"Event",
"]",
")",
":",
"num_interval_to_record",
"=",
"(",
"env_tick",
"-",
"1",
")",
"//",
"self",
".",
"_ticks_per_interval",
"-",
"self",
".",
"_num_recorded_interval",
"if",
"num_interval_to_record",
"<=",
"0",
":",
"return",
"demand_history",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_interval_to_record",
",",
"self",
".",
"_num_station",
")",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
"supply_history",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_interval_to_record",
",",
"self",
".",
"_num_station",
")",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
"while",
"self",
".",
"_next_event_idx",
"<",
"len",
"(",
"finished_events",
")",
":",
"# Calculate the interval index of this finished event.",
"interval_idx",
"=",
"(",
"finished_events",
"[",
"self",
".",
"_next_event_idx",
"]",
".",
"tick",
"//",
"self",
".",
"_ticks_per_interval",
"-",
"self",
".",
"_num_recorded_interval",
")",
"assert",
"interval_idx",
">=",
"0",
",",
"\"The finished events are not sorted by tick!\"",
"if",
"interval_idx",
">=",
"num_interval_to_record",
":",
"break",
"# Check the event_type to get the historical demand and supply.",
"event_type",
"=",
"finished_events",
"[",
"self",
".",
"_next_event_idx",
"]",
".",
"event_type",
"if",
"event_type",
"==",
"CitiBikeEvents",
".",
"RequireBike",
":",
"# TODO: Replace it with a pre-defined PayLoad.",
"payload",
"=",
"finished_events",
"[",
"self",
".",
"_next_event_idx",
"]",
".",
"payload",
"demand_history",
"[",
"interval_idx",
",",
"payload",
".",
"src_station",
"]",
"+=",
"1",
"elif",
"event_type",
"==",
"CitiBikeEvents",
".",
"ReturnBike",
":",
"payload",
":",
"BikeReturnPayload",
"=",
"finished_events",
"[",
"self",
".",
"_next_event_idx",
"]",
".",
"payload",
"supply_history",
"[",
"interval_idx",
",",
"payload",
".",
"to_station_idx",
"]",
"+=",
"payload",
".",
"number",
"# Update the index to the finished event that has not been processed.",
"self",
".",
"_next_event_idx",
"+=",
"1",
"self",
".",
"_num_recorded_interval",
"+=",
"num_interval_to_record",
"# Record to the forecasters.",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_num_station",
")",
":",
"self",
".",
"_demand_forecaster",
"[",
"i",
"]",
".",
"record",
"(",
"demand_history",
"[",
":",
",",
"i",
"]",
")",
"self",
".",
"_supply_forecaster",
"[",
"i",
"]",
".",
"record",
"(",
"supply_history",
"[",
":",
",",
"i",
"]",
")"
] | [
52,
4
] | [
91,
67
] | python | en | ['en', 'error', 'th'] | False |
MaIlpAgent._forecast_demand_and_supply | (self) |
Returns:
Tuple[np.ndarray, np.ndarray]:
The first item indicates the forecasting demand for each station in each time interval,
with shape: (num_time_interval, num_station).
The second item indicates the forecasting supply for each station in each time interval,
with shape: (num_time_interval, num_station).
|
Returns:
Tuple[np.ndarray, np.ndarray]:
The first item indicates the forecasting demand for each station in each time interval,
with shape: (num_time_interval, num_station).
The second item indicates the forecasting supply for each station in each time interval,
with shape: (num_time_interval, num_station).
| def _forecast_demand_and_supply(self) -> Tuple[np.ndarray, np.ndarray]:
"""
Returns:
Tuple[np.ndarray, np.ndarray]:
The first item indicates the forecasting demand for each station in each time interval,
with shape: (num_time_interval, num_station).
The second item indicates the forecasting supply for each station in each time interval,
with shape: (num_time_interval, num_station).
"""
demand = np.array(
[round(self._demand_forecaster[i].forecast()) for i in range(self._num_station)],
dtype=np.int16
).reshape((1, -1)).repeat(self._num_time_interval, axis=0)
supply = np.array(
[round(self._supply_forecaster[i].forecast()) for i in range(self._num_station)],
dtype=np.int16
).reshape((1, -1)).repeat(self._num_time_interval, axis=0)
return demand, supply | [
"def",
"_forecast_demand_and_supply",
"(",
"self",
")",
"->",
"Tuple",
"[",
"np",
".",
"ndarray",
",",
"np",
".",
"ndarray",
"]",
":",
"demand",
"=",
"np",
".",
"array",
"(",
"[",
"round",
"(",
"self",
".",
"_demand_forecaster",
"[",
"i",
"]",
".",
"forecast",
"(",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_num_station",
")",
"]",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
".",
"reshape",
"(",
"(",
"1",
",",
"-",
"1",
")",
")",
".",
"repeat",
"(",
"self",
".",
"_num_time_interval",
",",
"axis",
"=",
"0",
")",
"supply",
"=",
"np",
".",
"array",
"(",
"[",
"round",
"(",
"self",
".",
"_supply_forecaster",
"[",
"i",
"]",
".",
"forecast",
"(",
")",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_num_station",
")",
"]",
",",
"dtype",
"=",
"np",
".",
"int16",
")",
".",
"reshape",
"(",
"(",
"1",
",",
"-",
"1",
")",
")",
".",
"repeat",
"(",
"self",
".",
"_num_time_interval",
",",
"axis",
"=",
"0",
")",
"return",
"demand",
",",
"supply"
] | [
93,
4
] | [
112,
29
] | python | en | ['en', 'error', 'th'] | False |
test_show_set_form | (hass) | Test that the setup form is served. | Test that the setup form is served. | async def test_show_set_form(hass):
"""Test that the setup form is served."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=None
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user" | [
"async",
"def",
"test_show_set_form",
"(",
"hass",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"None",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\""
] | [
34,
0
] | [
41,
38
] | python | en | ['en', 'en', 'en'] | True |
test_urlize_plain_host | (hass, requests_mock) | Test that plain host or IP gets converted to a URL. | Test that plain host or IP gets converted to a URL. | async def test_urlize_plain_host(hass, requests_mock):
"""Test that plain host or IP gets converted to a URL."""
requests_mock.request(ANY, ANY, exc=ConnectionError())
host = "192.168.100.1"
user_input = {**FIXTURE_USER_INPUT, CONF_URL: host}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=user_input
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
assert user_input[CONF_URL] == f"http://{host}/" | [
"async",
"def",
"test_urlize_plain_host",
"(",
"hass",
",",
"requests_mock",
")",
":",
"requests_mock",
".",
"request",
"(",
"ANY",
",",
"ANY",
",",
"exc",
"=",
"ConnectionError",
"(",
")",
")",
"host",
"=",
"\"192.168.100.1\"",
"user_input",
"=",
"{",
"*",
"*",
"FIXTURE_USER_INPUT",
",",
"CONF_URL",
":",
"host",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"user_input",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"user_input",
"[",
"CONF_URL",
"]",
"==",
"f\"http://{host}/\""
] | [
44,
0
] | [
55,
52
] | python | en | ['en', 'en', 'en'] | True |
test_already_configured | (hass) | Test we reject already configured devices. | Test we reject already configured devices. | async def test_already_configured(hass):
"""Test we reject already configured devices."""
MockConfigEntry(
domain=DOMAIN, data=FIXTURE_USER_INPUT, title="Already configured"
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={
**FIXTURE_USER_INPUT,
# Tweak URL a bit to check that doesn't fail duplicate detection
CONF_URL: FIXTURE_USER_INPUT[CONF_URL].replace("http", "HTTP"),
},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "already_configured" | [
"async",
"def",
"test_already_configured",
"(",
"hass",
")",
":",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"data",
"=",
"FIXTURE_USER_INPUT",
",",
"title",
"=",
"\"Already configured\"",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"{",
"*",
"*",
"FIXTURE_USER_INPUT",
",",
"# Tweak URL a bit to check that doesn't fail duplicate detection",
"CONF_URL",
":",
"FIXTURE_USER_INPUT",
"[",
"CONF_URL",
"]",
".",
"replace",
"(",
"\"http\"",
",",
"\"HTTP\"",
")",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_ABORT",
"assert",
"result",
"[",
"\"reason\"",
"]",
"==",
"\"already_configured\""
] | [
58,
0
] | [
75,
51
] | python | en | ['en', 'en', 'en'] | True |
test_connection_error | (hass, requests_mock) | Test we show user form on connection error. | Test we show user form on connection error. | async def test_connection_error(hass, requests_mock):
"""Test we show user form on connection error."""
requests_mock.request(ANY, ANY, exc=ConnectionError())
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=FIXTURE_USER_INPUT
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
assert result["errors"] == {CONF_URL: "unknown"} | [
"async",
"def",
"test_connection_error",
"(",
"hass",
",",
"requests_mock",
")",
":",
"requests_mock",
".",
"request",
"(",
"ANY",
",",
"ANY",
",",
"exc",
"=",
"ConnectionError",
"(",
")",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"FIXTURE_USER_INPUT",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"CONF_URL",
":",
"\"unknown\"",
"}"
] | [
78,
0
] | [
87,
52
] | python | en | ['en', 'en', 'en'] | True |
login_requests_mock | (requests_mock) | Set up a requests_mock with base mocks for login tests. | Set up a requests_mock with base mocks for login tests. | def login_requests_mock(requests_mock):
"""Set up a requests_mock with base mocks for login tests."""
requests_mock.request(
ANY, FIXTURE_USER_INPUT[CONF_URL], text='<meta name="csrf_token" content="x"/>'
)
requests_mock.request(
ANY,
f"{FIXTURE_USER_INPUT[CONF_URL]}api/user/state-login",
text=(
f"<response><State>{LoginStateEnum.LOGGED_OUT}</State>"
f"<password_type>{PasswordTypeEnum.SHA256}</password_type></response>"
),
)
return requests_mock | [
"def",
"login_requests_mock",
"(",
"requests_mock",
")",
":",
"requests_mock",
".",
"request",
"(",
"ANY",
",",
"FIXTURE_USER_INPUT",
"[",
"CONF_URL",
"]",
",",
"text",
"=",
"'<meta name=\"csrf_token\" content=\"x\"/>'",
")",
"requests_mock",
".",
"request",
"(",
"ANY",
",",
"f\"{FIXTURE_USER_INPUT[CONF_URL]}api/user/state-login\"",
",",
"text",
"=",
"(",
"f\"<response><State>{LoginStateEnum.LOGGED_OUT}</State>\"",
"f\"<password_type>{PasswordTypeEnum.SHA256}</password_type></response>\"",
")",
",",
")",
"return",
"requests_mock"
] | [
91,
0
] | [
104,
24
] | python | en | ['en', 'da', 'en'] | True |
test_login_error | (hass, login_requests_mock, code, errors) | Test we show user form with appropriate error on response failure. | Test we show user form with appropriate error on response failure. | async def test_login_error(hass, login_requests_mock, code, errors):
"""Test we show user form with appropriate error on response failure."""
login_requests_mock.request(
ANY,
f"{FIXTURE_USER_INPUT[CONF_URL]}api/user/login",
text=f"<error><code>{code}</code><message/></error>",
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}, data=FIXTURE_USER_INPUT
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
assert result["errors"] == errors | [
"async",
"def",
"test_login_error",
"(",
"hass",
",",
"login_requests_mock",
",",
"code",
",",
"errors",
")",
":",
"login_requests_mock",
".",
"request",
"(",
"ANY",
",",
"f\"{FIXTURE_USER_INPUT[CONF_URL]}api/user/login\"",
",",
"text",
"=",
"f\"<error><code>{code}</code><message/></error>\"",
",",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"FIXTURE_USER_INPUT",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"errors"
] | [
120,
0
] | [
133,
37
] | python | en | ['en', 'en', 'en'] | True |
test_success | (hass, login_requests_mock) | Test successful flow provides entry creation data. | Test successful flow provides entry creation data. | async def test_success(hass, login_requests_mock):
"""Test successful flow provides entry creation data."""
login_requests_mock.request(
ANY,
f"{FIXTURE_USER_INPUT[CONF_URL]}api/user/login",
text="<response>OK</response>",
)
with patch("homeassistant.components.huawei_lte.async_setup"), patch(
"homeassistant.components.huawei_lte.async_setup_entry"
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data=FIXTURE_USER_INPUT,
)
await hass.async_block_till_done()
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert result["data"][CONF_URL] == FIXTURE_USER_INPUT[CONF_URL]
assert result["data"][CONF_USERNAME] == FIXTURE_USER_INPUT[CONF_USERNAME]
assert result["data"][CONF_PASSWORD] == FIXTURE_USER_INPUT[CONF_PASSWORD] | [
"async",
"def",
"test_success",
"(",
"hass",
",",
"login_requests_mock",
")",
":",
"login_requests_mock",
".",
"request",
"(",
"ANY",
",",
"f\"{FIXTURE_USER_INPUT[CONF_URL]}api/user/login\"",
",",
"text",
"=",
"\"<response>OK</response>\"",
",",
")",
"with",
"patch",
"(",
"\"homeassistant.components.huawei_lte.async_setup\"",
")",
",",
"patch",
"(",
"\"homeassistant.components.huawei_lte.async_setup_entry\"",
")",
":",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_USER",
"}",
",",
"data",
"=",
"FIXTURE_USER_INPUT",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_CREATE_ENTRY",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_URL",
"]",
"==",
"FIXTURE_USER_INPUT",
"[",
"CONF_URL",
"]",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_USERNAME",
"]",
"==",
"FIXTURE_USER_INPUT",
"[",
"CONF_USERNAME",
"]",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_PASSWORD",
"]",
"==",
"FIXTURE_USER_INPUT",
"[",
"CONF_PASSWORD",
"]"
] | [
136,
0
] | [
156,
77
] | python | en | ['en', 'en', 'en'] | True |
test_ssdp | (hass) | Test SSDP discovery initiates config properly. | Test SSDP discovery initiates config properly. | async def test_ssdp(hass):
"""Test SSDP discovery initiates config properly."""
url = "http://192.168.100.1/"
context = {"source": config_entries.SOURCE_SSDP}
result = await hass.config_entries.flow.async_init(
DOMAIN,
context=context,
data={
ssdp.ATTR_SSDP_LOCATION: "http://192.168.100.1:60957/rootDesc.xml",
ssdp.ATTR_SSDP_ST: "upnp:rootdevice",
ssdp.ATTR_UPNP_DEVICE_TYPE: "urn:schemas-upnp-org:device:InternetGatewayDevice:1",
ssdp.ATTR_UPNP_FRIENDLY_NAME: "Mobile Wi-Fi",
ssdp.ATTR_UPNP_MANUFACTURER: "Huawei",
ssdp.ATTR_UPNP_MANUFACTURER_URL: "http://www.huawei.com/",
ssdp.ATTR_UPNP_MODEL_NAME: "Huawei router",
ssdp.ATTR_UPNP_MODEL_NUMBER: "12345678",
ssdp.ATTR_UPNP_PRESENTATION_URL: url,
ssdp.ATTR_UPNP_SERIAL: "00000000",
ssdp.ATTR_UPNP_UDN: "uuid:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "user"
assert context[CONF_URL] == url | [
"async",
"def",
"test_ssdp",
"(",
"hass",
")",
":",
"url",
"=",
"\"http://192.168.100.1/\"",
"context",
"=",
"{",
"\"source\"",
":",
"config_entries",
".",
"SOURCE_SSDP",
"}",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"context",
",",
"data",
"=",
"{",
"ssdp",
".",
"ATTR_SSDP_LOCATION",
":",
"\"http://192.168.100.1:60957/rootDesc.xml\"",
",",
"ssdp",
".",
"ATTR_SSDP_ST",
":",
"\"upnp:rootdevice\"",
",",
"ssdp",
".",
"ATTR_UPNP_DEVICE_TYPE",
":",
"\"urn:schemas-upnp-org:device:InternetGatewayDevice:1\"",
",",
"ssdp",
".",
"ATTR_UPNP_FRIENDLY_NAME",
":",
"\"Mobile Wi-Fi\"",
",",
"ssdp",
".",
"ATTR_UPNP_MANUFACTURER",
":",
"\"Huawei\"",
",",
"ssdp",
".",
"ATTR_UPNP_MANUFACTURER_URL",
":",
"\"http://www.huawei.com/\"",
",",
"ssdp",
".",
"ATTR_UPNP_MODEL_NAME",
":",
"\"Huawei router\"",
",",
"ssdp",
".",
"ATTR_UPNP_MODEL_NUMBER",
":",
"\"12345678\"",
",",
"ssdp",
".",
"ATTR_UPNP_PRESENTATION_URL",
":",
"url",
",",
"ssdp",
".",
"ATTR_UPNP_SERIAL",
":",
"\"00000000\"",
",",
"ssdp",
".",
"ATTR_UPNP_UDN",
":",
"\"uuid:XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\"",
",",
"}",
",",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"context",
"[",
"CONF_URL",
"]",
"==",
"url"
] | [
159,
0
] | [
183,
35
] | python | en | ['en', 'en', 'en'] | True |
test_options | (hass) | Test options produce expected data. | Test options produce expected data. | async def test_options(hass):
"""Test options produce expected data."""
config_entry = MockConfigEntry(
domain=DOMAIN, data=FIXTURE_USER_INPUT, options=FIXTURE_USER_INPUT_OPTIONS
)
config_entry.add_to_hass(hass)
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "init"
recipient = "+15555550000"
result = await hass.config_entries.options.async_configure(
result["flow_id"], user_input={CONF_RECIPIENT: recipient}
)
assert result["data"][CONF_NAME] == DOMAIN
assert result["data"][CONF_RECIPIENT] == [recipient] | [
"async",
"def",
"test_options",
"(",
"hass",
")",
":",
"config_entry",
"=",
"MockConfigEntry",
"(",
"domain",
"=",
"DOMAIN",
",",
"data",
"=",
"FIXTURE_USER_INPUT",
",",
"options",
"=",
"FIXTURE_USER_INPUT_OPTIONS",
")",
"config_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"options",
".",
"async_init",
"(",
"config_entry",
".",
"entry_id",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"data_entry_flow",
".",
"RESULT_TYPE_FORM",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"init\"",
"recipient",
"=",
"\"+15555550000\"",
"result",
"=",
"await",
"hass",
".",
"config_entries",
".",
"options",
".",
"async_configure",
"(",
"result",
"[",
"\"flow_id\"",
"]",
",",
"user_input",
"=",
"{",
"CONF_RECIPIENT",
":",
"recipient",
"}",
")",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_NAME",
"]",
"==",
"DOMAIN",
"assert",
"result",
"[",
"\"data\"",
"]",
"[",
"CONF_RECIPIENT",
"]",
"==",
"[",
"recipient",
"]"
] | [
186,
0
] | [
203,
56
] | python | en | ['en', 'en', 'en'] | True |
log_entry | (hass, name, message, domain=None, entity_id=None, context=None) | Add an entry to the logbook. | Add an entry to the logbook. | def log_entry(hass, name, message, domain=None, entity_id=None, context=None):
"""Add an entry to the logbook."""
hass.add_job(async_log_entry, hass, name, message, domain, entity_id, context) | [
"def",
"log_entry",
"(",
"hass",
",",
"name",
",",
"message",
",",
"domain",
"=",
"None",
",",
"entity_id",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"hass",
".",
"add_job",
"(",
"async_log_entry",
",",
"hass",
",",
"name",
",",
"message",
",",
"domain",
",",
"entity_id",
",",
"context",
")"
] | [
110,
0
] | [
112,
82
] | python | en | ['en', 'en', 'en'] | True |
async_log_entry | (hass, name, message, domain=None, entity_id=None, context=None) | Add an entry to the logbook. | Add an entry to the logbook. | def async_log_entry(hass, name, message, domain=None, entity_id=None, context=None):
"""Add an entry to the logbook."""
data = {ATTR_NAME: name, ATTR_MESSAGE: message}
if domain is not None:
data[ATTR_DOMAIN] = domain
if entity_id is not None:
data[ATTR_ENTITY_ID] = entity_id
hass.bus.async_fire(EVENT_LOGBOOK_ENTRY, data, context=context) | [
"def",
"async_log_entry",
"(",
"hass",
",",
"name",
",",
"message",
",",
"domain",
"=",
"None",
",",
"entity_id",
"=",
"None",
",",
"context",
"=",
"None",
")",
":",
"data",
"=",
"{",
"ATTR_NAME",
":",
"name",
",",
"ATTR_MESSAGE",
":",
"message",
"}",
"if",
"domain",
"is",
"not",
"None",
":",
"data",
"[",
"ATTR_DOMAIN",
"]",
"=",
"domain",
"if",
"entity_id",
"is",
"not",
"None",
":",
"data",
"[",
"ATTR_ENTITY_ID",
"]",
"=",
"entity_id",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_LOGBOOK_ENTRY",
",",
"data",
",",
"context",
"=",
"context",
")"
] | [
116,
0
] | [
124,
67
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Logbook setup. | Logbook setup. | async def async_setup(hass, config):
"""Logbook setup."""
hass.data[DOMAIN] = {}
@callback
def log_message(service):
"""Handle sending notification message service calls."""
message = service.data[ATTR_MESSAGE]
name = service.data[ATTR_NAME]
domain = service.data.get(ATTR_DOMAIN)
entity_id = service.data.get(ATTR_ENTITY_ID)
if entity_id is None and domain is None:
# If there is no entity_id or
# domain, the event will get filtered
# away so we use the "logbook" domain
domain = DOMAIN
message.hass = hass
message = message.async_render(parse_result=False)
async_log_entry(hass, name, message, domain, entity_id)
hass.components.frontend.async_register_built_in_panel(
"logbook", "logbook", "hass:format-list-bulleted-type"
)
conf = config.get(DOMAIN, {})
if conf:
filters = sqlalchemy_filter_from_include_exclude_conf(conf)
entities_filter = convert_include_exclude_filter(conf)
else:
filters = None
entities_filter = None
hass.http.register_view(LogbookView(conf, filters, entities_filter))
hass.services.async_register(DOMAIN, "log", log_message, schema=LOG_MESSAGE_SCHEMA)
await async_process_integration_platforms(hass, DOMAIN, _process_logbook_platform)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"}",
"@",
"callback",
"def",
"log_message",
"(",
"service",
")",
":",
"\"\"\"Handle sending notification message service calls.\"\"\"",
"message",
"=",
"service",
".",
"data",
"[",
"ATTR_MESSAGE",
"]",
"name",
"=",
"service",
".",
"data",
"[",
"ATTR_NAME",
"]",
"domain",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_DOMAIN",
")",
"entity_id",
"=",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ENTITY_ID",
")",
"if",
"entity_id",
"is",
"None",
"and",
"domain",
"is",
"None",
":",
"# If there is no entity_id or",
"# domain, the event will get filtered",
"# away so we use the \"logbook\" domain",
"domain",
"=",
"DOMAIN",
"message",
".",
"hass",
"=",
"hass",
"message",
"=",
"message",
".",
"async_render",
"(",
"parse_result",
"=",
"False",
")",
"async_log_entry",
"(",
"hass",
",",
"name",
",",
"message",
",",
"domain",
",",
"entity_id",
")",
"hass",
".",
"components",
".",
"frontend",
".",
"async_register_built_in_panel",
"(",
"\"logbook\"",
",",
"\"logbook\"",
",",
"\"hass:format-list-bulleted-type\"",
")",
"conf",
"=",
"config",
".",
"get",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"if",
"conf",
":",
"filters",
"=",
"sqlalchemy_filter_from_include_exclude_conf",
"(",
"conf",
")",
"entities_filter",
"=",
"convert_include_exclude_filter",
"(",
"conf",
")",
"else",
":",
"filters",
"=",
"None",
"entities_filter",
"=",
"None",
"hass",
".",
"http",
".",
"register_view",
"(",
"LogbookView",
"(",
"conf",
",",
"filters",
",",
"entities_filter",
")",
")",
"hass",
".",
"services",
".",
"async_register",
"(",
"DOMAIN",
",",
"\"log\"",
",",
"log_message",
",",
"schema",
"=",
"LOG_MESSAGE_SCHEMA",
")",
"await",
"async_process_integration_platforms",
"(",
"hass",
",",
"DOMAIN",
",",
"_process_logbook_platform",
")",
"return",
"True"
] | [
127,
0
] | [
168,
15
] | python | en | ['en', 'bs', 'en'] | False |
_process_logbook_platform | (hass, domain, platform) | Process a logbook platform. | Process a logbook platform. | async def _process_logbook_platform(hass, domain, platform):
"""Process a logbook platform."""
@callback
def _async_describe_event(domain, event_name, describe_callback):
"""Teach logbook how to describe a new event."""
hass.data[DOMAIN][event_name] = (domain, describe_callback)
platform.async_describe_events(hass, _async_describe_event) | [
"async",
"def",
"_process_logbook_platform",
"(",
"hass",
",",
"domain",
",",
"platform",
")",
":",
"@",
"callback",
"def",
"_async_describe_event",
"(",
"domain",
",",
"event_name",
",",
"describe_callback",
")",
":",
"\"\"\"Teach logbook how to describe a new event.\"\"\"",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"event_name",
"]",
"=",
"(",
"domain",
",",
"describe_callback",
")",
"platform",
".",
"async_describe_events",
"(",
"hass",
",",
"_async_describe_event",
")"
] | [
171,
0
] | [
179,
63
] | python | en | ['en', 'lv', 'en'] | True |
humanify | (hass, events, entity_attr_cache, context_lookup) | Generate a converted list of events into Entry objects.
Will try to group events if possible:
- if 2+ sensor updates in GROUP_BY_MINUTES, show last
- if Home Assistant stop and start happen in same minute call it restarted
| Generate a converted list of events into Entry objects. | def humanify(hass, events, entity_attr_cache, context_lookup):
"""Generate a converted list of events into Entry objects.
Will try to group events if possible:
- if 2+ sensor updates in GROUP_BY_MINUTES, show last
- if Home Assistant stop and start happen in same minute call it restarted
"""
external_events = hass.data.get(DOMAIN, {})
# Group events in batches of GROUP_BY_MINUTES
for _, g_events in groupby(
events, lambda event: event.time_fired_minute // GROUP_BY_MINUTES
):
events_batch = list(g_events)
# Keep track of last sensor states
last_sensor_event = {}
# Group HA start/stop events
# Maps minute of event to 1: stop, 2: stop + start
start_stop_events = {}
# Process events
for event in events_batch:
if event.event_type == EVENT_STATE_CHANGED:
if event.domain in CONTINUOUS_DOMAINS:
last_sensor_event[event.entity_id] = event
elif event.event_type == EVENT_HOMEASSISTANT_STOP:
if event.time_fired_minute in start_stop_events:
continue
start_stop_events[event.time_fired_minute] = 1
elif event.event_type == EVENT_HOMEASSISTANT_START:
if event.time_fired_minute not in start_stop_events:
continue
start_stop_events[event.time_fired_minute] = 2
# Yield entries
for event in events_batch:
if event.event_type == EVENT_STATE_CHANGED:
entity_id = event.entity_id
domain = event.domain
if (
domain in CONTINUOUS_DOMAINS
and event != last_sensor_event[entity_id]
):
# Skip all but the last sensor state
continue
data = {
"when": event.time_fired_isoformat,
"name": _entity_name_from_event(
entity_id, event, entity_attr_cache
),
"state": event.state,
"entity_id": entity_id,
}
icon = event.attributes_icon
if icon:
data["icon"] = icon
if event.context_user_id:
data["context_user_id"] = event.context_user_id
context_event = context_lookup.get(event.context_id)
if context_event and context_event != event:
_augment_data_with_context(
data,
entity_id,
event,
context_event,
entity_attr_cache,
external_events,
)
yield data
elif event.event_type in external_events:
domain, describe_event = external_events[event.event_type]
data = describe_event(event)
data["when"] = event.time_fired_isoformat
data["domain"] = domain
if event.context_user_id:
data["context_user_id"] = event.context_user_id
context_event = context_lookup.get(event.context_id)
if context_event:
_augment_data_with_context(
data,
data.get(ATTR_ENTITY_ID),
event,
context_event,
entity_attr_cache,
external_events,
)
yield data
elif event.event_type == EVENT_HOMEASSISTANT_START:
if start_stop_events.get(event.time_fired_minute) == 2:
continue
yield {
"when": event.time_fired_isoformat,
"name": "Home Assistant",
"message": "started",
"domain": HA_DOMAIN,
}
elif event.event_type == EVENT_HOMEASSISTANT_STOP:
if start_stop_events.get(event.time_fired_minute) == 2:
action = "restarted"
else:
action = "stopped"
yield {
"when": event.time_fired_isoformat,
"name": "Home Assistant",
"message": action,
"domain": HA_DOMAIN,
}
elif event.event_type == EVENT_LOGBOOK_ENTRY:
event_data = event.data
domain = event_data.get(ATTR_DOMAIN)
entity_id = event_data.get(ATTR_ENTITY_ID)
if domain is None and entity_id is not None:
try:
domain = split_entity_id(str(entity_id))[0]
except IndexError:
pass
data = {
"when": event.time_fired_isoformat,
"name": event_data.get(ATTR_NAME),
"message": event_data.get(ATTR_MESSAGE),
"domain": domain,
"entity_id": entity_id,
}
if event.context_user_id:
data["context_user_id"] = event.context_user_id
context_event = context_lookup.get(event.context_id)
if context_event and context_event != event:
_augment_data_with_context(
data,
entity_id,
event,
context_event,
entity_attr_cache,
external_events,
)
yield data | [
"def",
"humanify",
"(",
"hass",
",",
"events",
",",
"entity_attr_cache",
",",
"context_lookup",
")",
":",
"external_events",
"=",
"hass",
".",
"data",
".",
"get",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"# Group events in batches of GROUP_BY_MINUTES",
"for",
"_",
",",
"g_events",
"in",
"groupby",
"(",
"events",
",",
"lambda",
"event",
":",
"event",
".",
"time_fired_minute",
"//",
"GROUP_BY_MINUTES",
")",
":",
"events_batch",
"=",
"list",
"(",
"g_events",
")",
"# Keep track of last sensor states",
"last_sensor_event",
"=",
"{",
"}",
"# Group HA start/stop events",
"# Maps minute of event to 1: stop, 2: stop + start",
"start_stop_events",
"=",
"{",
"}",
"# Process events",
"for",
"event",
"in",
"events_batch",
":",
"if",
"event",
".",
"event_type",
"==",
"EVENT_STATE_CHANGED",
":",
"if",
"event",
".",
"domain",
"in",
"CONTINUOUS_DOMAINS",
":",
"last_sensor_event",
"[",
"event",
".",
"entity_id",
"]",
"=",
"event",
"elif",
"event",
".",
"event_type",
"==",
"EVENT_HOMEASSISTANT_STOP",
":",
"if",
"event",
".",
"time_fired_minute",
"in",
"start_stop_events",
":",
"continue",
"start_stop_events",
"[",
"event",
".",
"time_fired_minute",
"]",
"=",
"1",
"elif",
"event",
".",
"event_type",
"==",
"EVENT_HOMEASSISTANT_START",
":",
"if",
"event",
".",
"time_fired_minute",
"not",
"in",
"start_stop_events",
":",
"continue",
"start_stop_events",
"[",
"event",
".",
"time_fired_minute",
"]",
"=",
"2",
"# Yield entries",
"for",
"event",
"in",
"events_batch",
":",
"if",
"event",
".",
"event_type",
"==",
"EVENT_STATE_CHANGED",
":",
"entity_id",
"=",
"event",
".",
"entity_id",
"domain",
"=",
"event",
".",
"domain",
"if",
"(",
"domain",
"in",
"CONTINUOUS_DOMAINS",
"and",
"event",
"!=",
"last_sensor_event",
"[",
"entity_id",
"]",
")",
":",
"# Skip all but the last sensor state",
"continue",
"data",
"=",
"{",
"\"when\"",
":",
"event",
".",
"time_fired_isoformat",
",",
"\"name\"",
":",
"_entity_name_from_event",
"(",
"entity_id",
",",
"event",
",",
"entity_attr_cache",
")",
",",
"\"state\"",
":",
"event",
".",
"state",
",",
"\"entity_id\"",
":",
"entity_id",
",",
"}",
"icon",
"=",
"event",
".",
"attributes_icon",
"if",
"icon",
":",
"data",
"[",
"\"icon\"",
"]",
"=",
"icon",
"if",
"event",
".",
"context_user_id",
":",
"data",
"[",
"\"context_user_id\"",
"]",
"=",
"event",
".",
"context_user_id",
"context_event",
"=",
"context_lookup",
".",
"get",
"(",
"event",
".",
"context_id",
")",
"if",
"context_event",
"and",
"context_event",
"!=",
"event",
":",
"_augment_data_with_context",
"(",
"data",
",",
"entity_id",
",",
"event",
",",
"context_event",
",",
"entity_attr_cache",
",",
"external_events",
",",
")",
"yield",
"data",
"elif",
"event",
".",
"event_type",
"in",
"external_events",
":",
"domain",
",",
"describe_event",
"=",
"external_events",
"[",
"event",
".",
"event_type",
"]",
"data",
"=",
"describe_event",
"(",
"event",
")",
"data",
"[",
"\"when\"",
"]",
"=",
"event",
".",
"time_fired_isoformat",
"data",
"[",
"\"domain\"",
"]",
"=",
"domain",
"if",
"event",
".",
"context_user_id",
":",
"data",
"[",
"\"context_user_id\"",
"]",
"=",
"event",
".",
"context_user_id",
"context_event",
"=",
"context_lookup",
".",
"get",
"(",
"event",
".",
"context_id",
")",
"if",
"context_event",
":",
"_augment_data_with_context",
"(",
"data",
",",
"data",
".",
"get",
"(",
"ATTR_ENTITY_ID",
")",
",",
"event",
",",
"context_event",
",",
"entity_attr_cache",
",",
"external_events",
",",
")",
"yield",
"data",
"elif",
"event",
".",
"event_type",
"==",
"EVENT_HOMEASSISTANT_START",
":",
"if",
"start_stop_events",
".",
"get",
"(",
"event",
".",
"time_fired_minute",
")",
"==",
"2",
":",
"continue",
"yield",
"{",
"\"when\"",
":",
"event",
".",
"time_fired_isoformat",
",",
"\"name\"",
":",
"\"Home Assistant\"",
",",
"\"message\"",
":",
"\"started\"",
",",
"\"domain\"",
":",
"HA_DOMAIN",
",",
"}",
"elif",
"event",
".",
"event_type",
"==",
"EVENT_HOMEASSISTANT_STOP",
":",
"if",
"start_stop_events",
".",
"get",
"(",
"event",
".",
"time_fired_minute",
")",
"==",
"2",
":",
"action",
"=",
"\"restarted\"",
"else",
":",
"action",
"=",
"\"stopped\"",
"yield",
"{",
"\"when\"",
":",
"event",
".",
"time_fired_isoformat",
",",
"\"name\"",
":",
"\"Home Assistant\"",
",",
"\"message\"",
":",
"action",
",",
"\"domain\"",
":",
"HA_DOMAIN",
",",
"}",
"elif",
"event",
".",
"event_type",
"==",
"EVENT_LOGBOOK_ENTRY",
":",
"event_data",
"=",
"event",
".",
"data",
"domain",
"=",
"event_data",
".",
"get",
"(",
"ATTR_DOMAIN",
")",
"entity_id",
"=",
"event_data",
".",
"get",
"(",
"ATTR_ENTITY_ID",
")",
"if",
"domain",
"is",
"None",
"and",
"entity_id",
"is",
"not",
"None",
":",
"try",
":",
"domain",
"=",
"split_entity_id",
"(",
"str",
"(",
"entity_id",
")",
")",
"[",
"0",
"]",
"except",
"IndexError",
":",
"pass",
"data",
"=",
"{",
"\"when\"",
":",
"event",
".",
"time_fired_isoformat",
",",
"\"name\"",
":",
"event_data",
".",
"get",
"(",
"ATTR_NAME",
")",
",",
"\"message\"",
":",
"event_data",
".",
"get",
"(",
"ATTR_MESSAGE",
")",
",",
"\"domain\"",
":",
"domain",
",",
"\"entity_id\"",
":",
"entity_id",
",",
"}",
"if",
"event",
".",
"context_user_id",
":",
"data",
"[",
"\"context_user_id\"",
"]",
"=",
"event",
".",
"context_user_id",
"context_event",
"=",
"context_lookup",
".",
"get",
"(",
"event",
".",
"context_id",
")",
"if",
"context_event",
"and",
"context_event",
"!=",
"event",
":",
"_augment_data_with_context",
"(",
"data",
",",
"entity_id",
",",
"event",
",",
"context_event",
",",
"entity_attr_cache",
",",
"external_events",
",",
")",
"yield",
"data"
] | [
252,
0
] | [
410,
26
] | python | en | ['en', 'en', 'en'] | True |
_get_events | (
hass,
start_day,
end_day,
entity_ids=None,
filters=None,
entities_filter=None,
entity_matches_only=False,
) | Get events for a period of time. | Get events for a period of time. | def _get_events(
hass,
start_day,
end_day,
entity_ids=None,
filters=None,
entities_filter=None,
entity_matches_only=False,
):
"""Get events for a period of time."""
entity_attr_cache = EntityAttributeCache(hass)
context_lookup = {None: None}
def yield_events(query):
"""Yield Events that are not filtered away."""
for row in query.yield_per(1000):
event = LazyEventPartialState(row)
context_lookup.setdefault(event.context_id, event)
if event.event_type == EVENT_CALL_SERVICE:
continue
if event.event_type == EVENT_STATE_CHANGED or _keep_event(
hass, event, entities_filter
):
yield event
if entity_ids is not None:
entities_filter = generate_filter([], entity_ids, [], [])
with session_scope(hass=hass) as session:
old_state = aliased(States, name="old_state")
if entity_ids is not None:
query = _generate_events_query_without_states(session)
query = _apply_event_time_filter(query, start_day, end_day)
query = _apply_event_types_filter(
hass, query, ALL_EVENT_TYPES_EXCEPT_STATE_CHANGED
)
if entity_matches_only:
# When entity_matches_only is provided, contexts and events that do not
# contain the entity_ids are not included in the logbook response.
query = _apply_event_entity_id_matchers(query, entity_ids)
query = query.union_all(
_generate_states_query(
session, start_day, end_day, old_state, entity_ids
)
)
else:
query = _generate_events_query(session)
query = _apply_event_time_filter(query, start_day, end_day)
query = _apply_events_types_and_states_filter(
hass, query, old_state
).filter(
(States.last_updated == States.last_changed)
| (Events.event_type != EVENT_STATE_CHANGED)
)
if filters:
query = query.filter(
filters.entity_filter() | (Events.event_type != EVENT_STATE_CHANGED)
)
query = query.order_by(Events.time_fired)
return list(
humanify(hass, yield_events(query), entity_attr_cache, context_lookup)
) | [
"def",
"_get_events",
"(",
"hass",
",",
"start_day",
",",
"end_day",
",",
"entity_ids",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"entities_filter",
"=",
"None",
",",
"entity_matches_only",
"=",
"False",
",",
")",
":",
"entity_attr_cache",
"=",
"EntityAttributeCache",
"(",
"hass",
")",
"context_lookup",
"=",
"{",
"None",
":",
"None",
"}",
"def",
"yield_events",
"(",
"query",
")",
":",
"\"\"\"Yield Events that are not filtered away.\"\"\"",
"for",
"row",
"in",
"query",
".",
"yield_per",
"(",
"1000",
")",
":",
"event",
"=",
"LazyEventPartialState",
"(",
"row",
")",
"context_lookup",
".",
"setdefault",
"(",
"event",
".",
"context_id",
",",
"event",
")",
"if",
"event",
".",
"event_type",
"==",
"EVENT_CALL_SERVICE",
":",
"continue",
"if",
"event",
".",
"event_type",
"==",
"EVENT_STATE_CHANGED",
"or",
"_keep_event",
"(",
"hass",
",",
"event",
",",
"entities_filter",
")",
":",
"yield",
"event",
"if",
"entity_ids",
"is",
"not",
"None",
":",
"entities_filter",
"=",
"generate_filter",
"(",
"[",
"]",
",",
"entity_ids",
",",
"[",
"]",
",",
"[",
"]",
")",
"with",
"session_scope",
"(",
"hass",
"=",
"hass",
")",
"as",
"session",
":",
"old_state",
"=",
"aliased",
"(",
"States",
",",
"name",
"=",
"\"old_state\"",
")",
"if",
"entity_ids",
"is",
"not",
"None",
":",
"query",
"=",
"_generate_events_query_without_states",
"(",
"session",
")",
"query",
"=",
"_apply_event_time_filter",
"(",
"query",
",",
"start_day",
",",
"end_day",
")",
"query",
"=",
"_apply_event_types_filter",
"(",
"hass",
",",
"query",
",",
"ALL_EVENT_TYPES_EXCEPT_STATE_CHANGED",
")",
"if",
"entity_matches_only",
":",
"# When entity_matches_only is provided, contexts and events that do not",
"# contain the entity_ids are not included in the logbook response.",
"query",
"=",
"_apply_event_entity_id_matchers",
"(",
"query",
",",
"entity_ids",
")",
"query",
"=",
"query",
".",
"union_all",
"(",
"_generate_states_query",
"(",
"session",
",",
"start_day",
",",
"end_day",
",",
"old_state",
",",
"entity_ids",
")",
")",
"else",
":",
"query",
"=",
"_generate_events_query",
"(",
"session",
")",
"query",
"=",
"_apply_event_time_filter",
"(",
"query",
",",
"start_day",
",",
"end_day",
")",
"query",
"=",
"_apply_events_types_and_states_filter",
"(",
"hass",
",",
"query",
",",
"old_state",
")",
".",
"filter",
"(",
"(",
"States",
".",
"last_updated",
"==",
"States",
".",
"last_changed",
")",
"|",
"(",
"Events",
".",
"event_type",
"!=",
"EVENT_STATE_CHANGED",
")",
")",
"if",
"filters",
":",
"query",
"=",
"query",
".",
"filter",
"(",
"filters",
".",
"entity_filter",
"(",
")",
"|",
"(",
"Events",
".",
"event_type",
"!=",
"EVENT_STATE_CHANGED",
")",
")",
"query",
"=",
"query",
".",
"order_by",
"(",
"Events",
".",
"time_fired",
")",
"return",
"list",
"(",
"humanify",
"(",
"hass",
",",
"yield_events",
"(",
"query",
")",
",",
"entity_attr_cache",
",",
"context_lookup",
")",
")"
] | [
413,
0
] | [
479,
9
] | python | en | ['en', 'en', 'en'] | True |
_entity_name_from_event | (entity_id, event, entity_attr_cache) | Extract the entity name from the event using the cache if possible. | Extract the entity name from the event using the cache if possible. | def _entity_name_from_event(entity_id, event, entity_attr_cache):
"""Extract the entity name from the event using the cache if possible."""
return entity_attr_cache.get(
entity_id, ATTR_FRIENDLY_NAME, event
) or split_entity_id(entity_id)[1].replace("_", " ") | [
"def",
"_entity_name_from_event",
"(",
"entity_id",
",",
"event",
",",
"entity_attr_cache",
")",
":",
"return",
"entity_attr_cache",
".",
"get",
"(",
"entity_id",
",",
"ATTR_FRIENDLY_NAME",
",",
"event",
")",
"or",
"split_entity_id",
"(",
"entity_id",
")",
"[",
"1",
"]",
".",
"replace",
"(",
"\"_\"",
",",
"\" \"",
")"
] | [
653,
0
] | [
657,
56
] | python | en | ['en', 'en', 'en'] | True |
LogbookView.__init__ | (self, config, filters, entities_filter) | Initialize the logbook view. | Initialize the logbook view. | def __init__(self, config, filters, entities_filter):
"""Initialize the logbook view."""
self.config = config
self.filters = filters
self.entities_filter = entities_filter | [
"def",
"__init__",
"(",
"self",
",",
"config",
",",
"filters",
",",
"entities_filter",
")",
":",
"self",
".",
"config",
"=",
"config",
"self",
".",
"filters",
"=",
"filters",
"self",
".",
"entities_filter",
"=",
"entities_filter"
] | [
189,
4
] | [
193,
46
] | python | en | ['en', 'en', 'en'] | True |
LogbookView.get | (self, request, datetime=None) | Retrieve logbook entries. | Retrieve logbook entries. | async def get(self, request, datetime=None):
"""Retrieve logbook entries."""
if datetime:
datetime = dt_util.parse_datetime(datetime)
if datetime is None:
return self.json_message("Invalid datetime", HTTP_BAD_REQUEST)
else:
datetime = dt_util.start_of_local_day()
period = request.query.get("period")
if period is None:
period = 1
else:
period = int(period)
entity_ids = request.query.get("entity")
if entity_ids:
try:
entity_ids = cv.entity_ids(entity_ids)
except vol.Invalid:
raise InvalidEntityFormatError(
f"Invalid entity id(s) encountered: {entity_ids}. "
"Format should be <domain>.<object_id>"
) from vol.Invalid
end_time = request.query.get("end_time")
if end_time is None:
start_day = dt_util.as_utc(datetime) - timedelta(days=period - 1)
end_day = start_day + timedelta(days=period)
else:
start_day = datetime
end_day = dt_util.parse_datetime(end_time)
if end_day is None:
return self.json_message("Invalid end_time", HTTP_BAD_REQUEST)
hass = request.app["hass"]
entity_matches_only = "entity_matches_only" in request.query
def json_events():
"""Fetch events and generate JSON."""
return self.json(
_get_events(
hass,
start_day,
end_day,
entity_ids,
self.filters,
self.entities_filter,
entity_matches_only,
)
)
return await hass.async_add_executor_job(json_events) | [
"async",
"def",
"get",
"(",
"self",
",",
"request",
",",
"datetime",
"=",
"None",
")",
":",
"if",
"datetime",
":",
"datetime",
"=",
"dt_util",
".",
"parse_datetime",
"(",
"datetime",
")",
"if",
"datetime",
"is",
"None",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Invalid datetime\"",
",",
"HTTP_BAD_REQUEST",
")",
"else",
":",
"datetime",
"=",
"dt_util",
".",
"start_of_local_day",
"(",
")",
"period",
"=",
"request",
".",
"query",
".",
"get",
"(",
"\"period\"",
")",
"if",
"period",
"is",
"None",
":",
"period",
"=",
"1",
"else",
":",
"period",
"=",
"int",
"(",
"period",
")",
"entity_ids",
"=",
"request",
".",
"query",
".",
"get",
"(",
"\"entity\"",
")",
"if",
"entity_ids",
":",
"try",
":",
"entity_ids",
"=",
"cv",
".",
"entity_ids",
"(",
"entity_ids",
")",
"except",
"vol",
".",
"Invalid",
":",
"raise",
"InvalidEntityFormatError",
"(",
"f\"Invalid entity id(s) encountered: {entity_ids}. \"",
"\"Format should be <domain>.<object_id>\"",
")",
"from",
"vol",
".",
"Invalid",
"end_time",
"=",
"request",
".",
"query",
".",
"get",
"(",
"\"end_time\"",
")",
"if",
"end_time",
"is",
"None",
":",
"start_day",
"=",
"dt_util",
".",
"as_utc",
"(",
"datetime",
")",
"-",
"timedelta",
"(",
"days",
"=",
"period",
"-",
"1",
")",
"end_day",
"=",
"start_day",
"+",
"timedelta",
"(",
"days",
"=",
"period",
")",
"else",
":",
"start_day",
"=",
"datetime",
"end_day",
"=",
"dt_util",
".",
"parse_datetime",
"(",
"end_time",
")",
"if",
"end_day",
"is",
"None",
":",
"return",
"self",
".",
"json_message",
"(",
"\"Invalid end_time\"",
",",
"HTTP_BAD_REQUEST",
")",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"entity_matches_only",
"=",
"\"entity_matches_only\"",
"in",
"request",
".",
"query",
"def",
"json_events",
"(",
")",
":",
"\"\"\"Fetch events and generate JSON.\"\"\"",
"return",
"self",
".",
"json",
"(",
"_get_events",
"(",
"hass",
",",
"start_day",
",",
"end_day",
",",
"entity_ids",
",",
"self",
".",
"filters",
",",
"self",
".",
"entities_filter",
",",
"entity_matches_only",
",",
")",
")",
"return",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"json_events",
")"
] | [
195,
4
] | [
249,
61
] | python | en | ['en', 'sk', 'en'] | True |
LazyEventPartialState.__init__ | (self, row) | Init the lazy event. | Init the lazy event. | def __init__(self, row):
"""Init the lazy event."""
self._row = row
self._event_data = None
self._time_fired_isoformat = None
self._attributes = None
self.event_type = self._row.event_type
self.entity_id = self._row.entity_id
self.state = self._row.state
self.domain = self._row.domain
self.context_id = self._row.context_id
self.context_user_id = self._row.context_user_id
self.time_fired_minute = self._row.time_fired.minute | [
"def",
"__init__",
"(",
"self",
",",
"row",
")",
":",
"self",
".",
"_row",
"=",
"row",
"self",
".",
"_event_data",
"=",
"None",
"self",
".",
"_time_fired_isoformat",
"=",
"None",
"self",
".",
"_attributes",
"=",
"None",
"self",
".",
"event_type",
"=",
"self",
".",
"_row",
".",
"event_type",
"self",
".",
"entity_id",
"=",
"self",
".",
"_row",
".",
"entity_id",
"self",
".",
"state",
"=",
"self",
".",
"_row",
".",
"state",
"self",
".",
"domain",
"=",
"self",
".",
"_row",
".",
"domain",
"self",
".",
"context_id",
"=",
"self",
".",
"_row",
".",
"context_id",
"self",
".",
"context_user_id",
"=",
"self",
".",
"_row",
".",
"context_user_id",
"self",
".",
"time_fired_minute",
"=",
"self",
".",
"_row",
".",
"time_fired",
".",
"minute"
] | [
677,
4
] | [
689,
60
] | 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.