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 |
---|---|---|---|---|---|---|---|---|---|---|---|
StarlineAccount.engine_attrs | (device: StarlineDevice) | Attributes for engine switch. | Attributes for engine switch. | def engine_attrs(device: StarlineDevice) -> Dict[str, Any]:
"""Attributes for engine switch."""
return {
"autostart": device.car_state.get("r_start"),
"ignition": device.car_state.get("run"),
} | [
"def",
"engine_attrs",
"(",
"device",
":",
"StarlineDevice",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"{",
"\"autostart\"",
":",
"device",
".",
"car_state",
".",
"get",
"(",
"\"r_start\"",
")",
",",
"\"ignition\"",
":",
"device",
".",
"car_state",
".",
"get",
"(",
"\"run\"",
")",
",",
"}"
] | [
136,
4
] | [
141,
9
] | python | en | ['en', 'en', 'en'] | True |
async_enable_proactive_mode | (hass, smart_home_config) | Enable the proactive mode.
Proactive mode makes this component report state changes to Alexa.
| Enable the proactive mode. | async def async_enable_proactive_mode(hass, smart_home_config):
"""Enable the proactive mode.
Proactive mode makes this component report state changes to Alexa.
"""
# Validate we can get access token.
await smart_home_config.async_get_access_token()
async def async_entity_state_listener(changed_entity, old_state, new_state):
if not hass.is_running:
return
if not new_state:
return
if new_state.domain not in ENTITY_ADAPTERS:
return
if not smart_home_config.should_expose(changed_entity):
_LOGGER.debug("Not exposing %s because filtered by config", changed_entity)
return
alexa_changed_entity = ENTITY_ADAPTERS[new_state.domain](
hass, smart_home_config, new_state
)
for interface in alexa_changed_entity.interfaces():
if interface.properties_proactively_reported():
await async_send_changereport_message(
hass, smart_home_config, alexa_changed_entity
)
return
if (
interface.name() == "Alexa.DoorbellEventSource"
and new_state.state == STATE_ON
):
await async_send_doorbell_event_message(
hass, smart_home_config, alexa_changed_entity
)
return
return hass.helpers.event.async_track_state_change(
MATCH_ALL, async_entity_state_listener
) | [
"async",
"def",
"async_enable_proactive_mode",
"(",
"hass",
",",
"smart_home_config",
")",
":",
"# Validate we can get access token.",
"await",
"smart_home_config",
".",
"async_get_access_token",
"(",
")",
"async",
"def",
"async_entity_state_listener",
"(",
"changed_entity",
",",
"old_state",
",",
"new_state",
")",
":",
"if",
"not",
"hass",
".",
"is_running",
":",
"return",
"if",
"not",
"new_state",
":",
"return",
"if",
"new_state",
".",
"domain",
"not",
"in",
"ENTITY_ADAPTERS",
":",
"return",
"if",
"not",
"smart_home_config",
".",
"should_expose",
"(",
"changed_entity",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Not exposing %s because filtered by config\"",
",",
"changed_entity",
")",
"return",
"alexa_changed_entity",
"=",
"ENTITY_ADAPTERS",
"[",
"new_state",
".",
"domain",
"]",
"(",
"hass",
",",
"smart_home_config",
",",
"new_state",
")",
"for",
"interface",
"in",
"alexa_changed_entity",
".",
"interfaces",
"(",
")",
":",
"if",
"interface",
".",
"properties_proactively_reported",
"(",
")",
":",
"await",
"async_send_changereport_message",
"(",
"hass",
",",
"smart_home_config",
",",
"alexa_changed_entity",
")",
"return",
"if",
"(",
"interface",
".",
"name",
"(",
")",
"==",
"\"Alexa.DoorbellEventSource\"",
"and",
"new_state",
".",
"state",
"==",
"STATE_ON",
")",
":",
"await",
"async_send_doorbell_event_message",
"(",
"hass",
",",
"smart_home_config",
",",
"alexa_changed_entity",
")",
"return",
"return",
"hass",
".",
"helpers",
".",
"event",
".",
"async_track_state_change",
"(",
"MATCH_ALL",
",",
"async_entity_state_listener",
")"
] | [
19,
0
] | [
62,
5
] | python | en | ['en', 'xh', 'en'] | True |
async_send_changereport_message | (
hass, config, alexa_entity, *, invalidate_access_token=True
) | Send a ChangeReport message for an Alexa entity.
https://developer.amazon.com/docs/smarthome/state-reporting-for-a-smart-home-skill.html#report-state-with-changereport-events
| Send a ChangeReport message for an Alexa entity. | async def async_send_changereport_message(
hass, config, alexa_entity, *, invalidate_access_token=True
):
"""Send a ChangeReport message for an Alexa entity.
https://developer.amazon.com/docs/smarthome/state-reporting-for-a-smart-home-skill.html#report-state-with-changereport-events
"""
token = await config.async_get_access_token()
headers = {"Authorization": f"Bearer {token}"}
endpoint = alexa_entity.alexa_id()
# this sends all the properties of the Alexa Entity, whether they have
# changed or not. this should be improved, and properties that have not
# changed should be moved to the 'context' object
properties = list(alexa_entity.serialize_properties())
payload = {
API_CHANGE: {"cause": {"type": Cause.APP_INTERACTION}, "properties": properties}
}
message = AlexaResponse(name="ChangeReport", namespace="Alexa", payload=payload)
message.set_endpoint_full(token, endpoint)
message_serialized = message.serialize()
session = hass.helpers.aiohttp_client.async_get_clientsession()
try:
with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.post(
config.endpoint,
headers=headers,
json=message_serialized,
allow_redirects=True,
)
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout sending report to Alexa")
return
response_text = await response.text()
_LOGGER.debug("Sent: %s", json.dumps(message_serialized))
_LOGGER.debug("Received (%s): %s", response.status, response_text)
if response.status == HTTP_ACCEPTED:
return
response_json = json.loads(response_text)
if (
response_json["payload"]["code"] == "INVALID_ACCESS_TOKEN_EXCEPTION"
and not invalidate_access_token
):
config.async_invalidate_access_token()
return await async_send_changereport_message(
hass, config, alexa_entity, invalidate_access_token=False
)
_LOGGER.error(
"Error when sending ChangeReport to Alexa: %s: %s",
response_json["payload"]["code"],
response_json["payload"]["description"],
) | [
"async",
"def",
"async_send_changereport_message",
"(",
"hass",
",",
"config",
",",
"alexa_entity",
",",
"*",
",",
"invalidate_access_token",
"=",
"True",
")",
":",
"token",
"=",
"await",
"config",
".",
"async_get_access_token",
"(",
")",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"f\"Bearer {token}\"",
"}",
"endpoint",
"=",
"alexa_entity",
".",
"alexa_id",
"(",
")",
"# this sends all the properties of the Alexa Entity, whether they have",
"# changed or not. this should be improved, and properties that have not",
"# changed should be moved to the 'context' object",
"properties",
"=",
"list",
"(",
"alexa_entity",
".",
"serialize_properties",
"(",
")",
")",
"payload",
"=",
"{",
"API_CHANGE",
":",
"{",
"\"cause\"",
":",
"{",
"\"type\"",
":",
"Cause",
".",
"APP_INTERACTION",
"}",
",",
"\"properties\"",
":",
"properties",
"}",
"}",
"message",
"=",
"AlexaResponse",
"(",
"name",
"=",
"\"ChangeReport\"",
",",
"namespace",
"=",
"\"Alexa\"",
",",
"payload",
"=",
"payload",
")",
"message",
".",
"set_endpoint_full",
"(",
"token",
",",
"endpoint",
")",
"message_serialized",
"=",
"message",
".",
"serialize",
"(",
")",
"session",
"=",
"hass",
".",
"helpers",
".",
"aiohttp_client",
".",
"async_get_clientsession",
"(",
")",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"DEFAULT_TIMEOUT",
")",
":",
"response",
"=",
"await",
"session",
".",
"post",
"(",
"config",
".",
"endpoint",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"message_serialized",
",",
"allow_redirects",
"=",
"True",
",",
")",
"except",
"(",
"asyncio",
".",
"TimeoutError",
",",
"aiohttp",
".",
"ClientError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Timeout sending report to Alexa\"",
")",
"return",
"response_text",
"=",
"await",
"response",
".",
"text",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Sent: %s\"",
",",
"json",
".",
"dumps",
"(",
"message_serialized",
")",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Received (%s): %s\"",
",",
"response",
".",
"status",
",",
"response_text",
")",
"if",
"response",
".",
"status",
"==",
"HTTP_ACCEPTED",
":",
"return",
"response_json",
"=",
"json",
".",
"loads",
"(",
"response_text",
")",
"if",
"(",
"response_json",
"[",
"\"payload\"",
"]",
"[",
"\"code\"",
"]",
"==",
"\"INVALID_ACCESS_TOKEN_EXCEPTION\"",
"and",
"not",
"invalidate_access_token",
")",
":",
"config",
".",
"async_invalidate_access_token",
"(",
")",
"return",
"await",
"async_send_changereport_message",
"(",
"hass",
",",
"config",
",",
"alexa_entity",
",",
"invalidate_access_token",
"=",
"False",
")",
"_LOGGER",
".",
"error",
"(",
"\"Error when sending ChangeReport to Alexa: %s: %s\"",
",",
"response_json",
"[",
"\"payload\"",
"]",
"[",
"\"code\"",
"]",
",",
"response_json",
"[",
"\"payload\"",
"]",
"[",
"\"description\"",
"]",
",",
")"
] | [
65,
0
] | [
129,
5
] | python | en | ['en', 'lb', 'en'] | True |
async_send_add_or_update_message | (hass, config, entity_ids) | Send an AddOrUpdateReport message for entities.
https://developer.amazon.com/docs/device-apis/alexa-discovery.html#add-or-update-report
| Send an AddOrUpdateReport message for entities. | async def async_send_add_or_update_message(hass, config, entity_ids):
"""Send an AddOrUpdateReport message for entities.
https://developer.amazon.com/docs/device-apis/alexa-discovery.html#add-or-update-report
"""
token = await config.async_get_access_token()
headers = {"Authorization": f"Bearer {token}"}
endpoints = []
for entity_id in entity_ids:
domain = entity_id.split(".", 1)[0]
if domain not in ENTITY_ADAPTERS:
continue
alexa_entity = ENTITY_ADAPTERS[domain](hass, config, hass.states.get(entity_id))
endpoints.append(alexa_entity.serialize_discovery())
payload = {"endpoints": endpoints, "scope": {"type": "BearerToken", "token": token}}
message = AlexaResponse(
name="AddOrUpdateReport", namespace="Alexa.Discovery", payload=payload
)
message_serialized = message.serialize()
session = hass.helpers.aiohttp_client.async_get_clientsession()
return await session.post(
config.endpoint, headers=headers, json=message_serialized, allow_redirects=True
) | [
"async",
"def",
"async_send_add_or_update_message",
"(",
"hass",
",",
"config",
",",
"entity_ids",
")",
":",
"token",
"=",
"await",
"config",
".",
"async_get_access_token",
"(",
")",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"f\"Bearer {token}\"",
"}",
"endpoints",
"=",
"[",
"]",
"for",
"entity_id",
"in",
"entity_ids",
":",
"domain",
"=",
"entity_id",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"if",
"domain",
"not",
"in",
"ENTITY_ADAPTERS",
":",
"continue",
"alexa_entity",
"=",
"ENTITY_ADAPTERS",
"[",
"domain",
"]",
"(",
"hass",
",",
"config",
",",
"hass",
".",
"states",
".",
"get",
"(",
"entity_id",
")",
")",
"endpoints",
".",
"append",
"(",
"alexa_entity",
".",
"serialize_discovery",
"(",
")",
")",
"payload",
"=",
"{",
"\"endpoints\"",
":",
"endpoints",
",",
"\"scope\"",
":",
"{",
"\"type\"",
":",
"\"BearerToken\"",
",",
"\"token\"",
":",
"token",
"}",
"}",
"message",
"=",
"AlexaResponse",
"(",
"name",
"=",
"\"AddOrUpdateReport\"",
",",
"namespace",
"=",
"\"Alexa.Discovery\"",
",",
"payload",
"=",
"payload",
")",
"message_serialized",
"=",
"message",
".",
"serialize",
"(",
")",
"session",
"=",
"hass",
".",
"helpers",
".",
"aiohttp_client",
".",
"async_get_clientsession",
"(",
")",
"return",
"await",
"session",
".",
"post",
"(",
"config",
".",
"endpoint",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"message_serialized",
",",
"allow_redirects",
"=",
"True",
")"
] | [
132,
0
] | [
163,
5
] | python | en | ['en', 'lb', 'en'] | True |
async_send_delete_message | (hass, config, entity_ids) | Send an DeleteReport message for entities.
https://developer.amazon.com/docs/device-apis/alexa-discovery.html#deletereport-event
| Send an DeleteReport message for entities. | async def async_send_delete_message(hass, config, entity_ids):
"""Send an DeleteReport message for entities.
https://developer.amazon.com/docs/device-apis/alexa-discovery.html#deletereport-event
"""
token = await config.async_get_access_token()
headers = {"Authorization": f"Bearer {token}"}
endpoints = []
for entity_id in entity_ids:
domain = entity_id.split(".", 1)[0]
if domain not in ENTITY_ADAPTERS:
continue
endpoints.append({"endpointId": generate_alexa_id(entity_id)})
payload = {"endpoints": endpoints, "scope": {"type": "BearerToken", "token": token}}
message = AlexaResponse(
name="DeleteReport", namespace="Alexa.Discovery", payload=payload
)
message_serialized = message.serialize()
session = hass.helpers.aiohttp_client.async_get_clientsession()
return await session.post(
config.endpoint, headers=headers, json=message_serialized, allow_redirects=True
) | [
"async",
"def",
"async_send_delete_message",
"(",
"hass",
",",
"config",
",",
"entity_ids",
")",
":",
"token",
"=",
"await",
"config",
".",
"async_get_access_token",
"(",
")",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"f\"Bearer {token}\"",
"}",
"endpoints",
"=",
"[",
"]",
"for",
"entity_id",
"in",
"entity_ids",
":",
"domain",
"=",
"entity_id",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
"[",
"0",
"]",
"if",
"domain",
"not",
"in",
"ENTITY_ADAPTERS",
":",
"continue",
"endpoints",
".",
"append",
"(",
"{",
"\"endpointId\"",
":",
"generate_alexa_id",
"(",
"entity_id",
")",
"}",
")",
"payload",
"=",
"{",
"\"endpoints\"",
":",
"endpoints",
",",
"\"scope\"",
":",
"{",
"\"type\"",
":",
"\"BearerToken\"",
",",
"\"token\"",
":",
"token",
"}",
"}",
"message",
"=",
"AlexaResponse",
"(",
"name",
"=",
"\"DeleteReport\"",
",",
"namespace",
"=",
"\"Alexa.Discovery\"",
",",
"payload",
"=",
"payload",
")",
"message_serialized",
"=",
"message",
".",
"serialize",
"(",
")",
"session",
"=",
"hass",
".",
"helpers",
".",
"aiohttp_client",
".",
"async_get_clientsession",
"(",
")",
"return",
"await",
"session",
".",
"post",
"(",
"config",
".",
"endpoint",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"message_serialized",
",",
"allow_redirects",
"=",
"True",
")"
] | [
166,
0
] | [
196,
5
] | python | en | ['en', 'en', 'en'] | True |
async_send_doorbell_event_message | (hass, config, alexa_entity) | Send a DoorbellPress event message for an Alexa entity.
https://developer.amazon.com/docs/smarthome/send-events-to-the-alexa-event-gateway.html
| Send a DoorbellPress event message for an Alexa entity. | async def async_send_doorbell_event_message(hass, config, alexa_entity):
"""Send a DoorbellPress event message for an Alexa entity.
https://developer.amazon.com/docs/smarthome/send-events-to-the-alexa-event-gateway.html
"""
token = await config.async_get_access_token()
headers = {"Authorization": f"Bearer {token}"}
endpoint = alexa_entity.alexa_id()
message = AlexaResponse(
name="DoorbellPress",
namespace="Alexa.DoorbellEventSource",
payload={
"cause": {"type": Cause.PHYSICAL_INTERACTION},
"timestamp": f"{dt_util.utcnow().replace(tzinfo=None).isoformat()}Z",
},
)
message.set_endpoint_full(token, endpoint)
message_serialized = message.serialize()
session = hass.helpers.aiohttp_client.async_get_clientsession()
try:
with async_timeout.timeout(DEFAULT_TIMEOUT):
response = await session.post(
config.endpoint,
headers=headers,
json=message_serialized,
allow_redirects=True,
)
except (asyncio.TimeoutError, aiohttp.ClientError):
_LOGGER.error("Timeout sending report to Alexa")
return
response_text = await response.text()
_LOGGER.debug("Sent: %s", json.dumps(message_serialized))
_LOGGER.debug("Received (%s): %s", response.status, response_text)
if response.status == HTTP_ACCEPTED:
return
response_json = json.loads(response_text)
_LOGGER.error(
"Error when sending DoorbellPress event to Alexa: %s: %s",
response_json["payload"]["code"],
response_json["payload"]["description"],
) | [
"async",
"def",
"async_send_doorbell_event_message",
"(",
"hass",
",",
"config",
",",
"alexa_entity",
")",
":",
"token",
"=",
"await",
"config",
".",
"async_get_access_token",
"(",
")",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"f\"Bearer {token}\"",
"}",
"endpoint",
"=",
"alexa_entity",
".",
"alexa_id",
"(",
")",
"message",
"=",
"AlexaResponse",
"(",
"name",
"=",
"\"DoorbellPress\"",
",",
"namespace",
"=",
"\"Alexa.DoorbellEventSource\"",
",",
"payload",
"=",
"{",
"\"cause\"",
":",
"{",
"\"type\"",
":",
"Cause",
".",
"PHYSICAL_INTERACTION",
"}",
",",
"\"timestamp\"",
":",
"f\"{dt_util.utcnow().replace(tzinfo=None).isoformat()}Z\"",
",",
"}",
",",
")",
"message",
".",
"set_endpoint_full",
"(",
"token",
",",
"endpoint",
")",
"message_serialized",
"=",
"message",
".",
"serialize",
"(",
")",
"session",
"=",
"hass",
".",
"helpers",
".",
"aiohttp_client",
".",
"async_get_clientsession",
"(",
")",
"try",
":",
"with",
"async_timeout",
".",
"timeout",
"(",
"DEFAULT_TIMEOUT",
")",
":",
"response",
"=",
"await",
"session",
".",
"post",
"(",
"config",
".",
"endpoint",
",",
"headers",
"=",
"headers",
",",
"json",
"=",
"message_serialized",
",",
"allow_redirects",
"=",
"True",
",",
")",
"except",
"(",
"asyncio",
".",
"TimeoutError",
",",
"aiohttp",
".",
"ClientError",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Timeout sending report to Alexa\"",
")",
"return",
"response_text",
"=",
"await",
"response",
".",
"text",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Sent: %s\"",
",",
"json",
".",
"dumps",
"(",
"message_serialized",
")",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Received (%s): %s\"",
",",
"response",
".",
"status",
",",
"response_text",
")",
"if",
"response",
".",
"status",
"==",
"HTTP_ACCEPTED",
":",
"return",
"response_json",
"=",
"json",
".",
"loads",
"(",
"response_text",
")",
"_LOGGER",
".",
"error",
"(",
"\"Error when sending DoorbellPress event to Alexa: %s: %s\"",
",",
"response_json",
"[",
"\"payload\"",
"]",
"[",
"\"code\"",
"]",
",",
"response_json",
"[",
"\"payload\"",
"]",
"[",
"\"description\"",
"]",
",",
")"
] | [
199,
0
] | [
251,
5
] | python | en | ['en', 'lb', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Camera that works with local files. | Set up the Camera that works with local files. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Camera that works with local files."""
if DATA_LOCAL_FILE not in hass.data:
hass.data[DATA_LOCAL_FILE] = []
file_path = config[CONF_FILE_PATH]
camera = LocalFile(config[CONF_NAME], file_path)
hass.data[DATA_LOCAL_FILE].append(camera)
def update_file_path_service(call):
"""Update the file path."""
file_path = call.data.get(CONF_FILE_PATH)
entity_ids = call.data.get(ATTR_ENTITY_ID)
cameras = hass.data[DATA_LOCAL_FILE]
for camera in cameras:
if camera.entity_id in entity_ids:
camera.update_file_path(file_path)
return True
hass.services.register(
DOMAIN,
SERVICE_UPDATE_FILE_PATH,
update_file_path_service,
schema=CAMERA_SERVICE_UPDATE_FILE_PATH,
)
add_entities([camera]) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"DATA_LOCAL_FILE",
"not",
"in",
"hass",
".",
"data",
":",
"hass",
".",
"data",
"[",
"DATA_LOCAL_FILE",
"]",
"=",
"[",
"]",
"file_path",
"=",
"config",
"[",
"CONF_FILE_PATH",
"]",
"camera",
"=",
"LocalFile",
"(",
"config",
"[",
"CONF_NAME",
"]",
",",
"file_path",
")",
"hass",
".",
"data",
"[",
"DATA_LOCAL_FILE",
"]",
".",
"append",
"(",
"camera",
")",
"def",
"update_file_path_service",
"(",
"call",
")",
":",
"\"\"\"Update the file path.\"\"\"",
"file_path",
"=",
"call",
".",
"data",
".",
"get",
"(",
"CONF_FILE_PATH",
")",
"entity_ids",
"=",
"call",
".",
"data",
".",
"get",
"(",
"ATTR_ENTITY_ID",
")",
"cameras",
"=",
"hass",
".",
"data",
"[",
"DATA_LOCAL_FILE",
"]",
"for",
"camera",
"in",
"cameras",
":",
"if",
"camera",
".",
"entity_id",
"in",
"entity_ids",
":",
"camera",
".",
"update_file_path",
"(",
"file_path",
")",
"return",
"True",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_UPDATE_FILE_PATH",
",",
"update_file_path_service",
",",
"schema",
"=",
"CAMERA_SERVICE_UPDATE_FILE_PATH",
",",
")",
"add_entities",
"(",
"[",
"camera",
"]",
")"
] | [
37,
0
] | [
64,
26
] | python | en | ['en', 'en', 'en'] | True |
LocalFile.__init__ | (self, name, file_path) | Initialize Local File Camera component. | Initialize Local File Camera component. | def __init__(self, name, file_path):
"""Initialize Local File Camera component."""
super().__init__()
self._name = name
self.check_file_path_access(file_path)
self._file_path = file_path
# Set content type of local file
content, _ = mimetypes.guess_type(file_path)
if content is not None:
self.content_type = content | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"file_path",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
")",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"check_file_path_access",
"(",
"file_path",
")",
"self",
".",
"_file_path",
"=",
"file_path",
"# Set content type of local file",
"content",
",",
"_",
"=",
"mimetypes",
".",
"guess_type",
"(",
"file_path",
")",
"if",
"content",
"is",
"not",
"None",
":",
"self",
".",
"content_type",
"=",
"content"
] | [
70,
4
] | [
80,
39
] | python | co | ['es', 'co', 'it'] | False |
LocalFile.camera_image | (self) | Return image response. | Return image response. | def camera_image(self):
"""Return image response."""
try:
with open(self._file_path, "rb") as file:
return file.read()
except FileNotFoundError:
_LOGGER.warning(
"Could not read camera %s image from file: %s",
self._name,
self._file_path,
) | [
"def",
"camera_image",
"(",
"self",
")",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_file_path",
",",
"\"rb\"",
")",
"as",
"file",
":",
"return",
"file",
".",
"read",
"(",
")",
"except",
"FileNotFoundError",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Could not read camera %s image from file: %s\"",
",",
"self",
".",
"_name",
",",
"self",
".",
"_file_path",
",",
")"
] | [
82,
4
] | [
92,
13
] | python | en | ['en', 'jv', 'en'] | True |
LocalFile.check_file_path_access | (self, file_path) | Check that filepath given is readable. | Check that filepath given is readable. | def check_file_path_access(self, file_path):
"""Check that filepath given is readable."""
if not os.access(file_path, os.R_OK):
_LOGGER.warning(
"Could not read camera %s image from file: %s", self._name, file_path
) | [
"def",
"check_file_path_access",
"(",
"self",
",",
"file_path",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"file_path",
",",
"os",
".",
"R_OK",
")",
":",
"_LOGGER",
".",
"warning",
"(",
"\"Could not read camera %s image from file: %s\"",
",",
"self",
".",
"_name",
",",
"file_path",
")"
] | [
94,
4
] | [
99,
13
] | python | en | ['en', 'en', 'en'] | True |
LocalFile.update_file_path | (self, file_path) | Update the file_path. | Update the file_path. | def update_file_path(self, file_path):
"""Update the file_path."""
self.check_file_path_access(file_path)
self._file_path = file_path
self.schedule_update_ha_state() | [
"def",
"update_file_path",
"(",
"self",
",",
"file_path",
")",
":",
"self",
".",
"check_file_path_access",
"(",
"file_path",
")",
"self",
".",
"_file_path",
"=",
"file_path",
"self",
".",
"schedule_update_ha_state",
"(",
")"
] | [
101,
4
] | [
105,
39
] | python | en | ['en', 'co', 'en'] | True |
LocalFile.name | (self) | Return the name of this camera. | Return the name of this camera. | def name(self):
"""Return the name of this camera."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
108,
4
] | [
110,
25
] | python | en | ['en', 'en', 'en'] | True |
LocalFile.device_state_attributes | (self) | Return the camera state attributes. | Return the camera state attributes. | def device_state_attributes(self):
"""Return the camera state attributes."""
return {"file_path": self._file_path} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"file_path\"",
":",
"self",
".",
"_file_path",
"}"
] | [
113,
4
] | [
115,
45
] | python | en | ['en', 'co', 'en'] | True |
wait_recording_done | (hass) | Block till recording is done. | Block till recording is done. | def wait_recording_done(hass):
"""Block till recording is done."""
trigger_db_commit(hass)
hass.block_till_done()
hass.data[recorder.DATA_INSTANCE].block_till_done()
hass.block_till_done() | [
"def",
"wait_recording_done",
"(",
"hass",
")",
":",
"trigger_db_commit",
"(",
"hass",
")",
"hass",
".",
"block_till_done",
"(",
")",
"hass",
".",
"data",
"[",
"recorder",
".",
"DATA_INSTANCE",
"]",
".",
"block_till_done",
"(",
")",
"hass",
".",
"block_till_done",
"(",
")"
] | [
10,
0
] | [
15,
26
] | python | en | ['en', 'en', 'en'] | True |
trigger_db_commit | (hass) | Force the recorder to commit. | Force the recorder to commit. | def trigger_db_commit(hass):
"""Force the recorder to commit."""
for _ in range(recorder.DEFAULT_COMMIT_INTERVAL):
# We only commit on time change
fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=1)) | [
"def",
"trigger_db_commit",
"(",
"hass",
")",
":",
"for",
"_",
"in",
"range",
"(",
"recorder",
".",
"DEFAULT_COMMIT_INTERVAL",
")",
":",
"# We only commit on time change",
"fire_time_changed",
"(",
"hass",
",",
"dt_util",
".",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
")"
] | [
18,
0
] | [
22,
72
] | python | en | ['en', 'en', 'en'] | True |
get_service | (hass, config, discovery_info=None) | Get the Simplepush notification service. | Get the Simplepush notification service. | def get_service(hass, config, discovery_info=None):
"""Get the Simplepush notification service."""
return SimplePushNotificationService(config) | [
"def",
"get_service",
"(",
"hass",
",",
"config",
",",
"discovery_info",
"=",
"None",
")",
":",
"return",
"SimplePushNotificationService",
"(",
"config",
")"
] | [
29,
0
] | [
31,
48
] | python | en | ['en', 'en', 'en'] | True |
SimplePushNotificationService.__init__ | (self, config) | Initialize the Simplepush notification service. | Initialize the Simplepush notification service. | def __init__(self, config):
"""Initialize the Simplepush notification service."""
self._device_key = config.get(CONF_DEVICE_KEY)
self._event = config.get(CONF_EVENT)
self._password = config.get(CONF_PASSWORD)
self._salt = config.get(CONF_SALT) | [
"def",
"__init__",
"(",
"self",
",",
"config",
")",
":",
"self",
".",
"_device_key",
"=",
"config",
".",
"get",
"(",
"CONF_DEVICE_KEY",
")",
"self",
".",
"_event",
"=",
"config",
".",
"get",
"(",
"CONF_EVENT",
")",
"self",
".",
"_password",
"=",
"config",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"self",
".",
"_salt",
"=",
"config",
".",
"get",
"(",
"CONF_SALT",
")"
] | [
37,
4
] | [
42,
42
] | python | en | ['en', 'en', 'en'] | True |
SimplePushNotificationService.send_message | (self, message="", **kwargs) | Send a message to a Simplepush user. | Send a message to a Simplepush user. | def send_message(self, message="", **kwargs):
"""Send a message to a Simplepush user."""
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
if self._password:
send_encrypted(
self._device_key,
self._password,
self._salt,
title,
message,
event=self._event,
)
else:
send(self._device_key, title, message, event=self._event) | [
"def",
"send_message",
"(",
"self",
",",
"message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"title",
"=",
"kwargs",
".",
"get",
"(",
"ATTR_TITLE",
",",
"ATTR_TITLE_DEFAULT",
")",
"if",
"self",
".",
"_password",
":",
"send_encrypted",
"(",
"self",
".",
"_device_key",
",",
"self",
".",
"_password",
",",
"self",
".",
"_salt",
",",
"title",
",",
"message",
",",
"event",
"=",
"self",
".",
"_event",
",",
")",
"else",
":",
"send",
"(",
"self",
".",
"_device_key",
",",
"title",
",",
"message",
",",
"event",
"=",
"self",
".",
"_event",
")"
] | [
44,
4
] | [
59,
69
] | python | en | ['en', 'en', 'en'] | True |
test_get_device_config | (hass, hass_client) | Test getting device config. | Test getting device config. | async def test_get_device_config(hass, hass_client):
"""Test getting device config."""
with patch.object(config, "SECTIONS", ["automation"]):
await async_setup_component(hass, "config", {})
client = await hass_client()
def mock_read(path):
"""Mock reading data."""
return [{"id": "sun"}, {"id": "moon"}]
with patch("homeassistant.components.config._read", mock_read):
resp = await client.get("/api/config/automation/config/moon")
assert resp.status == 200
result = await resp.json()
assert result == {"id": "moon"} | [
"async",
"def",
"test_get_device_config",
"(",
"hass",
",",
"hass_client",
")",
":",
"with",
"patch",
".",
"object",
"(",
"config",
",",
"\"SECTIONS\"",
",",
"[",
"\"automation\"",
"]",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"config\"",
",",
"{",
"}",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"def",
"mock_read",
"(",
"path",
")",
":",
"\"\"\"Mock reading data.\"\"\"",
"return",
"[",
"{",
"\"id\"",
":",
"\"sun\"",
"}",
",",
"{",
"\"id\"",
":",
"\"moon\"",
"}",
"]",
"with",
"patch",
"(",
"\"homeassistant.components.config._read\"",
",",
"mock_read",
")",
":",
"resp",
"=",
"await",
"client",
".",
"get",
"(",
"\"/api/config/automation/config/moon\"",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"result",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"result",
"==",
"{",
"\"id\"",
":",
"\"moon\"",
"}"
] | [
9,
0
] | [
26,
35
] | python | en | ['de', 'en', 'en'] | True |
test_update_device_config | (hass, hass_client) | Test updating device config. | Test updating device config. | async def test_update_device_config(hass, hass_client):
"""Test updating device config."""
with patch.object(config, "SECTIONS", ["automation"]):
await async_setup_component(hass, "config", {})
client = await hass_client()
orig_data = [{"id": "sun"}, {"id": "moon"}]
def mock_read(path):
"""Mock reading data."""
return orig_data
written = []
def mock_write(path, data):
"""Mock writing data."""
written.append(data)
with patch("homeassistant.components.config._read", mock_read), patch(
"homeassistant.components.config._write", mock_write
), patch("homeassistant.config.async_hass_config_yaml", return_value={}):
resp = await client.post(
"/api/config/automation/config/moon",
data=json.dumps({"trigger": [], "action": [], "condition": []}),
)
assert resp.status == 200
result = await resp.json()
assert result == {"result": "ok"}
assert list(orig_data[1]) == ["id", "trigger", "condition", "action"]
assert orig_data[1] == {"id": "moon", "trigger": [], "condition": [], "action": []}
assert written[0] == orig_data | [
"async",
"def",
"test_update_device_config",
"(",
"hass",
",",
"hass_client",
")",
":",
"with",
"patch",
".",
"object",
"(",
"config",
",",
"\"SECTIONS\"",
",",
"[",
"\"automation\"",
"]",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"config\"",
",",
"{",
"}",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"orig_data",
"=",
"[",
"{",
"\"id\"",
":",
"\"sun\"",
"}",
",",
"{",
"\"id\"",
":",
"\"moon\"",
"}",
"]",
"def",
"mock_read",
"(",
"path",
")",
":",
"\"\"\"Mock reading data.\"\"\"",
"return",
"orig_data",
"written",
"=",
"[",
"]",
"def",
"mock_write",
"(",
"path",
",",
"data",
")",
":",
"\"\"\"Mock writing data.\"\"\"",
"written",
".",
"append",
"(",
"data",
")",
"with",
"patch",
"(",
"\"homeassistant.components.config._read\"",
",",
"mock_read",
")",
",",
"patch",
"(",
"\"homeassistant.components.config._write\"",
",",
"mock_write",
")",
",",
"patch",
"(",
"\"homeassistant.config.async_hass_config_yaml\"",
",",
"return_value",
"=",
"{",
"}",
")",
":",
"resp",
"=",
"await",
"client",
".",
"post",
"(",
"\"/api/config/automation/config/moon\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"trigger\"",
":",
"[",
"]",
",",
"\"action\"",
":",
"[",
"]",
",",
"\"condition\"",
":",
"[",
"]",
"}",
")",
",",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"result",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"result",
"==",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
"assert",
"list",
"(",
"orig_data",
"[",
"1",
"]",
")",
"==",
"[",
"\"id\"",
",",
"\"trigger\"",
",",
"\"condition\"",
",",
"\"action\"",
"]",
"assert",
"orig_data",
"[",
"1",
"]",
"==",
"{",
"\"id\"",
":",
"\"moon\"",
",",
"\"trigger\"",
":",
"[",
"]",
",",
"\"condition\"",
":",
"[",
"]",
",",
"\"action\"",
":",
"[",
"]",
"}",
"assert",
"written",
"[",
"0",
"]",
"==",
"orig_data"
] | [
29,
0
] | [
62,
34
] | python | en | ['de', 'en', 'en'] | True |
test_bad_formatted_automations | (hass, hass_client) | Test that we handle automations without ID. | Test that we handle automations without ID. | async def test_bad_formatted_automations(hass, hass_client):
"""Test that we handle automations without ID."""
with patch.object(config, "SECTIONS", ["automation"]):
await async_setup_component(hass, "config", {})
client = await hass_client()
orig_data = [
{
# No ID
"action": {"event": "hello"}
},
{"id": "moon"},
]
def mock_read(path):
"""Mock reading data."""
return orig_data
written = []
def mock_write(path, data):
"""Mock writing data."""
written.append(data)
with patch("homeassistant.components.config._read", mock_read), patch(
"homeassistant.components.config._write", mock_write
), patch("homeassistant.config.async_hass_config_yaml", return_value={}):
resp = await client.post(
"/api/config/automation/config/moon",
data=json.dumps({"trigger": [], "action": [], "condition": []}),
)
await hass.async_block_till_done()
assert resp.status == 200
result = await resp.json()
assert result == {"result": "ok"}
# Verify ID added to orig_data
assert "id" in orig_data[0]
assert orig_data[1] == {"id": "moon", "trigger": [], "condition": [], "action": []} | [
"async",
"def",
"test_bad_formatted_automations",
"(",
"hass",
",",
"hass_client",
")",
":",
"with",
"patch",
".",
"object",
"(",
"config",
",",
"\"SECTIONS\"",
",",
"[",
"\"automation\"",
"]",
")",
":",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"config\"",
",",
"{",
"}",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"orig_data",
"=",
"[",
"{",
"# No ID",
"\"action\"",
":",
"{",
"\"event\"",
":",
"\"hello\"",
"}",
"}",
",",
"{",
"\"id\"",
":",
"\"moon\"",
"}",
",",
"]",
"def",
"mock_read",
"(",
"path",
")",
":",
"\"\"\"Mock reading data.\"\"\"",
"return",
"orig_data",
"written",
"=",
"[",
"]",
"def",
"mock_write",
"(",
"path",
",",
"data",
")",
":",
"\"\"\"Mock writing data.\"\"\"",
"written",
".",
"append",
"(",
"data",
")",
"with",
"patch",
"(",
"\"homeassistant.components.config._read\"",
",",
"mock_read",
")",
",",
"patch",
"(",
"\"homeassistant.components.config._write\"",
",",
"mock_write",
")",
",",
"patch",
"(",
"\"homeassistant.config.async_hass_config_yaml\"",
",",
"return_value",
"=",
"{",
"}",
")",
":",
"resp",
"=",
"await",
"client",
".",
"post",
"(",
"\"/api/config/automation/config/moon\"",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"trigger\"",
":",
"[",
"]",
",",
"\"action\"",
":",
"[",
"]",
",",
"\"condition\"",
":",
"[",
"]",
"}",
")",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"result",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"result",
"==",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
"# Verify ID added to orig_data",
"assert",
"\"id\"",
"in",
"orig_data",
"[",
"0",
"]",
"assert",
"orig_data",
"[",
"1",
"]",
"==",
"{",
"\"id\"",
":",
"\"moon\"",
",",
"\"trigger\"",
":",
"[",
"]",
",",
"\"condition\"",
":",
"[",
"]",
",",
"\"action\"",
":",
"[",
"]",
"}"
] | [
65,
0
] | [
106,
87
] | python | en | ['en', 'en', 'en'] | True |
test_delete_automation | (hass, hass_client) | Test deleting an automation. | Test deleting an automation. | async def test_delete_automation(hass, hass_client):
"""Test deleting an automation."""
ent_reg = await hass.helpers.entity_registry.async_get_registry()
assert await async_setup_component(
hass,
"automation",
{
"automation": [
{
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"action": {"service": "test.automation"},
},
{
"id": "moon",
"trigger": {"platform": "event", "event_type": "test_event"},
"action": {"service": "test.automation"},
},
]
},
)
assert len(ent_reg.entities) == 2
with patch.object(config, "SECTIONS", ["automation"]):
assert await async_setup_component(hass, "config", {})
client = await hass_client()
orig_data = [{"id": "sun"}, {"id": "moon"}]
def mock_read(path):
"""Mock reading data."""
return orig_data
written = []
def mock_write(path, data):
"""Mock writing data."""
written.append(data)
with patch("homeassistant.components.config._read", mock_read), patch(
"homeassistant.components.config._write", mock_write
), patch("homeassistant.config.async_hass_config_yaml", return_value={}):
resp = await client.delete("/api/config/automation/config/sun")
await hass.async_block_till_done()
assert resp.status == 200
result = await resp.json()
assert result == {"result": "ok"}
assert len(written) == 1
assert written[0][0]["id"] == "moon"
assert len(ent_reg.entities) == 1 | [
"async",
"def",
"test_delete_automation",
"(",
"hass",
",",
"hass_client",
")",
":",
"ent_reg",
"=",
"await",
"hass",
".",
"helpers",
".",
"entity_registry",
".",
"async_get_registry",
"(",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"automation\"",
",",
"{",
"\"automation\"",
":",
"[",
"{",
"\"id\"",
":",
"\"sun\"",
",",
"\"trigger\"",
":",
"{",
"\"platform\"",
":",
"\"event\"",
",",
"\"event_type\"",
":",
"\"test_event\"",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.automation\"",
"}",
",",
"}",
",",
"{",
"\"id\"",
":",
"\"moon\"",
",",
"\"trigger\"",
":",
"{",
"\"platform\"",
":",
"\"event\"",
",",
"\"event_type\"",
":",
"\"test_event\"",
"}",
",",
"\"action\"",
":",
"{",
"\"service\"",
":",
"\"test.automation\"",
"}",
",",
"}",
",",
"]",
"}",
",",
")",
"assert",
"len",
"(",
"ent_reg",
".",
"entities",
")",
"==",
"2",
"with",
"patch",
".",
"object",
"(",
"config",
",",
"\"SECTIONS\"",
",",
"[",
"\"automation\"",
"]",
")",
":",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"\"config\"",
",",
"{",
"}",
")",
"client",
"=",
"await",
"hass_client",
"(",
")",
"orig_data",
"=",
"[",
"{",
"\"id\"",
":",
"\"sun\"",
"}",
",",
"{",
"\"id\"",
":",
"\"moon\"",
"}",
"]",
"def",
"mock_read",
"(",
"path",
")",
":",
"\"\"\"Mock reading data.\"\"\"",
"return",
"orig_data",
"written",
"=",
"[",
"]",
"def",
"mock_write",
"(",
"path",
",",
"data",
")",
":",
"\"\"\"Mock writing data.\"\"\"",
"written",
".",
"append",
"(",
"data",
")",
"with",
"patch",
"(",
"\"homeassistant.components.config._read\"",
",",
"mock_read",
")",
",",
"patch",
"(",
"\"homeassistant.components.config._write\"",
",",
"mock_write",
")",
",",
"patch",
"(",
"\"homeassistant.config.async_hass_config_yaml\"",
",",
"return_value",
"=",
"{",
"}",
")",
":",
"resp",
"=",
"await",
"client",
".",
"delete",
"(",
"\"/api/config/automation/config/sun\"",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"resp",
".",
"status",
"==",
"200",
"result",
"=",
"await",
"resp",
".",
"json",
"(",
")",
"assert",
"result",
"==",
"{",
"\"result\"",
":",
"\"ok\"",
"}",
"assert",
"len",
"(",
"written",
")",
"==",
"1",
"assert",
"written",
"[",
"0",
"]",
"[",
"0",
"]",
"[",
"\"id\"",
"]",
"==",
"\"moon\"",
"assert",
"len",
"(",
"ent_reg",
".",
"entities",
")",
"==",
"1"
] | [
109,
0
] | [
164,
37
] | python | de | ['de', 'en', 'nl'] | False |
OAuth2FlowHandler.logger | (self) | Return logger. | Return logger. | def logger(self) -> logging.Logger:
"""Return logger."""
return logging.getLogger(__name__) | [
"def",
"logger",
"(",
"self",
")",
"->",
"logging",
".",
"Logger",
":",
"return",
"logging",
".",
"getLogger",
"(",
"__name__",
")"
] | [
18,
4
] | [
20,
42
] | python | en | ['es', 'no', 'en'] | False |
OAuth2FlowHandler.extra_authorize_data | (self) | Extra data that needs to be appended to the authorize url. | Extra data that needs to be appended to the authorize url. | def extra_authorize_data(self) -> dict:
"""Extra data that needs to be appended to the authorize url."""
scopes = ["Xboxlive.signin", "Xboxlive.offline_access"]
return {"scope": " ".join(scopes)} | [
"def",
"extra_authorize_data",
"(",
"self",
")",
"->",
"dict",
":",
"scopes",
"=",
"[",
"\"Xboxlive.signin\"",
",",
"\"Xboxlive.offline_access\"",
"]",
"return",
"{",
"\"scope\"",
":",
"\" \"",
".",
"join",
"(",
"scopes",
")",
"}"
] | [
23,
4
] | [
26,
42
] | python | en | ['en', 'en', 'en'] | True |
OAuth2FlowHandler.async_step_user | (self, user_input=None) | Handle a flow start. | Handle a flow start. | async def async_step_user(self, user_input=None):
"""Handle a flow start."""
await self.async_set_unique_id(DOMAIN)
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")
return await super().async_step_user(user_input) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"await",
"self",
".",
"async_set_unique_id",
"(",
"DOMAIN",
")",
"if",
"self",
".",
"_async_current_entries",
"(",
")",
":",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"single_instance_allowed\"",
")",
"return",
"await",
"super",
"(",
")",
".",
"async_step_user",
"(",
"user_input",
")"
] | [
28,
4
] | [
35,
56
] | python | en | ['en', 'lb', 'en'] | True |
EsphomeFlowHandler.__init__ | (self) | Initialize flow. | Initialize flow. | def __init__(self):
"""Initialize flow."""
self._host: Optional[str] = None
self._port: Optional[int] = None
self._password: Optional[str] = None | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"_host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
"self",
".",
"_port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
"self",
".",
"_password",
":",
"Optional",
"[",
"str",
"]",
"=",
"None"
] | [
24,
4
] | [
28,
44
] | python | en | ['en', 'pl', 'en'] | False |
EsphomeFlowHandler.async_step_user | (
self, user_input: Optional[ConfigType] = None, error: Optional[str] = None
) | Handle a flow initialized by the user. | Handle a flow initialized by the user. | async def async_step_user(
self, user_input: Optional[ConfigType] = None, error: Optional[str] = None
): # pylint: disable=arguments-differ
"""Handle a flow initialized by the user."""
if user_input is not None:
return await self._async_authenticate_or_add(user_input)
fields = OrderedDict()
fields[vol.Required(CONF_HOST, default=self._host or vol.UNDEFINED)] = str
fields[vol.Optional(CONF_PORT, default=self._port or 6053)] = int
errors = {}
if error is not None:
errors["base"] = error
return self.async_show_form(
step_id="user", data_schema=vol.Schema(fields), errors=errors
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
":",
"Optional",
"[",
"ConfigType",
"]",
"=",
"None",
",",
"error",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
")",
":",
"# pylint: disable=arguments-differ",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"await",
"self",
".",
"_async_authenticate_or_add",
"(",
"user_input",
")",
"fields",
"=",
"OrderedDict",
"(",
")",
"fields",
"[",
"vol",
".",
"Required",
"(",
"CONF_HOST",
",",
"default",
"=",
"self",
".",
"_host",
"or",
"vol",
".",
"UNDEFINED",
")",
"]",
"=",
"str",
"fields",
"[",
"vol",
".",
"Optional",
"(",
"CONF_PORT",
",",
"default",
"=",
"self",
".",
"_port",
"or",
"6053",
")",
"]",
"=",
"int",
"errors",
"=",
"{",
"}",
"if",
"error",
"is",
"not",
"None",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"error",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"fields",
")",
",",
"errors",
"=",
"errors",
")"
] | [
30,
4
] | [
47,
9
] | python | en | ['en', 'en', 'en'] | True |
EsphomeFlowHandler.async_step_discovery_confirm | (self, user_input=None) | Handle user-confirmation of discovered node. | Handle user-confirmation of discovered node. | async def async_step_discovery_confirm(self, user_input=None):
"""Handle user-confirmation of discovered node."""
if user_input is not None:
return await self._async_authenticate_or_add(None)
return self.async_show_form(
step_id="discovery_confirm", description_placeholders={"name": self._name}
) | [
"async",
"def",
"async_step_discovery_confirm",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"await",
"self",
".",
"_async_authenticate_or_add",
"(",
"None",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"discovery_confirm\"",
",",
"description_placeholders",
"=",
"{",
"\"name\"",
":",
"self",
".",
"_name",
"}",
")"
] | [
79,
4
] | [
85,
9
] | python | en | ['en', 'en', 'en'] | True |
EsphomeFlowHandler.async_step_zeroconf | (self, discovery_info: DiscoveryInfoType) | Handle zeroconf discovery. | Handle zeroconf discovery. | async def async_step_zeroconf(self, discovery_info: DiscoveryInfoType):
"""Handle zeroconf discovery."""
# Hostname is format: livingroom.local.
local_name = discovery_info["hostname"][:-1]
node_name = local_name[: -len(".local")]
address = discovery_info["properties"].get("address", local_name)
# Check if already configured
await self.async_set_unique_id(node_name)
self._abort_if_unique_id_configured(
updates={CONF_HOST: discovery_info[CONF_HOST]}
)
for entry in self._async_current_entries():
already_configured = False
if CONF_HOST in entry.data and entry.data[CONF_HOST] in [
address,
discovery_info[CONF_HOST],
]:
# Is this address or IP address already configured?
already_configured = True
elif entry.entry_id in self.hass.data.get(DATA_KEY, {}):
# Does a config entry with this name already exist?
data: RuntimeEntryData = self.hass.data[DATA_KEY][entry.entry_id]
# Node names are unique in the network
if data.device_info is not None:
already_configured = data.device_info.name == node_name
if already_configured:
# Backwards compat, we update old entries
if not entry.unique_id:
self.hass.config_entries.async_update_entry(
entry,
data={**entry.data, CONF_HOST: discovery_info[CONF_HOST]},
unique_id=node_name,
)
return self.async_abort(reason="already_configured")
self._host = discovery_info[CONF_HOST]
self._port = discovery_info[CONF_PORT]
self._name = node_name
return await self.async_step_discovery_confirm() | [
"async",
"def",
"async_step_zeroconf",
"(",
"self",
",",
"discovery_info",
":",
"DiscoveryInfoType",
")",
":",
"# Hostname is format: livingroom.local.",
"local_name",
"=",
"discovery_info",
"[",
"\"hostname\"",
"]",
"[",
":",
"-",
"1",
"]",
"node_name",
"=",
"local_name",
"[",
":",
"-",
"len",
"(",
"\".local\"",
")",
"]",
"address",
"=",
"discovery_info",
"[",
"\"properties\"",
"]",
".",
"get",
"(",
"\"address\"",
",",
"local_name",
")",
"# Check if already configured",
"await",
"self",
".",
"async_set_unique_id",
"(",
"node_name",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
"updates",
"=",
"{",
"CONF_HOST",
":",
"discovery_info",
"[",
"CONF_HOST",
"]",
"}",
")",
"for",
"entry",
"in",
"self",
".",
"_async_current_entries",
"(",
")",
":",
"already_configured",
"=",
"False",
"if",
"CONF_HOST",
"in",
"entry",
".",
"data",
"and",
"entry",
".",
"data",
"[",
"CONF_HOST",
"]",
"in",
"[",
"address",
",",
"discovery_info",
"[",
"CONF_HOST",
"]",
",",
"]",
":",
"# Is this address or IP address already configured?",
"already_configured",
"=",
"True",
"elif",
"entry",
".",
"entry_id",
"in",
"self",
".",
"hass",
".",
"data",
".",
"get",
"(",
"DATA_KEY",
",",
"{",
"}",
")",
":",
"# Does a config entry with this name already exist?",
"data",
":",
"RuntimeEntryData",
"=",
"self",
".",
"hass",
".",
"data",
"[",
"DATA_KEY",
"]",
"[",
"entry",
".",
"entry_id",
"]",
"# Node names are unique in the network",
"if",
"data",
".",
"device_info",
"is",
"not",
"None",
":",
"already_configured",
"=",
"data",
".",
"device_info",
".",
"name",
"==",
"node_name",
"if",
"already_configured",
":",
"# Backwards compat, we update old entries",
"if",
"not",
"entry",
".",
"unique_id",
":",
"self",
".",
"hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"entry",
",",
"data",
"=",
"{",
"*",
"*",
"entry",
".",
"data",
",",
"CONF_HOST",
":",
"discovery_info",
"[",
"CONF_HOST",
"]",
"}",
",",
"unique_id",
"=",
"node_name",
",",
")",
"return",
"self",
".",
"async_abort",
"(",
"reason",
"=",
"\"already_configured\"",
")",
"self",
".",
"_host",
"=",
"discovery_info",
"[",
"CONF_HOST",
"]",
"self",
".",
"_port",
"=",
"discovery_info",
"[",
"CONF_PORT",
"]",
"self",
".",
"_name",
"=",
"node_name",
"return",
"await",
"self",
".",
"async_step_discovery_confirm",
"(",
")"
] | [
87,
4
] | [
132,
56
] | python | de | ['de', 'sr', 'en'] | False |
EsphomeFlowHandler.async_step_authenticate | (self, user_input=None, error=None) | Handle getting password for authentication. | Handle getting password for authentication. | async def async_step_authenticate(self, user_input=None, error=None):
"""Handle getting password for authentication."""
if user_input is not None:
self._password = user_input[CONF_PASSWORD]
error = await self.try_login()
if error:
return await self.async_step_authenticate(error=error)
return self._async_get_entry()
errors = {}
if error is not None:
errors["base"] = error
return self.async_show_form(
step_id="authenticate",
data_schema=vol.Schema({vol.Required("password"): str}),
description_placeholders={"name": self._name},
errors=errors,
) | [
"async",
"def",
"async_step_authenticate",
"(",
"self",
",",
"user_input",
"=",
"None",
",",
"error",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"self",
".",
"_password",
"=",
"user_input",
"[",
"CONF_PASSWORD",
"]",
"error",
"=",
"await",
"self",
".",
"try_login",
"(",
")",
"if",
"error",
":",
"return",
"await",
"self",
".",
"async_step_authenticate",
"(",
"error",
"=",
"error",
")",
"return",
"self",
".",
"_async_get_entry",
"(",
")",
"errors",
"=",
"{",
"}",
"if",
"error",
"is",
"not",
"None",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"error",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"authenticate\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Required",
"(",
"\"password\"",
")",
":",
"str",
"}",
")",
",",
"description_placeholders",
"=",
"{",
"\"name\"",
":",
"self",
".",
"_name",
"}",
",",
"errors",
"=",
"errors",
",",
")"
] | [
146,
4
] | [
164,
9
] | python | en | ['en', 'en', 'en'] | True |
EsphomeFlowHandler.fetch_device_info | (self) | Fetch device info from API and return any errors. | Fetch device info from API and return any errors. | async def fetch_device_info(self):
"""Fetch device info from API and return any errors."""
zeroconf_instance = await zeroconf.async_get_instance(self.hass)
cli = APIClient(
self.hass.loop,
self._host,
self._port,
"",
zeroconf_instance=zeroconf_instance,
)
try:
await cli.connect()
device_info = await cli.device_info()
except APIConnectionError as err:
if "resolving" in str(err):
return "resolve_error", None
return "connection_error", None
finally:
await cli.disconnect(force=True)
return None, device_info | [
"async",
"def",
"fetch_device_info",
"(",
"self",
")",
":",
"zeroconf_instance",
"=",
"await",
"zeroconf",
".",
"async_get_instance",
"(",
"self",
".",
"hass",
")",
"cli",
"=",
"APIClient",
"(",
"self",
".",
"hass",
".",
"loop",
",",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"\"\"",
",",
"zeroconf_instance",
"=",
"zeroconf_instance",
",",
")",
"try",
":",
"await",
"cli",
".",
"connect",
"(",
")",
"device_info",
"=",
"await",
"cli",
".",
"device_info",
"(",
")",
"except",
"APIConnectionError",
"as",
"err",
":",
"if",
"\"resolving\"",
"in",
"str",
"(",
"err",
")",
":",
"return",
"\"resolve_error\"",
",",
"None",
"return",
"\"connection_error\"",
",",
"None",
"finally",
":",
"await",
"cli",
".",
"disconnect",
"(",
"force",
"=",
"True",
")",
"return",
"None",
",",
"device_info"
] | [
166,
4
] | [
187,
32
] | python | en | ['en', 'en', 'en'] | True |
EsphomeFlowHandler.try_login | (self) | Try logging in to device and return any errors. | Try logging in to device and return any errors. | async def try_login(self):
"""Try logging in to device and return any errors."""
zeroconf_instance = await zeroconf.async_get_instance(self.hass)
cli = APIClient(
self.hass.loop,
self._host,
self._port,
self._password,
zeroconf_instance=zeroconf_instance,
)
try:
await cli.connect(login=True)
except APIConnectionError:
await cli.disconnect(force=True)
return "invalid_auth"
return None | [
"async",
"def",
"try_login",
"(",
"self",
")",
":",
"zeroconf_instance",
"=",
"await",
"zeroconf",
".",
"async_get_instance",
"(",
"self",
".",
"hass",
")",
"cli",
"=",
"APIClient",
"(",
"self",
".",
"hass",
".",
"loop",
",",
"self",
".",
"_host",
",",
"self",
".",
"_port",
",",
"self",
".",
"_password",
",",
"zeroconf_instance",
"=",
"zeroconf_instance",
",",
")",
"try",
":",
"await",
"cli",
".",
"connect",
"(",
"login",
"=",
"True",
")",
"except",
"APIConnectionError",
":",
"await",
"cli",
".",
"disconnect",
"(",
"force",
"=",
"True",
")",
"return",
"\"invalid_auth\"",
"return",
"None"
] | [
189,
4
] | [
206,
19
] | python | en | ['en', 'en', 'en'] | True |
EmulatedRoku.__init__ | (
self,
hass,
name,
host_ip,
listen_port,
advertise_ip,
advertise_port,
upnp_bind_multicast,
) | Initialize the properties. | Initialize the properties. | def __init__(
self,
hass,
name,
host_ip,
listen_port,
advertise_ip,
advertise_port,
upnp_bind_multicast,
):
"""Initialize the properties."""
self.hass = hass
self.roku_usn = name
self.host_ip = host_ip
self.listen_port = listen_port
self.advertise_port = advertise_port
self.advertise_ip = advertise_ip
self.bind_multicast = upnp_bind_multicast
self._api_server = None
self._unsub_start_listener = None
self._unsub_stop_listener = None | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"name",
",",
"host_ip",
",",
"listen_port",
",",
"advertise_ip",
",",
"advertise_port",
",",
"upnp_bind_multicast",
",",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"roku_usn",
"=",
"name",
"self",
".",
"host_ip",
"=",
"host_ip",
"self",
".",
"listen_port",
"=",
"listen_port",
"self",
".",
"advertise_port",
"=",
"advertise_port",
"self",
".",
"advertise_ip",
"=",
"advertise_ip",
"self",
".",
"bind_multicast",
"=",
"upnp_bind_multicast",
"self",
".",
"_api_server",
"=",
"None",
"self",
".",
"_unsub_start_listener",
"=",
"None",
"self",
".",
"_unsub_stop_listener",
"=",
"None"
] | [
26,
4
] | [
51,
40
] | python | en | ['en', 'en', 'en'] | True |
EmulatedRoku.setup | (self) | Start the emulated_roku server. | Start the emulated_roku server. | async def setup(self):
"""Start the emulated_roku server."""
class EventCommandHandler(EmulatedRokuCommandHandler):
"""emulated_roku command handler to turn commands into events."""
def __init__(self, hass):
self.hass = hass
def on_keydown(self, roku_usn, key):
"""Handle keydown event."""
self.hass.bus.async_fire(
EVENT_ROKU_COMMAND,
{
ATTR_SOURCE_NAME: roku_usn,
ATTR_COMMAND_TYPE: ROKU_COMMAND_KEYDOWN,
ATTR_KEY: key,
},
EventOrigin.local,
)
def on_keyup(self, roku_usn, key):
"""Handle keyup event."""
self.hass.bus.async_fire(
EVENT_ROKU_COMMAND,
{
ATTR_SOURCE_NAME: roku_usn,
ATTR_COMMAND_TYPE: ROKU_COMMAND_KEYUP,
ATTR_KEY: key,
},
EventOrigin.local,
)
def on_keypress(self, roku_usn, key):
"""Handle keypress event."""
self.hass.bus.async_fire(
EVENT_ROKU_COMMAND,
{
ATTR_SOURCE_NAME: roku_usn,
ATTR_COMMAND_TYPE: ROKU_COMMAND_KEYPRESS,
ATTR_KEY: key,
},
EventOrigin.local,
)
def launch(self, roku_usn, app_id):
"""Handle launch event."""
self.hass.bus.async_fire(
EVENT_ROKU_COMMAND,
{
ATTR_SOURCE_NAME: roku_usn,
ATTR_COMMAND_TYPE: ROKU_COMMAND_LAUNCH,
ATTR_APP_ID: app_id,
},
EventOrigin.local,
)
LOGGER.debug(
"Initializing emulated_roku %s on %s:%s",
self.roku_usn,
self.host_ip,
self.listen_port,
)
handler = EventCommandHandler(self.hass)
self._api_server = EmulatedRokuServer(
self.hass.loop,
handler,
self.roku_usn,
self.host_ip,
self.listen_port,
advertise_ip=self.advertise_ip,
advertise_port=self.advertise_port,
bind_multicast=self.bind_multicast,
)
async def emulated_roku_stop(event):
"""Wrap the call to emulated_roku.close."""
LOGGER.debug("Stopping emulated_roku %s", self.roku_usn)
self._unsub_stop_listener = None
await self._api_server.close()
async def emulated_roku_start(event):
"""Wrap the call to emulated_roku.start."""
try:
LOGGER.debug("Starting emulated_roku %s", self.roku_usn)
self._unsub_start_listener = None
await self._api_server.start()
except OSError:
LOGGER.exception(
"Failed to start Emulated Roku %s on %s:%s",
self.roku_usn,
self.host_ip,
self.listen_port,
)
# clean up inconsistent state on errors
await emulated_roku_stop(None)
else:
self._unsub_stop_listener = self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, emulated_roku_stop
)
# start immediately if already running
if self.hass.state == CoreState.running:
await emulated_roku_start(None)
else:
self._unsub_start_listener = self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, emulated_roku_start
)
return True | [
"async",
"def",
"setup",
"(",
"self",
")",
":",
"class",
"EventCommandHandler",
"(",
"EmulatedRokuCommandHandler",
")",
":",
"\"\"\"emulated_roku command handler to turn commands into events.\"\"\"",
"def",
"__init__",
"(",
"self",
",",
"hass",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"def",
"on_keydown",
"(",
"self",
",",
"roku_usn",
",",
"key",
")",
":",
"\"\"\"Handle keydown event.\"\"\"",
"self",
".",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_ROKU_COMMAND",
",",
"{",
"ATTR_SOURCE_NAME",
":",
"roku_usn",
",",
"ATTR_COMMAND_TYPE",
":",
"ROKU_COMMAND_KEYDOWN",
",",
"ATTR_KEY",
":",
"key",
",",
"}",
",",
"EventOrigin",
".",
"local",
",",
")",
"def",
"on_keyup",
"(",
"self",
",",
"roku_usn",
",",
"key",
")",
":",
"\"\"\"Handle keyup event.\"\"\"",
"self",
".",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_ROKU_COMMAND",
",",
"{",
"ATTR_SOURCE_NAME",
":",
"roku_usn",
",",
"ATTR_COMMAND_TYPE",
":",
"ROKU_COMMAND_KEYUP",
",",
"ATTR_KEY",
":",
"key",
",",
"}",
",",
"EventOrigin",
".",
"local",
",",
")",
"def",
"on_keypress",
"(",
"self",
",",
"roku_usn",
",",
"key",
")",
":",
"\"\"\"Handle keypress event.\"\"\"",
"self",
".",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_ROKU_COMMAND",
",",
"{",
"ATTR_SOURCE_NAME",
":",
"roku_usn",
",",
"ATTR_COMMAND_TYPE",
":",
"ROKU_COMMAND_KEYPRESS",
",",
"ATTR_KEY",
":",
"key",
",",
"}",
",",
"EventOrigin",
".",
"local",
",",
")",
"def",
"launch",
"(",
"self",
",",
"roku_usn",
",",
"app_id",
")",
":",
"\"\"\"Handle launch event.\"\"\"",
"self",
".",
"hass",
".",
"bus",
".",
"async_fire",
"(",
"EVENT_ROKU_COMMAND",
",",
"{",
"ATTR_SOURCE_NAME",
":",
"roku_usn",
",",
"ATTR_COMMAND_TYPE",
":",
"ROKU_COMMAND_LAUNCH",
",",
"ATTR_APP_ID",
":",
"app_id",
",",
"}",
",",
"EventOrigin",
".",
"local",
",",
")",
"LOGGER",
".",
"debug",
"(",
"\"Initializing emulated_roku %s on %s:%s\"",
",",
"self",
".",
"roku_usn",
",",
"self",
".",
"host_ip",
",",
"self",
".",
"listen_port",
",",
")",
"handler",
"=",
"EventCommandHandler",
"(",
"self",
".",
"hass",
")",
"self",
".",
"_api_server",
"=",
"EmulatedRokuServer",
"(",
"self",
".",
"hass",
".",
"loop",
",",
"handler",
",",
"self",
".",
"roku_usn",
",",
"self",
".",
"host_ip",
",",
"self",
".",
"listen_port",
",",
"advertise_ip",
"=",
"self",
".",
"advertise_ip",
",",
"advertise_port",
"=",
"self",
".",
"advertise_port",
",",
"bind_multicast",
"=",
"self",
".",
"bind_multicast",
",",
")",
"async",
"def",
"emulated_roku_stop",
"(",
"event",
")",
":",
"\"\"\"Wrap the call to emulated_roku.close.\"\"\"",
"LOGGER",
".",
"debug",
"(",
"\"Stopping emulated_roku %s\"",
",",
"self",
".",
"roku_usn",
")",
"self",
".",
"_unsub_stop_listener",
"=",
"None",
"await",
"self",
".",
"_api_server",
".",
"close",
"(",
")",
"async",
"def",
"emulated_roku_start",
"(",
"event",
")",
":",
"\"\"\"Wrap the call to emulated_roku.start.\"\"\"",
"try",
":",
"LOGGER",
".",
"debug",
"(",
"\"Starting emulated_roku %s\"",
",",
"self",
".",
"roku_usn",
")",
"self",
".",
"_unsub_start_listener",
"=",
"None",
"await",
"self",
".",
"_api_server",
".",
"start",
"(",
")",
"except",
"OSError",
":",
"LOGGER",
".",
"exception",
"(",
"\"Failed to start Emulated Roku %s on %s:%s\"",
",",
"self",
".",
"roku_usn",
",",
"self",
".",
"host_ip",
",",
"self",
".",
"listen_port",
",",
")",
"# clean up inconsistent state on errors",
"await",
"emulated_roku_stop",
"(",
"None",
")",
"else",
":",
"self",
".",
"_unsub_stop_listener",
"=",
"self",
".",
"hass",
".",
"bus",
".",
"async_listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"emulated_roku_stop",
")",
"# start immediately if already running",
"if",
"self",
".",
"hass",
".",
"state",
"==",
"CoreState",
".",
"running",
":",
"await",
"emulated_roku_start",
"(",
"None",
")",
"else",
":",
"self",
".",
"_unsub_start_listener",
"=",
"self",
".",
"hass",
".",
"bus",
".",
"async_listen_once",
"(",
"EVENT_HOMEASSISTANT_START",
",",
"emulated_roku_start",
")",
"return",
"True"
] | [
53,
4
] | [
164,
19
] | python | en | ['en', 'lb', 'en'] | True |
EmulatedRoku.unload | (self) | Unload the emulated_roku server. | Unload the emulated_roku server. | async def unload(self):
"""Unload the emulated_roku server."""
LOGGER.debug("Unloading emulated_roku %s", self.roku_usn)
if self._unsub_start_listener:
self._unsub_start_listener()
self._unsub_start_listener = None
if self._unsub_stop_listener:
self._unsub_stop_listener()
self._unsub_stop_listener = None
await self._api_server.close()
return True | [
"async",
"def",
"unload",
"(",
"self",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Unloading emulated_roku %s\"",
",",
"self",
".",
"roku_usn",
")",
"if",
"self",
".",
"_unsub_start_listener",
":",
"self",
".",
"_unsub_start_listener",
"(",
")",
"self",
".",
"_unsub_start_listener",
"=",
"None",
"if",
"self",
".",
"_unsub_stop_listener",
":",
"self",
".",
"_unsub_stop_listener",
"(",
")",
"self",
".",
"_unsub_stop_listener",
"=",
"None",
"await",
"self",
".",
"_api_server",
".",
"close",
"(",
")",
"return",
"True"
] | [
166,
4
] | [
180,
19
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up switches attached to a Konnected device from a config entry. | Set up switches attached to a Konnected device from a config entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up switches attached to a Konnected device from a config entry."""
data = hass.data[KONNECTED_DOMAIN]
device_id = config_entry.data["id"]
switches = [
KonnectedSwitch(device_id, zone_data.get(CONF_ZONE), zone_data)
for zone_data in data[CONF_DEVICES][device_id][CONF_SWITCHES]
]
async_add_entities(switches) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"data",
"=",
"hass",
".",
"data",
"[",
"KONNECTED_DOMAIN",
"]",
"device_id",
"=",
"config_entry",
".",
"data",
"[",
"\"id\"",
"]",
"switches",
"=",
"[",
"KonnectedSwitch",
"(",
"device_id",
",",
"zone_data",
".",
"get",
"(",
"CONF_ZONE",
")",
",",
"zone_data",
")",
"for",
"zone_data",
"in",
"data",
"[",
"CONF_DEVICES",
"]",
"[",
"device_id",
"]",
"[",
"CONF_SWITCHES",
"]",
"]",
"async_add_entities",
"(",
"switches",
")"
] | [
25,
0
] | [
33,
32
] | python | en | ['en', 'en', 'en'] | True |
KonnectedSwitch.__init__ | (self, device_id, zone_num, data) | Initialize the Konnected switch. | Initialize the Konnected switch. | def __init__(self, device_id, zone_num, data):
"""Initialize the Konnected switch."""
self._data = data
self._device_id = device_id
self._zone_num = zone_num
self._activation = self._data.get(CONF_ACTIVATION, STATE_HIGH)
self._momentary = self._data.get(CONF_MOMENTARY)
self._pause = self._data.get(CONF_PAUSE)
self._repeat = self._data.get(CONF_REPEAT)
self._state = self._boolean_state(self._data.get(ATTR_STATE))
self._name = self._data.get(CONF_NAME)
self._unique_id = (
f"{device_id}-{self._zone_num}-{self._momentary}-"
f"{self._pause}-{self._repeat}"
) | [
"def",
"__init__",
"(",
"self",
",",
"device_id",
",",
"zone_num",
",",
"data",
")",
":",
"self",
".",
"_data",
"=",
"data",
"self",
".",
"_device_id",
"=",
"device_id",
"self",
".",
"_zone_num",
"=",
"zone_num",
"self",
".",
"_activation",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"CONF_ACTIVATION",
",",
"STATE_HIGH",
")",
"self",
".",
"_momentary",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"CONF_MOMENTARY",
")",
"self",
".",
"_pause",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"CONF_PAUSE",
")",
"self",
".",
"_repeat",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"CONF_REPEAT",
")",
"self",
".",
"_state",
"=",
"self",
".",
"_boolean_state",
"(",
"self",
".",
"_data",
".",
"get",
"(",
"ATTR_STATE",
")",
")",
"self",
".",
"_name",
"=",
"self",
".",
"_data",
".",
"get",
"(",
"CONF_NAME",
")",
"self",
".",
"_unique_id",
"=",
"(",
"f\"{device_id}-{self._zone_num}-{self._momentary}-\"",
"f\"{self._pause}-{self._repeat}\"",
")"
] | [
39,
4
] | [
53,
9
] | python | en | ['en', 'en', 'en'] | True |
KonnectedSwitch.unique_id | (self) | Return the unique id. | Return the unique id. | def unique_id(self) -> str:
"""Return the unique id."""
return self._unique_id | [
"def",
"unique_id",
"(",
"self",
")",
"->",
"str",
":",
"return",
"self",
".",
"_unique_id"
] | [
56,
4
] | [
58,
30
] | python | en | ['en', 'la', 'en'] | True |
KonnectedSwitch.name | (self) | Return the name of the switch. | Return the name of the switch. | def name(self):
"""Return the name of the switch."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
61,
4
] | [
63,
25
] | python | en | ['en', 'en', 'en'] | True |
KonnectedSwitch.is_on | (self) | Return the status of the sensor. | Return the status of the sensor. | def is_on(self):
"""Return the status of the sensor."""
return self._state | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
66,
4
] | [
68,
26
] | python | en | ['en', 'id', 'en'] | True |
KonnectedSwitch.panel | (self) | Return the Konnected HTTP client. | Return the Konnected HTTP client. | def panel(self):
"""Return the Konnected HTTP client."""
device_data = self.hass.data[KONNECTED_DOMAIN][CONF_DEVICES][self._device_id]
return device_data.get("panel") | [
"def",
"panel",
"(",
"self",
")",
":",
"device_data",
"=",
"self",
".",
"hass",
".",
"data",
"[",
"KONNECTED_DOMAIN",
"]",
"[",
"CONF_DEVICES",
"]",
"[",
"self",
".",
"_device_id",
"]",
"return",
"device_data",
".",
"get",
"(",
"\"panel\"",
")"
] | [
71,
4
] | [
74,
39
] | python | en | ['en', 'en', 'en'] | True |
KonnectedSwitch.device_info | (self) | Return the device info. | Return the device info. | def device_info(self):
"""Return the device info."""
return {
"identifiers": {(KONNECTED_DOMAIN, self._device_id)},
} | [
"def",
"device_info",
"(",
"self",
")",
":",
"return",
"{",
"\"identifiers\"",
":",
"{",
"(",
"KONNECTED_DOMAIN",
",",
"self",
".",
"_device_id",
")",
"}",
",",
"}"
] | [
77,
4
] | [
81,
9
] | python | en | ['en', 'en', 'en'] | True |
KonnectedSwitch.available | (self) | Return whether the panel is available. | Return whether the panel is available. | def available(self):
"""Return whether the panel is available."""
return self.panel.available | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"panel",
".",
"available"
] | [
84,
4
] | [
86,
35
] | python | en | ['en', 'en', 'en'] | True |
KonnectedSwitch.async_turn_on | (self, **kwargs) | Send a command to turn on the switch. | Send a command to turn on the switch. | async def async_turn_on(self, **kwargs):
"""Send a command to turn on the switch."""
resp = await self.panel.update_switch(
self._zone_num,
int(self._activation == STATE_HIGH),
self._momentary,
self._repeat,
self._pause,
)
if resp.get(ATTR_STATE) is not None:
self._set_state(True)
if self._momentary and resp.get(ATTR_STATE) != -1:
# Immediately set the state back off for momentary switches
self._set_state(False) | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"await",
"self",
".",
"panel",
".",
"update_switch",
"(",
"self",
".",
"_zone_num",
",",
"int",
"(",
"self",
".",
"_activation",
"==",
"STATE_HIGH",
")",
",",
"self",
".",
"_momentary",
",",
"self",
".",
"_repeat",
",",
"self",
".",
"_pause",
",",
")",
"if",
"resp",
".",
"get",
"(",
"ATTR_STATE",
")",
"is",
"not",
"None",
":",
"self",
".",
"_set_state",
"(",
"True",
")",
"if",
"self",
".",
"_momentary",
"and",
"resp",
".",
"get",
"(",
"ATTR_STATE",
")",
"!=",
"-",
"1",
":",
"# Immediately set the state back off for momentary switches",
"self",
".",
"_set_state",
"(",
"False",
")"
] | [
88,
4
] | [
103,
38
] | python | en | ['en', 'en', 'en'] | True |
KonnectedSwitch.async_turn_off | (self, **kwargs) | Send a command to turn off the switch. | Send a command to turn off the switch. | async def async_turn_off(self, **kwargs):
"""Send a command to turn off the switch."""
resp = await self.panel.update_switch(
self._zone_num, int(self._activation == STATE_LOW)
)
if resp.get(ATTR_STATE) is not None:
self._set_state(self._boolean_state(resp.get(ATTR_STATE))) | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"resp",
"=",
"await",
"self",
".",
"panel",
".",
"update_switch",
"(",
"self",
".",
"_zone_num",
",",
"int",
"(",
"self",
".",
"_activation",
"==",
"STATE_LOW",
")",
")",
"if",
"resp",
".",
"get",
"(",
"ATTR_STATE",
")",
"is",
"not",
"None",
":",
"self",
".",
"_set_state",
"(",
"self",
".",
"_boolean_state",
"(",
"resp",
".",
"get",
"(",
"ATTR_STATE",
")",
")",
")"
] | [
105,
4
] | [
112,
70
] | python | en | ['en', 'en', 'en'] | True |
KonnectedSwitch.async_added_to_hass | (self) | Store entity_id. | Store entity_id. | async def async_added_to_hass(self):
"""Store entity_id."""
self._data["entity_id"] = self.entity_id | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"_data",
"[",
"\"entity_id\"",
"]",
"=",
"self",
".",
"entity_id"
] | [
132,
4
] | [
134,
48
] | python | en | ['en', 'cy', 'en'] | False |
async_setup_entry | (hass, config_entry, async_add_entities) | Set up the switches from a config entry. | Set up the switches from a config entry. | async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up the switches from a config entry."""
board_api = hass.data[DOMAIN][config_entry.entry_id]
relay_count = config_entry.data["relay_count"]
switches = []
async def async_update_data():
"""Fetch data from API endpoint of board."""
async with async_timeout.timeout(5):
return await board_api.get_switches()
coordinator = DataUpdateCoordinator(
hass,
_LOGGER,
name="switch",
update_method=async_update_data,
update_interval=timedelta(seconds=DEFAULT_POLLING_INTERVAL_SEC),
)
await coordinator.async_refresh()
for i in range(1, int(relay_count) + 1):
switches.append(
ProgettihwswSwitch(
coordinator,
f"Relay #{i}",
setup_switch(board_api, i, config_entry.data[f"relay_{str(i)}"]),
)
)
async_add_entities(switches) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"config_entry",
",",
"async_add_entities",
")",
":",
"board_api",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"relay_count",
"=",
"config_entry",
".",
"data",
"[",
"\"relay_count\"",
"]",
"switches",
"=",
"[",
"]",
"async",
"def",
"async_update_data",
"(",
")",
":",
"\"\"\"Fetch data from API endpoint of board.\"\"\"",
"async",
"with",
"async_timeout",
".",
"timeout",
"(",
"5",
")",
":",
"return",
"await",
"board_api",
".",
"get_switches",
"(",
")",
"coordinator",
"=",
"DataUpdateCoordinator",
"(",
"hass",
",",
"_LOGGER",
",",
"name",
"=",
"\"switch\"",
",",
"update_method",
"=",
"async_update_data",
",",
"update_interval",
"=",
"timedelta",
"(",
"seconds",
"=",
"DEFAULT_POLLING_INTERVAL_SEC",
")",
",",
")",
"await",
"coordinator",
".",
"async_refresh",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"int",
"(",
"relay_count",
")",
"+",
"1",
")",
":",
"switches",
".",
"append",
"(",
"ProgettihwswSwitch",
"(",
"coordinator",
",",
"f\"Relay #{i}\"",
",",
"setup_switch",
"(",
"board_api",
",",
"i",
",",
"config_entry",
".",
"data",
"[",
"f\"relay_{str(i)}\"",
"]",
")",
",",
")",
")",
"async_add_entities",
"(",
"switches",
")"
] | [
20,
0
] | [
49,
32
] | python | en | ['en', 'en', 'en'] | True |
ProgettihwswSwitch.__init__ | (self, coordinator, name, switch: Relay) | Initialize the values. | Initialize the values. | def __init__(self, coordinator, name, switch: Relay):
"""Initialize the values."""
super().__init__(coordinator)
self._switch = switch
self._name = name | [
"def",
"__init__",
"(",
"self",
",",
"coordinator",
",",
"name",
",",
"switch",
":",
"Relay",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"coordinator",
")",
"self",
".",
"_switch",
"=",
"switch",
"self",
".",
"_name",
"=",
"name"
] | [
55,
4
] | [
59,
25
] | python | en | ['en', 'en', 'en'] | True |
ProgettihwswSwitch.async_turn_on | (self, **kwargs) | Turn the switch on. | Turn the switch on. | async def async_turn_on(self, **kwargs):
"""Turn the switch on."""
await self._switch.control(True)
await self.coordinator.async_request_refresh() | [
"async",
"def",
"async_turn_on",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_switch",
".",
"control",
"(",
"True",
")",
"await",
"self",
".",
"coordinator",
".",
"async_request_refresh",
"(",
")"
] | [
61,
4
] | [
64,
54
] | python | en | ['en', 'en', 'en'] | True |
ProgettihwswSwitch.async_turn_off | (self, **kwargs) | Turn the switch off. | Turn the switch off. | async def async_turn_off(self, **kwargs):
"""Turn the switch off."""
await self._switch.control(False)
await self.coordinator.async_request_refresh() | [
"async",
"def",
"async_turn_off",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_switch",
".",
"control",
"(",
"False",
")",
"await",
"self",
".",
"coordinator",
".",
"async_request_refresh",
"(",
")"
] | [
66,
4
] | [
69,
54
] | python | en | ['en', 'en', 'en'] | True |
ProgettihwswSwitch.async_toggle | (self, **kwargs) | Toggle the state of switch. | Toggle the state of switch. | async def async_toggle(self, **kwargs):
"""Toggle the state of switch."""
await self._switch.toggle()
await self.coordinator.async_request_refresh() | [
"async",
"def",
"async_toggle",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"await",
"self",
".",
"_switch",
".",
"toggle",
"(",
")",
"await",
"self",
".",
"coordinator",
".",
"async_request_refresh",
"(",
")"
] | [
71,
4
] | [
74,
54
] | python | en | ['en', 'en', 'en'] | True |
ProgettihwswSwitch.name | (self) | Return the switch name. | Return the switch name. | def name(self):
"""Return the switch name."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
77,
4
] | [
79,
25
] | python | en | ['en', 'en', 'en'] | True |
ProgettihwswSwitch.is_on | (self) | Get switch state. | Get switch state. | def is_on(self):
"""Get switch state."""
return self.coordinator.data[self._switch.id] | [
"def",
"is_on",
"(",
"self",
")",
":",
"return",
"self",
".",
"coordinator",
".",
"data",
"[",
"self",
".",
"_switch",
".",
"id",
"]"
] | [
82,
4
] | [
84,
53
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the Tahoma scenes. | Set up the Tahoma scenes. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Tahoma scenes."""
if discovery_info is None:
return
controller = hass.data[TAHOMA_DOMAIN]["controller"]
scenes = [
TahomaScene(scene, controller) for scene in hass.data[TAHOMA_DOMAIN]["scenes"]
]
add_entities(scenes, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"if",
"discovery_info",
"is",
"None",
":",
"return",
"controller",
"=",
"hass",
".",
"data",
"[",
"TAHOMA_DOMAIN",
"]",
"[",
"\"controller\"",
"]",
"scenes",
"=",
"[",
"TahomaScene",
"(",
"scene",
",",
"controller",
")",
"for",
"scene",
"in",
"hass",
".",
"data",
"[",
"TAHOMA_DOMAIN",
"]",
"[",
"\"scenes\"",
"]",
"]",
"add_entities",
"(",
"scenes",
",",
"True",
")"
] | [
8,
0
] | [
17,
30
] | python | en | ['en', 'mg', 'en'] | True |
TahomaScene.__init__ | (self, tahoma_scene, controller) | Initialize the scene. | Initialize the scene. | def __init__(self, tahoma_scene, controller):
"""Initialize the scene."""
self.tahoma_scene = tahoma_scene
self.controller = controller
self._name = self.tahoma_scene.name | [
"def",
"__init__",
"(",
"self",
",",
"tahoma_scene",
",",
"controller",
")",
":",
"self",
".",
"tahoma_scene",
"=",
"tahoma_scene",
"self",
".",
"controller",
"=",
"controller",
"self",
".",
"_name",
"=",
"self",
".",
"tahoma_scene",
".",
"name"
] | [
23,
4
] | [
27,
43
] | python | en | ['en', 'it', 'en'] | True |
TahomaScene.activate | (self, **kwargs: Any) | Activate the scene. | Activate the scene. | def activate(self, **kwargs: Any) -> None:
"""Activate the scene."""
self.controller.launch_action_group(self.tahoma_scene.oid) | [
"def",
"activate",
"(",
"self",
",",
"*",
"*",
"kwargs",
":",
"Any",
")",
"->",
"None",
":",
"self",
".",
"controller",
".",
"launch_action_group",
"(",
"self",
".",
"tahoma_scene",
".",
"oid",
")"
] | [
29,
4
] | [
31,
66
] | python | en | ['en', 'it', 'en'] | True |
TahomaScene.name | (self) | Return the name of the scene. | Return the name of the scene. | def name(self):
"""Return the name of the scene."""
return self._name | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"_name"
] | [
34,
4
] | [
36,
25
] | python | en | ['en', 'ig', 'en'] | True |
TahomaScene.device_state_attributes | (self) | Return the state attributes of the scene. | Return the state attributes of the scene. | def device_state_attributes(self):
"""Return the state attributes of the scene."""
return {"tahoma_scene_oid": self.tahoma_scene.oid} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"tahoma_scene_oid\"",
":",
"self",
".",
"tahoma_scene",
".",
"oid",
"}"
] | [
39,
4
] | [
41,
58
] | python | en | ['en', 'en', 'en'] | True |
DexcomConfigFlow.async_step_user | (self, user_input=None) | Handle the initial step. | Handle the initial step. | async def async_step_user(self, user_input=None):
"""Handle the initial step."""
errors = {}
if user_input is not None:
try:
await self.hass.async_add_executor_job(
Dexcom,
user_input[CONF_USERNAME],
user_input[CONF_PASSWORD],
user_input[CONF_SERVER] == SERVER_OUS,
)
except SessionError:
errors["base"] = "cannot_connect"
except AccountError:
errors["base"] = "invalid_auth"
except Exception: # pylint: disable=broad-except
errors["base"] = "unknown"
if "base" not in errors:
await self.async_set_unique_id(user_input[CONF_USERNAME])
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=user_input[CONF_USERNAME], data=user_input
)
return self.async_show_form(
step_id="user", data_schema=DATA_SCHEMA, errors=errors
) | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"errors",
"=",
"{",
"}",
"if",
"user_input",
"is",
"not",
"None",
":",
"try",
":",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"Dexcom",
",",
"user_input",
"[",
"CONF_USERNAME",
"]",
",",
"user_input",
"[",
"CONF_PASSWORD",
"]",
",",
"user_input",
"[",
"CONF_SERVER",
"]",
"==",
"SERVER_OUS",
",",
")",
"except",
"SessionError",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"cannot_connect\"",
"except",
"AccountError",
":",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"invalid_auth\"",
"except",
"Exception",
":",
"# pylint: disable=broad-except",
"errors",
"[",
"\"base\"",
"]",
"=",
"\"unknown\"",
"if",
"\"base\"",
"not",
"in",
"errors",
":",
"await",
"self",
".",
"async_set_unique_id",
"(",
"user_input",
"[",
"CONF_USERNAME",
"]",
")",
"self",
".",
"_abort_if_unique_id_configured",
"(",
")",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"user_input",
"[",
"CONF_USERNAME",
"]",
",",
"data",
"=",
"user_input",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
",",
"data_schema",
"=",
"DATA_SCHEMA",
",",
"errors",
"=",
"errors",
")"
] | [
32,
4
] | [
59,
9
] | python | en | ['en', 'en', 'en'] | True |
DexcomConfigFlow.async_get_options_flow | (config_entry) | Get the options flow for this handler. | Get the options flow for this handler. | def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return DexcomOptionsFlowHandler(config_entry) | [
"def",
"async_get_options_flow",
"(",
"config_entry",
")",
":",
"return",
"DexcomOptionsFlowHandler",
"(",
"config_entry",
")"
] | [
63,
4
] | [
65,
53
] | python | en | ['en', 'en', 'en'] | True |
DexcomOptionsFlowHandler.__init__ | (self, config_entry: config_entries.ConfigEntry) | Initialize options flow. | Initialize options flow. | def __init__(self, config_entry: config_entries.ConfigEntry):
"""Initialize options flow."""
self.config_entry = config_entry | [
"def",
"__init__",
"(",
"self",
",",
"config_entry",
":",
"config_entries",
".",
"ConfigEntry",
")",
":",
"self",
".",
"config_entry",
"=",
"config_entry"
] | [
71,
4
] | [
73,
40
] | python | en | ['en', 'en', 'en'] | True |
DexcomOptionsFlowHandler.async_step_init | (self, user_input=None) | Handle options flow. | Handle options flow. | async def async_step_init(self, user_input=None):
"""Handle options flow."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
data_schema = vol.Schema(
{
vol.Optional(
CONF_UNIT_OF_MEASUREMENT,
default=self.config_entry.options.get(
CONF_UNIT_OF_MEASUREMENT, MG_DL
),
): vol.In({MG_DL, MMOL_L}),
}
)
return self.async_show_form(step_id="init", data_schema=data_schema) | [
"async",
"def",
"async_step_init",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"self",
".",
"async_create_entry",
"(",
"title",
"=",
"\"\"",
",",
"data",
"=",
"user_input",
")",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Optional",
"(",
"CONF_UNIT_OF_MEASUREMENT",
",",
"default",
"=",
"self",
".",
"config_entry",
".",
"options",
".",
"get",
"(",
"CONF_UNIT_OF_MEASUREMENT",
",",
"MG_DL",
")",
",",
")",
":",
"vol",
".",
"In",
"(",
"{",
"MG_DL",
",",
"MMOL_L",
"}",
")",
",",
"}",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"init\"",
",",
"data_schema",
"=",
"data_schema",
")"
] | [
75,
4
] | [
90,
76
] | python | en | ['en', 'nl', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Validate configuration, create devices and start monitoring thread. | Validate configuration, create devices and start monitoring thread. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Validate configuration, create devices and start monitoring thread."""
bt_device_id = config.get("bt_device_id")
beacons = config.get(CONF_BEACONS)
devices = []
for dev_name, properties in beacons.items():
namespace = get_from_conf(properties, CONF_NAMESPACE, 20)
instance = get_from_conf(properties, CONF_INSTANCE, 12)
name = properties.get(CONF_NAME, dev_name)
if instance is None or namespace is None:
_LOGGER.error("Skipping %s", dev_name)
continue
devices.append(EddystoneTemp(name, namespace, instance))
if devices:
mon = Monitor(hass, devices, bt_device_id)
def monitor_stop(_service_or_event):
"""Stop the monitor thread."""
_LOGGER.info("Stopping scanner for Eddystone beacons")
mon.stop()
def monitor_start(_service_or_event):
"""Start the monitor thread."""
_LOGGER.info("Starting scanner for Eddystone beacons")
mon.start()
add_entities(devices)
mon.start()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, monitor_stop)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, monitor_start)
else:
_LOGGER.warning("No devices were added") | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"bt_device_id",
"=",
"config",
".",
"get",
"(",
"\"bt_device_id\"",
")",
"beacons",
"=",
"config",
".",
"get",
"(",
"CONF_BEACONS",
")",
"devices",
"=",
"[",
"]",
"for",
"dev_name",
",",
"properties",
"in",
"beacons",
".",
"items",
"(",
")",
":",
"namespace",
"=",
"get_from_conf",
"(",
"properties",
",",
"CONF_NAMESPACE",
",",
"20",
")",
"instance",
"=",
"get_from_conf",
"(",
"properties",
",",
"CONF_INSTANCE",
",",
"12",
")",
"name",
"=",
"properties",
".",
"get",
"(",
"CONF_NAME",
",",
"dev_name",
")",
"if",
"instance",
"is",
"None",
"or",
"namespace",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"Skipping %s\"",
",",
"dev_name",
")",
"continue",
"devices",
".",
"append",
"(",
"EddystoneTemp",
"(",
"name",
",",
"namespace",
",",
"instance",
")",
")",
"if",
"devices",
":",
"mon",
"=",
"Monitor",
"(",
"hass",
",",
"devices",
",",
"bt_device_id",
")",
"def",
"monitor_stop",
"(",
"_service_or_event",
")",
":",
"\"\"\"Stop the monitor thread.\"\"\"",
"_LOGGER",
".",
"info",
"(",
"\"Stopping scanner for Eddystone beacons\"",
")",
"mon",
".",
"stop",
"(",
")",
"def",
"monitor_start",
"(",
"_service_or_event",
")",
":",
"\"\"\"Start the monitor thread.\"\"\"",
"_LOGGER",
".",
"info",
"(",
"\"Starting scanner for Eddystone beacons\"",
")",
"mon",
".",
"start",
"(",
")",
"add_entities",
"(",
"devices",
")",
"mon",
".",
"start",
"(",
")",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"monitor_stop",
")",
"hass",
".",
"bus",
".",
"listen_once",
"(",
"EVENT_HOMEASSISTANT_START",
",",
"monitor_start",
")",
"else",
":",
"_LOGGER",
".",
"warning",
"(",
"\"No devices were added\"",
")"
] | [
46,
0
] | [
82,
48
] | python | en | ['en', 'en', 'en'] | True |
get_from_conf | (config, config_key, length) | Retrieve value from config and validate length. | Retrieve value from config and validate length. | def get_from_conf(config, config_key, length):
"""Retrieve value from config and validate length."""
string = config.get(config_key)
if len(string) != length:
_LOGGER.error(
"Error in configuration parameter %s: Must be exactly %d "
"bytes. Device will not be added",
config_key,
length / 2,
)
return None
return string | [
"def",
"get_from_conf",
"(",
"config",
",",
"config_key",
",",
"length",
")",
":",
"string",
"=",
"config",
".",
"get",
"(",
"config_key",
")",
"if",
"len",
"(",
"string",
")",
"!=",
"length",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error in configuration parameter %s: Must be exactly %d \"",
"\"bytes. Device will not be added\"",
",",
"config_key",
",",
"length",
"/",
"2",
",",
")",
"return",
"None",
"return",
"string"
] | [
85,
0
] | [
96,
17
] | python | en | ['en', 'en', 'en'] | True |
EddystoneTemp.__init__ | (self, name, namespace, instance) | Initialize a sensor. | Initialize a sensor. | def __init__(self, name, namespace, instance):
"""Initialize a sensor."""
self._name = name
self.namespace = namespace
self.instance = instance
self.bt_addr = None
self.temperature = STATE_UNKNOWN | [
"def",
"__init__",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"instance",
")",
":",
"self",
".",
"_name",
"=",
"name",
"self",
".",
"namespace",
"=",
"namespace",
"self",
".",
"instance",
"=",
"instance",
"self",
".",
"bt_addr",
"=",
"None",
"self",
".",
"temperature",
"=",
"STATE_UNKNOWN"
] | [
102,
4
] | [
108,
40
] | python | en | ['en', 'pt', 'it'] | False |
EddystoneTemp.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"
] | [
111,
4
] | [
113,
25
] | python | en | ['en', 'mi', 'en'] | True |
EddystoneTemp.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
return self.temperature | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"temperature"
] | [
116,
4
] | [
118,
31
] | python | en | ['en', 'en', 'en'] | True |
EddystoneTemp.unit_of_measurement | (self) | Return the unit the value is expressed in. | Return the unit the value is expressed in. | def unit_of_measurement(self):
"""Return the unit the value is expressed in."""
return TEMP_CELSIUS | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"TEMP_CELSIUS"
] | [
121,
4
] | [
123,
27
] | python | en | ['en', 'en', 'en'] | True |
EddystoneTemp.should_poll | (self) | Return the polling state. | Return the polling state. | def should_poll(self):
"""Return the polling state."""
return False | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"False"
] | [
126,
4
] | [
128,
20
] | python | en | ['en', 'en', 'en'] | True |
Monitor.__init__ | (self, hass, devices, bt_device_id) | Construct interface object. | Construct interface object. | def __init__(self, hass, devices, bt_device_id):
"""Construct interface object."""
self.hass = hass
# List of beacons to monitor
self.devices = devices
# Number of the bt device (hciX)
self.bt_device_id = bt_device_id
def callback(bt_addr, _, packet, additional_info):
"""Handle new packets."""
self.process_packet(
additional_info["namespace"],
additional_info["instance"],
packet.temperature,
)
device_filters = [EddystoneFilter(d.namespace, d.instance) for d in devices]
self.scanner = BeaconScanner(
callback, bt_device_id, device_filters, EddystoneTLMFrame
)
self.scanning = False | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"devices",
",",
"bt_device_id",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"# List of beacons to monitor",
"self",
".",
"devices",
"=",
"devices",
"# Number of the bt device (hciX)",
"self",
".",
"bt_device_id",
"=",
"bt_device_id",
"def",
"callback",
"(",
"bt_addr",
",",
"_",
",",
"packet",
",",
"additional_info",
")",
":",
"\"\"\"Handle new packets.\"\"\"",
"self",
".",
"process_packet",
"(",
"additional_info",
"[",
"\"namespace\"",
"]",
",",
"additional_info",
"[",
"\"instance\"",
"]",
",",
"packet",
".",
"temperature",
",",
")",
"device_filters",
"=",
"[",
"EddystoneFilter",
"(",
"d",
".",
"namespace",
",",
"d",
".",
"instance",
")",
"for",
"d",
"in",
"devices",
"]",
"self",
".",
"scanner",
"=",
"BeaconScanner",
"(",
"callback",
",",
"bt_device_id",
",",
"device_filters",
",",
"EddystoneTLMFrame",
")",
"self",
".",
"scanning",
"=",
"False"
] | [
134,
4
] | [
156,
29
] | python | en | ['en', 'en', 'en'] | True |
Monitor.start | (self) | Continuously scan for BLE advertisements. | Continuously scan for BLE advertisements. | def start(self):
"""Continuously scan for BLE advertisements."""
if not self.scanning:
self.scanner.start()
self.scanning = True
else:
_LOGGER.debug("start() called, but scanner is already running") | [
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"scanning",
":",
"self",
".",
"scanner",
".",
"start",
"(",
")",
"self",
".",
"scanning",
"=",
"True",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"start() called, but scanner is already running\"",
")"
] | [
158,
4
] | [
164,
75
] | python | en | ['en', 'en', 'en'] | True |
Monitor.process_packet | (self, namespace, instance, temperature) | Assign temperature to device. | Assign temperature to device. | def process_packet(self, namespace, instance, temperature):
"""Assign temperature to device."""
_LOGGER.debug(
"Received temperature for <%s,%s>: %d", namespace, instance, temperature
)
for dev in self.devices:
if dev.namespace == namespace and dev.instance == instance:
if dev.temperature != temperature:
dev.temperature = temperature
dev.schedule_update_ha_state() | [
"def",
"process_packet",
"(",
"self",
",",
"namespace",
",",
"instance",
",",
"temperature",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Received temperature for <%s,%s>: %d\"",
",",
"namespace",
",",
"instance",
",",
"temperature",
")",
"for",
"dev",
"in",
"self",
".",
"devices",
":",
"if",
"dev",
".",
"namespace",
"==",
"namespace",
"and",
"dev",
".",
"instance",
"==",
"instance",
":",
"if",
"dev",
".",
"temperature",
"!=",
"temperature",
":",
"dev",
".",
"temperature",
"=",
"temperature",
"dev",
".",
"schedule_update_ha_state",
"(",
")"
] | [
166,
4
] | [
176,
50
] | python | en | ['it', 'en', 'en'] | True |
Monitor.stop | (self) | Signal runner to stop and join thread. | Signal runner to stop and join thread. | def stop(self):
"""Signal runner to stop and join thread."""
if self.scanning:
_LOGGER.debug("Stopping...")
self.scanner.stop()
_LOGGER.debug("Stopped")
self.scanning = False
else:
_LOGGER.debug("stop() called but scanner was not running") | [
"def",
"stop",
"(",
"self",
")",
":",
"if",
"self",
".",
"scanning",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Stopping...\"",
")",
"self",
".",
"scanner",
".",
"stop",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Stopped\"",
")",
"self",
".",
"scanning",
"=",
"False",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"stop() called but scanner was not running\"",
")"
] | [
178,
4
] | [
186,
70
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Mock config. | Mock config. | async def async_setup(hass, config):
"""Mock config."""
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"return",
"True"
] | [
4,
0
] | [
6,
15
] | python | en | ['en', 'es', 'en'] | False |
async_condition_from_config | (
config: ConfigType, config_validation: bool
) | Evaluate state based on configuration. | Evaluate state based on configuration. | def async_condition_from_config(
config: ConfigType, config_validation: bool
) -> ConditionCheckerType:
"""Evaluate state based on configuration."""
if config_validation:
config = CONDITION_SCHEMA(config)
return toggle_entity.async_condition_from_config(config) | [
"def",
"async_condition_from_config",
"(",
"config",
":",
"ConfigType",
",",
"config_validation",
":",
"bool",
")",
"->",
"ConditionCheckerType",
":",
"if",
"config_validation",
":",
"config",
"=",
"CONDITION_SCHEMA",
"(",
"config",
")",
"return",
"toggle_entity",
".",
"async_condition_from_config",
"(",
"config",
")"
] | [
19,
0
] | [
25,
60
] | python | en | ['en', 'en', 'en'] | True |
async_get_conditions | (
hass: HomeAssistant, device_id: str
) | List device conditions. | List device conditions. | async def async_get_conditions(
hass: HomeAssistant, device_id: str
) -> List[Dict[str, str]]:
"""List device conditions."""
return await toggle_entity.async_get_conditions(hass, device_id, DOMAIN) | [
"async",
"def",
"async_get_conditions",
"(",
"hass",
":",
"HomeAssistant",
",",
"device_id",
":",
"str",
")",
"->",
"List",
"[",
"Dict",
"[",
"str",
",",
"str",
"]",
"]",
":",
"return",
"await",
"toggle_entity",
".",
"async_get_conditions",
"(",
"hass",
",",
"device_id",
",",
"DOMAIN",
")"
] | [
28,
0
] | [
32,
76
] | python | en | ['fr', 'en', 'en'] | True |
async_get_condition_capabilities | (hass: HomeAssistant, config: dict) | List condition capabilities. | List condition capabilities. | async def async_get_condition_capabilities(hass: HomeAssistant, config: dict) -> dict:
"""List condition capabilities."""
return await toggle_entity.async_get_condition_capabilities(hass, config) | [
"async",
"def",
"async_get_condition_capabilities",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
")",
"->",
"dict",
":",
"return",
"await",
"toggle_entity",
".",
"async_get_condition_capabilities",
"(",
"hass",
",",
"config",
")"
] | [
35,
0
] | [
37,
77
] | python | en | ['ro', 'sr', 'en'] | False |
is_on | (hass, entity_id) | Return if the switch is on based on the statemachine.
Async friendly.
| Return if the switch is on based on the statemachine. | def is_on(hass, entity_id):
"""Return if the switch is on based on the statemachine.
Async friendly.
"""
return hass.states.is_state(entity_id, STATE_ON) | [
"def",
"is_on",
"(",
"hass",
",",
"entity_id",
")",
":",
"return",
"hass",
".",
"states",
".",
"is_state",
"(",
"entity_id",
",",
"STATE_ON",
")"
] | [
48,
0
] | [
53,
52
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) | Track states and offer events for switches. | Track states and offer events for switches. | async def async_setup(hass, config):
"""Track states and offer events for switches."""
component = hass.data[DOMAIN] = EntityComponent(
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
await component.async_setup(config)
component.async_register_entity_service(SERVICE_TURN_OFF, {}, "async_turn_off")
component.async_register_entity_service(SERVICE_TURN_ON, {}, "async_turn_on")
component.async_register_entity_service(SERVICE_TOGGLE, {}, "async_toggle")
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"component",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"EntityComponent",
"(",
"_LOGGER",
",",
"DOMAIN",
",",
"hass",
",",
"SCAN_INTERVAL",
")",
"await",
"component",
".",
"async_setup",
"(",
"config",
")",
"component",
".",
"async_register_entity_service",
"(",
"SERVICE_TURN_OFF",
",",
"{",
"}",
",",
"\"async_turn_off\"",
")",
"component",
".",
"async_register_entity_service",
"(",
"SERVICE_TURN_ON",
",",
"{",
"}",
",",
"\"async_turn_on\"",
")",
"component",
".",
"async_register_entity_service",
"(",
"SERVICE_TOGGLE",
",",
"{",
"}",
",",
"\"async_toggle\"",
")",
"return",
"True"
] | [
56,
0
] | [
67,
15
] | python | en | ['en', 'en', 'en'] | True |
async_setup_entry | (hass, entry) | Set up a config entry. | Set up a config entry. | async def async_setup_entry(hass, entry):
"""Set up a config entry."""
return await hass.data[DOMAIN].async_setup_entry(entry) | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
")",
":",
"return",
"await",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"async_setup_entry",
"(",
"entry",
")"
] | [
70,
0
] | [
72,
59
] | python | en | ['en', 'en', 'en'] | True |
async_unload_entry | (hass, entry) | Unload a config entry. | Unload a config entry. | async def async_unload_entry(hass, entry):
"""Unload a config entry."""
return await hass.data[DOMAIN].async_unload_entry(entry) | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
",",
"entry",
")",
":",
"return",
"await",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
".",
"async_unload_entry",
"(",
"entry",
")"
] | [
75,
0
] | [
77,
60
] | python | en | ['en', 'es', 'en'] | True |
SwitchEntity.current_power_w | (self) | Return the current power usage in W. | Return the current power usage in W. | def current_power_w(self):
"""Return the current power usage in W."""
return None | [
"def",
"current_power_w",
"(",
"self",
")",
":",
"return",
"None"
] | [
84,
4
] | [
86,
19
] | python | en | ['en', 'en', 'en'] | True |
SwitchEntity.today_energy_kwh | (self) | Return the today total energy usage in kWh. | Return the today total energy usage in kWh. | def today_energy_kwh(self):
"""Return the today total energy usage in kWh."""
return None | [
"def",
"today_energy_kwh",
"(",
"self",
")",
":",
"return",
"None"
] | [
89,
4
] | [
91,
19
] | python | en | ['en', 'en', 'en'] | True |
SwitchEntity.is_standby | (self) | Return true if device is in standby. | Return true if device is in standby. | def is_standby(self):
"""Return true if device is in standby."""
return None | [
"def",
"is_standby",
"(",
"self",
")",
":",
"return",
"None"
] | [
94,
4
] | [
96,
19
] | python | en | ['en', 'en', 'en'] | True |
SwitchEntity.state_attributes | (self) | Return the optional state attributes. | Return the optional state attributes. | def state_attributes(self):
"""Return the optional state attributes."""
data = {}
for prop, attr in PROP_TO_ATTR.items():
value = getattr(self, prop)
if value is not None:
data[attr] = value
return data | [
"def",
"state_attributes",
"(",
"self",
")",
":",
"data",
"=",
"{",
"}",
"for",
"prop",
",",
"attr",
"in",
"PROP_TO_ATTR",
".",
"items",
"(",
")",
":",
"value",
"=",
"getattr",
"(",
"self",
",",
"prop",
")",
"if",
"value",
"is",
"not",
"None",
":",
"data",
"[",
"attr",
"]",
"=",
"value",
"return",
"data"
] | [
99,
4
] | [
108,
19
] | python | en | ['en', 'en', 'en'] | True |
SwitchEntity.device_class | (self) | Return the class of this device, from component DEVICE_CLASSES. | Return the class of this device, from component DEVICE_CLASSES. | def device_class(self):
"""Return the class of this device, from component DEVICE_CLASSES."""
return None | [
"def",
"device_class",
"(",
"self",
")",
":",
"return",
"None"
] | [
111,
4
] | [
113,
19
] | python | en | ['en', 'en', 'en'] | True |
SwitchDevice.__init_subclass__ | (cls, **kwargs) | Print deprecation warning. | Print deprecation warning. | def __init_subclass__(cls, **kwargs):
"""Print deprecation warning."""
super().__init_subclass__(**kwargs)
_LOGGER.warning(
"SwitchDevice is deprecated, modify %s to extend SwitchEntity",
cls.__name__,
) | [
"def",
"__init_subclass__",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"super",
"(",
")",
".",
"__init_subclass__",
"(",
"*",
"*",
"kwargs",
")",
"_LOGGER",
".",
"warning",
"(",
"\"SwitchDevice is deprecated, modify %s to extend SwitchEntity\"",
",",
"cls",
".",
"__name__",
",",
")"
] | [
119,
4
] | [
125,
9
] | python | de | ['de', 'sv', 'en'] | False |
reshape | (model, n: int = 1, h: int = 480, w: int = 640, mode='auto') |
:param model: Input ONNX model object
:param n: Batch size dimension
:param h: Height dimension
:param w: Width dimension
:param mode: Set `retinaface` to reshape RetinaFace model, otherwise reshape Centerface
:return: ONNX model with reshaped input and outputs
|
:param model: Input ONNX model object
:param n: Batch size dimension
:param h: Height dimension
:param w: Width dimension
:param mode: Set `retinaface` to reshape RetinaFace model, otherwise reshape Centerface
:return: ONNX model with reshaped input and outputs
| def reshape(model, n: int = 1, h: int = 480, w: int = 640, mode='auto'):
'''
:param model: Input ONNX model object
:param n: Batch size dimension
:param h: Height dimension
:param w: Width dimension
:param mode: Set `retinaface` to reshape RetinaFace model, otherwise reshape Centerface
:return: ONNX model with reshaped input and outputs
'''
if mode == 'auto':
# Assert that retinaface models have outputs containing word 'stride' in their names
out_name = model.graph.output[0].name
if 'stride' in out_name.lower():
mode = 'retinaface'
elif out_name.lower() == 'fc1':
mode = 'arcface'
else:
mode = 'centerface'
d = model.graph.input[0].type.tensor_type.shape.dim
d[0].dim_value = n
if mode != 'arcface':
d[2].dim_value = h
d[3].dim_value = w
divisor = 4
for output in model.graph.output:
if mode == 'retinaface':
divisor = int(output.name.split('stride')[-1])
d = output.type.tensor_type.shape.dim
d[0].dim_value = n
if mode != 'arcface':
d[2].dim_value = math.ceil(h / divisor)
d[3].dim_value = math.ceil(w / divisor)
return model | [
"def",
"reshape",
"(",
"model",
",",
"n",
":",
"int",
"=",
"1",
",",
"h",
":",
"int",
"=",
"480",
",",
"w",
":",
"int",
"=",
"640",
",",
"mode",
"=",
"'auto'",
")",
":",
"if",
"mode",
"==",
"'auto'",
":",
"# Assert that retinaface models have outputs containing word 'stride' in their names",
"out_name",
"=",
"model",
".",
"graph",
".",
"output",
"[",
"0",
"]",
".",
"name",
"if",
"'stride'",
"in",
"out_name",
".",
"lower",
"(",
")",
":",
"mode",
"=",
"'retinaface'",
"elif",
"out_name",
".",
"lower",
"(",
")",
"==",
"'fc1'",
":",
"mode",
"=",
"'arcface'",
"else",
":",
"mode",
"=",
"'centerface'",
"d",
"=",
"model",
".",
"graph",
".",
"input",
"[",
"0",
"]",
".",
"type",
".",
"tensor_type",
".",
"shape",
".",
"dim",
"d",
"[",
"0",
"]",
".",
"dim_value",
"=",
"n",
"if",
"mode",
"!=",
"'arcface'",
":",
"d",
"[",
"2",
"]",
".",
"dim_value",
"=",
"h",
"d",
"[",
"3",
"]",
".",
"dim_value",
"=",
"w",
"divisor",
"=",
"4",
"for",
"output",
"in",
"model",
".",
"graph",
".",
"output",
":",
"if",
"mode",
"==",
"'retinaface'",
":",
"divisor",
"=",
"int",
"(",
"output",
".",
"name",
".",
"split",
"(",
"'stride'",
")",
"[",
"-",
"1",
"]",
")",
"d",
"=",
"output",
".",
"type",
".",
"tensor_type",
".",
"shape",
".",
"dim",
"d",
"[",
"0",
"]",
".",
"dim_value",
"=",
"n",
"if",
"mode",
"!=",
"'arcface'",
":",
"d",
"[",
"2",
"]",
".",
"dim_value",
"=",
"math",
".",
"ceil",
"(",
"h",
"/",
"divisor",
")",
"d",
"[",
"3",
"]",
".",
"dim_value",
"=",
"math",
".",
"ceil",
"(",
"w",
"/",
"divisor",
")",
"return",
"model"
] | [
6,
0
] | [
40,
16
] | python | en | ['en', 'error', 'th'] | False |
reshape_onnx_input | (onnx_path: str, out_path: str, im_size: List[int] = None, batch_size: int = 1,
mode: str = 'auto') |
Reshape ONNX file input and output for different image sizes. Only applicable for MXNet Retinaface models
and official Centerface models.
:param onnx_path: Path to input ONNX file
:param out_path: Path to output ONNX file
:param im_size: Desired output image size in W, H format. Default: [640, 480]
:param mode: Available modes: retinaface, centerface, auto (try to detect if input model is retina- or centerface)
:return:
|
Reshape ONNX file input and output for different image sizes. Only applicable for MXNet Retinaface models
and official Centerface models. | def reshape_onnx_input(onnx_path: str, out_path: str, im_size: List[int] = None, batch_size: int = 1,
mode: str = 'auto'):
'''
Reshape ONNX file input and output for different image sizes. Only applicable for MXNet Retinaface models
and official Centerface models.
:param onnx_path: Path to input ONNX file
:param out_path: Path to output ONNX file
:param im_size: Desired output image size in W, H format. Default: [640, 480]
:param mode: Available modes: retinaface, centerface, auto (try to detect if input model is retina- or centerface)
:return:
'''
if im_size is None:
im_size = [640, 480]
model = onnx.load(onnx_path)
reshaped = reshape(model, n=batch_size, h=im_size[1], w=im_size[0], mode=mode)
with open(out_path, "wb") as file_handle:
serialized = reshaped.SerializeToString()
file_handle.write(serialized) | [
"def",
"reshape_onnx_input",
"(",
"onnx_path",
":",
"str",
",",
"out_path",
":",
"str",
",",
"im_size",
":",
"List",
"[",
"int",
"]",
"=",
"None",
",",
"batch_size",
":",
"int",
"=",
"1",
",",
"mode",
":",
"str",
"=",
"'auto'",
")",
":",
"if",
"im_size",
"is",
"None",
":",
"im_size",
"=",
"[",
"640",
",",
"480",
"]",
"model",
"=",
"onnx",
".",
"load",
"(",
"onnx_path",
")",
"reshaped",
"=",
"reshape",
"(",
"model",
",",
"n",
"=",
"batch_size",
",",
"h",
"=",
"im_size",
"[",
"1",
"]",
",",
"w",
"=",
"im_size",
"[",
"0",
"]",
",",
"mode",
"=",
"mode",
")",
"with",
"open",
"(",
"out_path",
",",
"\"wb\"",
")",
"as",
"file_handle",
":",
"serialized",
"=",
"reshaped",
".",
"SerializeToString",
"(",
")",
"file_handle",
".",
"write",
"(",
"serialized",
")"
] | [
43,
0
] | [
64,
37
] | python | en | ['en', 'error', 'th'] | False |
Subprocess.run | (command: str, timeout: int = None) | Run one-time command with subprocess.run().
Args:
command (str): command to be executed.
timeout (int): timeout in seconds.
Returns:
str: return stdout of the command.
| Run one-time command with subprocess.run(). | def run(command: str, timeout: int = None) -> None:
"""Run one-time command with subprocess.run().
Args:
command (str): command to be executed.
timeout (int): timeout in seconds.
Returns:
str: return stdout of the command.
"""
# TODO: Windows node
completed_process = subprocess.run(
command,
shell=True,
executable="/bin/bash",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
timeout=timeout
)
if completed_process.returncode != 0:
raise Exception(completed_process.stderr)
sys.stderr.write(completed_process.stderr) | [
"def",
"run",
"(",
"command",
":",
"str",
",",
"timeout",
":",
"int",
"=",
"None",
")",
"->",
"None",
":",
"# TODO: Windows node",
"completed_process",
"=",
"subprocess",
".",
"run",
"(",
"command",
",",
"shell",
"=",
"True",
",",
"executable",
"=",
"\"/bin/bash\"",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"universal_newlines",
"=",
"True",
",",
"timeout",
"=",
"timeout",
")",
"if",
"completed_process",
".",
"returncode",
"!=",
"0",
":",
"raise",
"Exception",
"(",
"completed_process",
".",
"stderr",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"completed_process",
".",
"stderr",
")"
] | [
67,
4
] | [
89,
50
] | python | en | ['en', 'en', 'en'] | True |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the sigfox sensor. | Set up the sigfox sensor. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the sigfox sensor."""
api_login = config[CONF_API_LOGIN]
api_password = config[CONF_API_PASSWORD]
name = config[CONF_NAME]
try:
sigfox = SigfoxAPI(api_login, api_password)
except ValueError:
return False
auth = sigfox.auth
devices = sigfox.devices
sensors = []
for device in devices:
sensors.append(SigfoxDevice(device, auth, name))
add_entities(sensors, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"api_login",
"=",
"config",
"[",
"CONF_API_LOGIN",
"]",
"api_password",
"=",
"config",
"[",
"CONF_API_PASSWORD",
"]",
"name",
"=",
"config",
"[",
"CONF_NAME",
"]",
"try",
":",
"sigfox",
"=",
"SigfoxAPI",
"(",
"api_login",
",",
"api_password",
")",
"except",
"ValueError",
":",
"return",
"False",
"auth",
"=",
"sigfox",
".",
"auth",
"devices",
"=",
"sigfox",
".",
"devices",
"sensors",
"=",
"[",
"]",
"for",
"device",
"in",
"devices",
":",
"sensors",
".",
"append",
"(",
"SigfoxDevice",
"(",
"device",
",",
"auth",
",",
"name",
")",
")",
"add_entities",
"(",
"sensors",
",",
"True",
")"
] | [
31,
0
] | [
46,
31
] | python | en | ['en', 'su', 'en'] | True |
epoch_to_datetime | (epoch_time) | Take an ms since epoch and return datetime string. | Take an ms since epoch and return datetime string. | def epoch_to_datetime(epoch_time):
"""Take an ms since epoch and return datetime string."""
return datetime.datetime.fromtimestamp(epoch_time).isoformat() | [
"def",
"epoch_to_datetime",
"(",
"epoch_time",
")",
":",
"return",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"epoch_time",
")",
".",
"isoformat",
"(",
")"
] | [
49,
0
] | [
51,
66
] | python | en | ['en', 'en', 'en'] | True |
SigfoxAPI.__init__ | (self, api_login, api_password) | Initialise the API object. | Initialise the API object. | def __init__(self, api_login, api_password):
"""Initialise the API object."""
self._auth = requests.auth.HTTPBasicAuth(api_login, api_password)
if self.check_credentials():
device_types = self.get_device_types()
self._devices = self.get_devices(device_types) | [
"def",
"__init__",
"(",
"self",
",",
"api_login",
",",
"api_password",
")",
":",
"self",
".",
"_auth",
"=",
"requests",
".",
"auth",
".",
"HTTPBasicAuth",
"(",
"api_login",
",",
"api_password",
")",
"if",
"self",
".",
"check_credentials",
"(",
")",
":",
"device_types",
"=",
"self",
".",
"get_device_types",
"(",
")",
"self",
".",
"_devices",
"=",
"self",
".",
"get_devices",
"(",
"device_types",
")"
] | [
57,
4
] | [
62,
58
] | python | en | ['en', 'zu', 'en'] | True |
SigfoxAPI.check_credentials | (self) | Check API credentials are valid. | Check API credentials are valid. | def check_credentials(self):
"""Check API credentials are valid."""
url = urljoin(API_URL, "devicetypes")
response = requests.get(url, auth=self._auth, timeout=10)
if response.status_code != HTTP_OK:
if response.status_code == HTTP_UNAUTHORIZED:
_LOGGER.error("Invalid credentials for Sigfox API")
else:
_LOGGER.error(
"Unable to login to Sigfox API, error code %s",
str(response.status_code),
)
raise ValueError("Sigfox integration not set up")
return True | [
"def",
"check_credentials",
"(",
"self",
")",
":",
"url",
"=",
"urljoin",
"(",
"API_URL",
",",
"\"devicetypes\"",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"self",
".",
"_auth",
",",
"timeout",
"=",
"10",
")",
"if",
"response",
".",
"status_code",
"!=",
"HTTP_OK",
":",
"if",
"response",
".",
"status_code",
"==",
"HTTP_UNAUTHORIZED",
":",
"_LOGGER",
".",
"error",
"(",
"\"Invalid credentials for Sigfox API\"",
")",
"else",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to login to Sigfox API, error code %s\"",
",",
"str",
"(",
"response",
".",
"status_code",
")",
",",
")",
"raise",
"ValueError",
"(",
"\"Sigfox integration not set up\"",
")",
"return",
"True"
] | [
64,
4
] | [
77,
19
] | python | en | ['en', 'en', 'en'] | True |
SigfoxAPI.get_device_types | (self) | Get a list of device types. | Get a list of device types. | def get_device_types(self):
"""Get a list of device types."""
url = urljoin(API_URL, "devicetypes")
response = requests.get(url, auth=self._auth, timeout=10)
device_types = []
for device in json.loads(response.text)["data"]:
device_types.append(device["id"])
return device_types | [
"def",
"get_device_types",
"(",
"self",
")",
":",
"url",
"=",
"urljoin",
"(",
"API_URL",
",",
"\"devicetypes\"",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"self",
".",
"_auth",
",",
"timeout",
"=",
"10",
")",
"device_types",
"=",
"[",
"]",
"for",
"device",
"in",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
"[",
"\"data\"",
"]",
":",
"device_types",
".",
"append",
"(",
"device",
"[",
"\"id\"",
"]",
")",
"return",
"device_types"
] | [
79,
4
] | [
86,
27
] | python | en | ['en', 'en', 'en'] | True |
SigfoxAPI.get_devices | (self, device_types) | Get the device_id of each device registered. | Get the device_id of each device registered. | def get_devices(self, device_types):
"""Get the device_id of each device registered."""
devices = []
for unique_type in device_types:
location_url = f"devicetypes/{unique_type}/devices"
url = urljoin(API_URL, location_url)
response = requests.get(url, auth=self._auth, timeout=10)
devices_data = json.loads(response.text)["data"]
for device in devices_data:
devices.append(device["id"])
return devices | [
"def",
"get_devices",
"(",
"self",
",",
"device_types",
")",
":",
"devices",
"=",
"[",
"]",
"for",
"unique_type",
"in",
"device_types",
":",
"location_url",
"=",
"f\"devicetypes/{unique_type}/devices\"",
"url",
"=",
"urljoin",
"(",
"API_URL",
",",
"location_url",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"self",
".",
"_auth",
",",
"timeout",
"=",
"10",
")",
"devices_data",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
"[",
"\"data\"",
"]",
"for",
"device",
"in",
"devices_data",
":",
"devices",
".",
"append",
"(",
"device",
"[",
"\"id\"",
"]",
")",
"return",
"devices"
] | [
88,
4
] | [
98,
22
] | python | en | ['en', 'en', 'en'] | True |
SigfoxAPI.auth | (self) | Return the API authentication. | Return the API authentication. | def auth(self):
"""Return the API authentication."""
return self._auth | [
"def",
"auth",
"(",
"self",
")",
":",
"return",
"self",
".",
"_auth"
] | [
101,
4
] | [
103,
25
] | python | en | ['en', 'en', 'en'] | True |
SigfoxAPI.devices | (self) | Return the list of device_id. | Return the list of device_id. | def devices(self):
"""Return the list of device_id."""
return self._devices | [
"def",
"devices",
"(",
"self",
")",
":",
"return",
"self",
".",
"_devices"
] | [
106,
4
] | [
108,
28
] | python | en | ['en', 'en', 'en'] | True |
SigfoxDevice.__init__ | (self, device_id, auth, name) | Initialise the device object. | Initialise the device object. | def __init__(self, device_id, auth, name):
"""Initialise the device object."""
self._device_id = device_id
self._auth = auth
self._message_data = {}
self._name = f"{name}_{device_id}"
self._state = None | [
"def",
"__init__",
"(",
"self",
",",
"device_id",
",",
"auth",
",",
"name",
")",
":",
"self",
".",
"_device_id",
"=",
"device_id",
"self",
".",
"_auth",
"=",
"auth",
"self",
".",
"_message_data",
"=",
"{",
"}",
"self",
".",
"_name",
"=",
"f\"{name}_{device_id}\"",
"self",
".",
"_state",
"=",
"None"
] | [
114,
4
] | [
120,
26
] | python | en | ['en', 'en', 'en'] | True |
SigfoxDevice.get_last_message | (self) | Return the last message from a device. | Return the last message from a device. | def get_last_message(self):
"""Return the last message from a device."""
device_url = f"devices/{self._device_id}/messages?limit=1"
url = urljoin(API_URL, device_url)
response = requests.get(url, auth=self._auth, timeout=10)
data = json.loads(response.text)["data"][0]
payload = bytes.fromhex(data["data"]).decode("utf-8")
lat = data["rinfos"][0]["lat"]
lng = data["rinfos"][0]["lng"]
snr = data["snr"]
epoch_time = data["time"]
return {
"lat": lat,
"lng": lng,
"payload": payload,
"snr": snr,
"time": epoch_to_datetime(epoch_time),
} | [
"def",
"get_last_message",
"(",
"self",
")",
":",
"device_url",
"=",
"f\"devices/{self._device_id}/messages?limit=1\"",
"url",
"=",
"urljoin",
"(",
"API_URL",
",",
"device_url",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"self",
".",
"_auth",
",",
"timeout",
"=",
"10",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
"[",
"\"data\"",
"]",
"[",
"0",
"]",
"payload",
"=",
"bytes",
".",
"fromhex",
"(",
"data",
"[",
"\"data\"",
"]",
")",
".",
"decode",
"(",
"\"utf-8\"",
")",
"lat",
"=",
"data",
"[",
"\"rinfos\"",
"]",
"[",
"0",
"]",
"[",
"\"lat\"",
"]",
"lng",
"=",
"data",
"[",
"\"rinfos\"",
"]",
"[",
"0",
"]",
"[",
"\"lng\"",
"]",
"snr",
"=",
"data",
"[",
"\"snr\"",
"]",
"epoch_time",
"=",
"data",
"[",
"\"time\"",
"]",
"return",
"{",
"\"lat\"",
":",
"lat",
",",
"\"lng\"",
":",
"lng",
",",
"\"payload\"",
":",
"payload",
",",
"\"snr\"",
":",
"snr",
",",
"\"time\"",
":",
"epoch_to_datetime",
"(",
"epoch_time",
")",
",",
"}"
] | [
122,
4
] | [
139,
9
] | python | en | ['en', 'en', 'en'] | True |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.