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_location_zone | (hass, requests_mock_truck_response, legacy_patchable_time) | Test that origin/destination supplied by a zone works. | Test that origin/destination supplied by a zone works. | async def test_location_zone(hass, requests_mock_truck_response, legacy_patchable_time):
"""Test that origin/destination supplied by a zone works."""
utcnow = dt_util.utcnow()
# Patching 'utcnow' to gain more control over the timed update.
with patch("homeassistant.util.dt.utcnow", return_value=utcnow):
zone_config = {
"zone": [
{
"name": "Destination",
"latitude": TRUCK_DESTINATION_LATITUDE,
"longitude": TRUCK_DESTINATION_LONGITUDE,
"radius": 250,
"passive": False,
},
{
"name": "Origin",
"latitude": TRUCK_ORIGIN_LATITUDE,
"longitude": TRUCK_ORIGIN_LONGITUDE,
"radius": 250,
"passive": False,
},
]
}
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "zone.origin",
"destination_entity_id": "zone.destination",
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
assert await async_setup_component(hass, "zone", zone_config)
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor)
# Test that update works more than once
async_fire_time_changed(hass, utcnow + SCAN_INTERVAL)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor) | [
"async",
"def",
"test_location_zone",
"(",
"hass",
",",
"requests_mock_truck_response",
",",
"legacy_patchable_time",
")",
":",
"utcnow",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"# Patching 'utcnow' to gain more control over the timed update.",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"utcnow",
")",
":",
"zone_config",
"=",
"{",
"\"zone\"",
":",
"[",
"{",
"\"name\"",
":",
"\"Destination\"",
",",
"\"latitude\"",
":",
"TRUCK_DESTINATION_LATITUDE",
",",
"\"longitude\"",
":",
"TRUCK_DESTINATION_LONGITUDE",
",",
"\"radius\"",
":",
"250",
",",
"\"passive\"",
":",
"False",
",",
"}",
",",
"{",
"\"name\"",
":",
"\"Origin\"",
",",
"\"latitude\"",
":",
"TRUCK_ORIGIN_LATITUDE",
",",
"\"longitude\"",
":",
"TRUCK_ORIGIN_LONGITUDE",
",",
"\"radius\"",
":",
"250",
",",
"\"passive\"",
":",
"False",
",",
"}",
",",
"]",
"}",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"zone.origin\"",
",",
"\"destination_entity_id\"",
":",
"\"zone.destination\"",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"zone\"",
",",
"zone_config",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")",
"# Test that update works more than once",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")"
] | [
569,
0
] | [
617,
36
] | python | en | ['en', 'de', 'en'] | True |
test_location_sensor | (
hass, requests_mock_truck_response, legacy_patchable_time
) | Test that origin/destination supplied by a sensor works. | Test that origin/destination supplied by a sensor works. | async def test_location_sensor(
hass, requests_mock_truck_response, legacy_patchable_time
):
"""Test that origin/destination supplied by a sensor works."""
utcnow = dt_util.utcnow()
# Patching 'utcnow' to gain more control over the timed update.
with patch("homeassistant.util.dt.utcnow", return_value=utcnow):
hass.states.async_set(
"sensor.origin", ",".join([TRUCK_ORIGIN_LATITUDE, TRUCK_ORIGIN_LONGITUDE])
)
hass.states.async_set(
"sensor.destination",
",".join([TRUCK_DESTINATION_LATITUDE, TRUCK_DESTINATION_LONGITUDE]),
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "sensor.origin",
"destination_entity_id": "sensor.destination",
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor)
# Test that update works more than once
async_fire_time_changed(hass, utcnow + SCAN_INTERVAL)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor) | [
"async",
"def",
"test_location_sensor",
"(",
"hass",
",",
"requests_mock_truck_response",
",",
"legacy_patchable_time",
")",
":",
"utcnow",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"# Patching 'utcnow' to gain more control over the timed update.",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"utcnow",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"sensor.origin\"",
",",
"\",\"",
".",
"join",
"(",
"[",
"TRUCK_ORIGIN_LATITUDE",
",",
"TRUCK_ORIGIN_LONGITUDE",
"]",
")",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"sensor.destination\"",
",",
"\",\"",
".",
"join",
"(",
"[",
"TRUCK_DESTINATION_LATITUDE",
",",
"TRUCK_DESTINATION_LONGITUDE",
"]",
")",
",",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"sensor.origin\"",
",",
"\"destination_entity_id\"",
":",
"\"sensor.destination\"",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")",
"# Test that update works more than once",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")"
] | [
620,
0
] | [
659,
36
] | python | en | ['en', 'de', 'en'] | True |
test_location_person | (
hass, requests_mock_truck_response, legacy_patchable_time
) | Test that origin/destination supplied by a person works. | Test that origin/destination supplied by a person works. | async def test_location_person(
hass, requests_mock_truck_response, legacy_patchable_time
):
"""Test that origin/destination supplied by a person works."""
utcnow = dt_util.utcnow()
# Patching 'utcnow' to gain more control over the timed update.
with patch("homeassistant.util.dt.utcnow", return_value=utcnow):
hass.states.async_set(
"person.origin",
"unknown",
{
"latitude": float(TRUCK_ORIGIN_LATITUDE),
"longitude": float(TRUCK_ORIGIN_LONGITUDE),
},
)
hass.states.async_set(
"person.destination",
"unknown",
{
"latitude": float(TRUCK_DESTINATION_LATITUDE),
"longitude": float(TRUCK_DESTINATION_LONGITUDE),
},
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "person.origin",
"destination_entity_id": "person.destination",
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor)
# Test that update works more than once
async_fire_time_changed(hass, utcnow + SCAN_INTERVAL)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor) | [
"async",
"def",
"test_location_person",
"(",
"hass",
",",
"requests_mock_truck_response",
",",
"legacy_patchable_time",
")",
":",
"utcnow",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"# Patching 'utcnow' to gain more control over the timed update.",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"utcnow",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"person.origin\"",
",",
"\"unknown\"",
",",
"{",
"\"latitude\"",
":",
"float",
"(",
"TRUCK_ORIGIN_LATITUDE",
")",
",",
"\"longitude\"",
":",
"float",
"(",
"TRUCK_ORIGIN_LONGITUDE",
")",
",",
"}",
",",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"person.destination\"",
",",
"\"unknown\"",
",",
"{",
"\"latitude\"",
":",
"float",
"(",
"TRUCK_DESTINATION_LATITUDE",
")",
",",
"\"longitude\"",
":",
"float",
"(",
"TRUCK_DESTINATION_LONGITUDE",
")",
",",
"}",
",",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"person.origin\"",
",",
"\"destination_entity_id\"",
":",
"\"person.destination\"",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")",
"# Test that update works more than once",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")"
] | [
662,
0
] | [
710,
36
] | python | en | ['en', 'en', 'en'] | True |
test_location_device_tracker | (
hass, requests_mock_truck_response, legacy_patchable_time
) | Test that origin/destination supplied by a device_tracker works. | Test that origin/destination supplied by a device_tracker works. | async def test_location_device_tracker(
hass, requests_mock_truck_response, legacy_patchable_time
):
"""Test that origin/destination supplied by a device_tracker works."""
utcnow = dt_util.utcnow()
# Patching 'utcnow' to gain more control over the timed update.
with patch("homeassistant.util.dt.utcnow", return_value=utcnow):
hass.states.async_set(
"device_tracker.origin",
"unknown",
{
"latitude": float(TRUCK_ORIGIN_LATITUDE),
"longitude": float(TRUCK_ORIGIN_LONGITUDE),
},
)
hass.states.async_set(
"device_tracker.destination",
"unknown",
{
"latitude": float(TRUCK_DESTINATION_LATITUDE),
"longitude": float(TRUCK_DESTINATION_LONGITUDE),
},
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "device_tracker.origin",
"destination_entity_id": "device_tracker.destination",
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor)
# Test that update works more than once
async_fire_time_changed(hass, utcnow + SCAN_INTERVAL)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor) | [
"async",
"def",
"test_location_device_tracker",
"(",
"hass",
",",
"requests_mock_truck_response",
",",
"legacy_patchable_time",
")",
":",
"utcnow",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"# Patching 'utcnow' to gain more control over the timed update.",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"utcnow",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.origin\"",
",",
"\"unknown\"",
",",
"{",
"\"latitude\"",
":",
"float",
"(",
"TRUCK_ORIGIN_LATITUDE",
")",
",",
"\"longitude\"",
":",
"float",
"(",
"TRUCK_ORIGIN_LONGITUDE",
")",
",",
"}",
",",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.destination\"",
",",
"\"unknown\"",
",",
"{",
"\"latitude\"",
":",
"float",
"(",
"TRUCK_DESTINATION_LATITUDE",
")",
",",
"\"longitude\"",
":",
"float",
"(",
"TRUCK_DESTINATION_LONGITUDE",
")",
",",
"}",
",",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"device_tracker.origin\"",
",",
"\"destination_entity_id\"",
":",
"\"device_tracker.destination\"",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")",
"# Test that update works more than once",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")"
] | [
713,
0
] | [
761,
36
] | python | en | ['en', 'en', 'en'] | True |
test_location_device_tracker_added_after_update | (
hass, requests_mock_truck_response, legacy_patchable_time, caplog
) | Test that device_tracker added after first update works. | Test that device_tracker added after first update works. | async def test_location_device_tracker_added_after_update(
hass, requests_mock_truck_response, legacy_patchable_time, caplog
):
"""Test that device_tracker added after first update works."""
caplog.set_level(logging.ERROR)
utcnow = dt_util.utcnow()
# Patching 'utcnow' to gain more control over the timed update.
with patch("homeassistant.util.dt.utcnow", return_value=utcnow):
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "device_tracker.origin",
"destination_entity_id": "device_tracker.destination",
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
assert len(caplog.records) == 2
assert "Unable to find entity" in caplog.text
caplog.clear()
# Device tracker appear after first update
hass.states.async_set(
"device_tracker.origin",
"unknown",
{
"latitude": float(TRUCK_ORIGIN_LATITUDE),
"longitude": float(TRUCK_ORIGIN_LONGITUDE),
},
)
hass.states.async_set(
"device_tracker.destination",
"unknown",
{
"latitude": float(TRUCK_DESTINATION_LATITUDE),
"longitude": float(TRUCK_DESTINATION_LONGITUDE),
},
)
# Test that update works more than once
async_fire_time_changed(hass, utcnow + SCAN_INTERVAL)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor)
assert len(caplog.records) == 0 | [
"async",
"def",
"test_location_device_tracker_added_after_update",
"(",
"hass",
",",
"requests_mock_truck_response",
",",
"legacy_patchable_time",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"utcnow",
"=",
"dt_util",
".",
"utcnow",
"(",
")",
"# Patching 'utcnow' to gain more control over the timed update.",
"with",
"patch",
"(",
"\"homeassistant.util.dt.utcnow\"",
",",
"return_value",
"=",
"utcnow",
")",
":",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"device_tracker.origin\"",
",",
"\"destination_entity_id\"",
":",
"\"device_tracker.destination\"",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"2",
"assert",
"\"Unable to find entity\"",
"in",
"caplog",
".",
"text",
"caplog",
".",
"clear",
"(",
")",
"# Device tracker appear after first update",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.origin\"",
",",
"\"unknown\"",
",",
"{",
"\"latitude\"",
":",
"float",
"(",
"TRUCK_ORIGIN_LATITUDE",
")",
",",
"\"longitude\"",
":",
"float",
"(",
"TRUCK_ORIGIN_LONGITUDE",
")",
",",
"}",
",",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.destination\"",
",",
"\"unknown\"",
",",
"{",
"\"latitude\"",
":",
"float",
"(",
"TRUCK_DESTINATION_LATITUDE",
")",
",",
"\"longitude\"",
":",
"float",
"(",
"TRUCK_DESTINATION_LONGITUDE",
")",
",",
"}",
",",
")",
"# Test that update works more than once",
"async_fire_time_changed",
"(",
"hass",
",",
"utcnow",
"+",
"SCAN_INTERVAL",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"0"
] | [
764,
0
] | [
817,
39
] | python | en | ['en', 'en', 'en'] | True |
test_location_device_tracker_in_zone | (
hass, requests_mock_truck_response, caplog
) | Test that device_tracker in zone uses device_tracker state works. | Test that device_tracker in zone uses device_tracker state works. | async def test_location_device_tracker_in_zone(
hass, requests_mock_truck_response, caplog
):
"""Test that device_tracker in zone uses device_tracker state works."""
caplog.set_level(logging.DEBUG)
zone_config = {
"zone": [
{
"name": "Origin",
"latitude": TRUCK_ORIGIN_LATITUDE,
"longitude": TRUCK_ORIGIN_LONGITUDE,
"radius": 250,
"passive": False,
}
]
}
assert await async_setup_component(hass, "zone", zone_config)
hass.states.async_set(
"device_tracker.origin", "origin", {"latitude": None, "longitude": None}
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "device_tracker.origin",
"destination_latitude": TRUCK_DESTINATION_LATITUDE,
"destination_longitude": TRUCK_DESTINATION_LONGITUDE,
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
_assert_truck_sensor(sensor)
assert ", getting zone location" in caplog.text | [
"async",
"def",
"test_location_device_tracker_in_zone",
"(",
"hass",
",",
"requests_mock_truck_response",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"DEBUG",
")",
"zone_config",
"=",
"{",
"\"zone\"",
":",
"[",
"{",
"\"name\"",
":",
"\"Origin\"",
",",
"\"latitude\"",
":",
"TRUCK_ORIGIN_LATITUDE",
",",
"\"longitude\"",
":",
"TRUCK_ORIGIN_LONGITUDE",
",",
"\"radius\"",
":",
"250",
",",
"\"passive\"",
":",
"False",
",",
"}",
"]",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"zone\"",
",",
"zone_config",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"device_tracker.origin\"",
",",
"\"origin\"",
",",
"{",
"\"latitude\"",
":",
"None",
",",
"\"longitude\"",
":",
"None",
"}",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"device_tracker.origin\"",
",",
"\"destination_latitude\"",
":",
"TRUCK_DESTINATION_LATITUDE",
",",
"\"destination_longitude\"",
":",
"TRUCK_DESTINATION_LONGITUDE",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"_assert_truck_sensor",
"(",
"sensor",
")",
"assert",
"\", getting zone location\"",
"in",
"caplog",
".",
"text"
] | [
820,
0
] | [
859,
51
] | python | en | ['en', 'en', 'en'] | True |
test_route_not_found | (hass, requests_mock_credentials_check, caplog) | Test that route not found error is correctly handled. | Test that route not found error is correctly handled. | async def test_route_not_found(hass, requests_mock_credentials_check, caplog):
"""Test that route not found error is correctly handled."""
caplog.set_level(logging.ERROR)
origin = "52.516,13.3779"
destination = "47.013399,-10.171986"
modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_CAR, TRAFFIC_MODE_DISABLED]
response_url = _build_mock_url(origin, destination, modes, API_KEY)
requests_mock_credentials_check.get(
response_url,
text=load_fixture("here_travel_time/routing_error_no_route_found.json"),
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": origin.split(",")[0],
"origin_longitude": origin.split(",")[1],
"destination_latitude": destination.split(",")[0],
"destination_longitude": destination.split(",")[1],
"api_key": API_KEY,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert len(caplog.records) == 1
assert NO_ROUTE_ERROR_MESSAGE in caplog.text | [
"async",
"def",
"test_route_not_found",
"(",
"hass",
",",
"requests_mock_credentials_check",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"origin",
"=",
"\"52.516,13.3779\"",
"destination",
"=",
"\"47.013399,-10.171986\"",
"modes",
"=",
"[",
"ROUTE_MODE_FASTEST",
",",
"TRAVEL_MODE_CAR",
",",
"TRAFFIC_MODE_DISABLED",
"]",
"response_url",
"=",
"_build_mock_url",
"(",
"origin",
",",
"destination",
",",
"modes",
",",
"API_KEY",
")",
"requests_mock_credentials_check",
".",
"get",
"(",
"response_url",
",",
"text",
"=",
"load_fixture",
"(",
"\"here_travel_time/routing_error_no_route_found.json\"",
")",
",",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"origin_longitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"destination_latitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"destination_longitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"1",
"assert",
"NO_ROUTE_ERROR_MESSAGE",
"in",
"caplog",
".",
"text"
] | [
862,
0
] | [
892,
48
] | python | en | ['en', 'en', 'en'] | True |
test_pattern_origin | (hass, caplog) | Test that pattern matching the origin works. | Test that pattern matching the origin works. | async def test_pattern_origin(hass, caplog):
"""Test that pattern matching the origin works."""
caplog.set_level(logging.ERROR)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": "138.90",
"origin_longitude": "-77.04833",
"destination_latitude": CAR_DESTINATION_LATITUDE,
"destination_longitude": CAR_DESTINATION_LONGITUDE,
"api_key": API_KEY,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
assert len(caplog.records) == 2
assert "invalid latitude" in caplog.text | [
"async",
"def",
"test_pattern_origin",
"(",
"hass",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"\"138.90\"",
",",
"\"origin_longitude\"",
":",
"\"-77.04833\"",
",",
"\"destination_latitude\"",
":",
"CAR_DESTINATION_LATITUDE",
",",
"\"destination_longitude\"",
":",
"CAR_DESTINATION_LONGITUDE",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"2",
"assert",
"\"invalid latitude\"",
"in",
"caplog",
".",
"text"
] | [
895,
0
] | [
912,
44
] | python | en | ['en', 'en', 'en'] | True |
test_pattern_destination | (hass, caplog) | Test that pattern matching the destination works. | Test that pattern matching the destination works. | async def test_pattern_destination(hass, caplog):
"""Test that pattern matching the destination works."""
caplog.set_level(logging.ERROR)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": CAR_ORIGIN_LATITUDE,
"origin_longitude": CAR_ORIGIN_LONGITUDE,
"destination_latitude": "139.0",
"destination_longitude": "-77.1",
"api_key": API_KEY,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
assert len(caplog.records) == 2
assert "invalid latitude" in caplog.text | [
"async",
"def",
"test_pattern_destination",
"(",
"hass",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"CAR_ORIGIN_LATITUDE",
",",
"\"origin_longitude\"",
":",
"CAR_ORIGIN_LONGITUDE",
",",
"\"destination_latitude\"",
":",
"\"139.0\"",
",",
"\"destination_longitude\"",
":",
"\"-77.1\"",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"2",
"assert",
"\"invalid latitude\"",
"in",
"caplog",
".",
"text"
] | [
915,
0
] | [
932,
44
] | python | en | ['en', 'en', 'en'] | True |
test_invalid_credentials | (hass, requests_mock, caplog) | Test that invalid credentials error is correctly handled. | Test that invalid credentials error is correctly handled. | async def test_invalid_credentials(hass, requests_mock, caplog):
"""Test that invalid credentials error is correctly handled."""
caplog.set_level(logging.ERROR)
modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_CAR, TRAFFIC_MODE_DISABLED]
response_url = _build_mock_url(
",".join([CAR_ORIGIN_LATITUDE, CAR_ORIGIN_LONGITUDE]),
",".join([CAR_DESTINATION_LATITUDE, CAR_DESTINATION_LONGITUDE]),
modes,
API_KEY,
)
requests_mock.get(
response_url,
text=load_fixture("here_travel_time/routing_error_invalid_credentials.json"),
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": CAR_ORIGIN_LATITUDE,
"origin_longitude": CAR_ORIGIN_LONGITUDE,
"destination_latitude": CAR_DESTINATION_LATITUDE,
"destination_longitude": CAR_DESTINATION_LONGITUDE,
"api_key": API_KEY,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
assert len(caplog.records) == 1
assert "Invalid credentials" in caplog.text | [
"async",
"def",
"test_invalid_credentials",
"(",
"hass",
",",
"requests_mock",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"modes",
"=",
"[",
"ROUTE_MODE_FASTEST",
",",
"TRAVEL_MODE_CAR",
",",
"TRAFFIC_MODE_DISABLED",
"]",
"response_url",
"=",
"_build_mock_url",
"(",
"\",\"",
".",
"join",
"(",
"[",
"CAR_ORIGIN_LATITUDE",
",",
"CAR_ORIGIN_LONGITUDE",
"]",
")",
",",
"\",\"",
".",
"join",
"(",
"[",
"CAR_DESTINATION_LATITUDE",
",",
"CAR_DESTINATION_LONGITUDE",
"]",
")",
",",
"modes",
",",
"API_KEY",
",",
")",
"requests_mock",
".",
"get",
"(",
"response_url",
",",
"text",
"=",
"load_fixture",
"(",
"\"here_travel_time/routing_error_invalid_credentials.json\"",
")",
",",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"CAR_ORIGIN_LATITUDE",
",",
"\"origin_longitude\"",
":",
"CAR_ORIGIN_LONGITUDE",
",",
"\"destination_latitude\"",
":",
"CAR_DESTINATION_LATITUDE",
",",
"\"destination_longitude\"",
":",
"CAR_DESTINATION_LONGITUDE",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"1",
"assert",
"\"Invalid credentials\"",
"in",
"caplog",
".",
"text"
] | [
935,
0
] | [
964,
47
] | python | en | ['en', 'en', 'en'] | True |
test_attribution | (hass, requests_mock_credentials_check) | Test that attributions are correctly displayed. | Test that attributions are correctly displayed. | async def test_attribution(hass, requests_mock_credentials_check):
"""Test that attributions are correctly displayed."""
origin = "50.037751372637686,14.39233448220898"
destination = "50.07993838201255,14.42582157361062"
modes = [ROUTE_MODE_SHORTEST, TRAVEL_MODE_PUBLIC_TIME_TABLE, TRAFFIC_MODE_ENABLED]
response_url = _build_mock_url(origin, destination, modes, API_KEY)
requests_mock_credentials_check.get(
response_url, text=load_fixture("here_travel_time/attribution_response.json")
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": origin.split(",")[0],
"origin_longitude": origin.split(",")[1],
"destination_latitude": destination.split(",")[0],
"destination_longitude": destination.split(",")[1],
"api_key": API_KEY,
"traffic_mode": True,
"route_mode": ROUTE_MODE_SHORTEST,
"mode": TRAVEL_MODE_PUBLIC_TIME_TABLE,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
assert (
sensor.attributes.get(ATTR_ATTRIBUTION)
== "With the support of HERE Technologies. All information is provided without warranty of any kind."
) | [
"async",
"def",
"test_attribution",
"(",
"hass",
",",
"requests_mock_credentials_check",
")",
":",
"origin",
"=",
"\"50.037751372637686,14.39233448220898\"",
"destination",
"=",
"\"50.07993838201255,14.42582157361062\"",
"modes",
"=",
"[",
"ROUTE_MODE_SHORTEST",
",",
"TRAVEL_MODE_PUBLIC_TIME_TABLE",
",",
"TRAFFIC_MODE_ENABLED",
"]",
"response_url",
"=",
"_build_mock_url",
"(",
"origin",
",",
"destination",
",",
"modes",
",",
"API_KEY",
")",
"requests_mock_credentials_check",
".",
"get",
"(",
"response_url",
",",
"text",
"=",
"load_fixture",
"(",
"\"here_travel_time/attribution_response.json\"",
")",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"origin_longitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"destination_latitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"destination_longitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"traffic_mode\"",
":",
"True",
",",
"\"route_mode\"",
":",
"ROUTE_MODE_SHORTEST",
",",
"\"mode\"",
":",
"TRAVEL_MODE_PUBLIC_TIME_TABLE",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"assert",
"(",
"sensor",
".",
"attributes",
".",
"get",
"(",
"ATTR_ATTRIBUTION",
")",
"==",
"\"With the support of HERE Technologies. All information is provided without warranty of any kind.\"",
")"
] | [
967,
0
] | [
1001,
5
] | python | en | ['en', 'en', 'en'] | True |
test_pattern_entity_state | (hass, requests_mock_truck_response, caplog) | Test that pattern matching the state of an entity works. | Test that pattern matching the state of an entity works. | async def test_pattern_entity_state(hass, requests_mock_truck_response, caplog):
"""Test that pattern matching the state of an entity works."""
caplog.set_level(logging.ERROR)
hass.states.async_set("sensor.origin", "invalid")
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "sensor.origin",
"destination_latitude": TRUCK_DESTINATION_LATITUDE,
"destination_longitude": TRUCK_DESTINATION_LONGITUDE,
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert len(caplog.records) == 1
assert "is not a valid set of coordinates" in caplog.text | [
"async",
"def",
"test_pattern_entity_state",
"(",
"hass",
",",
"requests_mock_truck_response",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"sensor.origin\"",
",",
"\"invalid\"",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"sensor.origin\"",
",",
"\"destination_latitude\"",
":",
"TRUCK_DESTINATION_LATITUDE",
",",
"\"destination_longitude\"",
":",
"TRUCK_DESTINATION_LONGITUDE",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"1",
"assert",
"\"is not a valid set of coordinates\"",
"in",
"caplog",
".",
"text"
] | [
1004,
0
] | [
1027,
61
] | python | en | ['en', 'en', 'en'] | True |
test_pattern_entity_state_with_space | (hass, requests_mock_truck_response) | Test that pattern matching the state including a space of an entity works. | Test that pattern matching the state including a space of an entity works. | async def test_pattern_entity_state_with_space(hass, requests_mock_truck_response):
"""Test that pattern matching the state including a space of an entity works."""
hass.states.async_set(
"sensor.origin", ", ".join([TRUCK_ORIGIN_LATITUDE, TRUCK_ORIGIN_LONGITUDE])
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "sensor.origin",
"destination_latitude": TRUCK_DESTINATION_LATITUDE,
"destination_longitude": TRUCK_DESTINATION_LONGITUDE,
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done() | [
"async",
"def",
"test_pattern_entity_state_with_space",
"(",
"hass",
",",
"requests_mock_truck_response",
")",
":",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"sensor.origin\"",
",",
"\", \"",
".",
"join",
"(",
"[",
"TRUCK_ORIGIN_LATITUDE",
",",
"TRUCK_ORIGIN_LONGITUDE",
"]",
")",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"sensor.origin\"",
",",
"\"destination_latitude\"",
":",
"TRUCK_DESTINATION_LATITUDE",
",",
"\"destination_longitude\"",
":",
"TRUCK_DESTINATION_LONGITUDE",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")"
] | [
1030,
0
] | [
1048,
38
] | python | en | ['en', 'en', 'en'] | True |
test_delayed_update | (hass, requests_mock_truck_response, caplog) | Test that delayed update does not complain about missing entities. | Test that delayed update does not complain about missing entities. | async def test_delayed_update(hass, requests_mock_truck_response, caplog):
"""Test that delayed update does not complain about missing entities."""
caplog.set_level(logging.WARNING)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_entity_id": "sensor.origin",
"destination_latitude": TRUCK_DESTINATION_LATITUDE,
"destination_longitude": TRUCK_DESTINATION_LONGITUDE,
"api_key": API_KEY,
"mode": TRAVEL_MODE_TRUCK,
}
}
sensor_config = {
"sensor": {
"platform": "template",
"sensors": [
{"template_sensor": {"value_template": "{{states('sensor.origin')}}"}}
],
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
assert await async_setup_component(hass, "sensor", sensor_config)
hass.states.async_set(
"sensor.origin", ",".join([TRUCK_ORIGIN_LATITUDE, TRUCK_ORIGIN_LONGITUDE])
)
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert "Unable to find entity" not in caplog.text | [
"async",
"def",
"test_delayed_update",
"(",
"hass",
",",
"requests_mock_truck_response",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"WARNING",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_entity_id\"",
":",
"\"sensor.origin\"",
",",
"\"destination_latitude\"",
":",
"TRUCK_DESTINATION_LATITUDE",
",",
"\"destination_longitude\"",
":",
"TRUCK_DESTINATION_LONGITUDE",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_TRUCK",
",",
"}",
"}",
"sensor_config",
"=",
"{",
"\"sensor\"",
":",
"{",
"\"platform\"",
":",
"\"template\"",
",",
"\"sensors\"",
":",
"[",
"{",
"\"template_sensor\"",
":",
"{",
"\"value_template\"",
":",
"\"{{states('sensor.origin')}}\"",
"}",
"}",
"]",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"sensor\"",
",",
"sensor_config",
")",
"hass",
".",
"states",
".",
"async_set",
"(",
"\"sensor.origin\"",
",",
"\",\"",
".",
"join",
"(",
"[",
"TRUCK_ORIGIN_LATITUDE",
",",
"TRUCK_ORIGIN_LONGITUDE",
"]",
")",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"\"Unable to find entity\"",
"not",
"in",
"caplog",
".",
"text"
] | [
1051,
0
] | [
1084,
53
] | python | en | ['en', 'en', 'en'] | True |
test_arrival | (hass, requests_mock_credentials_check) | Test that arrival works. | Test that arrival works. | async def test_arrival(hass, requests_mock_credentials_check):
"""Test that arrival works."""
origin = "41.9798,-87.8801"
destination = "41.9043,-87.9216"
arrival = "01:00:00"
arrival_isodate = convert_time_to_isodate(arrival)
modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_PUBLIC_TIME_TABLE, TRAFFIC_MODE_DISABLED]
response_url = _build_mock_url(
origin, destination, modes, API_KEY, arrival=arrival_isodate
)
requests_mock_credentials_check.get(
response_url,
text=load_fixture("here_travel_time/public_time_table_response.json"),
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": origin.split(",")[0],
"origin_longitude": origin.split(",")[1],
"destination_latitude": destination.split(",")[0],
"destination_longitude": destination.split(",")[1],
"api_key": API_KEY,
"mode": TRAVEL_MODE_PUBLIC_TIME_TABLE,
"arrival": arrival,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
assert sensor.state == "80" | [
"async",
"def",
"test_arrival",
"(",
"hass",
",",
"requests_mock_credentials_check",
")",
":",
"origin",
"=",
"\"41.9798,-87.8801\"",
"destination",
"=",
"\"41.9043,-87.9216\"",
"arrival",
"=",
"\"01:00:00\"",
"arrival_isodate",
"=",
"convert_time_to_isodate",
"(",
"arrival",
")",
"modes",
"=",
"[",
"ROUTE_MODE_FASTEST",
",",
"TRAVEL_MODE_PUBLIC_TIME_TABLE",
",",
"TRAFFIC_MODE_DISABLED",
"]",
"response_url",
"=",
"_build_mock_url",
"(",
"origin",
",",
"destination",
",",
"modes",
",",
"API_KEY",
",",
"arrival",
"=",
"arrival_isodate",
")",
"requests_mock_credentials_check",
".",
"get",
"(",
"response_url",
",",
"text",
"=",
"load_fixture",
"(",
"\"here_travel_time/public_time_table_response.json\"",
")",
",",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"origin_longitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"destination_latitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"destination_longitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_PUBLIC_TIME_TABLE",
",",
"\"arrival\"",
":",
"arrival",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"assert",
"sensor",
".",
"state",
"==",
"\"80\""
] | [
1087,
0
] | [
1122,
31
] | python | en | ['en', 'en', 'en'] | True |
test_departure | (hass, requests_mock_credentials_check) | Test that arrival works. | Test that arrival works. | async def test_departure(hass, requests_mock_credentials_check):
"""Test that arrival works."""
origin = "41.9798,-87.8801"
destination = "41.9043,-87.9216"
departure = "23:00:00"
departure_isodate = convert_time_to_isodate(departure)
modes = [ROUTE_MODE_FASTEST, TRAVEL_MODE_PUBLIC_TIME_TABLE, TRAFFIC_MODE_DISABLED]
response_url = _build_mock_url(
origin, destination, modes, API_KEY, departure=departure_isodate
)
requests_mock_credentials_check.get(
response_url,
text=load_fixture("here_travel_time/public_time_table_response.json"),
)
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": origin.split(",")[0],
"origin_longitude": origin.split(",")[1],
"destination_latitude": destination.split(",")[0],
"destination_longitude": destination.split(",")[1],
"api_key": API_KEY,
"mode": TRAVEL_MODE_PUBLIC_TIME_TABLE,
"departure": departure,
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
sensor = hass.states.get("sensor.test")
assert sensor.state == "80" | [
"async",
"def",
"test_departure",
"(",
"hass",
",",
"requests_mock_credentials_check",
")",
":",
"origin",
"=",
"\"41.9798,-87.8801\"",
"destination",
"=",
"\"41.9043,-87.9216\"",
"departure",
"=",
"\"23:00:00\"",
"departure_isodate",
"=",
"convert_time_to_isodate",
"(",
"departure",
")",
"modes",
"=",
"[",
"ROUTE_MODE_FASTEST",
",",
"TRAVEL_MODE_PUBLIC_TIME_TABLE",
",",
"TRAFFIC_MODE_DISABLED",
"]",
"response_url",
"=",
"_build_mock_url",
"(",
"origin",
",",
"destination",
",",
"modes",
",",
"API_KEY",
",",
"departure",
"=",
"departure_isodate",
")",
"requests_mock_credentials_check",
".",
"get",
"(",
"response_url",
",",
"text",
"=",
"load_fixture",
"(",
"\"here_travel_time/public_time_table_response.json\"",
")",
",",
")",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"origin_longitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"destination_latitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"destination_longitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"mode\"",
":",
"TRAVEL_MODE_PUBLIC_TIME_TABLE",
",",
"\"departure\"",
":",
"departure",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_HOMEASSISTANT_START",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sensor",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"sensor.test\"",
")",
"assert",
"sensor",
".",
"state",
"==",
"\"80\""
] | [
1125,
0
] | [
1160,
31
] | python | en | ['en', 'en', 'en'] | True |
test_arrival_only_allowed_for_timetable | (hass, caplog) | Test that arrival is only allowed when mode is publicTransportTimeTable. | Test that arrival is only allowed when mode is publicTransportTimeTable. | async def test_arrival_only_allowed_for_timetable(hass, caplog):
"""Test that arrival is only allowed when mode is publicTransportTimeTable."""
caplog.set_level(logging.ERROR)
origin = "41.9798,-87.8801"
destination = "41.9043,-87.9216"
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": origin.split(",")[0],
"origin_longitude": origin.split(",")[1],
"destination_latitude": destination.split(",")[0],
"destination_longitude": destination.split(",")[1],
"api_key": API_KEY,
"arrival": "01:00:00",
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
assert len(caplog.records) == 2
assert "[arrival] is an invalid option" in caplog.text | [
"async",
"def",
"test_arrival_only_allowed_for_timetable",
"(",
"hass",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"origin",
"=",
"\"41.9798,-87.8801\"",
"destination",
"=",
"\"41.9043,-87.9216\"",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"origin_longitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"destination_latitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"destination_longitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"arrival\"",
":",
"\"01:00:00\"",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"2",
"assert",
"\"[arrival] is an invalid option\"",
"in",
"caplog",
".",
"text"
] | [
1163,
0
] | [
1183,
58
] | python | en | ['en', 'en', 'en'] | True |
test_exclusive_arrival_and_departure | (hass, caplog) | Test that arrival and departure are exclusive. | Test that arrival and departure are exclusive. | async def test_exclusive_arrival_and_departure(hass, caplog):
"""Test that arrival and departure are exclusive."""
caplog.set_level(logging.ERROR)
origin = "41.9798,-87.8801"
destination = "41.9043,-87.9216"
config = {
DOMAIN: {
"platform": PLATFORM,
"name": "test",
"origin_latitude": origin.split(",")[0],
"origin_longitude": origin.split(",")[1],
"destination_latitude": destination.split(",")[0],
"destination_longitude": destination.split(",")[1],
"api_key": API_KEY,
"arrival": "01:00:00",
"mode": TRAVEL_MODE_PUBLIC_TIME_TABLE,
"departure": "01:00:00",
}
}
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
assert len(caplog.records) == 2
assert "two or more values in the same group of exclusion" in caplog.text | [
"async",
"def",
"test_exclusive_arrival_and_departure",
"(",
"hass",
",",
"caplog",
")",
":",
"caplog",
".",
"set_level",
"(",
"logging",
".",
"ERROR",
")",
"origin",
"=",
"\"41.9798,-87.8801\"",
"destination",
"=",
"\"41.9043,-87.9216\"",
"config",
"=",
"{",
"DOMAIN",
":",
"{",
"\"platform\"",
":",
"PLATFORM",
",",
"\"name\"",
":",
"\"test\"",
",",
"\"origin_latitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"origin_longitude\"",
":",
"origin",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"destination_latitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"0",
"]",
",",
"\"destination_longitude\"",
":",
"destination",
".",
"split",
"(",
"\",\"",
")",
"[",
"1",
"]",
",",
"\"api_key\"",
":",
"API_KEY",
",",
"\"arrival\"",
":",
"\"01:00:00\"",
",",
"\"mode\"",
":",
"TRAVEL_MODE_PUBLIC_TIME_TABLE",
",",
"\"departure\"",
":",
"\"01:00:00\"",
",",
"}",
"}",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"caplog",
".",
"records",
")",
"==",
"2",
"assert",
"\"two or more values in the same group of exclusion\"",
"in",
"caplog",
".",
"text"
] | [
1186,
0
] | [
1208,
77
] | python | en | ['en', 'en', 'en'] | True |
test_client_connected | (hass) | Test client connected. | Test client connected. | async def test_client_connected(hass):
"""Test client connected."""
await init_integration(hass)
future = utcnow() + timedelta(minutes=60)
with patch(
"homeassistant.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients",
return_value={
TEST_CLIENT[API_MAC]: TEST_CLIENT,
},
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
await hass.helpers.entity_component.async_update_entity(TEST_CLIENT_ENTITY_ID)
test_client = hass.states.get(TEST_CLIENT_ENTITY_ID)
assert test_client.state == STATE_HOME | [
"async",
"def",
"test_client_connected",
"(",
"hass",
")",
":",
"await",
"init_integration",
"(",
"hass",
")",
"future",
"=",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"minutes",
"=",
"60",
")",
"with",
"patch",
"(",
"\"homeassistant.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients\"",
",",
"return_value",
"=",
"{",
"TEST_CLIENT",
"[",
"API_MAC",
"]",
":",
"TEST_CLIENT",
",",
"}",
",",
")",
":",
"async_fire_time_changed",
"(",
"hass",
",",
"future",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"helpers",
".",
"entity_component",
".",
"async_update_entity",
"(",
"TEST_CLIENT_ENTITY_ID",
")",
"test_client",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"TEST_CLIENT_ENTITY_ID",
")",
"assert",
"test_client",
".",
"state",
"==",
"STATE_HOME"
] | [
24,
0
] | [
40,
42
] | python | en | ['en', 'en', 'en'] | True |
test_client_disconnected | (hass) | Test client disconnected. | Test client disconnected. | async def test_client_disconnected(hass):
"""Test client disconnected."""
await init_integration(hass)
future = utcnow() + timedelta(minutes=60)
with patch(
"homeassistant.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients",
return_value={},
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
await hass.helpers.entity_component.async_update_entity(TEST_CLIENT_ENTITY_ID)
test_client = hass.states.get(TEST_CLIENT_ENTITY_ID)
assert test_client.state == STATE_NOT_HOME | [
"async",
"def",
"test_client_disconnected",
"(",
"hass",
")",
":",
"await",
"init_integration",
"(",
"hass",
")",
"future",
"=",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"minutes",
"=",
"60",
")",
"with",
"patch",
"(",
"\"homeassistant.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients\"",
",",
"return_value",
"=",
"{",
"}",
",",
")",
":",
"async_fire_time_changed",
"(",
"hass",
",",
"future",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"helpers",
".",
"entity_component",
".",
"async_update_entity",
"(",
"TEST_CLIENT_ENTITY_ID",
")",
"test_client",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"TEST_CLIENT_ENTITY_ID",
")",
"assert",
"test_client",
".",
"state",
"==",
"STATE_NOT_HOME"
] | [
43,
0
] | [
57,
50
] | python | en | ['fr', 'en', 'en'] | True |
test_clients_update_failed | (hass) | Test failed update. | Test failed update. | async def test_clients_update_failed(hass):
"""Test failed update."""
await init_integration(hass)
future = utcnow() + timedelta(minutes=60)
with patch(
"homeassistant.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients",
side_effect=ConnectionError,
):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
await hass.helpers.entity_component.async_update_entity(TEST_CLIENT_ENTITY_ID)
test_client = hass.states.get(TEST_CLIENT_ENTITY_ID)
assert test_client.state == STATE_UNAVAILABLE | [
"async",
"def",
"test_clients_update_failed",
"(",
"hass",
")",
":",
"await",
"init_integration",
"(",
"hass",
")",
"future",
"=",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"minutes",
"=",
"60",
")",
"with",
"patch",
"(",
"\"homeassistant.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients\"",
",",
"side_effect",
"=",
"ConnectionError",
",",
")",
":",
"async_fire_time_changed",
"(",
"hass",
",",
"future",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"await",
"hass",
".",
"helpers",
".",
"entity_component",
".",
"async_update_entity",
"(",
"TEST_CLIENT_ENTITY_ID",
")",
"test_client",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"TEST_CLIENT_ENTITY_ID",
")",
"assert",
"test_client",
".",
"state",
"==",
"STATE_UNAVAILABLE"
] | [
60,
0
] | [
74,
53
] | python | en | ['en', 'lb', 'en'] | True |
test_restoring_clients | (hass) | Test restoring existing device_tracker entities if not detected on startup. | Test restoring existing device_tracker entities if not detected on startup. | async def test_restoring_clients(hass):
"""Test restoring existing device_tracker entities if not detected on startup."""
entry = mock_config_entry()
entry.add_to_hass(hass)
registry = await entity_registry.async_get_registry(hass)
registry.async_get_or_create(
"device_tracker",
DOMAIN,
DEFAULT_UNIQUE_ID,
suggested_object_id="ruckus_test_device",
config_entry=entry,
)
with patch(
"homeassistant.components.ruckus_unleashed.Ruckus.connect",
return_value=None,
), patch(
"homeassistant.components.ruckus_unleashed.Ruckus.mesh_name",
return_value=DEFAULT_TITLE,
), patch(
"homeassistant.components.ruckus_unleashed.Ruckus.system_info",
return_value=DEFAULT_SYSTEM_INFO,
), patch(
"homeassistant.components.ruckus_unleashed.Ruckus.ap_info",
return_value=DEFAULT_AP_INFO,
), patch(
"homeassistant.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients",
return_value={},
):
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
device = hass.states.get(TEST_CLIENT_ENTITY_ID)
assert device is not None
assert device.state == STATE_NOT_HOME | [
"async",
"def",
"test_restoring_clients",
"(",
"hass",
")",
":",
"entry",
"=",
"mock_config_entry",
"(",
")",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"registry",
"=",
"await",
"entity_registry",
".",
"async_get_registry",
"(",
"hass",
")",
"registry",
".",
"async_get_or_create",
"(",
"\"device_tracker\"",
",",
"DOMAIN",
",",
"DEFAULT_UNIQUE_ID",
",",
"suggested_object_id",
"=",
"\"ruckus_test_device\"",
",",
"config_entry",
"=",
"entry",
",",
")",
"with",
"patch",
"(",
"\"homeassistant.components.ruckus_unleashed.Ruckus.connect\"",
",",
"return_value",
"=",
"None",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.ruckus_unleashed.Ruckus.mesh_name\"",
",",
"return_value",
"=",
"DEFAULT_TITLE",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.ruckus_unleashed.Ruckus.system_info\"",
",",
"return_value",
"=",
"DEFAULT_SYSTEM_INFO",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.ruckus_unleashed.Ruckus.ap_info\"",
",",
"return_value",
"=",
"DEFAULT_AP_INFO",
",",
")",
",",
"patch",
"(",
"\"homeassistant.components.ruckus_unleashed.RuckusUnleashedDataUpdateCoordinator._fetch_clients\"",
",",
"return_value",
"=",
"{",
"}",
",",
")",
":",
"entry",
".",
"add_to_hass",
"(",
"hass",
")",
"await",
"hass",
".",
"config_entries",
".",
"async_setup",
"(",
"entry",
".",
"entry_id",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"device",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"TEST_CLIENT_ENTITY_ID",
")",
"assert",
"device",
"is",
"not",
"None",
"assert",
"device",
".",
"state",
"==",
"STATE_NOT_HOME"
] | [
77,
0
] | [
113,
41
] | python | en | ['en', 'en', 'en'] | True |
test_client_device_setup | (hass) | Test a client device is created. | Test a client device is created. | async def test_client_device_setup(hass):
"""Test a client device is created."""
await init_integration(hass)
router_info = DEFAULT_AP_INFO[API_AP][API_ID]["1"]
device_registry = await hass.helpers.device_registry.async_get_registry()
client_device = device_registry.async_get_device(
identifiers={},
connections={(CONNECTION_NETWORK_MAC, TEST_CLIENT[API_MAC])},
)
router_device = device_registry.async_get_device(
identifiers={(CONNECTION_NETWORK_MAC, router_info[API_MAC])},
connections={(CONNECTION_NETWORK_MAC, router_info[API_MAC])},
)
assert client_device
assert client_device.name == TEST_CLIENT[API_NAME]
assert client_device.via_device_id == router_device.id | [
"async",
"def",
"test_client_device_setup",
"(",
"hass",
")",
":",
"await",
"init_integration",
"(",
"hass",
")",
"router_info",
"=",
"DEFAULT_AP_INFO",
"[",
"API_AP",
"]",
"[",
"API_ID",
"]",
"[",
"\"1\"",
"]",
"device_registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"device_registry",
".",
"async_get_registry",
"(",
")",
"client_device",
"=",
"device_registry",
".",
"async_get_device",
"(",
"identifiers",
"=",
"{",
"}",
",",
"connections",
"=",
"{",
"(",
"CONNECTION_NETWORK_MAC",
",",
"TEST_CLIENT",
"[",
"API_MAC",
"]",
")",
"}",
",",
")",
"router_device",
"=",
"device_registry",
".",
"async_get_device",
"(",
"identifiers",
"=",
"{",
"(",
"CONNECTION_NETWORK_MAC",
",",
"router_info",
"[",
"API_MAC",
"]",
")",
"}",
",",
"connections",
"=",
"{",
"(",
"CONNECTION_NETWORK_MAC",
",",
"router_info",
"[",
"API_MAC",
"]",
")",
"}",
",",
")",
"assert",
"client_device",
"assert",
"client_device",
".",
"name",
"==",
"TEST_CLIENT",
"[",
"API_NAME",
"]",
"assert",
"client_device",
".",
"via_device_id",
"==",
"router_device",
".",
"id"
] | [
116,
0
] | [
134,
58
] | python | en | ['en', 'en', 'en'] | True |
request_app_setup | (hass, config, add_entities, config_path, discovery_info=None) | Assist user with configuring the Fitbit dev application. | Assist user with configuring the Fitbit dev application. | def request_app_setup(hass, config, add_entities, config_path, discovery_info=None):
"""Assist user with configuring the Fitbit dev application."""
configurator = hass.components.configurator
def fitbit_configuration_callback(callback_data):
"""Handle configuration updates."""
config_path = hass.config.path(FITBIT_CONFIG_FILE)
if os.path.isfile(config_path):
config_file = load_json(config_path)
if config_file == DEFAULT_CONFIG:
error_msg = (
"You didn't correctly modify fitbit.conf",
" please try again",
)
configurator.notify_errors(_CONFIGURING["fitbit"], error_msg)
else:
setup_platform(hass, config, add_entities, discovery_info)
else:
setup_platform(hass, config, add_entities, discovery_info)
start_url = f"{get_url(hass)}{FITBIT_AUTH_CALLBACK_PATH}"
description = f"""Please create a Fitbit developer app at
https://dev.fitbit.com/apps/new.
For the OAuth 2.0 Application Type choose Personal.
Set the Callback URL to {start_url}.
They will provide you a Client ID and secret.
These need to be saved into the file located at: {config_path}.
Then come back here and hit the below button.
"""
submit = "I have saved my Client ID and Client Secret into fitbit.conf."
_CONFIGURING["fitbit"] = configurator.request_config(
"Fitbit",
fitbit_configuration_callback,
description=description,
submit_caption=submit,
description_image="/static/images/config_fitbit_app.png",
) | [
"def",
"request_app_setup",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"config_path",
",",
"discovery_info",
"=",
"None",
")",
":",
"configurator",
"=",
"hass",
".",
"components",
".",
"configurator",
"def",
"fitbit_configuration_callback",
"(",
"callback_data",
")",
":",
"\"\"\"Handle configuration updates.\"\"\"",
"config_path",
"=",
"hass",
".",
"config",
".",
"path",
"(",
"FITBIT_CONFIG_FILE",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"config_file",
"=",
"load_json",
"(",
"config_path",
")",
"if",
"config_file",
"==",
"DEFAULT_CONFIG",
":",
"error_msg",
"=",
"(",
"\"You didn't correctly modify fitbit.conf\"",
",",
"\" please try again\"",
",",
")",
"configurator",
".",
"notify_errors",
"(",
"_CONFIGURING",
"[",
"\"fitbit\"",
"]",
",",
"error_msg",
")",
"else",
":",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
")",
"else",
":",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
")",
"start_url",
"=",
"f\"{get_url(hass)}{FITBIT_AUTH_CALLBACK_PATH}\"",
"description",
"=",
"f\"\"\"Please create a Fitbit developer app at\n https://dev.fitbit.com/apps/new.\n For the OAuth 2.0 Application Type choose Personal.\n Set the Callback URL to {start_url}.\n They will provide you a Client ID and secret.\n These need to be saved into the file located at: {config_path}.\n Then come back here and hit the below button.\n \"\"\"",
"submit",
"=",
"\"I have saved my Client ID and Client Secret into fitbit.conf.\"",
"_CONFIGURING",
"[",
"\"fitbit\"",
"]",
"=",
"configurator",
".",
"request_config",
"(",
"\"Fitbit\"",
",",
"fitbit_configuration_callback",
",",
"description",
"=",
"description",
",",
"submit_caption",
"=",
"submit",
",",
"description_image",
"=",
"\"/static/images/config_fitbit_app.png\"",
",",
")"
] | [
167,
0
] | [
206,
5
] | python | en | ['en', 'en', 'en'] | True |
request_oauth_completion | (hass) | Request user complete Fitbit OAuth2 flow. | Request user complete Fitbit OAuth2 flow. | def request_oauth_completion(hass):
"""Request user complete Fitbit OAuth2 flow."""
configurator = hass.components.configurator
if "fitbit" in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING["fitbit"], "Failed to register, please try again."
)
return
def fitbit_configuration_callback(callback_data):
"""Handle configuration updates."""
start_url = f"{get_url(hass)}{FITBIT_AUTH_START}"
description = f"Please authorize Fitbit by visiting {start_url}"
_CONFIGURING["fitbit"] = configurator.request_config(
"Fitbit",
fitbit_configuration_callback,
description=description,
submit_caption="I have authorized Fitbit.",
) | [
"def",
"request_oauth_completion",
"(",
"hass",
")",
":",
"configurator",
"=",
"hass",
".",
"components",
".",
"configurator",
"if",
"\"fitbit\"",
"in",
"_CONFIGURING",
":",
"configurator",
".",
"notify_errors",
"(",
"_CONFIGURING",
"[",
"\"fitbit\"",
"]",
",",
"\"Failed to register, please try again.\"",
")",
"return",
"def",
"fitbit_configuration_callback",
"(",
"callback_data",
")",
":",
"\"\"\"Handle configuration updates.\"\"\"",
"start_url",
"=",
"f\"{get_url(hass)}{FITBIT_AUTH_START}\"",
"description",
"=",
"f\"Please authorize Fitbit by visiting {start_url}\"",
"_CONFIGURING",
"[",
"\"fitbit\"",
"]",
"=",
"configurator",
".",
"request_config",
"(",
"\"Fitbit\"",
",",
"fitbit_configuration_callback",
",",
"description",
"=",
"description",
",",
"submit_caption",
"=",
"\"I have authorized Fitbit.\"",
",",
")"
] | [
209,
0
] | [
231,
5
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Fitbit sensor. | Set up the Fitbit sensor. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Fitbit sensor."""
config_path = hass.config.path(FITBIT_CONFIG_FILE)
if os.path.isfile(config_path):
config_file = load_json(config_path)
if config_file == DEFAULT_CONFIG:
request_app_setup(
hass, config, add_entities, config_path, discovery_info=None
)
return False
else:
save_json(config_path, DEFAULT_CONFIG)
request_app_setup(hass, config, add_entities, config_path, discovery_info=None)
return False
if "fitbit" in _CONFIGURING:
hass.components.configurator.request_done(_CONFIGURING.pop("fitbit"))
access_token = config_file.get(ATTR_ACCESS_TOKEN)
refresh_token = config_file.get(ATTR_REFRESH_TOKEN)
expires_at = config_file.get(ATTR_LAST_SAVED_AT)
if None not in (access_token, refresh_token):
authd_client = Fitbit(
config_file.get(CONF_CLIENT_ID),
config_file.get(CONF_CLIENT_SECRET),
access_token=access_token,
refresh_token=refresh_token,
expires_at=expires_at,
refresh_cb=lambda x: None,
)
if int(time.time()) - expires_at > 3600:
authd_client.client.refresh_token()
unit_system = config.get(CONF_UNIT_SYSTEM)
if unit_system == "default":
authd_client.system = authd_client.user_profile_get()["user"]["locale"]
if authd_client.system != "en_GB":
if hass.config.units.is_metric:
authd_client.system = "metric"
else:
authd_client.system = "en_US"
else:
authd_client.system = unit_system
dev = []
registered_devs = authd_client.get_devices()
clock_format = config.get(CONF_CLOCK_FORMAT)
for resource in config.get(CONF_MONITORED_RESOURCES):
# monitor battery for all linked FitBit devices
if resource == "devices/battery":
for dev_extra in registered_devs:
dev.append(
FitbitSensor(
authd_client,
config_path,
resource,
hass.config.units.is_metric,
clock_format,
dev_extra,
)
)
else:
dev.append(
FitbitSensor(
authd_client,
config_path,
resource,
hass.config.units.is_metric,
clock_format,
)
)
add_entities(dev, True)
else:
oauth = FitbitOauth2Client(
config_file.get(CONF_CLIENT_ID), config_file.get(CONF_CLIENT_SECRET)
)
redirect_uri = f"{get_url(hass)}{FITBIT_AUTH_CALLBACK_PATH}"
fitbit_auth_start_url, _ = oauth.authorize_token_url(
redirect_uri=redirect_uri,
scope=[
"activity",
"heartrate",
"nutrition",
"profile",
"settings",
"sleep",
"weight",
],
)
hass.http.register_redirect(FITBIT_AUTH_START, fitbit_auth_start_url)
hass.http.register_view(FitbitAuthCallbackView(config, add_entities, oauth))
request_oauth_completion(hass) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"config_path",
"=",
"hass",
".",
"config",
".",
"path",
"(",
"FITBIT_CONFIG_FILE",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"config_file",
"=",
"load_json",
"(",
"config_path",
")",
"if",
"config_file",
"==",
"DEFAULT_CONFIG",
":",
"request_app_setup",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"config_path",
",",
"discovery_info",
"=",
"None",
")",
"return",
"False",
"else",
":",
"save_json",
"(",
"config_path",
",",
"DEFAULT_CONFIG",
")",
"request_app_setup",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"config_path",
",",
"discovery_info",
"=",
"None",
")",
"return",
"False",
"if",
"\"fitbit\"",
"in",
"_CONFIGURING",
":",
"hass",
".",
"components",
".",
"configurator",
".",
"request_done",
"(",
"_CONFIGURING",
".",
"pop",
"(",
"\"fitbit\"",
")",
")",
"access_token",
"=",
"config_file",
".",
"get",
"(",
"ATTR_ACCESS_TOKEN",
")",
"refresh_token",
"=",
"config_file",
".",
"get",
"(",
"ATTR_REFRESH_TOKEN",
")",
"expires_at",
"=",
"config_file",
".",
"get",
"(",
"ATTR_LAST_SAVED_AT",
")",
"if",
"None",
"not",
"in",
"(",
"access_token",
",",
"refresh_token",
")",
":",
"authd_client",
"=",
"Fitbit",
"(",
"config_file",
".",
"get",
"(",
"CONF_CLIENT_ID",
")",
",",
"config_file",
".",
"get",
"(",
"CONF_CLIENT_SECRET",
")",
",",
"access_token",
"=",
"access_token",
",",
"refresh_token",
"=",
"refresh_token",
",",
"expires_at",
"=",
"expires_at",
",",
"refresh_cb",
"=",
"lambda",
"x",
":",
"None",
",",
")",
"if",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
"-",
"expires_at",
">",
"3600",
":",
"authd_client",
".",
"client",
".",
"refresh_token",
"(",
")",
"unit_system",
"=",
"config",
".",
"get",
"(",
"CONF_UNIT_SYSTEM",
")",
"if",
"unit_system",
"==",
"\"default\"",
":",
"authd_client",
".",
"system",
"=",
"authd_client",
".",
"user_profile_get",
"(",
")",
"[",
"\"user\"",
"]",
"[",
"\"locale\"",
"]",
"if",
"authd_client",
".",
"system",
"!=",
"\"en_GB\"",
":",
"if",
"hass",
".",
"config",
".",
"units",
".",
"is_metric",
":",
"authd_client",
".",
"system",
"=",
"\"metric\"",
"else",
":",
"authd_client",
".",
"system",
"=",
"\"en_US\"",
"else",
":",
"authd_client",
".",
"system",
"=",
"unit_system",
"dev",
"=",
"[",
"]",
"registered_devs",
"=",
"authd_client",
".",
"get_devices",
"(",
")",
"clock_format",
"=",
"config",
".",
"get",
"(",
"CONF_CLOCK_FORMAT",
")",
"for",
"resource",
"in",
"config",
".",
"get",
"(",
"CONF_MONITORED_RESOURCES",
")",
":",
"# monitor battery for all linked FitBit devices",
"if",
"resource",
"==",
"\"devices/battery\"",
":",
"for",
"dev_extra",
"in",
"registered_devs",
":",
"dev",
".",
"append",
"(",
"FitbitSensor",
"(",
"authd_client",
",",
"config_path",
",",
"resource",
",",
"hass",
".",
"config",
".",
"units",
".",
"is_metric",
",",
"clock_format",
",",
"dev_extra",
",",
")",
")",
"else",
":",
"dev",
".",
"append",
"(",
"FitbitSensor",
"(",
"authd_client",
",",
"config_path",
",",
"resource",
",",
"hass",
".",
"config",
".",
"units",
".",
"is_metric",
",",
"clock_format",
",",
")",
")",
"add_entities",
"(",
"dev",
",",
"True",
")",
"else",
":",
"oauth",
"=",
"FitbitOauth2Client",
"(",
"config_file",
".",
"get",
"(",
"CONF_CLIENT_ID",
")",
",",
"config_file",
".",
"get",
"(",
"CONF_CLIENT_SECRET",
")",
")",
"redirect_uri",
"=",
"f\"{get_url(hass)}{FITBIT_AUTH_CALLBACK_PATH}\"",
"fitbit_auth_start_url",
",",
"_",
"=",
"oauth",
".",
"authorize_token_url",
"(",
"redirect_uri",
"=",
"redirect_uri",
",",
"scope",
"=",
"[",
"\"activity\"",
",",
"\"heartrate\"",
",",
"\"nutrition\"",
",",
"\"profile\"",
",",
"\"settings\"",
",",
"\"sleep\"",
",",
"\"weight\"",
",",
"]",
",",
")",
"hass",
".",
"http",
".",
"register_redirect",
"(",
"FITBIT_AUTH_START",
",",
"fitbit_auth_start_url",
")",
"hass",
".",
"http",
".",
"register_view",
"(",
"FitbitAuthCallbackView",
"(",
"config",
",",
"add_entities",
",",
"oauth",
")",
")",
"request_oauth_completion",
"(",
"hass",
")"
] | [
234,
0
] | [
332,
38
] | python | en | ['en', 'da', 'en'] | True |
FitbitAuthCallbackView.__init__ | (self, config, add_entities, oauth) | Initialize the OAuth callback view. | Initialize the OAuth callback view. | def __init__(self, config, add_entities, oauth):
"""Initialize the OAuth callback view."""
self.config = config
self.add_entities = add_entities
self.oauth = oauth | [
"def",
"__init__",
"(",
"self",
",",
"config",
",",
"add_entities",
",",
"oauth",
")",
":",
"self",
".",
"config",
"=",
"config",
"self",
".",
"add_entities",
"=",
"add_entities",
"self",
".",
"oauth",
"=",
"oauth"
] | [
342,
4
] | [
346,
26
] | python | en | ['en', 'en', 'en'] | True |
FitbitAuthCallbackView.get | (self, request) | Finish OAuth callback request. | Finish OAuth callback request. | def get(self, request):
"""Finish OAuth callback request."""
hass = request.app["hass"]
data = request.query
response_message = """Fitbit has been successfully authorized!
You can close this window now!"""
result = None
if data.get("code") is not None:
redirect_uri = f"{get_url(hass, require_current_request=True)}{FITBIT_AUTH_CALLBACK_PATH}"
try:
result = self.oauth.fetch_access_token(data.get("code"), redirect_uri)
except MissingTokenError as error:
_LOGGER.error("Missing token: %s", error)
response_message = f"""Something went wrong when
attempting authenticating with Fitbit. The error
encountered was {error}. Please try again!"""
except MismatchingStateError as error:
_LOGGER.error("Mismatched state, CSRF error: %s", error)
response_message = f"""Something went wrong when
attempting authenticating with Fitbit. The error
encountered was {error}. Please try again!"""
else:
_LOGGER.error("Unknown error when authing")
response_message = """Something went wrong when
attempting authenticating with Fitbit.
An unknown error occurred. Please try again!
"""
if result is None:
_LOGGER.error("Unknown error when authing")
response_message = """Something went wrong when
attempting authenticating with Fitbit.
An unknown error occurred. Please try again!
"""
html_response = f"""<html><head><title>Fitbit Auth</title></head>
<body><h1>{response_message}</h1></body></html>"""
if result:
config_contents = {
ATTR_ACCESS_TOKEN: result.get("access_token"),
ATTR_REFRESH_TOKEN: result.get("refresh_token"),
CONF_CLIENT_ID: self.oauth.client_id,
CONF_CLIENT_SECRET: self.oauth.client_secret,
ATTR_LAST_SAVED_AT: int(time.time()),
}
save_json(hass.config.path(FITBIT_CONFIG_FILE), config_contents)
hass.async_add_job(setup_platform, hass, self.config, self.add_entities)
return html_response | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"data",
"=",
"request",
".",
"query",
"response_message",
"=",
"\"\"\"Fitbit has been successfully authorized!\n You can close this window now!\"\"\"",
"result",
"=",
"None",
"if",
"data",
".",
"get",
"(",
"\"code\"",
")",
"is",
"not",
"None",
":",
"redirect_uri",
"=",
"f\"{get_url(hass, require_current_request=True)}{FITBIT_AUTH_CALLBACK_PATH}\"",
"try",
":",
"result",
"=",
"self",
".",
"oauth",
".",
"fetch_access_token",
"(",
"data",
".",
"get",
"(",
"\"code\"",
")",
",",
"redirect_uri",
")",
"except",
"MissingTokenError",
"as",
"error",
":",
"_LOGGER",
".",
"error",
"(",
"\"Missing token: %s\"",
",",
"error",
")",
"response_message",
"=",
"f\"\"\"Something went wrong when\n attempting authenticating with Fitbit. The error\n encountered was {error}. Please try again!\"\"\"",
"except",
"MismatchingStateError",
"as",
"error",
":",
"_LOGGER",
".",
"error",
"(",
"\"Mismatched state, CSRF error: %s\"",
",",
"error",
")",
"response_message",
"=",
"f\"\"\"Something went wrong when\n attempting authenticating with Fitbit. The error\n encountered was {error}. Please try again!\"\"\"",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unknown error when authing\"",
")",
"response_message",
"=",
"\"\"\"Something went wrong when\n attempting authenticating with Fitbit.\n An unknown error occurred. Please try again!\n \"\"\"",
"if",
"result",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unknown error when authing\"",
")",
"response_message",
"=",
"\"\"\"Something went wrong when\n attempting authenticating with Fitbit.\n An unknown error occurred. Please try again!\n \"\"\"",
"html_response",
"=",
"f\"\"\"<html><head><title>Fitbit Auth</title></head>\n <body><h1>{response_message}</h1></body></html>\"\"\"",
"if",
"result",
":",
"config_contents",
"=",
"{",
"ATTR_ACCESS_TOKEN",
":",
"result",
".",
"get",
"(",
"\"access_token\"",
")",
",",
"ATTR_REFRESH_TOKEN",
":",
"result",
".",
"get",
"(",
"\"refresh_token\"",
")",
",",
"CONF_CLIENT_ID",
":",
"self",
".",
"oauth",
".",
"client_id",
",",
"CONF_CLIENT_SECRET",
":",
"self",
".",
"oauth",
".",
"client_secret",
",",
"ATTR_LAST_SAVED_AT",
":",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"}",
"save_json",
"(",
"hass",
".",
"config",
".",
"path",
"(",
"FITBIT_CONFIG_FILE",
")",
",",
"config_contents",
")",
"hass",
".",
"async_add_job",
"(",
"setup_platform",
",",
"hass",
",",
"self",
".",
"config",
",",
"self",
".",
"add_entities",
")",
"return",
"html_response"
] | [
349,
4
] | [
402,
28
] | python | en | ['en', 'en', 'en'] | True |
FitbitSensor.__init__ | (
self, client, config_path, resource_type, is_metric, clock_format, extra=None
) | Initialize the Fitbit sensor. | Initialize the Fitbit sensor. | def __init__(
self, client, config_path, resource_type, is_metric, clock_format, extra=None
):
"""Initialize the Fitbit sensor."""
self.client = client
self.config_path = config_path
self.resource_type = resource_type
self.is_metric = is_metric
self.clock_format = clock_format
self.extra = extra
self._name = FITBIT_RESOURCES_LIST[self.resource_type][0]
if self.extra:
self._name = f"{self.extra.get('deviceVersion')} Battery"
unit_type = FITBIT_RESOURCES_LIST[self.resource_type][1]
if unit_type == "":
split_resource = self.resource_type.split("/")
try:
measurement_system = FITBIT_MEASUREMENTS[self.client.system]
except KeyError:
if self.is_metric:
measurement_system = FITBIT_MEASUREMENTS["metric"]
else:
measurement_system = FITBIT_MEASUREMENTS["en_US"]
unit_type = measurement_system[split_resource[-1]]
self._unit_of_measurement = unit_type
self._state = 0 | [
"def",
"__init__",
"(",
"self",
",",
"client",
",",
"config_path",
",",
"resource_type",
",",
"is_metric",
",",
"clock_format",
",",
"extra",
"=",
"None",
")",
":",
"self",
".",
"client",
"=",
"client",
"self",
".",
"config_path",
"=",
"config_path",
"self",
".",
"resource_type",
"=",
"resource_type",
"self",
".",
"is_metric",
"=",
"is_metric",
"self",
".",
"clock_format",
"=",
"clock_format",
"self",
".",
"extra",
"=",
"extra",
"self",
".",
"_name",
"=",
"FITBIT_RESOURCES_LIST",
"[",
"self",
".",
"resource_type",
"]",
"[",
"0",
"]",
"if",
"self",
".",
"extra",
":",
"self",
".",
"_name",
"=",
"f\"{self.extra.get('deviceVersion')} Battery\"",
"unit_type",
"=",
"FITBIT_RESOURCES_LIST",
"[",
"self",
".",
"resource_type",
"]",
"[",
"1",
"]",
"if",
"unit_type",
"==",
"\"\"",
":",
"split_resource",
"=",
"self",
".",
"resource_type",
".",
"split",
"(",
"\"/\"",
")",
"try",
":",
"measurement_system",
"=",
"FITBIT_MEASUREMENTS",
"[",
"self",
".",
"client",
".",
"system",
"]",
"except",
"KeyError",
":",
"if",
"self",
".",
"is_metric",
":",
"measurement_system",
"=",
"FITBIT_MEASUREMENTS",
"[",
"\"metric\"",
"]",
"else",
":",
"measurement_system",
"=",
"FITBIT_MEASUREMENTS",
"[",
"\"en_US\"",
"]",
"unit_type",
"=",
"measurement_system",
"[",
"split_resource",
"[",
"-",
"1",
"]",
"]",
"self",
".",
"_unit_of_measurement",
"=",
"unit_type",
"self",
".",
"_state",
"=",
"0"
] | [
408,
4
] | [
433,
23
] | python | en | ['en', 'en', 'en'] | True |
FitbitSensor.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"
] | [
436,
4
] | [
438,
25
] | python | en | ['en', 'mi', 'en'] | True |
FitbitSensor.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"
] | [
441,
4
] | [
443,
26
] | python | en | ['en', 'en', 'en'] | True |
FitbitSensor.unit_of_measurement | (self) | Return the unit of measurement of this entity, if any. | Return the unit of measurement of this entity, if any. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
446,
4
] | [
448,
40
] | python | en | ['en', 'en', 'en'] | True |
FitbitSensor.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
if self.resource_type == "devices/battery" and self.extra:
battery_level = BATTERY_LEVELS[self.extra.get("battery")]
return icon_for_battery_level(battery_level=battery_level, charging=None)
return f"mdi:{FITBIT_RESOURCES_LIST[self.resource_type][2]}" | [
"def",
"icon",
"(",
"self",
")",
":",
"if",
"self",
".",
"resource_type",
"==",
"\"devices/battery\"",
"and",
"self",
".",
"extra",
":",
"battery_level",
"=",
"BATTERY_LEVELS",
"[",
"self",
".",
"extra",
".",
"get",
"(",
"\"battery\"",
")",
"]",
"return",
"icon_for_battery_level",
"(",
"battery_level",
"=",
"battery_level",
",",
"charging",
"=",
"None",
")",
"return",
"f\"mdi:{FITBIT_RESOURCES_LIST[self.resource_type][2]}\""
] | [
451,
4
] | [
456,
68
] | python | en | ['en', 'en', 'en'] | True |
FitbitSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
attrs = {}
attrs[ATTR_ATTRIBUTION] = ATTRIBUTION
if self.extra:
attrs["model"] = self.extra.get("deviceVersion")
attrs["type"] = self.extra.get("type").lower()
return attrs | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attrs",
"=",
"{",
"}",
"attrs",
"[",
"ATTR_ATTRIBUTION",
"]",
"=",
"ATTRIBUTION",
"if",
"self",
".",
"extra",
":",
"attrs",
"[",
"\"model\"",
"]",
"=",
"self",
".",
"extra",
".",
"get",
"(",
"\"deviceVersion\"",
")",
"attrs",
"[",
"\"type\"",
"]",
"=",
"self",
".",
"extra",
".",
"get",
"(",
"\"type\"",
")",
".",
"lower",
"(",
")",
"return",
"attrs"
] | [
459,
4
] | [
469,
20
] | python | en | ['en', 'en', 'en'] | True |
FitbitSensor.update | (self) | Get the latest data from the Fitbit API and update the states. | Get the latest data from the Fitbit API and update the states. | def update(self):
"""Get the latest data from the Fitbit API and update the states."""
if self.resource_type == "devices/battery" and self.extra:
registered_devs = self.client.get_devices()
device_id = self.extra.get("id")
self.extra = list(
filter(lambda device: device.get("id") == device_id, registered_devs)
)[0]
self._state = self.extra.get("battery")
else:
container = self.resource_type.replace("/", "-")
response = self.client.time_series(self.resource_type, period="7d")
raw_state = response[container][-1].get("value")
if self.resource_type == "activities/distance":
self._state = format(float(raw_state), ".2f")
elif self.resource_type == "activities/tracker/distance":
self._state = format(float(raw_state), ".2f")
elif self.resource_type == "body/bmi":
self._state = format(float(raw_state), ".1f")
elif self.resource_type == "body/fat":
self._state = format(float(raw_state), ".1f")
elif self.resource_type == "body/weight":
self._state = format(float(raw_state), ".1f")
elif self.resource_type == "sleep/startTime":
if raw_state == "":
self._state = "-"
elif self.clock_format == "12H":
hours, minutes = raw_state.split(":")
hours, minutes = int(hours), int(minutes)
setting = "AM"
if hours > 12:
setting = "PM"
hours -= 12
elif hours == 0:
hours = 12
self._state = f"{hours}:{minutes:02d} {setting}"
else:
self._state = raw_state
else:
if self.is_metric:
self._state = raw_state
else:
try:
self._state = f"{int(raw_state):,}"
except TypeError:
self._state = raw_state
if self.resource_type == "activities/heart":
self._state = response[container][-1].get("value").get("restingHeartRate")
token = self.client.client.session.token
config_contents = {
ATTR_ACCESS_TOKEN: token.get("access_token"),
ATTR_REFRESH_TOKEN: token.get("refresh_token"),
CONF_CLIENT_ID: self.client.client.client_id,
CONF_CLIENT_SECRET: self.client.client.client_secret,
ATTR_LAST_SAVED_AT: int(time.time()),
}
save_json(self.config_path, config_contents) | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"resource_type",
"==",
"\"devices/battery\"",
"and",
"self",
".",
"extra",
":",
"registered_devs",
"=",
"self",
".",
"client",
".",
"get_devices",
"(",
")",
"device_id",
"=",
"self",
".",
"extra",
".",
"get",
"(",
"\"id\"",
")",
"self",
".",
"extra",
"=",
"list",
"(",
"filter",
"(",
"lambda",
"device",
":",
"device",
".",
"get",
"(",
"\"id\"",
")",
"==",
"device_id",
",",
"registered_devs",
")",
")",
"[",
"0",
"]",
"self",
".",
"_state",
"=",
"self",
".",
"extra",
".",
"get",
"(",
"\"battery\"",
")",
"else",
":",
"container",
"=",
"self",
".",
"resource_type",
".",
"replace",
"(",
"\"/\"",
",",
"\"-\"",
")",
"response",
"=",
"self",
".",
"client",
".",
"time_series",
"(",
"self",
".",
"resource_type",
",",
"period",
"=",
"\"7d\"",
")",
"raw_state",
"=",
"response",
"[",
"container",
"]",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"\"value\"",
")",
"if",
"self",
".",
"resource_type",
"==",
"\"activities/distance\"",
":",
"self",
".",
"_state",
"=",
"format",
"(",
"float",
"(",
"raw_state",
")",
",",
"\".2f\"",
")",
"elif",
"self",
".",
"resource_type",
"==",
"\"activities/tracker/distance\"",
":",
"self",
".",
"_state",
"=",
"format",
"(",
"float",
"(",
"raw_state",
")",
",",
"\".2f\"",
")",
"elif",
"self",
".",
"resource_type",
"==",
"\"body/bmi\"",
":",
"self",
".",
"_state",
"=",
"format",
"(",
"float",
"(",
"raw_state",
")",
",",
"\".1f\"",
")",
"elif",
"self",
".",
"resource_type",
"==",
"\"body/fat\"",
":",
"self",
".",
"_state",
"=",
"format",
"(",
"float",
"(",
"raw_state",
")",
",",
"\".1f\"",
")",
"elif",
"self",
".",
"resource_type",
"==",
"\"body/weight\"",
":",
"self",
".",
"_state",
"=",
"format",
"(",
"float",
"(",
"raw_state",
")",
",",
"\".1f\"",
")",
"elif",
"self",
".",
"resource_type",
"==",
"\"sleep/startTime\"",
":",
"if",
"raw_state",
"==",
"\"\"",
":",
"self",
".",
"_state",
"=",
"\"-\"",
"elif",
"self",
".",
"clock_format",
"==",
"\"12H\"",
":",
"hours",
",",
"minutes",
"=",
"raw_state",
".",
"split",
"(",
"\":\"",
")",
"hours",
",",
"minutes",
"=",
"int",
"(",
"hours",
")",
",",
"int",
"(",
"minutes",
")",
"setting",
"=",
"\"AM\"",
"if",
"hours",
">",
"12",
":",
"setting",
"=",
"\"PM\"",
"hours",
"-=",
"12",
"elif",
"hours",
"==",
"0",
":",
"hours",
"=",
"12",
"self",
".",
"_state",
"=",
"f\"{hours}:{minutes:02d} {setting}\"",
"else",
":",
"self",
".",
"_state",
"=",
"raw_state",
"else",
":",
"if",
"self",
".",
"is_metric",
":",
"self",
".",
"_state",
"=",
"raw_state",
"else",
":",
"try",
":",
"self",
".",
"_state",
"=",
"f\"{int(raw_state):,}\"",
"except",
"TypeError",
":",
"self",
".",
"_state",
"=",
"raw_state",
"if",
"self",
".",
"resource_type",
"==",
"\"activities/heart\"",
":",
"self",
".",
"_state",
"=",
"response",
"[",
"container",
"]",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"\"value\"",
")",
".",
"get",
"(",
"\"restingHeartRate\"",
")",
"token",
"=",
"self",
".",
"client",
".",
"client",
".",
"session",
".",
"token",
"config_contents",
"=",
"{",
"ATTR_ACCESS_TOKEN",
":",
"token",
".",
"get",
"(",
"\"access_token\"",
")",
",",
"ATTR_REFRESH_TOKEN",
":",
"token",
".",
"get",
"(",
"\"refresh_token\"",
")",
",",
"CONF_CLIENT_ID",
":",
"self",
".",
"client",
".",
"client",
".",
"client_id",
",",
"CONF_CLIENT_SECRET",
":",
"self",
".",
"client",
".",
"client",
".",
"client_secret",
",",
"ATTR_LAST_SAVED_AT",
":",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
",",
"}",
"save_json",
"(",
"self",
".",
"config_path",
",",
"config_contents",
")"
] | [
471,
4
] | [
530,
52
] | python | en | ['en', 'en', 'en'] | True |
get_checkpoint_callback | (output_dir, metric, save_top_k=1, lower_is_better=False) | Saves the best model by validation ROUGE2 score. | Saves the best model by validation ROUGE2 score. | def get_checkpoint_callback(output_dir, metric, save_top_k=1, lower_is_better=False):
"""Saves the best model by validation ROUGE2 score."""
if metric == "rouge2":
exp = "{val_avg_rouge2:.4f}-{step_count}"
elif metric == "bleu":
exp = "{val_avg_bleu:.4f}-{step_count}"
elif metric == "loss":
exp = "{val_avg_loss:.4f}-{step_count}"
else:
raise NotImplementedError(
f"seq2seq callbacks only support rouge2, bleu and loss, got {metric}, You can make your own by adding to this function."
)
checkpoint_callback = ModelCheckpoint(
dirpath=output_dir,
filename=exp,
monitor=f"val_{metric}",
mode="min" if "loss" in metric else "max",
save_top_k=save_top_k,
)
return checkpoint_callback | [
"def",
"get_checkpoint_callback",
"(",
"output_dir",
",",
"metric",
",",
"save_top_k",
"=",
"1",
",",
"lower_is_better",
"=",
"False",
")",
":",
"if",
"metric",
"==",
"\"rouge2\"",
":",
"exp",
"=",
"\"{val_avg_rouge2:.4f}-{step_count}\"",
"elif",
"metric",
"==",
"\"bleu\"",
":",
"exp",
"=",
"\"{val_avg_bleu:.4f}-{step_count}\"",
"elif",
"metric",
"==",
"\"loss\"",
":",
"exp",
"=",
"\"{val_avg_loss:.4f}-{step_count}\"",
"else",
":",
"raise",
"NotImplementedError",
"(",
"f\"seq2seq callbacks only support rouge2, bleu and loss, got {metric}, You can make your own by adding to this function.\"",
")",
"checkpoint_callback",
"=",
"ModelCheckpoint",
"(",
"dirpath",
"=",
"output_dir",
",",
"filename",
"=",
"exp",
",",
"monitor",
"=",
"f\"val_{metric}\"",
",",
"mode",
"=",
"\"min\"",
"if",
"\"loss\"",
"in",
"metric",
"else",
"\"max\"",
",",
"save_top_k",
"=",
"save_top_k",
",",
")",
"return",
"checkpoint_callback"
] | [
85,
0
] | [
105,
30
] | python | en | ['en', 'en', 'en'] | True |
format_mac | (mac: str) | Format the mac address string for entry into dev reg. | Format the mac address string for entry into dev reg. | def format_mac(mac: str) -> str:
"""Format the mac address string for entry into dev reg."""
to_test = mac
if len(to_test) == 17 and to_test.count(":") == 5:
return to_test.lower()
if len(to_test) == 17 and to_test.count("-") == 5:
to_test = to_test.replace("-", "")
elif len(to_test) == 14 and to_test.count(".") == 2:
to_test = to_test.replace(".", "")
if len(to_test) == 12:
# no : included
return ":".join(to_test.lower()[i : i + 2] for i in range(0, 12, 2))
# Not sure how formatted, return original
return mac | [
"def",
"format_mac",
"(",
"mac",
":",
"str",
")",
"->",
"str",
":",
"to_test",
"=",
"mac",
"if",
"len",
"(",
"to_test",
")",
"==",
"17",
"and",
"to_test",
".",
"count",
"(",
"\":\"",
")",
"==",
"5",
":",
"return",
"to_test",
".",
"lower",
"(",
")",
"if",
"len",
"(",
"to_test",
")",
"==",
"17",
"and",
"to_test",
".",
"count",
"(",
"\"-\"",
")",
"==",
"5",
":",
"to_test",
"=",
"to_test",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
"elif",
"len",
"(",
"to_test",
")",
"==",
"14",
"and",
"to_test",
".",
"count",
"(",
"\".\"",
")",
"==",
"2",
":",
"to_test",
"=",
"to_test",
".",
"replace",
"(",
"\".\"",
",",
"\"\"",
")",
"if",
"len",
"(",
"to_test",
")",
"==",
"12",
":",
"# no : included",
"return",
"\":\"",
".",
"join",
"(",
"to_test",
".",
"lower",
"(",
")",
"[",
"i",
":",
"i",
"+",
"2",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"12",
",",
"2",
")",
")",
"# Not sure how formatted, return original",
"return",
"mac"
] | [
80,
0
] | [
97,
14
] | python | en | ['en', 'kk', 'en'] | True |
async_get_registry | (hass: HomeAssistantType) | Create entity registry. | Create entity registry. | async def async_get_registry(hass: HomeAssistantType) -> DeviceRegistry:
"""Create entity registry."""
reg = DeviceRegistry(hass)
await reg.async_load()
return reg | [
"async",
"def",
"async_get_registry",
"(",
"hass",
":",
"HomeAssistantType",
")",
"->",
"DeviceRegistry",
":",
"reg",
"=",
"DeviceRegistry",
"(",
"hass",
")",
"await",
"reg",
".",
"async_load",
"(",
")",
"return",
"reg"
] | [
525,
0
] | [
529,
14
] | python | en | ['en', 'cy', 'en'] | True |
async_entries_for_area | (registry: DeviceRegistry, area_id: str) | Return entries that match an area. | Return entries that match an area. | def async_entries_for_area(registry: DeviceRegistry, area_id: str) -> List[DeviceEntry]:
"""Return entries that match an area."""
return [device for device in registry.devices.values() if device.area_id == area_id] | [
"def",
"async_entries_for_area",
"(",
"registry",
":",
"DeviceRegistry",
",",
"area_id",
":",
"str",
")",
"->",
"List",
"[",
"DeviceEntry",
"]",
":",
"return",
"[",
"device",
"for",
"device",
"in",
"registry",
".",
"devices",
".",
"values",
"(",
")",
"if",
"device",
".",
"area_id",
"==",
"area_id",
"]"
] | [
533,
0
] | [
535,
88
] | python | en | ['en', 'en', 'en'] | True |
async_entries_for_config_entry | (
registry: DeviceRegistry, config_entry_id: str
) | Return entries that match a config entry. | Return entries that match a config entry. | def async_entries_for_config_entry(
registry: DeviceRegistry, config_entry_id: str
) -> List[DeviceEntry]:
"""Return entries that match a config entry."""
return [
device
for device in registry.devices.values()
if config_entry_id in device.config_entries
] | [
"def",
"async_entries_for_config_entry",
"(",
"registry",
":",
"DeviceRegistry",
",",
"config_entry_id",
":",
"str",
")",
"->",
"List",
"[",
"DeviceEntry",
"]",
":",
"return",
"[",
"device",
"for",
"device",
"in",
"registry",
".",
"devices",
".",
"values",
"(",
")",
"if",
"config_entry_id",
"in",
"device",
".",
"config_entries",
"]"
] | [
539,
0
] | [
547,
5
] | python | en | ['en', 'en', 'en'] | True |
async_cleanup | (
hass: HomeAssistantType,
dev_reg: DeviceRegistry,
ent_reg: "entity_registry.EntityRegistry",
) | Clean up device registry. | Clean up device registry. | def async_cleanup(
hass: HomeAssistantType,
dev_reg: DeviceRegistry,
ent_reg: "entity_registry.EntityRegistry",
) -> None:
"""Clean up device registry."""
# Find all devices that are referenced by a config_entry.
config_entry_ids = {entry.entry_id for entry in hass.config_entries.async_entries()}
references_config_entries = {
device.id
for device in dev_reg.devices.values()
for config_entry_id in device.config_entries
if config_entry_id in config_entry_ids
}
# Find all devices that are referenced in the entity registry.
references_entities = {entry.device_id for entry in ent_reg.entities.values()}
orphan = set(dev_reg.devices) - references_entities - references_config_entries
for dev_id in orphan:
dev_reg.async_remove_device(dev_id)
# Find all referenced config entries that no longer exist
# This shouldn't happen but have not been able to track down the bug :(
for device in list(dev_reg.devices.values()):
for config_entry_id in device.config_entries:
if config_entry_id not in config_entry_ids:
dev_reg.async_update_device(
device.id, remove_config_entry_id=config_entry_id
) | [
"def",
"async_cleanup",
"(",
"hass",
":",
"HomeAssistantType",
",",
"dev_reg",
":",
"DeviceRegistry",
",",
"ent_reg",
":",
"\"entity_registry.EntityRegistry\"",
",",
")",
"->",
"None",
":",
"# Find all devices that are referenced by a config_entry.",
"config_entry_ids",
"=",
"{",
"entry",
".",
"entry_id",
"for",
"entry",
"in",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
")",
"}",
"references_config_entries",
"=",
"{",
"device",
".",
"id",
"for",
"device",
"in",
"dev_reg",
".",
"devices",
".",
"values",
"(",
")",
"for",
"config_entry_id",
"in",
"device",
".",
"config_entries",
"if",
"config_entry_id",
"in",
"config_entry_ids",
"}",
"# Find all devices that are referenced in the entity registry.",
"references_entities",
"=",
"{",
"entry",
".",
"device_id",
"for",
"entry",
"in",
"ent_reg",
".",
"entities",
".",
"values",
"(",
")",
"}",
"orphan",
"=",
"set",
"(",
"dev_reg",
".",
"devices",
")",
"-",
"references_entities",
"-",
"references_config_entries",
"for",
"dev_id",
"in",
"orphan",
":",
"dev_reg",
".",
"async_remove_device",
"(",
"dev_id",
")",
"# Find all referenced config entries that no longer exist",
"# This shouldn't happen but have not been able to track down the bug :(",
"for",
"device",
"in",
"list",
"(",
"dev_reg",
".",
"devices",
".",
"values",
"(",
")",
")",
":",
"for",
"config_entry_id",
"in",
"device",
".",
"config_entries",
":",
"if",
"config_entry_id",
"not",
"in",
"config_entry_ids",
":",
"dev_reg",
".",
"async_update_device",
"(",
"device",
".",
"id",
",",
"remove_config_entry_id",
"=",
"config_entry_id",
")"
] | [
551,
0
] | [
581,
17
] | python | en | ['nl', 'en', 'en'] | True |
async_setup_cleanup | (hass: HomeAssistantType, dev_reg: DeviceRegistry) | Clean up device registry when entities removed. | Clean up device registry when entities removed. | def async_setup_cleanup(hass: HomeAssistantType, dev_reg: DeviceRegistry) -> None:
"""Clean up device registry when entities removed."""
from . import entity_registry # pylint: disable=import-outside-toplevel
async def cleanup():
"""Cleanup."""
ent_reg = await entity_registry.async_get_registry(hass)
async_cleanup(hass, dev_reg, ent_reg)
debounced_cleanup = Debouncer(
hass, _LOGGER, cooldown=CLEANUP_DELAY, immediate=False, function=cleanup
)
async def entity_registry_changed(event: Event) -> None:
"""Handle entity updated or removed."""
if (
event.data["action"] == "update"
and "device_id" not in event.data["changes"]
) or event.data["action"] == "create":
return
await debounced_cleanup.async_call()
if hass.is_running:
hass.bus.async_listen(
entity_registry.EVENT_ENTITY_REGISTRY_UPDATED, entity_registry_changed
)
return
async def startup_clean(event: Event) -> None:
"""Clean up on startup."""
hass.bus.async_listen(
entity_registry.EVENT_ENTITY_REGISTRY_UPDATED, entity_registry_changed
)
await debounced_cleanup.async_call()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, startup_clean) | [
"def",
"async_setup_cleanup",
"(",
"hass",
":",
"HomeAssistantType",
",",
"dev_reg",
":",
"DeviceRegistry",
")",
"->",
"None",
":",
"from",
".",
"import",
"entity_registry",
"# pylint: disable=import-outside-toplevel",
"async",
"def",
"cleanup",
"(",
")",
":",
"\"\"\"Cleanup.\"\"\"",
"ent_reg",
"=",
"await",
"entity_registry",
".",
"async_get_registry",
"(",
"hass",
")",
"async_cleanup",
"(",
"hass",
",",
"dev_reg",
",",
"ent_reg",
")",
"debounced_cleanup",
"=",
"Debouncer",
"(",
"hass",
",",
"_LOGGER",
",",
"cooldown",
"=",
"CLEANUP_DELAY",
",",
"immediate",
"=",
"False",
",",
"function",
"=",
"cleanup",
")",
"async",
"def",
"entity_registry_changed",
"(",
"event",
":",
"Event",
")",
"->",
"None",
":",
"\"\"\"Handle entity updated or removed.\"\"\"",
"if",
"(",
"event",
".",
"data",
"[",
"\"action\"",
"]",
"==",
"\"update\"",
"and",
"\"device_id\"",
"not",
"in",
"event",
".",
"data",
"[",
"\"changes\"",
"]",
")",
"or",
"event",
".",
"data",
"[",
"\"action\"",
"]",
"==",
"\"create\"",
":",
"return",
"await",
"debounced_cleanup",
".",
"async_call",
"(",
")",
"if",
"hass",
".",
"is_running",
":",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"entity_registry",
".",
"EVENT_ENTITY_REGISTRY_UPDATED",
",",
"entity_registry_changed",
")",
"return",
"async",
"def",
"startup_clean",
"(",
"event",
":",
"Event",
")",
"->",
"None",
":",
"\"\"\"Clean up on startup.\"\"\"",
"hass",
".",
"bus",
".",
"async_listen",
"(",
"entity_registry",
".",
"EVENT_ENTITY_REGISTRY_UPDATED",
",",
"entity_registry_changed",
")",
"await",
"debounced_cleanup",
".",
"async_call",
"(",
")",
"hass",
".",
"bus",
".",
"async_listen_once",
"(",
"EVENT_HOMEASSISTANT_STARTED",
",",
"startup_clean",
")"
] | [
585,
0
] | [
621,
74
] | python | en | ['en', 'en', 'en'] | True |
_normalize_connections | (connections: set) | Normalize connections to ensure we can match mac addresses. | Normalize connections to ensure we can match mac addresses. | def _normalize_connections(connections: set) -> set:
"""Normalize connections to ensure we can match mac addresses."""
return {
(key, format_mac(value)) if key == CONNECTION_NETWORK_MAC else (key, value)
for key, value in connections
} | [
"def",
"_normalize_connections",
"(",
"connections",
":",
"set",
")",
"->",
"set",
":",
"return",
"{",
"(",
"key",
",",
"format_mac",
"(",
"value",
")",
")",
"if",
"key",
"==",
"CONNECTION_NETWORK_MAC",
"else",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"connections",
"}"
] | [
624,
0
] | [
629,
5
] | python | en | ['en', 'en', 'en'] | True |
_add_device_to_index | (
devices_index: dict, device: Union[DeviceEntry, DeletedDeviceEntry]
) | Add a device to the index. | Add a device to the index. | def _add_device_to_index(
devices_index: dict, device: Union[DeviceEntry, DeletedDeviceEntry]
) -> None:
"""Add a device to the index."""
for identifier in device.identifiers:
devices_index[IDX_IDENTIFIERS][identifier] = device.id
for connection in device.connections:
devices_index[IDX_CONNECTIONS][connection] = device.id | [
"def",
"_add_device_to_index",
"(",
"devices_index",
":",
"dict",
",",
"device",
":",
"Union",
"[",
"DeviceEntry",
",",
"DeletedDeviceEntry",
"]",
")",
"->",
"None",
":",
"for",
"identifier",
"in",
"device",
".",
"identifiers",
":",
"devices_index",
"[",
"IDX_IDENTIFIERS",
"]",
"[",
"identifier",
"]",
"=",
"device",
".",
"id",
"for",
"connection",
"in",
"device",
".",
"connections",
":",
"devices_index",
"[",
"IDX_CONNECTIONS",
"]",
"[",
"connection",
"]",
"=",
"device",
".",
"id"
] | [
632,
0
] | [
639,
62
] | python | en | ['en', 'en', 'en'] | True |
_remove_device_from_index | (
devices_index: dict, device: Union[DeviceEntry, DeletedDeviceEntry]
) | Remove a device from the index. | Remove a device from the index. | def _remove_device_from_index(
devices_index: dict, device: Union[DeviceEntry, DeletedDeviceEntry]
) -> None:
"""Remove a device from the index."""
for identifier in device.identifiers:
if identifier in devices_index[IDX_IDENTIFIERS]:
del devices_index[IDX_IDENTIFIERS][identifier]
for connection in device.connections:
if connection in devices_index[IDX_CONNECTIONS]:
del devices_index[IDX_CONNECTIONS][connection] | [
"def",
"_remove_device_from_index",
"(",
"devices_index",
":",
"dict",
",",
"device",
":",
"Union",
"[",
"DeviceEntry",
",",
"DeletedDeviceEntry",
"]",
")",
"->",
"None",
":",
"for",
"identifier",
"in",
"device",
".",
"identifiers",
":",
"if",
"identifier",
"in",
"devices_index",
"[",
"IDX_IDENTIFIERS",
"]",
":",
"del",
"devices_index",
"[",
"IDX_IDENTIFIERS",
"]",
"[",
"identifier",
"]",
"for",
"connection",
"in",
"device",
".",
"connections",
":",
"if",
"connection",
"in",
"devices_index",
"[",
"IDX_CONNECTIONS",
"]",
":",
"del",
"devices_index",
"[",
"IDX_CONNECTIONS",
"]",
"[",
"connection",
"]"
] | [
642,
0
] | [
651,
58
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry.__init__ | (self, hass: HomeAssistantType) | Initialize the device registry. | Initialize the device registry. | def __init__(self, hass: HomeAssistantType) -> None:
"""Initialize the device registry."""
self.hass = hass
self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
self._clear_index() | [
"def",
"__init__",
"(",
"self",
",",
"hass",
":",
"HomeAssistantType",
")",
"->",
"None",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"_store",
"=",
"hass",
".",
"helpers",
".",
"storage",
".",
"Store",
"(",
"STORAGE_VERSION",
",",
"STORAGE_KEY",
")",
"self",
".",
"_clear_index",
"(",
")"
] | [
107,
4
] | [
111,
27
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry.async_get | (self, device_id: str) | Get device. | Get device. | def async_get(self, device_id: str) -> Optional[DeviceEntry]:
"""Get device."""
return self.devices.get(device_id) | [
"def",
"async_get",
"(",
"self",
",",
"device_id",
":",
"str",
")",
"->",
"Optional",
"[",
"DeviceEntry",
"]",
":",
"return",
"self",
".",
"devices",
".",
"get",
"(",
"device_id",
")"
] | [
114,
4
] | [
116,
42
] | python | en | ['fr', 'en', 'en'] | False |
DeviceRegistry.async_get_device | (
self, identifiers: set, connections: set
) | Check if device is registered. | Check if device is registered. | def async_get_device(
self, identifiers: set, connections: set
) -> Optional[DeviceEntry]:
"""Check if device is registered."""
device_id = self._async_get_device_id_from_index(
REGISTERED_DEVICE, identifiers, connections
)
if device_id is None:
return None
return self.devices[device_id] | [
"def",
"async_get_device",
"(",
"self",
",",
"identifiers",
":",
"set",
",",
"connections",
":",
"set",
")",
"->",
"Optional",
"[",
"DeviceEntry",
"]",
":",
"device_id",
"=",
"self",
".",
"_async_get_device_id_from_index",
"(",
"REGISTERED_DEVICE",
",",
"identifiers",
",",
"connections",
")",
"if",
"device_id",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"devices",
"[",
"device_id",
"]"
] | [
119,
4
] | [
128,
38
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry._async_get_deleted_device | (
self, identifiers: set, connections: set
) | Check if device is deleted. | Check if device is deleted. | def _async_get_deleted_device(
self, identifiers: set, connections: set
) -> Optional[DeletedDeviceEntry]:
"""Check if device is deleted."""
device_id = self._async_get_device_id_from_index(
DELETED_DEVICE, identifiers, connections
)
if device_id is None:
return None
return self.deleted_devices[device_id] | [
"def",
"_async_get_deleted_device",
"(",
"self",
",",
"identifiers",
":",
"set",
",",
"connections",
":",
"set",
")",
"->",
"Optional",
"[",
"DeletedDeviceEntry",
"]",
":",
"device_id",
"=",
"self",
".",
"_async_get_device_id_from_index",
"(",
"DELETED_DEVICE",
",",
"identifiers",
",",
"connections",
")",
"if",
"device_id",
"is",
"None",
":",
"return",
"None",
"return",
"self",
".",
"deleted_devices",
"[",
"device_id",
"]"
] | [
130,
4
] | [
139,
46
] | python | en | ['nl', 'en', 'en'] | True |
DeviceRegistry._async_get_device_id_from_index | (
self, index: str, identifiers: set, connections: set
) | Check if device has previously been registered. | Check if device has previously been registered. | def _async_get_device_id_from_index(
self, index: str, identifiers: set, connections: set
) -> Optional[str]:
"""Check if device has previously been registered."""
devices_index = self._devices_index[index]
for identifier in identifiers:
if identifier in devices_index[IDX_IDENTIFIERS]:
return devices_index[IDX_IDENTIFIERS][identifier]
if not connections:
return None
for connection in _normalize_connections(connections):
if connection in devices_index[IDX_CONNECTIONS]:
return devices_index[IDX_CONNECTIONS][connection]
return None | [
"def",
"_async_get_device_id_from_index",
"(",
"self",
",",
"index",
":",
"str",
",",
"identifiers",
":",
"set",
",",
"connections",
":",
"set",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"devices_index",
"=",
"self",
".",
"_devices_index",
"[",
"index",
"]",
"for",
"identifier",
"in",
"identifiers",
":",
"if",
"identifier",
"in",
"devices_index",
"[",
"IDX_IDENTIFIERS",
"]",
":",
"return",
"devices_index",
"[",
"IDX_IDENTIFIERS",
"]",
"[",
"identifier",
"]",
"if",
"not",
"connections",
":",
"return",
"None",
"for",
"connection",
"in",
"_normalize_connections",
"(",
"connections",
")",
":",
"if",
"connection",
"in",
"devices_index",
"[",
"IDX_CONNECTIONS",
"]",
":",
"return",
"devices_index",
"[",
"IDX_CONNECTIONS",
"]",
"[",
"connection",
"]",
"return",
"None"
] | [
141,
4
] | [
154,
19
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry._add_device | (self, device: Union[DeviceEntry, DeletedDeviceEntry]) | Add a device and index it. | Add a device and index it. | def _add_device(self, device: Union[DeviceEntry, DeletedDeviceEntry]) -> None:
"""Add a device and index it."""
if isinstance(device, DeletedDeviceEntry):
devices_index = self._devices_index[DELETED_DEVICE]
self.deleted_devices[device.id] = device
else:
devices_index = self._devices_index[REGISTERED_DEVICE]
self.devices[device.id] = device
_add_device_to_index(devices_index, device) | [
"def",
"_add_device",
"(",
"self",
",",
"device",
":",
"Union",
"[",
"DeviceEntry",
",",
"DeletedDeviceEntry",
"]",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"device",
",",
"DeletedDeviceEntry",
")",
":",
"devices_index",
"=",
"self",
".",
"_devices_index",
"[",
"DELETED_DEVICE",
"]",
"self",
".",
"deleted_devices",
"[",
"device",
".",
"id",
"]",
"=",
"device",
"else",
":",
"devices_index",
"=",
"self",
".",
"_devices_index",
"[",
"REGISTERED_DEVICE",
"]",
"self",
".",
"devices",
"[",
"device",
".",
"id",
"]",
"=",
"device",
"_add_device_to_index",
"(",
"devices_index",
",",
"device",
")"
] | [
156,
4
] | [
165,
51
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry._remove_device | (self, device: Union[DeviceEntry, DeletedDeviceEntry]) | Remove a device and remove it from the index. | Remove a device and remove it from the index. | def _remove_device(self, device: Union[DeviceEntry, DeletedDeviceEntry]) -> None:
"""Remove a device and remove it from the index."""
if isinstance(device, DeletedDeviceEntry):
devices_index = self._devices_index[DELETED_DEVICE]
self.deleted_devices.pop(device.id)
else:
devices_index = self._devices_index[REGISTERED_DEVICE]
self.devices.pop(device.id)
_remove_device_from_index(devices_index, device) | [
"def",
"_remove_device",
"(",
"self",
",",
"device",
":",
"Union",
"[",
"DeviceEntry",
",",
"DeletedDeviceEntry",
"]",
")",
"->",
"None",
":",
"if",
"isinstance",
"(",
"device",
",",
"DeletedDeviceEntry",
")",
":",
"devices_index",
"=",
"self",
".",
"_devices_index",
"[",
"DELETED_DEVICE",
"]",
"self",
".",
"deleted_devices",
".",
"pop",
"(",
"device",
".",
"id",
")",
"else",
":",
"devices_index",
"=",
"self",
".",
"_devices_index",
"[",
"REGISTERED_DEVICE",
"]",
"self",
".",
"devices",
".",
"pop",
"(",
"device",
".",
"id",
")",
"_remove_device_from_index",
"(",
"devices_index",
",",
"device",
")"
] | [
167,
4
] | [
176,
56
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry._update_device | (self, old_device: DeviceEntry, new_device: DeviceEntry) | Update a device and the index. | Update a device and the index. | def _update_device(self, old_device: DeviceEntry, new_device: DeviceEntry) -> None:
"""Update a device and the index."""
self.devices[new_device.id] = new_device
devices_index = self._devices_index[REGISTERED_DEVICE]
_remove_device_from_index(devices_index, old_device)
_add_device_to_index(devices_index, new_device) | [
"def",
"_update_device",
"(",
"self",
",",
"old_device",
":",
"DeviceEntry",
",",
"new_device",
":",
"DeviceEntry",
")",
"->",
"None",
":",
"self",
".",
"devices",
"[",
"new_device",
".",
"id",
"]",
"=",
"new_device",
"devices_index",
"=",
"self",
".",
"_devices_index",
"[",
"REGISTERED_DEVICE",
"]",
"_remove_device_from_index",
"(",
"devices_index",
",",
"old_device",
")",
"_add_device_to_index",
"(",
"devices_index",
",",
"new_device",
")"
] | [
178,
4
] | [
184,
55
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry._clear_index | (self) | Clear the index. | Clear the index. | def _clear_index(self):
"""Clear the index."""
self._devices_index = {
REGISTERED_DEVICE: {IDX_IDENTIFIERS: {}, IDX_CONNECTIONS: {}},
DELETED_DEVICE: {IDX_IDENTIFIERS: {}, IDX_CONNECTIONS: {}},
} | [
"def",
"_clear_index",
"(",
"self",
")",
":",
"self",
".",
"_devices_index",
"=",
"{",
"REGISTERED_DEVICE",
":",
"{",
"IDX_IDENTIFIERS",
":",
"{",
"}",
",",
"IDX_CONNECTIONS",
":",
"{",
"}",
"}",
",",
"DELETED_DEVICE",
":",
"{",
"IDX_IDENTIFIERS",
":",
"{",
"}",
",",
"IDX_CONNECTIONS",
":",
"{",
"}",
"}",
",",
"}"
] | [
186,
4
] | [
191,
9
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry._rebuild_index | (self) | Create the index after loading devices. | Create the index after loading devices. | def _rebuild_index(self):
"""Create the index after loading devices."""
self._clear_index()
for device in self.devices.values():
_add_device_to_index(self._devices_index[REGISTERED_DEVICE], device)
for device in self.deleted_devices.values():
_add_device_to_index(self._devices_index[DELETED_DEVICE], device) | [
"def",
"_rebuild_index",
"(",
"self",
")",
":",
"self",
".",
"_clear_index",
"(",
")",
"for",
"device",
"in",
"self",
".",
"devices",
".",
"values",
"(",
")",
":",
"_add_device_to_index",
"(",
"self",
".",
"_devices_index",
"[",
"REGISTERED_DEVICE",
"]",
",",
"device",
")",
"for",
"device",
"in",
"self",
".",
"deleted_devices",
".",
"values",
"(",
")",
":",
"_add_device_to_index",
"(",
"self",
".",
"_devices_index",
"[",
"DELETED_DEVICE",
"]",
",",
"device",
")"
] | [
193,
4
] | [
199,
77
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry.async_get_or_create | (
self,
*,
config_entry_id,
connections=None,
identifiers=None,
manufacturer=_UNDEF,
model=_UNDEF,
name=_UNDEF,
default_manufacturer=_UNDEF,
default_model=_UNDEF,
default_name=_UNDEF,
sw_version=_UNDEF,
entry_type=_UNDEF,
via_device=None,
) | Get device. Create if it doesn't exist. | Get device. Create if it doesn't exist. | def async_get_or_create(
self,
*,
config_entry_id,
connections=None,
identifiers=None,
manufacturer=_UNDEF,
model=_UNDEF,
name=_UNDEF,
default_manufacturer=_UNDEF,
default_model=_UNDEF,
default_name=_UNDEF,
sw_version=_UNDEF,
entry_type=_UNDEF,
via_device=None,
):
"""Get device. Create if it doesn't exist."""
if not identifiers and not connections:
return None
if identifiers is None:
identifiers = set()
if connections is None:
connections = set()
else:
connections = _normalize_connections(connections)
device = self.async_get_device(identifiers, connections)
if device is None:
deleted_device = self._async_get_deleted_device(identifiers, connections)
if deleted_device is None:
device = DeviceEntry(is_new=True)
else:
self._remove_device(deleted_device)
device = deleted_device.to_device_entry(
config_entry_id, connections, identifiers
)
self._add_device(device)
if default_manufacturer is not _UNDEF and device.manufacturer is None:
manufacturer = default_manufacturer
if default_model is not _UNDEF and device.model is None:
model = default_model
if default_name is not _UNDEF and device.name is None:
name = default_name
if via_device is not None:
via = self.async_get_device({via_device}, set())
via_device_id = via.id if via else _UNDEF
else:
via_device_id = _UNDEF
return self._async_update_device(
device.id,
add_config_entry_id=config_entry_id,
via_device_id=via_device_id,
merge_connections=connections or _UNDEF,
merge_identifiers=identifiers or _UNDEF,
manufacturer=manufacturer,
model=model,
name=name,
sw_version=sw_version,
entry_type=entry_type,
) | [
"def",
"async_get_or_create",
"(",
"self",
",",
"*",
",",
"config_entry_id",
",",
"connections",
"=",
"None",
",",
"identifiers",
"=",
"None",
",",
"manufacturer",
"=",
"_UNDEF",
",",
"model",
"=",
"_UNDEF",
",",
"name",
"=",
"_UNDEF",
",",
"default_manufacturer",
"=",
"_UNDEF",
",",
"default_model",
"=",
"_UNDEF",
",",
"default_name",
"=",
"_UNDEF",
",",
"sw_version",
"=",
"_UNDEF",
",",
"entry_type",
"=",
"_UNDEF",
",",
"via_device",
"=",
"None",
",",
")",
":",
"if",
"not",
"identifiers",
"and",
"not",
"connections",
":",
"return",
"None",
"if",
"identifiers",
"is",
"None",
":",
"identifiers",
"=",
"set",
"(",
")",
"if",
"connections",
"is",
"None",
":",
"connections",
"=",
"set",
"(",
")",
"else",
":",
"connections",
"=",
"_normalize_connections",
"(",
"connections",
")",
"device",
"=",
"self",
".",
"async_get_device",
"(",
"identifiers",
",",
"connections",
")",
"if",
"device",
"is",
"None",
":",
"deleted_device",
"=",
"self",
".",
"_async_get_deleted_device",
"(",
"identifiers",
",",
"connections",
")",
"if",
"deleted_device",
"is",
"None",
":",
"device",
"=",
"DeviceEntry",
"(",
"is_new",
"=",
"True",
")",
"else",
":",
"self",
".",
"_remove_device",
"(",
"deleted_device",
")",
"device",
"=",
"deleted_device",
".",
"to_device_entry",
"(",
"config_entry_id",
",",
"connections",
",",
"identifiers",
")",
"self",
".",
"_add_device",
"(",
"device",
")",
"if",
"default_manufacturer",
"is",
"not",
"_UNDEF",
"and",
"device",
".",
"manufacturer",
"is",
"None",
":",
"manufacturer",
"=",
"default_manufacturer",
"if",
"default_model",
"is",
"not",
"_UNDEF",
"and",
"device",
".",
"model",
"is",
"None",
":",
"model",
"=",
"default_model",
"if",
"default_name",
"is",
"not",
"_UNDEF",
"and",
"device",
".",
"name",
"is",
"None",
":",
"name",
"=",
"default_name",
"if",
"via_device",
"is",
"not",
"None",
":",
"via",
"=",
"self",
".",
"async_get_device",
"(",
"{",
"via_device",
"}",
",",
"set",
"(",
")",
")",
"via_device_id",
"=",
"via",
".",
"id",
"if",
"via",
"else",
"_UNDEF",
"else",
":",
"via_device_id",
"=",
"_UNDEF",
"return",
"self",
".",
"_async_update_device",
"(",
"device",
".",
"id",
",",
"add_config_entry_id",
"=",
"config_entry_id",
",",
"via_device_id",
"=",
"via_device_id",
",",
"merge_connections",
"=",
"connections",
"or",
"_UNDEF",
",",
"merge_identifiers",
"=",
"identifiers",
"or",
"_UNDEF",
",",
"manufacturer",
"=",
"manufacturer",
",",
"model",
"=",
"model",
",",
"name",
"=",
"name",
",",
"sw_version",
"=",
"sw_version",
",",
"entry_type",
"=",
"entry_type",
",",
")"
] | [
202,
4
] | [
269,
9
] | python | en | ['fr', 'en', 'en'] | True |
DeviceRegistry.async_update_device | (
self,
device_id,
*,
area_id=_UNDEF,
manufacturer=_UNDEF,
model=_UNDEF,
name=_UNDEF,
name_by_user=_UNDEF,
new_identifiers=_UNDEF,
sw_version=_UNDEF,
via_device_id=_UNDEF,
remove_config_entry_id=_UNDEF,
) | Update properties of a device. | Update properties of a device. | def async_update_device(
self,
device_id,
*,
area_id=_UNDEF,
manufacturer=_UNDEF,
model=_UNDEF,
name=_UNDEF,
name_by_user=_UNDEF,
new_identifiers=_UNDEF,
sw_version=_UNDEF,
via_device_id=_UNDEF,
remove_config_entry_id=_UNDEF,
):
"""Update properties of a device."""
return self._async_update_device(
device_id,
area_id=area_id,
manufacturer=manufacturer,
model=model,
name=name,
name_by_user=name_by_user,
new_identifiers=new_identifiers,
sw_version=sw_version,
via_device_id=via_device_id,
remove_config_entry_id=remove_config_entry_id,
) | [
"def",
"async_update_device",
"(",
"self",
",",
"device_id",
",",
"*",
",",
"area_id",
"=",
"_UNDEF",
",",
"manufacturer",
"=",
"_UNDEF",
",",
"model",
"=",
"_UNDEF",
",",
"name",
"=",
"_UNDEF",
",",
"name_by_user",
"=",
"_UNDEF",
",",
"new_identifiers",
"=",
"_UNDEF",
",",
"sw_version",
"=",
"_UNDEF",
",",
"via_device_id",
"=",
"_UNDEF",
",",
"remove_config_entry_id",
"=",
"_UNDEF",
",",
")",
":",
"return",
"self",
".",
"_async_update_device",
"(",
"device_id",
",",
"area_id",
"=",
"area_id",
",",
"manufacturer",
"=",
"manufacturer",
",",
"model",
"=",
"model",
",",
"name",
"=",
"name",
",",
"name_by_user",
"=",
"name_by_user",
",",
"new_identifiers",
"=",
"new_identifiers",
",",
"sw_version",
"=",
"sw_version",
",",
"via_device_id",
"=",
"via_device_id",
",",
"remove_config_entry_id",
"=",
"remove_config_entry_id",
",",
")"
] | [
272,
4
] | [
298,
9
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry._async_update_device | (
self,
device_id,
*,
add_config_entry_id=_UNDEF,
remove_config_entry_id=_UNDEF,
merge_connections=_UNDEF,
merge_identifiers=_UNDEF,
new_identifiers=_UNDEF,
manufacturer=_UNDEF,
model=_UNDEF,
name=_UNDEF,
sw_version=_UNDEF,
entry_type=_UNDEF,
via_device_id=_UNDEF,
area_id=_UNDEF,
name_by_user=_UNDEF,
) | Update device attributes. | Update device attributes. | def _async_update_device(
self,
device_id,
*,
add_config_entry_id=_UNDEF,
remove_config_entry_id=_UNDEF,
merge_connections=_UNDEF,
merge_identifiers=_UNDEF,
new_identifiers=_UNDEF,
manufacturer=_UNDEF,
model=_UNDEF,
name=_UNDEF,
sw_version=_UNDEF,
entry_type=_UNDEF,
via_device_id=_UNDEF,
area_id=_UNDEF,
name_by_user=_UNDEF,
):
"""Update device attributes."""
old = self.devices[device_id]
changes = {}
config_entries = old.config_entries
if (
add_config_entry_id is not _UNDEF
and add_config_entry_id not in old.config_entries
):
config_entries = old.config_entries | {add_config_entry_id}
if (
remove_config_entry_id is not _UNDEF
and remove_config_entry_id in config_entries
):
if config_entries == {remove_config_entry_id}:
self.async_remove_device(device_id)
return
config_entries = config_entries - {remove_config_entry_id}
if config_entries != old.config_entries:
changes["config_entries"] = config_entries
for attr_name, value in (
("connections", merge_connections),
("identifiers", merge_identifiers),
):
old_value = getattr(old, attr_name)
# If not undefined, check if `value` contains new items.
if value is not _UNDEF and not value.issubset(old_value):
changes[attr_name] = old_value | value
if new_identifiers is not _UNDEF:
changes["identifiers"] = new_identifiers
for attr_name, value in (
("manufacturer", manufacturer),
("model", model),
("name", name),
("sw_version", sw_version),
("entry_type", entry_type),
("via_device_id", via_device_id),
):
if value is not _UNDEF and value != getattr(old, attr_name):
changes[attr_name] = value
if area_id is not _UNDEF and area_id != old.area_id:
changes["area_id"] = area_id
if name_by_user is not _UNDEF and name_by_user != old.name_by_user:
changes["name_by_user"] = name_by_user
if old.is_new:
changes["is_new"] = False
if not changes:
return old
new = attr.evolve(old, **changes)
self._update_device(old, new)
self.async_schedule_save()
self.hass.bus.async_fire(
EVENT_DEVICE_REGISTRY_UPDATED,
{
"action": "create" if "is_new" in changes else "update",
"device_id": new.id,
},
)
return new | [
"def",
"_async_update_device",
"(",
"self",
",",
"device_id",
",",
"*",
",",
"add_config_entry_id",
"=",
"_UNDEF",
",",
"remove_config_entry_id",
"=",
"_UNDEF",
",",
"merge_connections",
"=",
"_UNDEF",
",",
"merge_identifiers",
"=",
"_UNDEF",
",",
"new_identifiers",
"=",
"_UNDEF",
",",
"manufacturer",
"=",
"_UNDEF",
",",
"model",
"=",
"_UNDEF",
",",
"name",
"=",
"_UNDEF",
",",
"sw_version",
"=",
"_UNDEF",
",",
"entry_type",
"=",
"_UNDEF",
",",
"via_device_id",
"=",
"_UNDEF",
",",
"area_id",
"=",
"_UNDEF",
",",
"name_by_user",
"=",
"_UNDEF",
",",
")",
":",
"old",
"=",
"self",
".",
"devices",
"[",
"device_id",
"]",
"changes",
"=",
"{",
"}",
"config_entries",
"=",
"old",
".",
"config_entries",
"if",
"(",
"add_config_entry_id",
"is",
"not",
"_UNDEF",
"and",
"add_config_entry_id",
"not",
"in",
"old",
".",
"config_entries",
")",
":",
"config_entries",
"=",
"old",
".",
"config_entries",
"|",
"{",
"add_config_entry_id",
"}",
"if",
"(",
"remove_config_entry_id",
"is",
"not",
"_UNDEF",
"and",
"remove_config_entry_id",
"in",
"config_entries",
")",
":",
"if",
"config_entries",
"==",
"{",
"remove_config_entry_id",
"}",
":",
"self",
".",
"async_remove_device",
"(",
"device_id",
")",
"return",
"config_entries",
"=",
"config_entries",
"-",
"{",
"remove_config_entry_id",
"}",
"if",
"config_entries",
"!=",
"old",
".",
"config_entries",
":",
"changes",
"[",
"\"config_entries\"",
"]",
"=",
"config_entries",
"for",
"attr_name",
",",
"value",
"in",
"(",
"(",
"\"connections\"",
",",
"merge_connections",
")",
",",
"(",
"\"identifiers\"",
",",
"merge_identifiers",
")",
",",
")",
":",
"old_value",
"=",
"getattr",
"(",
"old",
",",
"attr_name",
")",
"# If not undefined, check if `value` contains new items.",
"if",
"value",
"is",
"not",
"_UNDEF",
"and",
"not",
"value",
".",
"issubset",
"(",
"old_value",
")",
":",
"changes",
"[",
"attr_name",
"]",
"=",
"old_value",
"|",
"value",
"if",
"new_identifiers",
"is",
"not",
"_UNDEF",
":",
"changes",
"[",
"\"identifiers\"",
"]",
"=",
"new_identifiers",
"for",
"attr_name",
",",
"value",
"in",
"(",
"(",
"\"manufacturer\"",
",",
"manufacturer",
")",
",",
"(",
"\"model\"",
",",
"model",
")",
",",
"(",
"\"name\"",
",",
"name",
")",
",",
"(",
"\"sw_version\"",
",",
"sw_version",
")",
",",
"(",
"\"entry_type\"",
",",
"entry_type",
")",
",",
"(",
"\"via_device_id\"",
",",
"via_device_id",
")",
",",
")",
":",
"if",
"value",
"is",
"not",
"_UNDEF",
"and",
"value",
"!=",
"getattr",
"(",
"old",
",",
"attr_name",
")",
":",
"changes",
"[",
"attr_name",
"]",
"=",
"value",
"if",
"area_id",
"is",
"not",
"_UNDEF",
"and",
"area_id",
"!=",
"old",
".",
"area_id",
":",
"changes",
"[",
"\"area_id\"",
"]",
"=",
"area_id",
"if",
"name_by_user",
"is",
"not",
"_UNDEF",
"and",
"name_by_user",
"!=",
"old",
".",
"name_by_user",
":",
"changes",
"[",
"\"name_by_user\"",
"]",
"=",
"name_by_user",
"if",
"old",
".",
"is_new",
":",
"changes",
"[",
"\"is_new\"",
"]",
"=",
"False",
"if",
"not",
"changes",
":",
"return",
"old",
"new",
"=",
"attr",
".",
"evolve",
"(",
"old",
",",
"*",
"*",
"changes",
")",
"self",
".",
"_update_device",
"(",
"old",
",",
"new",
")",
"self",
".",
"async_schedule_save",
"(",
")",
"self",
".",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_DEVICE_REGISTRY_UPDATED",
",",
"{",
"\"action\"",
":",
"\"create\"",
"if",
"\"is_new\"",
"in",
"changes",
"else",
"\"update\"",
",",
"\"device_id\"",
":",
"new",
".",
"id",
",",
"}",
",",
")",
"return",
"new"
] | [
301,
4
] | [
392,
18
] | python | en | ['fr', 'en', 'en'] | True |
DeviceRegistry.async_remove_device | (self, device_id: str) | Remove a device from the device registry. | Remove a device from the device registry. | def async_remove_device(self, device_id: str) -> None:
"""Remove a device from the device registry."""
device = self.devices[device_id]
self._remove_device(device)
self._add_device(
DeletedDeviceEntry(
config_entries=device.config_entries,
connections=device.connections,
identifiers=device.identifiers,
id=device.id,
)
)
self.hass.bus.async_fire(
EVENT_DEVICE_REGISTRY_UPDATED, {"action": "remove", "device_id": device_id}
)
self.async_schedule_save() | [
"def",
"async_remove_device",
"(",
"self",
",",
"device_id",
":",
"str",
")",
"->",
"None",
":",
"device",
"=",
"self",
".",
"devices",
"[",
"device_id",
"]",
"self",
".",
"_remove_device",
"(",
"device",
")",
"self",
".",
"_add_device",
"(",
"DeletedDeviceEntry",
"(",
"config_entries",
"=",
"device",
".",
"config_entries",
",",
"connections",
"=",
"device",
".",
"connections",
",",
"identifiers",
"=",
"device",
".",
"identifiers",
",",
"id",
"=",
"device",
".",
"id",
",",
")",
")",
"self",
".",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_DEVICE_REGISTRY_UPDATED",
",",
"{",
"\"action\"",
":",
"\"remove\"",
",",
"\"device_id\"",
":",
"device_id",
"}",
")",
"self",
".",
"async_schedule_save",
"(",
")"
] | [
395,
4
] | [
410,
34
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry.async_load | (self) | Load the device registry. | Load the device registry. | async def async_load(self):
"""Load the device registry."""
async_setup_cleanup(self.hass, self)
data = await self._store.async_load()
devices = OrderedDict()
deleted_devices = OrderedDict()
if data is not None:
for device in data["devices"]:
devices[device["id"]] = DeviceEntry(
config_entries=set(device["config_entries"]),
connections={tuple(conn) for conn in device["connections"]},
identifiers={tuple(iden) for iden in device["identifiers"]},
manufacturer=device["manufacturer"],
model=device["model"],
name=device["name"],
sw_version=device["sw_version"],
# Introduced in 0.110
entry_type=device.get("entry_type"),
id=device["id"],
# Introduced in 0.79
# renamed in 0.95
via_device_id=(
device.get("via_device_id") or device.get("hub_device_id")
),
# Introduced in 0.87
area_id=device.get("area_id"),
name_by_user=device.get("name_by_user"),
)
# Introduced in 0.111
for device in data.get("deleted_devices", []):
deleted_devices[device["id"]] = DeletedDeviceEntry(
config_entries=set(device["config_entries"]),
connections={tuple(conn) for conn in device["connections"]},
identifiers={tuple(iden) for iden in device["identifiers"]},
id=device["id"],
)
self.devices = devices
self.deleted_devices = deleted_devices
self._rebuild_index() | [
"async",
"def",
"async_load",
"(",
"self",
")",
":",
"async_setup_cleanup",
"(",
"self",
".",
"hass",
",",
"self",
")",
"data",
"=",
"await",
"self",
".",
"_store",
".",
"async_load",
"(",
")",
"devices",
"=",
"OrderedDict",
"(",
")",
"deleted_devices",
"=",
"OrderedDict",
"(",
")",
"if",
"data",
"is",
"not",
"None",
":",
"for",
"device",
"in",
"data",
"[",
"\"devices\"",
"]",
":",
"devices",
"[",
"device",
"[",
"\"id\"",
"]",
"]",
"=",
"DeviceEntry",
"(",
"config_entries",
"=",
"set",
"(",
"device",
"[",
"\"config_entries\"",
"]",
")",
",",
"connections",
"=",
"{",
"tuple",
"(",
"conn",
")",
"for",
"conn",
"in",
"device",
"[",
"\"connections\"",
"]",
"}",
",",
"identifiers",
"=",
"{",
"tuple",
"(",
"iden",
")",
"for",
"iden",
"in",
"device",
"[",
"\"identifiers\"",
"]",
"}",
",",
"manufacturer",
"=",
"device",
"[",
"\"manufacturer\"",
"]",
",",
"model",
"=",
"device",
"[",
"\"model\"",
"]",
",",
"name",
"=",
"device",
"[",
"\"name\"",
"]",
",",
"sw_version",
"=",
"device",
"[",
"\"sw_version\"",
"]",
",",
"# Introduced in 0.110",
"entry_type",
"=",
"device",
".",
"get",
"(",
"\"entry_type\"",
")",
",",
"id",
"=",
"device",
"[",
"\"id\"",
"]",
",",
"# Introduced in 0.79",
"# renamed in 0.95",
"via_device_id",
"=",
"(",
"device",
".",
"get",
"(",
"\"via_device_id\"",
")",
"or",
"device",
".",
"get",
"(",
"\"hub_device_id\"",
")",
")",
",",
"# Introduced in 0.87",
"area_id",
"=",
"device",
".",
"get",
"(",
"\"area_id\"",
")",
",",
"name_by_user",
"=",
"device",
".",
"get",
"(",
"\"name_by_user\"",
")",
",",
")",
"# Introduced in 0.111",
"for",
"device",
"in",
"data",
".",
"get",
"(",
"\"deleted_devices\"",
",",
"[",
"]",
")",
":",
"deleted_devices",
"[",
"device",
"[",
"\"id\"",
"]",
"]",
"=",
"DeletedDeviceEntry",
"(",
"config_entries",
"=",
"set",
"(",
"device",
"[",
"\"config_entries\"",
"]",
")",
",",
"connections",
"=",
"{",
"tuple",
"(",
"conn",
")",
"for",
"conn",
"in",
"device",
"[",
"\"connections\"",
"]",
"}",
",",
"identifiers",
"=",
"{",
"tuple",
"(",
"iden",
")",
"for",
"iden",
"in",
"device",
"[",
"\"identifiers\"",
"]",
"}",
",",
"id",
"=",
"device",
"[",
"\"id\"",
"]",
",",
")",
"self",
".",
"devices",
"=",
"devices",
"self",
".",
"deleted_devices",
"=",
"deleted_devices",
"self",
".",
"_rebuild_index",
"(",
")"
] | [
412,
4
] | [
454,
29
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry.async_schedule_save | (self) | Schedule saving the device registry. | Schedule saving the device registry. | def async_schedule_save(self) -> None:
"""Schedule saving the device registry."""
self._store.async_delay_save(self._data_to_save, SAVE_DELAY) | [
"def",
"async_schedule_save",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_store",
".",
"async_delay_save",
"(",
"self",
".",
"_data_to_save",
",",
"SAVE_DELAY",
")"
] | [
457,
4
] | [
459,
68
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry._data_to_save | (self) | Return data of device registry to store in a file. | Return data of device registry to store in a file. | def _data_to_save(self) -> Dict[str, List[Dict[str, Any]]]:
"""Return data of device registry to store in a file."""
data = {}
data["devices"] = [
{
"config_entries": list(entry.config_entries),
"connections": list(entry.connections),
"identifiers": list(entry.identifiers),
"manufacturer": entry.manufacturer,
"model": entry.model,
"name": entry.name,
"sw_version": entry.sw_version,
"entry_type": entry.entry_type,
"id": entry.id,
"via_device_id": entry.via_device_id,
"area_id": entry.area_id,
"name_by_user": entry.name_by_user,
}
for entry in self.devices.values()
]
data["deleted_devices"] = [
{
"config_entries": list(entry.config_entries),
"connections": list(entry.connections),
"identifiers": list(entry.identifiers),
"id": entry.id,
}
for entry in self.deleted_devices.values()
]
return data | [
"def",
"_data_to_save",
"(",
"self",
")",
"->",
"Dict",
"[",
"str",
",",
"List",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
"]",
":",
"data",
"=",
"{",
"}",
"data",
"[",
"\"devices\"",
"]",
"=",
"[",
"{",
"\"config_entries\"",
":",
"list",
"(",
"entry",
".",
"config_entries",
")",
",",
"\"connections\"",
":",
"list",
"(",
"entry",
".",
"connections",
")",
",",
"\"identifiers\"",
":",
"list",
"(",
"entry",
".",
"identifiers",
")",
",",
"\"manufacturer\"",
":",
"entry",
".",
"manufacturer",
",",
"\"model\"",
":",
"entry",
".",
"model",
",",
"\"name\"",
":",
"entry",
".",
"name",
",",
"\"sw_version\"",
":",
"entry",
".",
"sw_version",
",",
"\"entry_type\"",
":",
"entry",
".",
"entry_type",
",",
"\"id\"",
":",
"entry",
".",
"id",
",",
"\"via_device_id\"",
":",
"entry",
".",
"via_device_id",
",",
"\"area_id\"",
":",
"entry",
".",
"area_id",
",",
"\"name_by_user\"",
":",
"entry",
".",
"name_by_user",
",",
"}",
"for",
"entry",
"in",
"self",
".",
"devices",
".",
"values",
"(",
")",
"]",
"data",
"[",
"\"deleted_devices\"",
"]",
"=",
"[",
"{",
"\"config_entries\"",
":",
"list",
"(",
"entry",
".",
"config_entries",
")",
",",
"\"connections\"",
":",
"list",
"(",
"entry",
".",
"connections",
")",
",",
"\"identifiers\"",
":",
"list",
"(",
"entry",
".",
"identifiers",
")",
",",
"\"id\"",
":",
"entry",
".",
"id",
",",
"}",
"for",
"entry",
"in",
"self",
".",
"deleted_devices",
".",
"values",
"(",
")",
"]",
"return",
"data"
] | [
462,
4
] | [
493,
19
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry.async_clear_config_entry | (self, config_entry_id: str) | Clear config entry from registry entries. | Clear config entry from registry entries. | def async_clear_config_entry(self, config_entry_id: str) -> None:
"""Clear config entry from registry entries."""
for device in list(self.devices.values()):
self._async_update_device(device.id, remove_config_entry_id=config_entry_id)
for deleted_device in list(self.deleted_devices.values()):
config_entries = deleted_device.config_entries
if config_entry_id not in config_entries:
continue
if config_entries == {config_entry_id}:
# Permanently remove the device from the device registry.
self._remove_device(deleted_device)
else:
config_entries = config_entries - {config_entry_id}
# No need to reindex here since we currently
# do not have a lookup by config entry
self.deleted_devices[deleted_device.id] = attr.evolve(
deleted_device, config_entries=config_entries
)
self.async_schedule_save() | [
"def",
"async_clear_config_entry",
"(",
"self",
",",
"config_entry_id",
":",
"str",
")",
"->",
"None",
":",
"for",
"device",
"in",
"list",
"(",
"self",
".",
"devices",
".",
"values",
"(",
")",
")",
":",
"self",
".",
"_async_update_device",
"(",
"device",
".",
"id",
",",
"remove_config_entry_id",
"=",
"config_entry_id",
")",
"for",
"deleted_device",
"in",
"list",
"(",
"self",
".",
"deleted_devices",
".",
"values",
"(",
")",
")",
":",
"config_entries",
"=",
"deleted_device",
".",
"config_entries",
"if",
"config_entry_id",
"not",
"in",
"config_entries",
":",
"continue",
"if",
"config_entries",
"==",
"{",
"config_entry_id",
"}",
":",
"# Permanently remove the device from the device registry.",
"self",
".",
"_remove_device",
"(",
"deleted_device",
")",
"else",
":",
"config_entries",
"=",
"config_entries",
"-",
"{",
"config_entry_id",
"}",
"# No need to reindex here since we currently",
"# do not have a lookup by config entry",
"self",
".",
"deleted_devices",
"[",
"deleted_device",
".",
"id",
"]",
"=",
"attr",
".",
"evolve",
"(",
"deleted_device",
",",
"config_entries",
"=",
"config_entries",
")",
"self",
".",
"async_schedule_save",
"(",
")"
] | [
496,
4
] | [
514,
38
] | python | en | ['en', 'en', 'en'] | True |
DeviceRegistry.async_clear_area_id | (self, area_id: str) | Clear area id from registry entries. | Clear area id from registry entries. | def async_clear_area_id(self, area_id: str) -> None:
"""Clear area id from registry entries."""
for dev_id, device in self.devices.items():
if area_id == device.area_id:
self._async_update_device(dev_id, area_id=None) | [
"def",
"async_clear_area_id",
"(",
"self",
",",
"area_id",
":",
"str",
")",
"->",
"None",
":",
"for",
"dev_id",
",",
"device",
"in",
"self",
".",
"devices",
".",
"items",
"(",
")",
":",
"if",
"area_id",
"==",
"device",
".",
"area_id",
":",
"self",
".",
"_async_update_device",
"(",
"dev_id",
",",
"area_id",
"=",
"None",
")"
] | [
517,
4
] | [
521,
63
] | python | en | ['en', 'en', 'en'] | True |
test_switch_state | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test the creation and values of the WLED switches. | Test the creation and values of the WLED switches. | async def test_switch_state(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the creation and values of the WLED switches."""
await init_integration(hass, aioclient_mock)
entity_registry = await hass.helpers.entity_registry.async_get_registry()
state = hass.states.get("switch.wled_rgb_light_nightlight")
assert state
assert state.attributes.get(ATTR_DURATION) == 60
assert state.attributes.get(ATTR_ICON) == "mdi:weather-night"
assert state.attributes.get(ATTR_TARGET_BRIGHTNESS) == 0
assert state.attributes.get(ATTR_FADE)
assert state.state == STATE_OFF
entry = entity_registry.async_get("switch.wled_rgb_light_nightlight")
assert entry
assert entry.unique_id == "aabbccddeeff_nightlight"
state = hass.states.get("switch.wled_rgb_light_sync_send")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:upload-network-outline"
assert state.attributes.get(ATTR_UDP_PORT) == 21324
assert state.state == STATE_OFF
entry = entity_registry.async_get("switch.wled_rgb_light_sync_send")
assert entry
assert entry.unique_id == "aabbccddeeff_sync_send"
state = hass.states.get("switch.wled_rgb_light_sync_receive")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:download-network-outline"
assert state.attributes.get(ATTR_UDP_PORT) == 21324
assert state.state == STATE_ON
entry = entity_registry.async_get("switch.wled_rgb_light_sync_receive")
assert entry
assert entry.unique_id == "aabbccddeeff_sync_receive" | [
"async",
"def",
"test_switch_state",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"await",
"init_integration",
"(",
"hass",
",",
"aioclient_mock",
")",
"entity_registry",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.wled_rgb_light_nightlight\"",
")",
"assert",
"state",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_DURATION",
")",
"==",
"60",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_ICON",
")",
"==",
"\"mdi:weather-night\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_TARGET_BRIGHTNESS",
")",
"==",
"0",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_FADE",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"entry",
"=",
"entity_registry",
".",
"async_get",
"(",
"\"switch.wled_rgb_light_nightlight\"",
")",
"assert",
"entry",
"assert",
"entry",
".",
"unique_id",
"==",
"\"aabbccddeeff_nightlight\"",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.wled_rgb_light_sync_send\"",
")",
"assert",
"state",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_ICON",
")",
"==",
"\"mdi:upload-network-outline\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_UDP_PORT",
")",
"==",
"21324",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"entry",
"=",
"entity_registry",
".",
"async_get",
"(",
"\"switch.wled_rgb_light_sync_send\"",
")",
"assert",
"entry",
"assert",
"entry",
".",
"unique_id",
"==",
"\"aabbccddeeff_sync_send\"",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.wled_rgb_light_sync_receive\"",
")",
"assert",
"state",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_ICON",
")",
"==",
"\"mdi:download-network-outline\"",
"assert",
"state",
".",
"attributes",
".",
"get",
"(",
"ATTR_UDP_PORT",
")",
"==",
"21324",
"assert",
"state",
".",
"state",
"==",
"STATE_ON",
"entry",
"=",
"entity_registry",
".",
"async_get",
"(",
"\"switch.wled_rgb_light_sync_receive\"",
")",
"assert",
"entry",
"assert",
"entry",
".",
"unique_id",
"==",
"\"aabbccddeeff_sync_receive\""
] | [
26,
0
] | [
64,
57
] | python | en | ['en', 'en', 'en'] | True |
test_switch_change_state | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test the change of state of the WLED switches. | Test the change of state of the WLED switches. | async def test_switch_change_state(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the change of state of the WLED switches."""
await init_integration(hass, aioclient_mock)
# Nightlight
with patch("wled.WLED.nightlight") as nightlight_mock:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.wled_rgb_light_nightlight"},
blocking=True,
)
await hass.async_block_till_done()
nightlight_mock.assert_called_once_with(on=True)
with patch("wled.WLED.nightlight") as nightlight_mock:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.wled_rgb_light_nightlight"},
blocking=True,
)
await hass.async_block_till_done()
nightlight_mock.assert_called_once_with(on=False)
# Sync send
with patch("wled.WLED.sync") as sync_mock:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.wled_rgb_light_sync_send"},
blocking=True,
)
await hass.async_block_till_done()
sync_mock.assert_called_once_with(send=True)
with patch("wled.WLED.sync") as sync_mock:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.wled_rgb_light_sync_send"},
blocking=True,
)
await hass.async_block_till_done()
sync_mock.assert_called_once_with(send=False)
# Sync receive
with patch("wled.WLED.sync") as sync_mock:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.wled_rgb_light_sync_receive"},
blocking=True,
)
await hass.async_block_till_done()
sync_mock.assert_called_once_with(receive=False)
with patch("wled.WLED.sync") as sync_mock:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.wled_rgb_light_sync_receive"},
blocking=True,
)
await hass.async_block_till_done()
sync_mock.assert_called_once_with(receive=True) | [
"async",
"def",
"test_switch_change_state",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"await",
"init_integration",
"(",
"hass",
",",
"aioclient_mock",
")",
"# Nightlight",
"with",
"patch",
"(",
"\"wled.WLED.nightlight\"",
")",
"as",
"nightlight_mock",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"SWITCH_DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"switch.wled_rgb_light_nightlight\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"nightlight_mock",
".",
"assert_called_once_with",
"(",
"on",
"=",
"True",
")",
"with",
"patch",
"(",
"\"wled.WLED.nightlight\"",
")",
"as",
"nightlight_mock",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"SWITCH_DOMAIN",
",",
"SERVICE_TURN_OFF",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"switch.wled_rgb_light_nightlight\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"nightlight_mock",
".",
"assert_called_once_with",
"(",
"on",
"=",
"False",
")",
"# Sync send",
"with",
"patch",
"(",
"\"wled.WLED.sync\"",
")",
"as",
"sync_mock",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"SWITCH_DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"switch.wled_rgb_light_sync_send\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sync_mock",
".",
"assert_called_once_with",
"(",
"send",
"=",
"True",
")",
"with",
"patch",
"(",
"\"wled.WLED.sync\"",
")",
"as",
"sync_mock",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"SWITCH_DOMAIN",
",",
"SERVICE_TURN_OFF",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"switch.wled_rgb_light_sync_send\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sync_mock",
".",
"assert_called_once_with",
"(",
"send",
"=",
"False",
")",
"# Sync receive",
"with",
"patch",
"(",
"\"wled.WLED.sync\"",
")",
"as",
"sync_mock",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"SWITCH_DOMAIN",
",",
"SERVICE_TURN_OFF",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"switch.wled_rgb_light_sync_receive\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sync_mock",
".",
"assert_called_once_with",
"(",
"receive",
"=",
"False",
")",
"with",
"patch",
"(",
"\"wled.WLED.sync\"",
")",
"as",
"sync_mock",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"SWITCH_DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"switch.wled_rgb_light_sync_receive\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"sync_mock",
".",
"assert_called_once_with",
"(",
"receive",
"=",
"True",
")"
] | [
67,
0
] | [
134,
55
] | python | en | ['en', 'en', 'en'] | True |
test_switch_error | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog
) | Test error handling of the WLED switches. | Test error handling of the WLED switches. | async def test_switch_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, caplog
) -> None:
"""Test error handling of the WLED switches."""
aioclient_mock.post("http://192.168.1.123:80/json/state", text="", status=400)
await init_integration(hass, aioclient_mock)
with patch("homeassistant.components.wled.WLED.update"):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.wled_rgb_light_nightlight"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("switch.wled_rgb_light_nightlight")
assert state.state == STATE_OFF
assert "Invalid response from API" in caplog.text | [
"async",
"def",
"test_switch_error",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
",",
"caplog",
")",
"->",
"None",
":",
"aioclient_mock",
".",
"post",
"(",
"\"http://192.168.1.123:80/json/state\"",
",",
"text",
"=",
"\"\"",
",",
"status",
"=",
"400",
")",
"await",
"init_integration",
"(",
"hass",
",",
"aioclient_mock",
")",
"with",
"patch",
"(",
"\"homeassistant.components.wled.WLED.update\"",
")",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"SWITCH_DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"switch.wled_rgb_light_nightlight\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.wled_rgb_light_nightlight\"",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_OFF",
"assert",
"\"Invalid response from API\"",
"in",
"caplog",
".",
"text"
] | [
137,
0
] | [
155,
57
] | python | en | ['en', 'en', 'en'] | True |
test_switch_connection_error | (
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) | Test error handling of the WLED switches. | Test error handling of the WLED switches. | async def test_switch_connection_error(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test error handling of the WLED switches."""
await init_integration(hass, aioclient_mock)
with patch("homeassistant.components.wled.WLED.update"), patch(
"homeassistant.components.wled.WLED.nightlight", side_effect=WLEDConnectionError
):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.wled_rgb_light_nightlight"},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get("switch.wled_rgb_light_nightlight")
assert state.state == STATE_UNAVAILABLE | [
"async",
"def",
"test_switch_connection_error",
"(",
"hass",
":",
"HomeAssistant",
",",
"aioclient_mock",
":",
"AiohttpClientMocker",
")",
"->",
"None",
":",
"await",
"init_integration",
"(",
"hass",
",",
"aioclient_mock",
")",
"with",
"patch",
"(",
"\"homeassistant.components.wled.WLED.update\"",
")",
",",
"patch",
"(",
"\"homeassistant.components.wled.WLED.nightlight\"",
",",
"side_effect",
"=",
"WLEDConnectionError",
")",
":",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"SWITCH_DOMAIN",
",",
"SERVICE_TURN_ON",
",",
"{",
"ATTR_ENTITY_ID",
":",
"\"switch.wled_rgb_light_nightlight\"",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"state",
"=",
"hass",
".",
"states",
".",
"get",
"(",
"\"switch.wled_rgb_light_nightlight\"",
")",
"assert",
"state",
".",
"state",
"==",
"STATE_UNAVAILABLE"
] | [
158,
0
] | [
176,
47
] | python | en | ['en', 'en', 'en'] | True |
documentation_url | (value: str) | Validate that a documentation url has the correct path and domain. | Validate that a documentation url has the correct path and domain. | def documentation_url(value: str) -> str:
"""Validate that a documentation url has the correct path and domain."""
if value in DOCUMENTATION_URL_EXCEPTIONS:
return value
parsed_url = urlparse(value)
if parsed_url.scheme != DOCUMENTATION_URL_SCHEMA:
raise vol.Invalid("Documentation url is not prefixed with https")
if parsed_url.netloc == DOCUMENTATION_URL_HOST and not parsed_url.path.startswith(
DOCUMENTATION_URL_PATH_PREFIX
):
raise vol.Invalid(
"Documentation url does not begin with www.home-assistant.io/integrations"
)
return value | [
"def",
"documentation_url",
"(",
"value",
":",
"str",
")",
"->",
"str",
":",
"if",
"value",
"in",
"DOCUMENTATION_URL_EXCEPTIONS",
":",
"return",
"value",
"parsed_url",
"=",
"urlparse",
"(",
"value",
")",
"if",
"parsed_url",
".",
"scheme",
"!=",
"DOCUMENTATION_URL_SCHEMA",
":",
"raise",
"vol",
".",
"Invalid",
"(",
"\"Documentation url is not prefixed with https\"",
")",
"if",
"parsed_url",
".",
"netloc",
"==",
"DOCUMENTATION_URL_HOST",
"and",
"not",
"parsed_url",
".",
"path",
".",
"startswith",
"(",
"DOCUMENTATION_URL_PATH_PREFIX",
")",
":",
"raise",
"vol",
".",
"Invalid",
"(",
"\"Documentation url does not begin with www.home-assistant.io/integrations\"",
")",
"return",
"value"
] | [
17,
0
] | [
32,
16
] | python | en | ['en', 'en', 'en'] | True |
validate_manifest | (integration: Integration) | Validate manifest. | Validate manifest. | def validate_manifest(integration: Integration):
"""Validate manifest."""
try:
MANIFEST_SCHEMA(integration.manifest)
except vol.Invalid as err:
integration.add_error(
"manifest", f"Invalid manifest: {humanize_error(integration.manifest, err)}"
)
integration.manifest = None
return
if integration.manifest["domain"] != integration.path.name:
integration.add_error("manifest", "Domain does not match dir name") | [
"def",
"validate_manifest",
"(",
"integration",
":",
"Integration",
")",
":",
"try",
":",
"MANIFEST_SCHEMA",
"(",
"integration",
".",
"manifest",
")",
"except",
"vol",
".",
"Invalid",
"as",
"err",
":",
"integration",
".",
"add_error",
"(",
"\"manifest\"",
",",
"f\"Invalid manifest: {humanize_error(integration.manifest, err)}\"",
")",
"integration",
".",
"manifest",
"=",
"None",
"return",
"if",
"integration",
".",
"manifest",
"[",
"\"domain\"",
"]",
"!=",
"integration",
".",
"path",
".",
"name",
":",
"integration",
".",
"add_error",
"(",
"\"manifest\"",
",",
"\"Domain does not match dir name\"",
")"
] | [
73,
0
] | [
85,
75
] | python | bg | ['en', 'et', 'bg'] | False |
validate | (integrations: Dict[str, Integration], config) | Handle all integrations manifests. | Handle all integrations manifests. | def validate(integrations: Dict[str, Integration], config):
"""Handle all integrations manifests."""
for integration in integrations.values():
if integration.manifest:
validate_manifest(integration) | [
"def",
"validate",
"(",
"integrations",
":",
"Dict",
"[",
"str",
",",
"Integration",
"]",
",",
"config",
")",
":",
"for",
"integration",
"in",
"integrations",
".",
"values",
"(",
")",
":",
"if",
"integration",
".",
"manifest",
":",
"validate_manifest",
"(",
"integration",
")"
] | [
88,
0
] | [
92,
42
] | python | en | ['en', 'en', 'en'] | True |
list_containers | () | List the jobs in the cluster.
Returns:
None.
| List the jobs in the cluster. | def list_containers():
"""List the jobs in the cluster.
Returns:
None.
"""
name_to_container_details = redis_controller.get_name_to_container_details()
return list(name_to_container_details.values()) | [
"def",
"list_containers",
"(",
")",
":",
"name_to_container_details",
"=",
"redis_controller",
".",
"get_name_to_container_details",
"(",
")",
"return",
"list",
"(",
"name_to_container_details",
".",
"values",
"(",
")",
")"
] | [
19,
0
] | [
27,
51
] | python | en | ['en', 'en', 'en'] | True |
test_reproducing_states | (hass, caplog) | Test reproducing Input number states. | Test reproducing Input number states. | async def test_reproducing_states(hass, caplog):
"""Test reproducing Input number states."""
assert await async_setup_component(
hass,
"input_number",
{
"input_number": {
"test_number": {"min": "5", "max": "100", "initial": VALID_NUMBER1}
}
},
)
# These calls should do nothing as entities already in desired state
await hass.helpers.state.async_reproduce_state(
[
State("input_number.test_number", VALID_NUMBER1),
# Should not raise
State("input_number.non_existing", "234"),
],
)
assert hass.states.get("input_number.test_number").state == VALID_NUMBER1
# Test reproducing with different state
await hass.helpers.state.async_reproduce_state(
[
State("input_number.test_number", VALID_NUMBER2),
# Should not raise
State("input_number.non_existing", "234"),
],
)
assert hass.states.get("input_number.test_number").state == VALID_NUMBER2
# Test setting state to number out of range
await hass.helpers.state.async_reproduce_state(
[State("input_number.test_number", "150")]
)
# The entity states should be unchanged after trying to set them to out-of-range number
assert hass.states.get("input_number.test_number").state == VALID_NUMBER2
await hass.helpers.state.async_reproduce_state(
[
# Test invalid state
State("input_number.test_number", "invalid_state"),
# Set to state it already is.
State("input_number.test_number", VALID_NUMBER2),
],
) | [
"async",
"def",
"test_reproducing_states",
"(",
"hass",
",",
"caplog",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"input_number\"",
",",
"{",
"\"input_number\"",
":",
"{",
"\"test_number\"",
":",
"{",
"\"min\"",
":",
"\"5\"",
",",
"\"max\"",
":",
"\"100\"",
",",
"\"initial\"",
":",
"VALID_NUMBER1",
"}",
"}",
"}",
",",
")",
"# These calls should do nothing as entities already in desired state",
"await",
"hass",
".",
"helpers",
".",
"state",
".",
"async_reproduce_state",
"(",
"[",
"State",
"(",
"\"input_number.test_number\"",
",",
"VALID_NUMBER1",
")",
",",
"# Should not raise",
"State",
"(",
"\"input_number.non_existing\"",
",",
"\"234\"",
")",
",",
"]",
",",
")",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"input_number.test_number\"",
")",
".",
"state",
"==",
"VALID_NUMBER1",
"# Test reproducing with different state",
"await",
"hass",
".",
"helpers",
".",
"state",
".",
"async_reproduce_state",
"(",
"[",
"State",
"(",
"\"input_number.test_number\"",
",",
"VALID_NUMBER2",
")",
",",
"# Should not raise",
"State",
"(",
"\"input_number.non_existing\"",
",",
"\"234\"",
")",
",",
"]",
",",
")",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"input_number.test_number\"",
")",
".",
"state",
"==",
"VALID_NUMBER2",
"# Test setting state to number out of range",
"await",
"hass",
".",
"helpers",
".",
"state",
".",
"async_reproduce_state",
"(",
"[",
"State",
"(",
"\"input_number.test_number\"",
",",
"\"150\"",
")",
"]",
")",
"# The entity states should be unchanged after trying to set them to out-of-range number",
"assert",
"hass",
".",
"states",
".",
"get",
"(",
"\"input_number.test_number\"",
")",
".",
"state",
"==",
"VALID_NUMBER2",
"await",
"hass",
".",
"helpers",
".",
"state",
".",
"async_reproduce_state",
"(",
"[",
"# Test invalid state",
"State",
"(",
"\"input_number.test_number\"",
",",
"\"invalid_state\"",
")",
",",
"# Set to state it already is.",
"State",
"(",
"\"input_number.test_number\"",
",",
"VALID_NUMBER2",
")",
",",
"]",
",",
")"
] | [
8,
0
] | [
58,
5
] | python | en | ['en', 'en', 'en'] | True |
test_already_configured | (hass, step) | Test config flow when iaqualink component is already setup. | Test config flow when iaqualink component is already setup. | async def test_already_configured(hass, step):
"""Test config flow when iaqualink component is already setup."""
MockConfigEntry(domain="iaqualink", data=DATA).add_to_hass(hass)
flow = config_flow.AqualinkFlowHandler()
flow.hass = hass
flow.context = {}
fname = f"async_step_{step}"
func = getattr(flow, fname)
result = await func(DATA)
assert result["type"] == "abort" | [
"async",
"def",
"test_already_configured",
"(",
"hass",
",",
"step",
")",
":",
"MockConfigEntry",
"(",
"domain",
"=",
"\"iaqualink\"",
",",
"data",
"=",
"DATA",
")",
".",
"add_to_hass",
"(",
"hass",
")",
"flow",
"=",
"config_flow",
".",
"AqualinkFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"flow",
".",
"context",
"=",
"{",
"}",
"fname",
"=",
"f\"async_step_{step}\"",
"func",
"=",
"getattr",
"(",
"flow",
",",
"fname",
")",
"result",
"=",
"await",
"func",
"(",
"DATA",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"abort\""
] | [
14,
0
] | [
26,
36
] | python | en | ['en', 'en', 'en'] | True |
test_without_config | (hass, step) | Test with no configuration. | Test with no configuration. | async def test_without_config(hass, step):
"""Test with no configuration."""
flow = config_flow.AqualinkFlowHandler()
flow.hass = hass
flow.context = {}
fname = f"async_step_{step}"
func = getattr(flow, fname)
result = await func()
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {} | [
"async",
"def",
"test_without_config",
"(",
"hass",
",",
"step",
")",
":",
"flow",
"=",
"config_flow",
".",
"AqualinkFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"flow",
".",
"context",
"=",
"{",
"}",
"fname",
"=",
"f\"async_step_{step}\"",
"func",
"=",
"getattr",
"(",
"flow",
",",
"fname",
")",
"result",
"=",
"await",
"func",
"(",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"}"
] | [
30,
0
] | [
42,
33
] | python | en | ['en', 'en', 'en'] | True |
test_with_invalid_credentials | (hass, step) | Test config flow with invalid username and/or password. | Test config flow with invalid username and/or password. | async def test_with_invalid_credentials(hass, step):
"""Test config flow with invalid username and/or password."""
flow = config_flow.AqualinkFlowHandler()
flow.hass = hass
fname = f"async_step_{step}"
func = getattr(flow, fname)
with patch(
"iaqualink.AqualinkClient.login", side_effect=iaqualink.AqualinkLoginException
):
result = await func(DATA)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"} | [
"async",
"def",
"test_with_invalid_credentials",
"(",
"hass",
",",
"step",
")",
":",
"flow",
"=",
"config_flow",
".",
"AqualinkFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"fname",
"=",
"f\"async_step_{step}\"",
"func",
"=",
"getattr",
"(",
"flow",
",",
"fname",
")",
"with",
"patch",
"(",
"\"iaqualink.AqualinkClient.login\"",
",",
"side_effect",
"=",
"iaqualink",
".",
"AqualinkLoginException",
")",
":",
"result",
"=",
"await",
"func",
"(",
"DATA",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"form\"",
"assert",
"result",
"[",
"\"step_id\"",
"]",
"==",
"\"user\"",
"assert",
"result",
"[",
"\"errors\"",
"]",
"==",
"{",
"\"base\"",
":",
"\"cannot_connect\"",
"}"
] | [
46,
0
] | [
60,
57
] | python | en | ['en', 'en', 'en'] | True |
test_with_existing_config | (hass, step) | Test with existing configuration. | Test with existing configuration. | async def test_with_existing_config(hass, step):
"""Test with existing configuration."""
flow = config_flow.AqualinkFlowHandler()
flow.hass = hass
flow.context = {}
fname = f"async_step_{step}"
func = getattr(flow, fname)
with patch("iaqualink.AqualinkClient.login", return_value=mock_coro(None)):
result = await func(DATA)
assert result["type"] == "create_entry"
assert result["title"] == DATA["username"]
assert result["data"] == DATA | [
"async",
"def",
"test_with_existing_config",
"(",
"hass",
",",
"step",
")",
":",
"flow",
"=",
"config_flow",
".",
"AqualinkFlowHandler",
"(",
")",
"flow",
".",
"hass",
"=",
"hass",
"flow",
".",
"context",
"=",
"{",
"}",
"fname",
"=",
"f\"async_step_{step}\"",
"func",
"=",
"getattr",
"(",
"flow",
",",
"fname",
")",
"with",
"patch",
"(",
"\"iaqualink.AqualinkClient.login\"",
",",
"return_value",
"=",
"mock_coro",
"(",
"None",
")",
")",
":",
"result",
"=",
"await",
"func",
"(",
"DATA",
")",
"assert",
"result",
"[",
"\"type\"",
"]",
"==",
"\"create_entry\"",
"assert",
"result",
"[",
"\"title\"",
"]",
"==",
"DATA",
"[",
"\"username\"",
"]",
"assert",
"result",
"[",
"\"data\"",
"]",
"==",
"DATA"
] | [
64,
0
] | [
77,
33
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], bool], None],
) | Set up WLED switch based on a config entry. | Set up WLED switch based on a config entry. | async def async_setup_entry(
hass: HomeAssistantType,
entry: ConfigEntry,
async_add_entities: Callable[[List[Entity], bool], None],
) -> None:
"""Set up WLED switch based on a config entry."""
coordinator: WLEDDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
switches = [
WLEDNightlightSwitch(entry.entry_id, coordinator),
WLEDSyncSendSwitch(entry.entry_id, coordinator),
WLEDSyncReceiveSwitch(entry.entry_id, coordinator),
]
async_add_entities(switches, True) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistantType",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
":",
"Callable",
"[",
"[",
"List",
"[",
"Entity",
"]",
",",
"bool",
"]",
",",
"None",
"]",
",",
")",
"->",
"None",
":",
"coordinator",
":",
"WLEDDataUpdateCoordinator",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"switches",
"=",
"[",
"WLEDNightlightSwitch",
"(",
"entry",
".",
"entry_id",
",",
"coordinator",
")",
",",
"WLEDSyncSendSwitch",
"(",
"entry",
".",
"entry_id",
",",
"coordinator",
")",
",",
"WLEDSyncReceiveSwitch",
"(",
"entry",
".",
"entry_id",
",",
"coordinator",
")",
",",
"]",
"async_add_entities",
"(",
"switches",
",",
"True",
")"
] | [
20,
0
] | [
33,
38
] | python | en | ['en', 'en', 'en'] | True |
WLEDSwitch.__init__ | (
self,
*,
entry_id: str,
coordinator: WLEDDataUpdateCoordinator,
name: str,
icon: str,
key: str,
) | Initialize WLED switch. | Initialize WLED switch. | def __init__(
self,
*,
entry_id: str,
coordinator: WLEDDataUpdateCoordinator,
name: str,
icon: str,
key: str,
) -> None:
"""Initialize WLED switch."""
self._key = key
super().__init__(
entry_id=entry_id, coordinator=coordinator, name=name, icon=icon
) | [
"def",
"__init__",
"(",
"self",
",",
"*",
",",
"entry_id",
":",
"str",
",",
"coordinator",
":",
"WLEDDataUpdateCoordinator",
",",
"name",
":",
"str",
",",
"icon",
":",
"str",
",",
"key",
":",
"str",
",",
")",
"->",
"None",
":",
"self",
".",
"_key",
"=",
"key",
"super",
"(",
")",
".",
"__init__",
"(",
"entry_id",
"=",
"entry_id",
",",
"coordinator",
"=",
"coordinator",
",",
"name",
"=",
"name",
",",
"icon",
"=",
"icon",
")"
] | [
39,
4
] | [
52,
9
] | python | en | ['en', 'pl', 'en'] | True |
WLEDSwitch.unique_id | (self) | Return the unique ID for this sensor. | Return the unique ID for this sensor. | def unique_id(self) -> str:
"""Return the unique ID for this sensor."""
return f"{self.coordinator.data.info.mac_address}_{self._key}" | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"f\"{self.coordinator.data.info.mac_address}_{self._key}\""
] | [
55,
4
] | [
57,
70
] | python | en | ['en', 'la', 'en'] | True |
WLEDNightlightSwitch.__init__ | (self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) | Initialize WLED nightlight switch. | Initialize WLED nightlight switch. | def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED nightlight switch."""
super().__init__(
coordinator=coordinator,
entry_id=entry_id,
icon="mdi:weather-night",
key="nightlight",
name=f"{coordinator.data.info.name} Nightlight",
) | [
"def",
"__init__",
"(",
"self",
",",
"entry_id",
":",
"str",
",",
"coordinator",
":",
"WLEDDataUpdateCoordinator",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
"=",
"coordinator",
",",
"entry_id",
"=",
"entry_id",
",",
"icon",
"=",
"\"mdi:weather-night\"",
",",
"key",
"=",
"\"nightlight\"",
",",
"name",
"=",
"f\"{coordinator.data.info.name} Nightlight\"",
",",
")"
] | [
63,
4
] | [
71,
9
] | python | en | ['en', 'pl', 'en'] | True |
WLEDNightlightSwitch.device_state_attributes | (self) | Return the state attributes of the entity. | Return the state attributes of the entity. | def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes of the entity."""
return {
ATTR_DURATION: self.coordinator.data.state.nightlight.duration,
ATTR_FADE: self.coordinator.data.state.nightlight.fade,
ATTR_TARGET_BRIGHTNESS: self.coordinator.data.state.nightlight.target_brightness,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"{",
"ATTR_DURATION",
":",
"self",
".",
"coordinator",
".",
"data",
".",
"state",
".",
"nightlight",
".",
"duration",
",",
"ATTR_FADE",
":",
"self",
".",
"coordinator",
".",
"data",
".",
"state",
".",
"nightlight",
".",
"fade",
",",
"ATTR_TARGET_BRIGHTNESS",
":",
"self",
".",
"coordinator",
".",
"data",
".",
"state",
".",
"nightlight",
".",
"target_brightness",
",",
"}"
] | [
74,
4
] | [
80,
9
] | python | en | ['en', 'en', 'en'] | True |
WLEDNightlightSwitch.is_on | (self) | Return the state of the switch. | Return the state of the switch. | def is_on(self) -> bool:
"""Return the state of the switch."""
return bool(self.coordinator.data.state.nightlight.on) | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"coordinator",
".",
"data",
".",
"state",
".",
"nightlight",
".",
"on",
")"
] | [
83,
4
] | [
85,
62
] | python | en | ['en', 'en', 'en'] | True |
WLEDNightlightSwitch.async_turn_off | (self, **kwargs: Any) | Turn off the WLED nightlight switch. | Turn off the WLED nightlight switch. | async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the WLED nightlight switch."""
await self.coordinator.wled.nightlight(on=False) | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"await",
"self",
".",
"coordinator",
".",
"wled",
".",
"nightlight",
"(",
"on",
"=",
"False",
")"
] | [
88,
4
] | [
90,
56
] | python | en | ['en', 'en', 'en'] | True |
WLEDNightlightSwitch.async_turn_on | (self, **kwargs: Any) | Turn on the WLED nightlight switch. | Turn on the WLED nightlight switch. | async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the WLED nightlight switch."""
await self.coordinator.wled.nightlight(on=True) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"await",
"self",
".",
"coordinator",
".",
"wled",
".",
"nightlight",
"(",
"on",
"=",
"True",
")"
] | [
93,
4
] | [
95,
55
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncSendSwitch.__init__ | (self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) | Initialize WLED sync send switch. | Initialize WLED sync send switch. | def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) -> None:
"""Initialize WLED sync send switch."""
super().__init__(
coordinator=coordinator,
entry_id=entry_id,
icon="mdi:upload-network-outline",
key="sync_send",
name=f"{coordinator.data.info.name} Sync Send",
) | [
"def",
"__init__",
"(",
"self",
",",
"entry_id",
":",
"str",
",",
"coordinator",
":",
"WLEDDataUpdateCoordinator",
")",
"->",
"None",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
"=",
"coordinator",
",",
"entry_id",
"=",
"entry_id",
",",
"icon",
"=",
"\"mdi:upload-network-outline\"",
",",
"key",
"=",
"\"sync_send\"",
",",
"name",
"=",
"f\"{coordinator.data.info.name} Sync Send\"",
",",
")"
] | [
101,
4
] | [
109,
9
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncSendSwitch.device_state_attributes | (self) | Return the state attributes of the entity. | Return the state attributes of the entity. | def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes of the entity."""
return {ATTR_UDP_PORT: self.coordinator.data.info.udp_port} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"{",
"ATTR_UDP_PORT",
":",
"self",
".",
"coordinator",
".",
"data",
".",
"info",
".",
"udp_port",
"}"
] | [
112,
4
] | [
114,
67
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncSendSwitch.is_on | (self) | Return the state of the switch. | Return the state of the switch. | def is_on(self) -> bool:
"""Return the state of the switch."""
return bool(self.coordinator.data.state.sync.send) | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"coordinator",
".",
"data",
".",
"state",
".",
"sync",
".",
"send",
")"
] | [
117,
4
] | [
119,
58
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncSendSwitch.async_turn_off | (self, **kwargs: Any) | Turn off the WLED sync send switch. | Turn off the WLED sync send switch. | async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the WLED sync send switch."""
await self.coordinator.wled.sync(send=False) | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"await",
"self",
".",
"coordinator",
".",
"wled",
".",
"sync",
"(",
"send",
"=",
"False",
")"
] | [
122,
4
] | [
124,
52
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncSendSwitch.async_turn_on | (self, **kwargs: Any) | Turn on the WLED sync send switch. | Turn on the WLED sync send switch. | async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the WLED sync send switch."""
await self.coordinator.wled.sync(send=True) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"await",
"self",
".",
"coordinator",
".",
"wled",
".",
"sync",
"(",
"send",
"=",
"True",
")"
] | [
127,
4
] | [
129,
51
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncReceiveSwitch.__init__ | (self, entry_id: str, coordinator: WLEDDataUpdateCoordinator) | Initialize WLED sync receive switch. | Initialize WLED sync receive switch. | def __init__(self, entry_id: str, coordinator: WLEDDataUpdateCoordinator):
"""Initialize WLED sync receive switch."""
super().__init__(
coordinator=coordinator,
entry_id=entry_id,
icon="mdi:download-network-outline",
key="sync_receive",
name=f"{coordinator.data.info.name} Sync Receive",
) | [
"def",
"__init__",
"(",
"self",
",",
"entry_id",
":",
"str",
",",
"coordinator",
":",
"WLEDDataUpdateCoordinator",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
"=",
"coordinator",
",",
"entry_id",
"=",
"entry_id",
",",
"icon",
"=",
"\"mdi:download-network-outline\"",
",",
"key",
"=",
"\"sync_receive\"",
",",
"name",
"=",
"f\"{coordinator.data.info.name} Sync Receive\"",
",",
")"
] | [
135,
4
] | [
143,
9
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncReceiveSwitch.device_state_attributes | (self) | Return the state attributes of the entity. | Return the state attributes of the entity. | def device_state_attributes(self) -> Optional[Dict[str, Any]]:
"""Return the state attributes of the entity."""
return {ATTR_UDP_PORT: self.coordinator.data.info.udp_port} | [
"def",
"device_state_attributes",
"(",
"self",
")",
"->",
"Optional",
"[",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"{",
"ATTR_UDP_PORT",
":",
"self",
".",
"coordinator",
".",
"data",
".",
"info",
".",
"udp_port",
"}"
] | [
146,
4
] | [
148,
67
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncReceiveSwitch.is_on | (self) | Return the state of the switch. | Return the state of the switch. | def is_on(self) -> bool:
"""Return the state of the switch."""
return bool(self.coordinator.data.state.sync.receive) | [
"def",
"is_on",
"(",
"self",
")",
"->",
"bool",
":",
"return",
"bool",
"(",
"self",
".",
"coordinator",
".",
"data",
".",
"state",
".",
"sync",
".",
"receive",
")"
] | [
151,
4
] | [
153,
61
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncReceiveSwitch.async_turn_off | (self, **kwargs: Any) | Turn off the WLED sync receive switch. | Turn off the WLED sync receive switch. | async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the WLED sync receive switch."""
await self.coordinator.wled.sync(receive=False) | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"await",
"self",
".",
"coordinator",
".",
"wled",
".",
"sync",
"(",
"receive",
"=",
"False",
")"
] | [
156,
4
] | [
158,
55
] | python | en | ['en', 'en', 'en'] | True |
WLEDSyncReceiveSwitch.async_turn_on | (self, **kwargs: Any) | Turn on the WLED sync receive switch. | Turn on the WLED sync receive switch. | async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the WLED sync receive switch."""
await self.coordinator.wled.sync(receive=True) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"await",
"self",
".",
"coordinator",
".",
"wled",
".",
"sync",
"(",
"receive",
"=",
"True",
")"
] | [
161,
4
] | [
163,
54
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass: HomeAssistant, config: dict) | Set up Home Connect component. | Set up Home Connect component. | async def async_setup(hass: HomeAssistant, config: dict) -> bool:
"""Set up Home Connect component."""
hass.data[DOMAIN] = {}
if DOMAIN not in config:
return True
config_flow.OAuth2FlowHandler.async_register_implementation(
hass,
config_entry_oauth2_flow.LocalOAuth2Implementation(
hass,
DOMAIN,
config[DOMAIN][CONF_CLIENT_ID],
config[DOMAIN][CONF_CLIENT_SECRET],
OAUTH2_AUTHORIZE,
OAUTH2_TOKEN,
),
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
"->",
"bool",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"}",
"if",
"DOMAIN",
"not",
"in",
"config",
":",
"return",
"True",
"config_flow",
".",
"OAuth2FlowHandler",
".",
"async_register_implementation",
"(",
"hass",
",",
"config_entry_oauth2_flow",
".",
"LocalOAuth2Implementation",
"(",
"hass",
",",
"DOMAIN",
",",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_CLIENT_ID",
"]",
",",
"config",
"[",
"DOMAIN",
"]",
"[",
"CONF_CLIENT_SECRET",
"]",
",",
"OAUTH2_AUTHORIZE",
",",
"OAUTH2_TOKEN",
",",
")",
",",
")",
"return",
"True"
] | [
37,
0
] | [
56,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass: HomeAssistant, entry: ConfigEntry) | Set up Home Connect from a config entry. | Set up Home Connect from a config entry. | async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Home Connect from a config entry."""
implementation = (
await config_entry_oauth2_flow.async_get_config_entry_implementation(
hass, entry
)
)
hc_api = api.ConfigEntryAuth(hass, entry, implementation)
hass.data[DOMAIN][entry.entry_id] = hc_api
await update_all_devices(hass, entry)
for component in PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
"->",
"bool",
":",
"implementation",
"=",
"(",
"await",
"config_entry_oauth2_flow",
".",
"async_get_config_entry_implementation",
"(",
"hass",
",",
"entry",
")",
")",
"hc_api",
"=",
"api",
".",
"ConfigEntryAuth",
"(",
"hass",
",",
"entry",
",",
"implementation",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"=",
"hc_api",
"await",
"update_all_devices",
"(",
"hass",
",",
"entry",
")",
"for",
"component",
"in",
"PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"entry",
",",
"component",
")",
")",
"return",
"True"
] | [
59,
0
] | [
78,
15
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass: HomeAssistant, entry: ConfigEntry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = all(
await asyncio.gather(
*[
hass.config_entries.async_forward_entry_unload(entry, component)
for component in PLATFORMS
]
)
)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
")",
"->",
"bool",
":",
"unload_ok",
"=",
"all",
"(",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"[",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"entry",
",",
"component",
")",
"for",
"component",
"in",
"PLATFORMS",
"]",
")",
")",
"if",
"unload_ok",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"pop",
"(",
"entry",
".",
"entry_id",
")",
"return",
"unload_ok"
] | [
81,
0
] | [
94,
20
] | python | en | ['en', 'es', 'en'] | True |
update_all_devices | (hass, entry) | Update all the devices. | Update all the devices. | async def update_all_devices(hass, entry):
"""Update all the devices."""
data = hass.data[DOMAIN]
hc_api = data[entry.entry_id]
try:
await hass.async_add_executor_job(hc_api.get_devices)
for device_dict in hc_api.devices:
await hass.async_add_executor_job(device_dict["device"].initialize)
except HTTPError as err:
_LOGGER.warning("Cannot update devices: %s", err.response.status_code) | [
"async",
"def",
"update_all_devices",
"(",
"hass",
",",
"entry",
")",
":",
"data",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"hc_api",
"=",
"data",
"[",
"entry",
".",
"entry_id",
"]",
"try",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"hc_api",
".",
"get_devices",
")",
"for",
"device_dict",
"in",
"hc_api",
".",
"devices",
":",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"device_dict",
"[",
"\"device\"",
"]",
".",
"initialize",
")",
"except",
"HTTPError",
"as",
"err",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Cannot update devices: %s\"",
",",
"err",
".",
"response",
".",
"status_code",
")"
] | [
98,
0
] | [
107,
78
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Set up the PS4 Component. | Set up the PS4 Component. | async def async_setup(hass, config):
"""Set up the PS4 Component."""
hass.data[PS4_DATA] = PS4Data()
transport, protocol = await async_create_ddp_endpoint()
hass.data[PS4_DATA].protocol = protocol
_LOGGER.debug("PS4 DDP endpoint created: %s, %s", transport, protocol)
service_handle(hass)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
"[",
"PS4_DATA",
"]",
"=",
"PS4Data",
"(",
")",
"transport",
",",
"protocol",
"=",
"await",
"async_create_ddp_endpoint",
"(",
")",
"hass",
".",
"data",
"[",
"PS4_DATA",
"]",
".",
"protocol",
"=",
"protocol",
"_LOGGER",
".",
"debug",
"(",
"\"PS4 DDP endpoint created: %s, %s\"",
",",
"transport",
",",
"protocol",
")",
"service_handle",
"(",
"hass",
")",
"return",
"True"
] | [
51,
0
] | [
59,
15
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.