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 |
---|---|---|---|---|---|---|---|---|---|---|---|
FritzBoxCallSensor.state | (self) | Return the state of the device. | Return the state of the device. | def state(self):
"""Return the state of the device."""
return self._state | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"_state"
] | [
128,
4
] | [
130,
26
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxCallSensor.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"
] | [
133,
4
] | [
135,
25
] | python | en | ['en', 'mi', 'en'] | True |
FritzBoxCallSensor.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
return self._attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"self",
".",
"_attributes"
] | [
138,
4
] | [
140,
31
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxCallSensor.number_to_name | (self, number) | Return a name for a given phone number. | Return a name for a given phone number. | def number_to_name(self, number):
"""Return a name for a given phone number."""
if self.phonebook is None:
return "unknown"
return self.phonebook.get_name(number) | [
"def",
"number_to_name",
"(",
"self",
",",
"number",
")",
":",
"if",
"self",
".",
"phonebook",
"is",
"None",
":",
"return",
"\"unknown\"",
"return",
"self",
".",
"phonebook",
".",
"get_name",
"(",
"number",
")"
] | [
142,
4
] | [
146,
46
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxCallSensor.update | (self) | Update the phonebook if it is defined. | Update the phonebook if it is defined. | def update(self):
"""Update the phonebook if it is defined."""
if self.phonebook is not None:
self.phonebook.update_phonebook() | [
"def",
"update",
"(",
"self",
")",
":",
"if",
"self",
".",
"phonebook",
"is",
"not",
"None",
":",
"self",
".",
"phonebook",
".",
"update_phonebook",
"(",
")"
] | [
148,
4
] | [
151,
45
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxCallMonitor.__init__ | (self, host, port, sensor) | Initialize Fritz!Box monitor instance. | Initialize Fritz!Box monitor instance. | def __init__(self, host, port, sensor):
"""Initialize Fritz!Box monitor instance."""
self.host = host
self.port = port
self.sock = None
self._sensor = sensor
self.stopped = threading.Event() | [
"def",
"__init__",
"(",
"self",
",",
"host",
",",
"port",
",",
"sensor",
")",
":",
"self",
".",
"host",
"=",
"host",
"self",
".",
"port",
"=",
"port",
"self",
".",
"sock",
"=",
"None",
"self",
".",
"_sensor",
"=",
"sensor",
"self",
".",
"stopped",
"=",
"threading",
".",
"Event",
"(",
")"
] | [
157,
4
] | [
163,
40
] | python | en | ['eu', 'en', 'en'] | True |
FritzBoxCallMonitor.connect | (self) | Connect to the Fritz!Box. | Connect to the Fritz!Box. | def connect(self):
"""Connect to the Fritz!Box."""
_LOGGER.debug("Setting up socket...")
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.settimeout(10)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
try:
self.sock.connect((self.host, self.port))
threading.Thread(target=self._listen).start()
except OSError as err:
self.sock = None
_LOGGER.error(
"Cannot connect to %s on port %s: %s", self.host, self.port, err
) | [
"def",
"connect",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Setting up socket...\"",
")",
"self",
".",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"sock",
".",
"settimeout",
"(",
"10",
")",
"self",
".",
"sock",
".",
"setsockopt",
"(",
"socket",
".",
"SOL_SOCKET",
",",
"socket",
".",
"SO_KEEPALIVE",
",",
"1",
")",
"try",
":",
"self",
".",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"host",
",",
"self",
".",
"port",
")",
")",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_listen",
")",
".",
"start",
"(",
")",
"except",
"OSError",
"as",
"err",
":",
"self",
".",
"sock",
"=",
"None",
"_LOGGER",
".",
"error",
"(",
"\"Cannot connect to %s on port %s: %s\"",
",",
"self",
".",
"host",
",",
"self",
".",
"port",
",",
"err",
")"
] | [
165,
4
] | [
178,
13
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxCallMonitor._listen | (self) | Listen to incoming or outgoing calls. | Listen to incoming or outgoing calls. | def _listen(self):
"""Listen to incoming or outgoing calls."""
_LOGGER.debug("Connection established, waiting for response...")
while not self.stopped.isSet():
try:
response = self.sock.recv(2048)
except socket.timeout:
# if no response after 10 seconds, just recv again
continue
response = str(response, "utf-8")
_LOGGER.debug("Received %s", response)
if not response:
# if the response is empty, the connection has been lost.
# try to reconnect
_LOGGER.warning("Connection lost, reconnecting...")
self.sock = None
while self.sock is None:
self.connect()
time.sleep(INTERVAL_RECONNECT)
else:
line = response.split("\n", 1)[0]
self._parse(line)
time.sleep(1) | [
"def",
"_listen",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Connection established, waiting for response...\"",
")",
"while",
"not",
"self",
".",
"stopped",
".",
"isSet",
"(",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"sock",
".",
"recv",
"(",
"2048",
")",
"except",
"socket",
".",
"timeout",
":",
"# if no response after 10 seconds, just recv again",
"continue",
"response",
"=",
"str",
"(",
"response",
",",
"\"utf-8\"",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Received %s\"",
",",
"response",
")",
"if",
"not",
"response",
":",
"# if the response is empty, the connection has been lost.",
"# try to reconnect",
"_LOGGER",
".",
"warning",
"(",
"\"Connection lost, reconnecting...\"",
")",
"self",
".",
"sock",
"=",
"None",
"while",
"self",
".",
"sock",
"is",
"None",
":",
"self",
".",
"connect",
"(",
")",
"time",
".",
"sleep",
"(",
"INTERVAL_RECONNECT",
")",
"else",
":",
"line",
"=",
"response",
".",
"split",
"(",
"\"\\n\"",
",",
"1",
")",
"[",
"0",
"]",
"self",
".",
"_parse",
"(",
"line",
")",
"time",
".",
"sleep",
"(",
"1",
")"
] | [
180,
4
] | [
203,
29
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxCallMonitor._parse | (self, line) | Parse the call information and set the sensor states. | Parse the call information and set the sensor states. | def _parse(self, line):
"""Parse the call information and set the sensor states."""
line = line.split(";")
df_in = "%d.%m.%y %H:%M:%S"
df_out = "%Y-%m-%dT%H:%M:%S"
isotime = datetime.datetime.strptime(line[0], df_in).strftime(df_out)
if line[1] == "RING":
self._sensor.set_state(VALUE_RING)
att = {
"type": "incoming",
"from": line[3],
"to": line[4],
"device": line[5],
"initiated": isotime,
}
att["from_name"] = self._sensor.number_to_name(att["from"])
self._sensor.set_attributes(att)
elif line[1] == "CALL":
self._sensor.set_state(VALUE_CALL)
att = {
"type": "outgoing",
"from": line[4],
"to": line[5],
"device": line[6],
"initiated": isotime,
}
att["to_name"] = self._sensor.number_to_name(att["to"])
self._sensor.set_attributes(att)
elif line[1] == "CONNECT":
self._sensor.set_state(VALUE_CONNECT)
att = {"with": line[4], "device": line[3], "accepted": isotime}
att["with_name"] = self._sensor.number_to_name(att["with"])
self._sensor.set_attributes(att)
elif line[1] == "DISCONNECT":
self._sensor.set_state(VALUE_DISCONNECT)
att = {"duration": line[3], "closed": isotime}
self._sensor.set_attributes(att)
self._sensor.schedule_update_ha_state() | [
"def",
"_parse",
"(",
"self",
",",
"line",
")",
":",
"line",
"=",
"line",
".",
"split",
"(",
"\";\"",
")",
"df_in",
"=",
"\"%d.%m.%y %H:%M:%S\"",
"df_out",
"=",
"\"%Y-%m-%dT%H:%M:%S\"",
"isotime",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
"line",
"[",
"0",
"]",
",",
"df_in",
")",
".",
"strftime",
"(",
"df_out",
")",
"if",
"line",
"[",
"1",
"]",
"==",
"\"RING\"",
":",
"self",
".",
"_sensor",
".",
"set_state",
"(",
"VALUE_RING",
")",
"att",
"=",
"{",
"\"type\"",
":",
"\"incoming\"",
",",
"\"from\"",
":",
"line",
"[",
"3",
"]",
",",
"\"to\"",
":",
"line",
"[",
"4",
"]",
",",
"\"device\"",
":",
"line",
"[",
"5",
"]",
",",
"\"initiated\"",
":",
"isotime",
",",
"}",
"att",
"[",
"\"from_name\"",
"]",
"=",
"self",
".",
"_sensor",
".",
"number_to_name",
"(",
"att",
"[",
"\"from\"",
"]",
")",
"self",
".",
"_sensor",
".",
"set_attributes",
"(",
"att",
")",
"elif",
"line",
"[",
"1",
"]",
"==",
"\"CALL\"",
":",
"self",
".",
"_sensor",
".",
"set_state",
"(",
"VALUE_CALL",
")",
"att",
"=",
"{",
"\"type\"",
":",
"\"outgoing\"",
",",
"\"from\"",
":",
"line",
"[",
"4",
"]",
",",
"\"to\"",
":",
"line",
"[",
"5",
"]",
",",
"\"device\"",
":",
"line",
"[",
"6",
"]",
",",
"\"initiated\"",
":",
"isotime",
",",
"}",
"att",
"[",
"\"to_name\"",
"]",
"=",
"self",
".",
"_sensor",
".",
"number_to_name",
"(",
"att",
"[",
"\"to\"",
"]",
")",
"self",
".",
"_sensor",
".",
"set_attributes",
"(",
"att",
")",
"elif",
"line",
"[",
"1",
"]",
"==",
"\"CONNECT\"",
":",
"self",
".",
"_sensor",
".",
"set_state",
"(",
"VALUE_CONNECT",
")",
"att",
"=",
"{",
"\"with\"",
":",
"line",
"[",
"4",
"]",
",",
"\"device\"",
":",
"line",
"[",
"3",
"]",
",",
"\"accepted\"",
":",
"isotime",
"}",
"att",
"[",
"\"with_name\"",
"]",
"=",
"self",
".",
"_sensor",
".",
"number_to_name",
"(",
"att",
"[",
"\"with\"",
"]",
")",
"self",
".",
"_sensor",
".",
"set_attributes",
"(",
"att",
")",
"elif",
"line",
"[",
"1",
"]",
"==",
"\"DISCONNECT\"",
":",
"self",
".",
"_sensor",
".",
"set_state",
"(",
"VALUE_DISCONNECT",
")",
"att",
"=",
"{",
"\"duration\"",
":",
"line",
"[",
"3",
"]",
",",
"\"closed\"",
":",
"isotime",
"}",
"self",
".",
"_sensor",
".",
"set_attributes",
"(",
"att",
")",
"self",
".",
"_sensor",
".",
"schedule_update_ha_state",
"(",
")"
] | [
205,
4
] | [
242,
47
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxPhonebook.__init__ | (self, host, port, username, password, phonebook_id=0, prefixes=None) | Initialize the class. | Initialize the class. | def __init__(self, host, port, username, password, phonebook_id=0, prefixes=None):
"""Initialize the class."""
self.host = host
self.username = username
self.password = password
self.port = port
self.phonebook_id = phonebook_id
self.phonebook_dict = None
self.number_dict = None
self.prefixes = prefixes or []
# Establish a connection to the FRITZ!Box.
self.fph = FritzPhonebook(
address=self.host, user=self.username, password=self.password
)
if self.phonebook_id not in self.fph.list_phonebooks:
raise ValueError("Phonebook with this ID not found.")
self.update_phonebook() | [
"def",
"__init__",
"(",
"self",
",",
"host",
",",
"port",
",",
"username",
",",
"password",
",",
"phonebook_id",
"=",
"0",
",",
"prefixes",
"=",
"None",
")",
":",
"self",
".",
"host",
"=",
"host",
"self",
".",
"username",
"=",
"username",
"self",
".",
"password",
"=",
"password",
"self",
".",
"port",
"=",
"port",
"self",
".",
"phonebook_id",
"=",
"phonebook_id",
"self",
".",
"phonebook_dict",
"=",
"None",
"self",
".",
"number_dict",
"=",
"None",
"self",
".",
"prefixes",
"=",
"prefixes",
"or",
"[",
"]",
"# Establish a connection to the FRITZ!Box.",
"self",
".",
"fph",
"=",
"FritzPhonebook",
"(",
"address",
"=",
"self",
".",
"host",
",",
"user",
"=",
"self",
".",
"username",
",",
"password",
"=",
"self",
".",
"password",
")",
"if",
"self",
".",
"phonebook_id",
"not",
"in",
"self",
".",
"fph",
".",
"list_phonebooks",
":",
"raise",
"ValueError",
"(",
"\"Phonebook with this ID not found.\"",
")",
"self",
".",
"update_phonebook",
"(",
")"
] | [
248,
4
] | [
267,
31
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxPhonebook.update_phonebook | (self) | Update the phone book dictionary. | Update the phone book dictionary. | def update_phonebook(self):
"""Update the phone book dictionary."""
self.phonebook_dict = self.fph.get_all_names(self.phonebook_id)
self.number_dict = {
re.sub(r"[^\d\+]", "", nr): name
for name, nrs in self.phonebook_dict.items()
for nr in nrs
}
_LOGGER.info("Fritz!Box phone book successfully updated") | [
"def",
"update_phonebook",
"(",
"self",
")",
":",
"self",
".",
"phonebook_dict",
"=",
"self",
".",
"fph",
".",
"get_all_names",
"(",
"self",
".",
"phonebook_id",
")",
"self",
".",
"number_dict",
"=",
"{",
"re",
".",
"sub",
"(",
"r\"[^\\d\\+]\"",
",",
"\"\"",
",",
"nr",
")",
":",
"name",
"for",
"name",
",",
"nrs",
"in",
"self",
".",
"phonebook_dict",
".",
"items",
"(",
")",
"for",
"nr",
"in",
"nrs",
"}",
"_LOGGER",
".",
"info",
"(",
"\"Fritz!Box phone book successfully updated\"",
")"
] | [
270,
4
] | [
278,
65
] | python | en | ['en', 'en', 'en'] | True |
FritzBoxPhonebook.get_name | (self, number) | Return a name for a given phone number. | Return a name for a given phone number. | def get_name(self, number):
"""Return a name for a given phone number."""
number = re.sub(r"[^\d\+]", "", str(number))
if self.number_dict is None:
return "unknown"
try:
return self.number_dict[number]
except KeyError:
pass
if self.prefixes:
for prefix in self.prefixes:
try:
return self.number_dict[prefix + number]
except KeyError:
pass
try:
return self.number_dict[prefix + number.lstrip("0")]
except KeyError:
pass
return "unknown" | [
"def",
"get_name",
"(",
"self",
",",
"number",
")",
":",
"number",
"=",
"re",
".",
"sub",
"(",
"r\"[^\\d\\+]\"",
",",
"\"\"",
",",
"str",
"(",
"number",
")",
")",
"if",
"self",
".",
"number_dict",
"is",
"None",
":",
"return",
"\"unknown\"",
"try",
":",
"return",
"self",
".",
"number_dict",
"[",
"number",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"self",
".",
"prefixes",
":",
"for",
"prefix",
"in",
"self",
".",
"prefixes",
":",
"try",
":",
"return",
"self",
".",
"number_dict",
"[",
"prefix",
"+",
"number",
"]",
"except",
"KeyError",
":",
"pass",
"try",
":",
"return",
"self",
".",
"number_dict",
"[",
"prefix",
"+",
"number",
".",
"lstrip",
"(",
"\"0\"",
")",
"]",
"except",
"KeyError",
":",
"pass",
"return",
"\"unknown\""
] | [
280,
4
] | [
299,
24
] | python | en | ['en', 'en', 'en'] | True |
_request_app_setup | (hass, config) | Assist user with configuring the Wink dev application. | Assist user with configuring the Wink dev application. | def _request_app_setup(hass, config):
"""Assist user with configuring the Wink dev application."""
hass.data[DOMAIN]["configurator"] = True
configurator = hass.components.configurator
def wink_configuration_callback(callback_data):
"""Handle configuration updates."""
_config_path = hass.config.path(WINK_CONFIG_FILE)
if not os.path.isfile(_config_path):
setup(hass, config)
return
client_id = callback_data.get(CONF_CLIENT_ID).strip()
client_secret = callback_data.get(CONF_CLIENT_SECRET).strip()
if None not in (client_id, client_secret):
save_json(
_config_path,
{CONF_CLIENT_ID: client_id, CONF_CLIENT_SECRET: client_secret},
)
setup(hass, config)
return
error_msg = "Your input was invalid. Please try again."
_configurator = hass.data[DOMAIN]["configuring"][DOMAIN]
configurator.notify_errors(_configurator, error_msg)
start_url = f"{get_url(hass)}{WINK_AUTH_CALLBACK_PATH}"
description = f"""Please create a Wink developer app at
https://developer.wink.com.
Add a Redirect URI of {start_url}.
They will provide you a Client ID and secret
after reviewing your request.
(This can take several days).
"""
hass.data[DOMAIN]["configuring"][DOMAIN] = configurator.request_config(
DOMAIN,
wink_configuration_callback,
description=description,
submit_caption="submit",
description_image="/static/images/config_wink.png",
fields=[
{"id": CONF_CLIENT_ID, "name": "Client ID", "type": "string"},
{"id": CONF_CLIENT_SECRET, "name": "Client secret", "type": "string"},
],
) | [
"def",
"_request_app_setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configurator\"",
"]",
"=",
"True",
"configurator",
"=",
"hass",
".",
"components",
".",
"configurator",
"def",
"wink_configuration_callback",
"(",
"callback_data",
")",
":",
"\"\"\"Handle configuration updates.\"\"\"",
"_config_path",
"=",
"hass",
".",
"config",
".",
"path",
"(",
"WINK_CONFIG_FILE",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"_config_path",
")",
":",
"setup",
"(",
"hass",
",",
"config",
")",
"return",
"client_id",
"=",
"callback_data",
".",
"get",
"(",
"CONF_CLIENT_ID",
")",
".",
"strip",
"(",
")",
"client_secret",
"=",
"callback_data",
".",
"get",
"(",
"CONF_CLIENT_SECRET",
")",
".",
"strip",
"(",
")",
"if",
"None",
"not",
"in",
"(",
"client_id",
",",
"client_secret",
")",
":",
"save_json",
"(",
"_config_path",
",",
"{",
"CONF_CLIENT_ID",
":",
"client_id",
",",
"CONF_CLIENT_SECRET",
":",
"client_secret",
"}",
",",
")",
"setup",
"(",
"hass",
",",
"config",
")",
"return",
"error_msg",
"=",
"\"Your input was invalid. Please try again.\"",
"_configurator",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configuring\"",
"]",
"[",
"DOMAIN",
"]",
"configurator",
".",
"notify_errors",
"(",
"_configurator",
",",
"error_msg",
")",
"start_url",
"=",
"f\"{get_url(hass)}{WINK_AUTH_CALLBACK_PATH}\"",
"description",
"=",
"f\"\"\"Please create a Wink developer app at\n https://developer.wink.com.\n Add a Redirect URI of {start_url}.\n They will provide you a Client ID and secret\n after reviewing your request.\n (This can take several days).\n \"\"\"",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configuring\"",
"]",
"[",
"DOMAIN",
"]",
"=",
"configurator",
".",
"request_config",
"(",
"DOMAIN",
",",
"wink_configuration_callback",
",",
"description",
"=",
"description",
",",
"submit_caption",
"=",
"\"submit\"",
",",
"description_image",
"=",
"\"/static/images/config_wink.png\"",
",",
"fields",
"=",
"[",
"{",
"\"id\"",
":",
"CONF_CLIENT_ID",
",",
"\"name\"",
":",
"\"Client ID\"",
",",
"\"type\"",
":",
"\"string\"",
"}",
",",
"{",
"\"id\"",
":",
"CONF_CLIENT_SECRET",
",",
"\"name\"",
":",
"\"Client secret\"",
",",
"\"type\"",
":",
"\"string\"",
"}",
",",
"]",
",",
")"
] | [
210,
0
] | [
255,
5
] | python | en | ['en', 'en', 'en'] | True |
_request_oauth_completion | (hass, config) | Request user complete Wink OAuth2 flow. | Request user complete Wink OAuth2 flow. | def _request_oauth_completion(hass, config):
"""Request user complete Wink OAuth2 flow."""
hass.data[DOMAIN]["configurator"] = True
configurator = hass.components.configurator
if DOMAIN in hass.data[DOMAIN]["configuring"]:
configurator.notify_errors(
hass.data[DOMAIN]["configuring"][DOMAIN],
"Failed to register, please try again.",
)
return
def wink_configuration_callback(callback_data):
"""Call setup again."""
setup(hass, config)
start_url = f"{get_url(hass)}{WINK_AUTH_START}"
description = f"Please authorize Wink by visiting {start_url}"
hass.data[DOMAIN]["configuring"][DOMAIN] = configurator.request_config(
DOMAIN, wink_configuration_callback, description=description
) | [
"def",
"_request_oauth_completion",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configurator\"",
"]",
"=",
"True",
"configurator",
"=",
"hass",
".",
"components",
".",
"configurator",
"if",
"DOMAIN",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configuring\"",
"]",
":",
"configurator",
".",
"notify_errors",
"(",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configuring\"",
"]",
"[",
"DOMAIN",
"]",
",",
"\"Failed to register, please try again.\"",
",",
")",
"return",
"def",
"wink_configuration_callback",
"(",
"callback_data",
")",
":",
"\"\"\"Call setup again.\"\"\"",
"setup",
"(",
"hass",
",",
"config",
")",
"start_url",
"=",
"f\"{get_url(hass)}{WINK_AUTH_START}\"",
"description",
"=",
"f\"Please authorize Wink by visiting {start_url}\"",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configuring\"",
"]",
"[",
"DOMAIN",
"]",
"=",
"configurator",
".",
"request_config",
"(",
"DOMAIN",
",",
"wink_configuration_callback",
",",
"description",
"=",
"description",
")"
] | [
258,
0
] | [
279,
5
] | python | en | ['en', 'nl', 'en'] | True |
setup | (hass, config) | Set up the Wink component. | Set up the Wink component. | def setup(hass, config):
"""Set up the Wink component."""
if hass.data.get(DOMAIN) is None:
hass.data[DOMAIN] = {
"unique_ids": [],
"entities": {},
"oauth": {},
"configuring": {},
"pubnub": None,
"configurator": False,
}
if config.get(DOMAIN) is not None:
client_id = config[DOMAIN].get(CONF_CLIENT_ID)
client_secret = config[DOMAIN].get(CONF_CLIENT_SECRET)
email = config[DOMAIN].get(CONF_EMAIL)
password = config[DOMAIN].get(CONF_PASSWORD)
local_control = config[DOMAIN].get(CONF_LOCAL_CONTROL)
else:
client_id = None
client_secret = None
email = None
password = None
local_control = None
hass.data[DOMAIN]["configurator"] = True
if None not in [client_id, client_secret]:
_LOGGER.info("Using legacy OAuth authentication")
if not local_control:
pywink.disable_local_control()
hass.data[DOMAIN]["oauth"][CONF_CLIENT_ID] = client_id
hass.data[DOMAIN]["oauth"][CONF_CLIENT_SECRET] = client_secret
hass.data[DOMAIN]["oauth"]["email"] = email
hass.data[DOMAIN]["oauth"]["password"] = password
pywink.legacy_set_wink_credentials(email, password, client_id, client_secret)
else:
_LOGGER.info("Using OAuth authentication")
if not local_control:
pywink.disable_local_control()
config_path = hass.config.path(WINK_CONFIG_FILE)
if os.path.isfile(config_path):
config_file = load_json(config_path)
if config_file == DEFAULT_CONFIG:
_request_app_setup(hass, config)
return True
# else move on because the user modified the file
else:
save_json(config_path, DEFAULT_CONFIG)
_request_app_setup(hass, config)
return True
if DOMAIN in hass.data[DOMAIN]["configuring"]:
_configurator = hass.data[DOMAIN]["configuring"]
hass.components.configurator.request_done(_configurator.pop(DOMAIN))
# Using oauth
access_token = config_file.get(ATTR_ACCESS_TOKEN)
refresh_token = config_file.get(ATTR_REFRESH_TOKEN)
# This will be called after authorizing Home-Assistant
if None not in (access_token, refresh_token):
pywink.set_wink_credentials(
config_file.get(CONF_CLIENT_ID),
config_file.get(CONF_CLIENT_SECRET),
access_token=access_token,
refresh_token=refresh_token,
)
# This is called to create the redirect so the user can Authorize
# Home .
else:
redirect_uri = f"{get_url(hass)}{WINK_AUTH_CALLBACK_PATH}"
wink_auth_start_url = pywink.get_authorization_url(
config_file.get(CONF_CLIENT_ID), redirect_uri
)
hass.http.register_redirect(WINK_AUTH_START, wink_auth_start_url)
hass.http.register_view(
WinkAuthCallbackView(config, config_file, pywink.request_token)
)
_request_oauth_completion(hass, config)
return True
pywink.set_user_agent(USER_AGENT)
sub_details = pywink.get_subscription_details()
hass.data[DOMAIN]["pubnub"] = PubNubSubscriptionHandler(
sub_details[0], origin=sub_details[1]
)
def _subscribe():
hass.data[DOMAIN]["pubnub"].subscribe()
# Call subscribe after the user sets up wink via the configurator
# All other methods will complete setup before
# EVENT_HOMEASSISTANT_START is called meaning they
# will call subscribe via the method below. (start_subscription)
if hass.data[DOMAIN]["configurator"]:
_subscribe()
def keep_alive_call(event_time):
"""Call the Wink API endpoints to keep PubNub working."""
_LOGGER.info("Polling the Wink API to keep PubNub updates flowing")
pywink.set_user_agent(str(int(time.time())))
_temp_response = pywink.get_user()
_LOGGER.debug(str(json.dumps(_temp_response)))
time.sleep(1)
pywink.set_user_agent(USER_AGENT)
_temp_response = pywink.wink_api_fetch()
_LOGGER.debug("%s", _temp_response)
_temp_response = pywink.post_session()
_LOGGER.debug("%s", _temp_response)
# Call the Wink API every hour to keep PubNub updates flowing
track_time_interval(hass, keep_alive_call, timedelta(minutes=60))
def start_subscription(event):
"""Start the PubNub subscription."""
_subscribe()
hass.bus.listen(EVENT_HOMEASSISTANT_START, start_subscription)
def stop_subscription(event):
"""Stop the PubNub subscription."""
hass.data[DOMAIN]["pubnub"].unsubscribe()
hass.data[DOMAIN]["pubnub"] = None
hass.bus.listen(EVENT_HOMEASSISTANT_STOP, stop_subscription)
def save_credentials(event):
"""Save currently set OAuth credentials."""
if hass.data[DOMAIN]["oauth"].get("email") is None:
config_path = hass.config.path(WINK_CONFIG_FILE)
_config = pywink.get_current_oauth_credentials()
save_json(config_path, _config)
hass.bus.listen(EVENT_HOMEASSISTANT_STOP, save_credentials)
# Save the users potentially updated oauth credentials at a regular
# interval to prevent them from being expired after a HA reboot.
track_time_interval(hass, save_credentials, timedelta(minutes=60))
def force_update(call):
"""Force all devices to poll the Wink API."""
_LOGGER.info("Refreshing Wink states from API")
for entity_list in hass.data[DOMAIN]["entities"].values():
# Throttle the calls to Wink API
for entity in entity_list:
time.sleep(1)
entity.schedule_update_ha_state(True)
hass.services.register(DOMAIN, SERVICE_REFRESH_STATES, force_update)
def pull_new_devices(call):
"""Pull new devices added to users Wink account since startup."""
_LOGGER.info("Getting new devices from Wink API")
for _component in WINK_COMPONENTS:
discovery.load_platform(hass, _component, DOMAIN, {}, config)
hass.services.register(DOMAIN, SERVICE_ADD_NEW_DEVICES, pull_new_devices)
def set_pairing_mode(call):
"""Put the hub in provided pairing mode."""
hub_name = call.data.get("hub_name")
pairing_mode = call.data.get("pairing_mode")
kidde_code = call.data.get("kidde_radio_code")
for hub in WINK_HUBS:
if hub.name() == hub_name:
hub.pair_new_device(pairing_mode, kidde_radio_code=kidde_code)
def rename_device(call):
"""Set specified device's name."""
# This should only be called on one device at a time.
found_device = None
entity_id = call.data.get("entity_id")[0]
all_devices = []
for list_of_devices in hass.data[DOMAIN]["entities"].values():
all_devices += list_of_devices
for device in all_devices:
if device.entity_id == entity_id:
found_device = device
if found_device is not None:
name = call.data.get("name")
found_device.wink.set_name(name)
hass.services.register(
DOMAIN, SERVICE_RENAME_DEVICE, rename_device, schema=RENAME_DEVICE_SCHEMA
)
def delete_device(call):
"""Delete specified device."""
# This should only be called on one device at a time.
found_device = None
entity_id = call.data.get("entity_id")[0]
all_devices = []
for list_of_devices in hass.data[DOMAIN]["entities"].values():
all_devices += list_of_devices
for device in all_devices:
if device.entity_id == entity_id:
found_device = device
if found_device is not None:
found_device.wink.remove_device()
hass.services.register(
DOMAIN, SERVICE_DELETE_DEVICE, delete_device, schema=DELETE_DEVICE_SCHEMA
)
hubs = pywink.get_hubs()
for hub in hubs:
if hub.device_manufacturer() == "wink":
WINK_HUBS.append(hub)
if WINK_HUBS:
hass.services.register(
DOMAIN,
SERVICE_SET_PAIRING_MODE,
set_pairing_mode,
schema=SET_PAIRING_MODE_SCHEMA,
)
def nimbus_service_handle(service):
"""Handle nimbus services."""
entity_id = service.data.get("entity_id")[0]
_all_dials = []
for sensor in hass.data[DOMAIN]["entities"]["sensor"]:
if isinstance(sensor, WinkNimbusDialDevice):
_all_dials.append(sensor)
for _dial in _all_dials:
if _dial.entity_id == entity_id:
if service.service == SERVICE_SET_DIAL_CONFIG:
_dial.set_configuration(**service.data)
if service.service == SERVICE_SET_DIAL_STATE:
_dial.wink.set_state(
service.data.get("value"), service.data.get("labels")
)
def siren_service_handle(service):
"""Handle siren services."""
entity_ids = service.data.get("entity_id")
all_sirens = []
for switch in hass.data[DOMAIN]["entities"]["switch"]:
if isinstance(switch, WinkSirenDevice):
all_sirens.append(switch)
sirens_to_set = []
if entity_ids is None:
sirens_to_set = all_sirens
else:
for siren in all_sirens:
if siren.entity_id in entity_ids:
sirens_to_set.append(siren)
for siren in sirens_to_set:
_man = siren.wink.device_manufacturer()
if (
service.service != SERVICE_SET_AUTO_SHUTOFF
and service.service != SERVICE_ENABLE_SIREN
and _man not in ("dome", "wink")
):
_LOGGER.error("Service only valid for Dome or Wink sirens")
return
if service.service == SERVICE_ENABLE_SIREN:
siren.wink.set_state(service.data.get(ATTR_ENABLED))
elif service.service == SERVICE_SET_AUTO_SHUTOFF:
siren.wink.set_auto_shutoff(service.data.get(ATTR_AUTO_SHUTOFF))
elif service.service == SERVICE_SET_CHIME_VOLUME:
siren.wink.set_chime_volume(service.data.get(ATTR_VOLUME))
elif service.service == SERVICE_SET_SIREN_VOLUME:
siren.wink.set_siren_volume(service.data.get(ATTR_VOLUME))
elif service.service == SERVICE_SET_SIREN_TONE:
siren.wink.set_siren_sound(service.data.get(ATTR_TONE))
elif service.service == SERVICE_ENABLE_CHIME:
siren.wink.set_chime(service.data.get(ATTR_TONE))
elif service.service == SERVICE_SIREN_STROBE_ENABLED:
siren.wink.set_siren_strobe_enabled(service.data.get(ATTR_ENABLED))
elif service.service == SERVICE_CHIME_STROBE_ENABLED:
siren.wink.set_chime_strobe_enabled(service.data.get(ATTR_ENABLED))
# Load components for the devices in Wink that we support
for wink_component in WINK_COMPONENTS:
hass.data[DOMAIN]["entities"][wink_component] = []
discovery.load_platform(hass, wink_component, DOMAIN, {}, config)
component = EntityComponent(_LOGGER, DOMAIN, hass)
sirens = []
has_dome_or_wink_siren = False
for siren in pywink.get_sirens():
_man = siren.device_manufacturer()
if _man in ("dome", "wink"):
has_dome_or_wink_siren = True
_id = siren.object_id() + siren.name()
if _id not in hass.data[DOMAIN]["unique_ids"]:
sirens.append(WinkSirenDevice(siren, hass))
if sirens:
hass.services.register(
DOMAIN,
SERVICE_SET_AUTO_SHUTOFF,
siren_service_handle,
schema=SET_AUTO_SHUTOFF_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_ENABLE_SIREN,
siren_service_handle,
schema=ENABLED_SIREN_SCHEMA,
)
if has_dome_or_wink_siren:
hass.services.register(
DOMAIN,
SERVICE_SET_SIREN_TONE,
siren_service_handle,
schema=SET_SIREN_TONE_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_ENABLE_CHIME,
siren_service_handle,
schema=SET_CHIME_MODE_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_SET_SIREN_VOLUME,
siren_service_handle,
schema=SET_VOLUME_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_SET_CHIME_VOLUME,
siren_service_handle,
schema=SET_VOLUME_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_SIREN_STROBE_ENABLED,
siren_service_handle,
schema=SET_STROBE_ENABLED_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_CHIME_STROBE_ENABLED,
siren_service_handle,
schema=SET_STROBE_ENABLED_SCHEMA,
)
component.add_entities(sirens)
nimbi = []
dials = {}
all_nimbi = pywink.get_cloud_clocks()
all_dials = []
for nimbus in all_nimbi:
if nimbus.object_type() == "cloud_clock":
nimbi.append(nimbus)
dials[nimbus.object_id()] = []
for nimbus in all_nimbi:
if nimbus.object_type() == "dial":
dials[nimbus.parent_id()].append(nimbus)
for nimbus in nimbi:
for dial in dials[nimbus.object_id()]:
all_dials.append(WinkNimbusDialDevice(nimbus, dial, hass))
if nimbi:
hass.services.register(
DOMAIN,
SERVICE_SET_DIAL_CONFIG,
nimbus_service_handle,
schema=DIAL_CONFIG_SCHEMA,
)
hass.services.register(
DOMAIN,
SERVICE_SET_DIAL_STATE,
nimbus_service_handle,
schema=DIAL_STATE_SCHEMA,
)
component.add_entities(all_dials)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"if",
"hass",
".",
"data",
".",
"get",
"(",
"DOMAIN",
")",
"is",
"None",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"{",
"\"unique_ids\"",
":",
"[",
"]",
",",
"\"entities\"",
":",
"{",
"}",
",",
"\"oauth\"",
":",
"{",
"}",
",",
"\"configuring\"",
":",
"{",
"}",
",",
"\"pubnub\"",
":",
"None",
",",
"\"configurator\"",
":",
"False",
",",
"}",
"if",
"config",
".",
"get",
"(",
"DOMAIN",
")",
"is",
"not",
"None",
":",
"client_id",
"=",
"config",
"[",
"DOMAIN",
"]",
".",
"get",
"(",
"CONF_CLIENT_ID",
")",
"client_secret",
"=",
"config",
"[",
"DOMAIN",
"]",
".",
"get",
"(",
"CONF_CLIENT_SECRET",
")",
"email",
"=",
"config",
"[",
"DOMAIN",
"]",
".",
"get",
"(",
"CONF_EMAIL",
")",
"password",
"=",
"config",
"[",
"DOMAIN",
"]",
".",
"get",
"(",
"CONF_PASSWORD",
")",
"local_control",
"=",
"config",
"[",
"DOMAIN",
"]",
".",
"get",
"(",
"CONF_LOCAL_CONTROL",
")",
"else",
":",
"client_id",
"=",
"None",
"client_secret",
"=",
"None",
"email",
"=",
"None",
"password",
"=",
"None",
"local_control",
"=",
"None",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configurator\"",
"]",
"=",
"True",
"if",
"None",
"not",
"in",
"[",
"client_id",
",",
"client_secret",
"]",
":",
"_LOGGER",
".",
"info",
"(",
"\"Using legacy OAuth authentication\"",
")",
"if",
"not",
"local_control",
":",
"pywink",
".",
"disable_local_control",
"(",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"oauth\"",
"]",
"[",
"CONF_CLIENT_ID",
"]",
"=",
"client_id",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"oauth\"",
"]",
"[",
"CONF_CLIENT_SECRET",
"]",
"=",
"client_secret",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"oauth\"",
"]",
"[",
"\"email\"",
"]",
"=",
"email",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"oauth\"",
"]",
"[",
"\"password\"",
"]",
"=",
"password",
"pywink",
".",
"legacy_set_wink_credentials",
"(",
"email",
",",
"password",
",",
"client_id",
",",
"client_secret",
")",
"else",
":",
"_LOGGER",
".",
"info",
"(",
"\"Using OAuth authentication\"",
")",
"if",
"not",
"local_control",
":",
"pywink",
".",
"disable_local_control",
"(",
")",
"config_path",
"=",
"hass",
".",
"config",
".",
"path",
"(",
"WINK_CONFIG_FILE",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"config_path",
")",
":",
"config_file",
"=",
"load_json",
"(",
"config_path",
")",
"if",
"config_file",
"==",
"DEFAULT_CONFIG",
":",
"_request_app_setup",
"(",
"hass",
",",
"config",
")",
"return",
"True",
"# else move on because the user modified the file",
"else",
":",
"save_json",
"(",
"config_path",
",",
"DEFAULT_CONFIG",
")",
"_request_app_setup",
"(",
"hass",
",",
"config",
")",
"return",
"True",
"if",
"DOMAIN",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configuring\"",
"]",
":",
"_configurator",
"=",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configuring\"",
"]",
"hass",
".",
"components",
".",
"configurator",
".",
"request_done",
"(",
"_configurator",
".",
"pop",
"(",
"DOMAIN",
")",
")",
"# Using oauth",
"access_token",
"=",
"config_file",
".",
"get",
"(",
"ATTR_ACCESS_TOKEN",
")",
"refresh_token",
"=",
"config_file",
".",
"get",
"(",
"ATTR_REFRESH_TOKEN",
")",
"# This will be called after authorizing Home-Assistant",
"if",
"None",
"not",
"in",
"(",
"access_token",
",",
"refresh_token",
")",
":",
"pywink",
".",
"set_wink_credentials",
"(",
"config_file",
".",
"get",
"(",
"CONF_CLIENT_ID",
")",
",",
"config_file",
".",
"get",
"(",
"CONF_CLIENT_SECRET",
")",
",",
"access_token",
"=",
"access_token",
",",
"refresh_token",
"=",
"refresh_token",
",",
")",
"# This is called to create the redirect so the user can Authorize",
"# Home .",
"else",
":",
"redirect_uri",
"=",
"f\"{get_url(hass)}{WINK_AUTH_CALLBACK_PATH}\"",
"wink_auth_start_url",
"=",
"pywink",
".",
"get_authorization_url",
"(",
"config_file",
".",
"get",
"(",
"CONF_CLIENT_ID",
")",
",",
"redirect_uri",
")",
"hass",
".",
"http",
".",
"register_redirect",
"(",
"WINK_AUTH_START",
",",
"wink_auth_start_url",
")",
"hass",
".",
"http",
".",
"register_view",
"(",
"WinkAuthCallbackView",
"(",
"config",
",",
"config_file",
",",
"pywink",
".",
"request_token",
")",
")",
"_request_oauth_completion",
"(",
"hass",
",",
"config",
")",
"return",
"True",
"pywink",
".",
"set_user_agent",
"(",
"USER_AGENT",
")",
"sub_details",
"=",
"pywink",
".",
"get_subscription_details",
"(",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"pubnub\"",
"]",
"=",
"PubNubSubscriptionHandler",
"(",
"sub_details",
"[",
"0",
"]",
",",
"origin",
"=",
"sub_details",
"[",
"1",
"]",
")",
"def",
"_subscribe",
"(",
")",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"pubnub\"",
"]",
".",
"subscribe",
"(",
")",
"# Call subscribe after the user sets up wink via the configurator",
"# All other methods will complete setup before",
"# EVENT_HOMEASSISTANT_START is called meaning they",
"# will call subscribe via the method below. (start_subscription)",
"if",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"configurator\"",
"]",
":",
"_subscribe",
"(",
")",
"def",
"keep_alive_call",
"(",
"event_time",
")",
":",
"\"\"\"Call the Wink API endpoints to keep PubNub working.\"\"\"",
"_LOGGER",
".",
"info",
"(",
"\"Polling the Wink API to keep PubNub updates flowing\"",
")",
"pywink",
".",
"set_user_agent",
"(",
"str",
"(",
"int",
"(",
"time",
".",
"time",
"(",
")",
")",
")",
")",
"_temp_response",
"=",
"pywink",
".",
"get_user",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"str",
"(",
"json",
".",
"dumps",
"(",
"_temp_response",
")",
")",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"pywink",
".",
"set_user_agent",
"(",
"USER_AGENT",
")",
"_temp_response",
"=",
"pywink",
".",
"wink_api_fetch",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"%s\"",
",",
"_temp_response",
")",
"_temp_response",
"=",
"pywink",
".",
"post_session",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"%s\"",
",",
"_temp_response",
")",
"# Call the Wink API every hour to keep PubNub updates flowing",
"track_time_interval",
"(",
"hass",
",",
"keep_alive_call",
",",
"timedelta",
"(",
"minutes",
"=",
"60",
")",
")",
"def",
"start_subscription",
"(",
"event",
")",
":",
"\"\"\"Start the PubNub subscription.\"\"\"",
"_subscribe",
"(",
")",
"hass",
".",
"bus",
".",
"listen",
"(",
"EVENT_HOMEASSISTANT_START",
",",
"start_subscription",
")",
"def",
"stop_subscription",
"(",
"event",
")",
":",
"\"\"\"Stop the PubNub subscription.\"\"\"",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"pubnub\"",
"]",
".",
"unsubscribe",
"(",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"pubnub\"",
"]",
"=",
"None",
"hass",
".",
"bus",
".",
"listen",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"stop_subscription",
")",
"def",
"save_credentials",
"(",
"event",
")",
":",
"\"\"\"Save currently set OAuth credentials.\"\"\"",
"if",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"oauth\"",
"]",
".",
"get",
"(",
"\"email\"",
")",
"is",
"None",
":",
"config_path",
"=",
"hass",
".",
"config",
".",
"path",
"(",
"WINK_CONFIG_FILE",
")",
"_config",
"=",
"pywink",
".",
"get_current_oauth_credentials",
"(",
")",
"save_json",
"(",
"config_path",
",",
"_config",
")",
"hass",
".",
"bus",
".",
"listen",
"(",
"EVENT_HOMEASSISTANT_STOP",
",",
"save_credentials",
")",
"# Save the users potentially updated oauth credentials at a regular",
"# interval to prevent them from being expired after a HA reboot.",
"track_time_interval",
"(",
"hass",
",",
"save_credentials",
",",
"timedelta",
"(",
"minutes",
"=",
"60",
")",
")",
"def",
"force_update",
"(",
"call",
")",
":",
"\"\"\"Force all devices to poll the Wink API.\"\"\"",
"_LOGGER",
".",
"info",
"(",
"\"Refreshing Wink states from API\"",
")",
"for",
"entity_list",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
".",
"values",
"(",
")",
":",
"# Throttle the calls to Wink API",
"for",
"entity",
"in",
"entity_list",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"entity",
".",
"schedule_update_ha_state",
"(",
"True",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_REFRESH_STATES",
",",
"force_update",
")",
"def",
"pull_new_devices",
"(",
"call",
")",
":",
"\"\"\"Pull new devices added to users Wink account since startup.\"\"\"",
"_LOGGER",
".",
"info",
"(",
"\"Getting new devices from Wink API\"",
")",
"for",
"_component",
"in",
"WINK_COMPONENTS",
":",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"_component",
",",
"DOMAIN",
",",
"{",
"}",
",",
"config",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_ADD_NEW_DEVICES",
",",
"pull_new_devices",
")",
"def",
"set_pairing_mode",
"(",
"call",
")",
":",
"\"\"\"Put the hub in provided pairing mode.\"\"\"",
"hub_name",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"hub_name\"",
")",
"pairing_mode",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"pairing_mode\"",
")",
"kidde_code",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"kidde_radio_code\"",
")",
"for",
"hub",
"in",
"WINK_HUBS",
":",
"if",
"hub",
".",
"name",
"(",
")",
"==",
"hub_name",
":",
"hub",
".",
"pair_new_device",
"(",
"pairing_mode",
",",
"kidde_radio_code",
"=",
"kidde_code",
")",
"def",
"rename_device",
"(",
"call",
")",
":",
"\"\"\"Set specified device's name.\"\"\"",
"# This should only be called on one device at a time.",
"found_device",
"=",
"None",
"entity_id",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"entity_id\"",
")",
"[",
"0",
"]",
"all_devices",
"=",
"[",
"]",
"for",
"list_of_devices",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
".",
"values",
"(",
")",
":",
"all_devices",
"+=",
"list_of_devices",
"for",
"device",
"in",
"all_devices",
":",
"if",
"device",
".",
"entity_id",
"==",
"entity_id",
":",
"found_device",
"=",
"device",
"if",
"found_device",
"is",
"not",
"None",
":",
"name",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"name\"",
")",
"found_device",
".",
"wink",
".",
"set_name",
"(",
"name",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_RENAME_DEVICE",
",",
"rename_device",
",",
"schema",
"=",
"RENAME_DEVICE_SCHEMA",
")",
"def",
"delete_device",
"(",
"call",
")",
":",
"\"\"\"Delete specified device.\"\"\"",
"# This should only be called on one device at a time.",
"found_device",
"=",
"None",
"entity_id",
"=",
"call",
".",
"data",
".",
"get",
"(",
"\"entity_id\"",
")",
"[",
"0",
"]",
"all_devices",
"=",
"[",
"]",
"for",
"list_of_devices",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
".",
"values",
"(",
")",
":",
"all_devices",
"+=",
"list_of_devices",
"for",
"device",
"in",
"all_devices",
":",
"if",
"device",
".",
"entity_id",
"==",
"entity_id",
":",
"found_device",
"=",
"device",
"if",
"found_device",
"is",
"not",
"None",
":",
"found_device",
".",
"wink",
".",
"remove_device",
"(",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_DELETE_DEVICE",
",",
"delete_device",
",",
"schema",
"=",
"DELETE_DEVICE_SCHEMA",
")",
"hubs",
"=",
"pywink",
".",
"get_hubs",
"(",
")",
"for",
"hub",
"in",
"hubs",
":",
"if",
"hub",
".",
"device_manufacturer",
"(",
")",
"==",
"\"wink\"",
":",
"WINK_HUBS",
".",
"append",
"(",
"hub",
")",
"if",
"WINK_HUBS",
":",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_PAIRING_MODE",
",",
"set_pairing_mode",
",",
"schema",
"=",
"SET_PAIRING_MODE_SCHEMA",
",",
")",
"def",
"nimbus_service_handle",
"(",
"service",
")",
":",
"\"\"\"Handle nimbus services.\"\"\"",
"entity_id",
"=",
"service",
".",
"data",
".",
"get",
"(",
"\"entity_id\"",
")",
"[",
"0",
"]",
"_all_dials",
"=",
"[",
"]",
"for",
"sensor",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
"[",
"\"sensor\"",
"]",
":",
"if",
"isinstance",
"(",
"sensor",
",",
"WinkNimbusDialDevice",
")",
":",
"_all_dials",
".",
"append",
"(",
"sensor",
")",
"for",
"_dial",
"in",
"_all_dials",
":",
"if",
"_dial",
".",
"entity_id",
"==",
"entity_id",
":",
"if",
"service",
".",
"service",
"==",
"SERVICE_SET_DIAL_CONFIG",
":",
"_dial",
".",
"set_configuration",
"(",
"*",
"*",
"service",
".",
"data",
")",
"if",
"service",
".",
"service",
"==",
"SERVICE_SET_DIAL_STATE",
":",
"_dial",
".",
"wink",
".",
"set_state",
"(",
"service",
".",
"data",
".",
"get",
"(",
"\"value\"",
")",
",",
"service",
".",
"data",
".",
"get",
"(",
"\"labels\"",
")",
")",
"def",
"siren_service_handle",
"(",
"service",
")",
":",
"\"\"\"Handle siren services.\"\"\"",
"entity_ids",
"=",
"service",
".",
"data",
".",
"get",
"(",
"\"entity_id\"",
")",
"all_sirens",
"=",
"[",
"]",
"for",
"switch",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
"[",
"\"switch\"",
"]",
":",
"if",
"isinstance",
"(",
"switch",
",",
"WinkSirenDevice",
")",
":",
"all_sirens",
".",
"append",
"(",
"switch",
")",
"sirens_to_set",
"=",
"[",
"]",
"if",
"entity_ids",
"is",
"None",
":",
"sirens_to_set",
"=",
"all_sirens",
"else",
":",
"for",
"siren",
"in",
"all_sirens",
":",
"if",
"siren",
".",
"entity_id",
"in",
"entity_ids",
":",
"sirens_to_set",
".",
"append",
"(",
"siren",
")",
"for",
"siren",
"in",
"sirens_to_set",
":",
"_man",
"=",
"siren",
".",
"wink",
".",
"device_manufacturer",
"(",
")",
"if",
"(",
"service",
".",
"service",
"!=",
"SERVICE_SET_AUTO_SHUTOFF",
"and",
"service",
".",
"service",
"!=",
"SERVICE_ENABLE_SIREN",
"and",
"_man",
"not",
"in",
"(",
"\"dome\"",
",",
"\"wink\"",
")",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Service only valid for Dome or Wink sirens\"",
")",
"return",
"if",
"service",
".",
"service",
"==",
"SERVICE_ENABLE_SIREN",
":",
"siren",
".",
"wink",
".",
"set_state",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ENABLED",
")",
")",
"elif",
"service",
".",
"service",
"==",
"SERVICE_SET_AUTO_SHUTOFF",
":",
"siren",
".",
"wink",
".",
"set_auto_shutoff",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_AUTO_SHUTOFF",
")",
")",
"elif",
"service",
".",
"service",
"==",
"SERVICE_SET_CHIME_VOLUME",
":",
"siren",
".",
"wink",
".",
"set_chime_volume",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_VOLUME",
")",
")",
"elif",
"service",
".",
"service",
"==",
"SERVICE_SET_SIREN_VOLUME",
":",
"siren",
".",
"wink",
".",
"set_siren_volume",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_VOLUME",
")",
")",
"elif",
"service",
".",
"service",
"==",
"SERVICE_SET_SIREN_TONE",
":",
"siren",
".",
"wink",
".",
"set_siren_sound",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_TONE",
")",
")",
"elif",
"service",
".",
"service",
"==",
"SERVICE_ENABLE_CHIME",
":",
"siren",
".",
"wink",
".",
"set_chime",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_TONE",
")",
")",
"elif",
"service",
".",
"service",
"==",
"SERVICE_SIREN_STROBE_ENABLED",
":",
"siren",
".",
"wink",
".",
"set_siren_strobe_enabled",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ENABLED",
")",
")",
"elif",
"service",
".",
"service",
"==",
"SERVICE_CHIME_STROBE_ENABLED",
":",
"siren",
".",
"wink",
".",
"set_chime_strobe_enabled",
"(",
"service",
".",
"data",
".",
"get",
"(",
"ATTR_ENABLED",
")",
")",
"# Load components for the devices in Wink that we support",
"for",
"wink_component",
"in",
"WINK_COMPONENTS",
":",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
"[",
"wink_component",
"]",
"=",
"[",
"]",
"discovery",
".",
"load_platform",
"(",
"hass",
",",
"wink_component",
",",
"DOMAIN",
",",
"{",
"}",
",",
"config",
")",
"component",
"=",
"EntityComponent",
"(",
"_LOGGER",
",",
"DOMAIN",
",",
"hass",
")",
"sirens",
"=",
"[",
"]",
"has_dome_or_wink_siren",
"=",
"False",
"for",
"siren",
"in",
"pywink",
".",
"get_sirens",
"(",
")",
":",
"_man",
"=",
"siren",
".",
"device_manufacturer",
"(",
")",
"if",
"_man",
"in",
"(",
"\"dome\"",
",",
"\"wink\"",
")",
":",
"has_dome_or_wink_siren",
"=",
"True",
"_id",
"=",
"siren",
".",
"object_id",
"(",
")",
"+",
"siren",
".",
"name",
"(",
")",
"if",
"_id",
"not",
"in",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"unique_ids\"",
"]",
":",
"sirens",
".",
"append",
"(",
"WinkSirenDevice",
"(",
"siren",
",",
"hass",
")",
")",
"if",
"sirens",
":",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_AUTO_SHUTOFF",
",",
"siren_service_handle",
",",
"schema",
"=",
"SET_AUTO_SHUTOFF_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_ENABLE_SIREN",
",",
"siren_service_handle",
",",
"schema",
"=",
"ENABLED_SIREN_SCHEMA",
",",
")",
"if",
"has_dome_or_wink_siren",
":",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_SIREN_TONE",
",",
"siren_service_handle",
",",
"schema",
"=",
"SET_SIREN_TONE_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_ENABLE_CHIME",
",",
"siren_service_handle",
",",
"schema",
"=",
"SET_CHIME_MODE_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_SIREN_VOLUME",
",",
"siren_service_handle",
",",
"schema",
"=",
"SET_VOLUME_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_CHIME_VOLUME",
",",
"siren_service_handle",
",",
"schema",
"=",
"SET_VOLUME_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SIREN_STROBE_ENABLED",
",",
"siren_service_handle",
",",
"schema",
"=",
"SET_STROBE_ENABLED_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_CHIME_STROBE_ENABLED",
",",
"siren_service_handle",
",",
"schema",
"=",
"SET_STROBE_ENABLED_SCHEMA",
",",
")",
"component",
".",
"add_entities",
"(",
"sirens",
")",
"nimbi",
"=",
"[",
"]",
"dials",
"=",
"{",
"}",
"all_nimbi",
"=",
"pywink",
".",
"get_cloud_clocks",
"(",
")",
"all_dials",
"=",
"[",
"]",
"for",
"nimbus",
"in",
"all_nimbi",
":",
"if",
"nimbus",
".",
"object_type",
"(",
")",
"==",
"\"cloud_clock\"",
":",
"nimbi",
".",
"append",
"(",
"nimbus",
")",
"dials",
"[",
"nimbus",
".",
"object_id",
"(",
")",
"]",
"=",
"[",
"]",
"for",
"nimbus",
"in",
"all_nimbi",
":",
"if",
"nimbus",
".",
"object_type",
"(",
")",
"==",
"\"dial\"",
":",
"dials",
"[",
"nimbus",
".",
"parent_id",
"(",
")",
"]",
".",
"append",
"(",
"nimbus",
")",
"for",
"nimbus",
"in",
"nimbi",
":",
"for",
"dial",
"in",
"dials",
"[",
"nimbus",
".",
"object_id",
"(",
")",
"]",
":",
"all_dials",
".",
"append",
"(",
"WinkNimbusDialDevice",
"(",
"nimbus",
",",
"dial",
",",
"hass",
")",
")",
"if",
"nimbi",
":",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_DIAL_CONFIG",
",",
"nimbus_service_handle",
",",
"schema",
"=",
"DIAL_CONFIG_SCHEMA",
",",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_SET_DIAL_STATE",
",",
"nimbus_service_handle",
",",
"schema",
"=",
"DIAL_STATE_SCHEMA",
",",
")",
"component",
".",
"add_entities",
"(",
"all_dials",
")",
"return",
"True"
] | [
282,
0
] | [
671,
15
] | python | en | ['en', 'en', 'en'] | True |
WinkAuthCallbackView.__init__ | (self, config, config_file, request_token) | Initialize the OAuth callback view. | Initialize the OAuth callback view. | def __init__(self, config, config_file, request_token):
"""Initialize the OAuth callback view."""
self.config = config
self.config_file = config_file
self.request_token = request_token | [
"def",
"__init__",
"(",
"self",
",",
"config",
",",
"config_file",
",",
"request_token",
")",
":",
"self",
".",
"config",
"=",
"config",
"self",
".",
"config_file",
"=",
"config_file",
"self",
".",
"request_token",
"=",
"request_token"
] | [
681,
4
] | [
685,
42
] | python | en | ['en', 'en', 'en'] | True |
WinkAuthCallbackView.get | (self, request) | Finish OAuth callback request. | Finish OAuth callback request. | def get(self, request):
"""Finish OAuth callback request."""
hass = request.app["hass"]
data = request.query
response_message = """Wink has been successfully authorized!
You can close this window now! For the best results you should reboot
Home Assistant"""
html_response = """<html><head><title>Wink Auth</title></head>
<body><h1>{}</h1></body></html>"""
if data.get("code") is not None:
response = self.request_token(
data.get("code"), self.config_file[CONF_CLIENT_SECRET]
)
config_contents = {
ATTR_ACCESS_TOKEN: response["access_token"],
ATTR_REFRESH_TOKEN: response["refresh_token"],
CONF_CLIENT_ID: self.config_file[CONF_CLIENT_ID],
CONF_CLIENT_SECRET: self.config_file[CONF_CLIENT_SECRET],
}
save_json(hass.config.path(WINK_CONFIG_FILE), config_contents)
hass.async_add_job(setup, hass, self.config)
return Response(
text=html_response.format(response_message), content_type="text/html"
)
error_msg = "No code returned from Wink API"
_LOGGER.error(error_msg)
return Response(text=html_response.format(error_msg), content_type="text/html") | [
"def",
"get",
"(",
"self",
",",
"request",
")",
":",
"hass",
"=",
"request",
".",
"app",
"[",
"\"hass\"",
"]",
"data",
"=",
"request",
".",
"query",
"response_message",
"=",
"\"\"\"Wink has been successfully authorized!\n You can close this window now! For the best results you should reboot\n Home Assistant\"\"\"",
"html_response",
"=",
"\"\"\"<html><head><title>Wink Auth</title></head>\n <body><h1>{}</h1></body></html>\"\"\"",
"if",
"data",
".",
"get",
"(",
"\"code\"",
")",
"is",
"not",
"None",
":",
"response",
"=",
"self",
".",
"request_token",
"(",
"data",
".",
"get",
"(",
"\"code\"",
")",
",",
"self",
".",
"config_file",
"[",
"CONF_CLIENT_SECRET",
"]",
")",
"config_contents",
"=",
"{",
"ATTR_ACCESS_TOKEN",
":",
"response",
"[",
"\"access_token\"",
"]",
",",
"ATTR_REFRESH_TOKEN",
":",
"response",
"[",
"\"refresh_token\"",
"]",
",",
"CONF_CLIENT_ID",
":",
"self",
".",
"config_file",
"[",
"CONF_CLIENT_ID",
"]",
",",
"CONF_CLIENT_SECRET",
":",
"self",
".",
"config_file",
"[",
"CONF_CLIENT_SECRET",
"]",
",",
"}",
"save_json",
"(",
"hass",
".",
"config",
".",
"path",
"(",
"WINK_CONFIG_FILE",
")",
",",
"config_contents",
")",
"hass",
".",
"async_add_job",
"(",
"setup",
",",
"hass",
",",
"self",
".",
"config",
")",
"return",
"Response",
"(",
"text",
"=",
"html_response",
".",
"format",
"(",
"response_message",
")",
",",
"content_type",
"=",
"\"text/html\"",
")",
"error_msg",
"=",
"\"No code returned from Wink API\"",
"_LOGGER",
".",
"error",
"(",
"error_msg",
")",
"return",
"Response",
"(",
"text",
"=",
"html_response",
".",
"format",
"(",
"error_msg",
")",
",",
"content_type",
"=",
"\"text/html\"",
")"
] | [
688,
4
] | [
720,
87
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice.__init__ | (self, wink, hass) | Initialize the Wink device. | Initialize the Wink device. | def __init__(self, wink, hass):
"""Initialize the Wink device."""
self.hass = hass
self.wink = wink
hass.data[DOMAIN]["pubnub"].add_subscription(
self.wink.pubnub_channel, self._pubnub_update
)
hass.data[DOMAIN]["unique_ids"].append(self.wink.object_id() + self.wink.name()) | [
"def",
"__init__",
"(",
"self",
",",
"wink",
",",
"hass",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"wink",
"=",
"wink",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"pubnub\"",
"]",
".",
"add_subscription",
"(",
"self",
".",
"wink",
".",
"pubnub_channel",
",",
"self",
".",
"_pubnub_update",
")",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"unique_ids\"",
"]",
".",
"append",
"(",
"self",
".",
"wink",
".",
"object_id",
"(",
")",
"+",
"self",
".",
"wink",
".",
"name",
"(",
")",
")"
] | [
726,
4
] | [
733,
88
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return self.wink.name() | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"name",
"(",
")"
] | [
754,
4
] | [
756,
31
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice.unique_id | (self) | Return the unique id of the Wink device. | Return the unique id of the Wink device. | def unique_id(self):
"""Return the unique id of the Wink device."""
if hasattr(self.wink, "capability") and self.wink.capability() is not None:
return f"{self.wink.object_id()}_{self.wink.capability()}"
return self.wink.object_id() | [
"def",
"unique_id",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"wink",
",",
"\"capability\"",
")",
"and",
"self",
".",
"wink",
".",
"capability",
"(",
")",
"is",
"not",
"None",
":",
"return",
"f\"{self.wink.object_id()}_{self.wink.capability()}\"",
"return",
"self",
".",
"wink",
".",
"object_id",
"(",
")"
] | [
759,
4
] | [
763,
36
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice.available | (self) | Return true if connection == True. | Return true if connection == True. | def available(self):
"""Return true if connection == True."""
return self.wink.available() | [
"def",
"available",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"available",
"(",
")"
] | [
766,
4
] | [
768,
36
] | python | en | ['en', 'de', 'en'] | True |
WinkDevice.update | (self) | Update state of the device. | Update state of the device. | def update(self):
"""Update state of the device."""
self.wink.update_state() | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"wink",
".",
"update_state",
"(",
")"
] | [
770,
4
] | [
772,
32
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice.should_poll | (self) | Only poll if we are not subscribed to pubnub. | Only poll if we are not subscribed to pubnub. | def should_poll(self):
"""Only poll if we are not subscribed to pubnub."""
return self.wink.pubnub_channel is None | [
"def",
"should_poll",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"pubnub_channel",
"is",
"None"
] | [
775,
4
] | [
777,
47
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice.device_state_attributes | (self) | Return the state attributes. | Return the state attributes. | def device_state_attributes(self):
"""Return the state attributes."""
attributes = {}
battery = self._battery_level
if battery:
attributes[ATTR_BATTERY_LEVEL] = battery
man_dev_model = self._manufacturer_device_model
if man_dev_model:
attributes["manufacturer_device_model"] = man_dev_model
man_dev_id = self._manufacturer_device_id
if man_dev_id:
attributes["manufacturer_device_id"] = man_dev_id
dev_man = self._device_manufacturer
if dev_man:
attributes["device_manufacturer"] = dev_man
model_name = self._model_name
if model_name:
attributes["model_name"] = model_name
tamper = self._tamper
if tamper is not None:
attributes["tamper_detected"] = tamper
return attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attributes",
"=",
"{",
"}",
"battery",
"=",
"self",
".",
"_battery_level",
"if",
"battery",
":",
"attributes",
"[",
"ATTR_BATTERY_LEVEL",
"]",
"=",
"battery",
"man_dev_model",
"=",
"self",
".",
"_manufacturer_device_model",
"if",
"man_dev_model",
":",
"attributes",
"[",
"\"manufacturer_device_model\"",
"]",
"=",
"man_dev_model",
"man_dev_id",
"=",
"self",
".",
"_manufacturer_device_id",
"if",
"man_dev_id",
":",
"attributes",
"[",
"\"manufacturer_device_id\"",
"]",
"=",
"man_dev_id",
"dev_man",
"=",
"self",
".",
"_device_manufacturer",
"if",
"dev_man",
":",
"attributes",
"[",
"\"device_manufacturer\"",
"]",
"=",
"dev_man",
"model_name",
"=",
"self",
".",
"_model_name",
"if",
"model_name",
":",
"attributes",
"[",
"\"model_name\"",
"]",
"=",
"model_name",
"tamper",
"=",
"self",
".",
"_tamper",
"if",
"tamper",
"is",
"not",
"None",
":",
"attributes",
"[",
"\"tamper_detected\"",
"]",
"=",
"tamper",
"return",
"attributes"
] | [
780,
4
] | [
801,
25
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice._battery_level | (self) | Return the battery level. | Return the battery level. | def _battery_level(self):
"""Return the battery level."""
if self.wink.battery_level() is not None:
return self.wink.battery_level() * 100 | [
"def",
"_battery_level",
"(",
"self",
")",
":",
"if",
"self",
".",
"wink",
".",
"battery_level",
"(",
")",
"is",
"not",
"None",
":",
"return",
"self",
".",
"wink",
".",
"battery_level",
"(",
")",
"*",
"100"
] | [
804,
4
] | [
807,
50
] | python | en | ['en', 'no', 'en'] | True |
WinkDevice._manufacturer_device_model | (self) | Return the manufacturer device model. | Return the manufacturer device model. | def _manufacturer_device_model(self):
"""Return the manufacturer device model."""
return self.wink.manufacturer_device_model() | [
"def",
"_manufacturer_device_model",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"manufacturer_device_model",
"(",
")"
] | [
810,
4
] | [
812,
52
] | python | en | ['en', 'da', 'en'] | True |
WinkDevice._manufacturer_device_id | (self) | Return the manufacturer device id. | Return the manufacturer device id. | def _manufacturer_device_id(self):
"""Return the manufacturer device id."""
return self.wink.manufacturer_device_id() | [
"def",
"_manufacturer_device_id",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"manufacturer_device_id",
"(",
")"
] | [
815,
4
] | [
817,
49
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice._device_manufacturer | (self) | Return the device manufacturer. | Return the device manufacturer. | def _device_manufacturer(self):
"""Return the device manufacturer."""
return self.wink.device_manufacturer() | [
"def",
"_device_manufacturer",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"device_manufacturer",
"(",
")"
] | [
820,
4
] | [
822,
46
] | python | en | ['en', 'en', 'en'] | True |
WinkDevice._model_name | (self) | Return the model name. | Return the model name. | def _model_name(self):
"""Return the model name."""
return self.wink.model_name() | [
"def",
"_model_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"model_name",
"(",
")"
] | [
825,
4
] | [
827,
37
] | python | en | ['en', 'ig', 'en'] | True |
WinkDevice._tamper | (self) | Return the devices tamper status. | Return the devices tamper status. | def _tamper(self):
"""Return the devices tamper status."""
if hasattr(self.wink, "tamper_detected"):
return self.wink.tamper_detected()
return None | [
"def",
"_tamper",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"wink",
",",
"\"tamper_detected\"",
")",
":",
"return",
"self",
".",
"wink",
".",
"tamper_detected",
"(",
")",
"return",
"None"
] | [
830,
4
] | [
834,
19
] | python | en | ['en', 'en', 'en'] | True |
WinkSirenDevice.async_added_to_hass | (self) | Call when entity is added to hass. | Call when entity is added to hass. | async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.data[DOMAIN]["entities"]["switch"].append(self) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
"[",
"\"switch\"",
"]",
".",
"append",
"(",
"self",
")"
] | [
840,
4
] | [
842,
65
] | python | en | ['en', 'en', 'en'] | True |
WinkSirenDevice.state | (self) | Return sirens state. | Return sirens state. | def state(self):
"""Return sirens state."""
if self.wink.state():
return STATE_ON
return STATE_OFF | [
"def",
"state",
"(",
"self",
")",
":",
"if",
"self",
".",
"wink",
".",
"state",
"(",
")",
":",
"return",
"STATE_ON",
"return",
"STATE_OFF"
] | [
845,
4
] | [
849,
24
] | python | en | ['no', 'ig', 'en'] | False |
WinkSirenDevice.icon | (self) | Return the icon to use in the frontend, if any. | Return the icon to use in the frontend, if any. | def icon(self):
"""Return the icon to use in the frontend, if any."""
return "mdi:bell-ring" | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"\"mdi:bell-ring\""
] | [
852,
4
] | [
854,
30
] | python | en | ['en', 'en', 'en'] | True |
WinkSirenDevice.device_state_attributes | (self) | Return the device state attributes. | Return the device state attributes. | def device_state_attributes(self):
"""Return the device state attributes."""
attributes = super().device_state_attributes
auto_shutoff = self.wink.auto_shutoff()
if auto_shutoff is not None:
attributes["auto_shutoff"] = auto_shutoff
siren_volume = self.wink.siren_volume()
if siren_volume is not None:
attributes["siren_volume"] = siren_volume
chime_volume = self.wink.chime_volume()
if chime_volume is not None:
attributes["chime_volume"] = chime_volume
strobe_enabled = self.wink.strobe_enabled()
if strobe_enabled is not None:
attributes["siren_strobe_enabled"] = strobe_enabled
chime_strobe_enabled = self.wink.chime_strobe_enabled()
if chime_strobe_enabled is not None:
attributes["chime_strobe_enabled"] = chime_strobe_enabled
siren_sound = self.wink.siren_sound()
if siren_sound is not None:
attributes["siren_sound"] = siren_sound
chime_mode = self.wink.chime_mode()
if chime_mode is not None:
attributes["chime_mode"] = chime_mode
return attributes | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attributes",
"=",
"super",
"(",
")",
".",
"device_state_attributes",
"auto_shutoff",
"=",
"self",
".",
"wink",
".",
"auto_shutoff",
"(",
")",
"if",
"auto_shutoff",
"is",
"not",
"None",
":",
"attributes",
"[",
"\"auto_shutoff\"",
"]",
"=",
"auto_shutoff",
"siren_volume",
"=",
"self",
".",
"wink",
".",
"siren_volume",
"(",
")",
"if",
"siren_volume",
"is",
"not",
"None",
":",
"attributes",
"[",
"\"siren_volume\"",
"]",
"=",
"siren_volume",
"chime_volume",
"=",
"self",
".",
"wink",
".",
"chime_volume",
"(",
")",
"if",
"chime_volume",
"is",
"not",
"None",
":",
"attributes",
"[",
"\"chime_volume\"",
"]",
"=",
"chime_volume",
"strobe_enabled",
"=",
"self",
".",
"wink",
".",
"strobe_enabled",
"(",
")",
"if",
"strobe_enabled",
"is",
"not",
"None",
":",
"attributes",
"[",
"\"siren_strobe_enabled\"",
"]",
"=",
"strobe_enabled",
"chime_strobe_enabled",
"=",
"self",
".",
"wink",
".",
"chime_strobe_enabled",
"(",
")",
"if",
"chime_strobe_enabled",
"is",
"not",
"None",
":",
"attributes",
"[",
"\"chime_strobe_enabled\"",
"]",
"=",
"chime_strobe_enabled",
"siren_sound",
"=",
"self",
".",
"wink",
".",
"siren_sound",
"(",
")",
"if",
"siren_sound",
"is",
"not",
"None",
":",
"attributes",
"[",
"\"siren_sound\"",
"]",
"=",
"siren_sound",
"chime_mode",
"=",
"self",
".",
"wink",
".",
"chime_mode",
"(",
")",
"if",
"chime_mode",
"is",
"not",
"None",
":",
"attributes",
"[",
"\"chime_mode\"",
"]",
"=",
"chime_mode",
"return",
"attributes"
] | [
857,
4
] | [
889,
25
] | python | en | ['en', 'en', 'en'] | True |
WinkNimbusDialDevice.__init__ | (self, nimbus, dial, hass) | Initialize the Nimbus dial. | Initialize the Nimbus dial. | def __init__(self, nimbus, dial, hass):
"""Initialize the Nimbus dial."""
super().__init__(dial, hass)
self.parent = nimbus | [
"def",
"__init__",
"(",
"self",
",",
"nimbus",
",",
"dial",
",",
"hass",
")",
":",
"super",
"(",
")",
".",
"__init__",
"(",
"dial",
",",
"hass",
")",
"self",
".",
"parent",
"=",
"nimbus"
] | [
895,
4
] | [
898,
28
] | python | en | ['en', 'en', 'en'] | True |
WinkNimbusDialDevice.async_added_to_hass | (self) | Call when entity is added to hass. | Call when entity is added to hass. | async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self.hass.data[DOMAIN]["entities"]["sensor"].append(self) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"[",
"\"entities\"",
"]",
"[",
"\"sensor\"",
"]",
".",
"append",
"(",
"self",
")"
] | [
900,
4
] | [
902,
65
] | python | en | ['en', 'en', 'en'] | True |
WinkNimbusDialDevice.state | (self) | Return dials current value. | Return dials current value. | def state(self):
"""Return dials current value."""
return self.wink.state() | [
"def",
"state",
"(",
"self",
")",
":",
"return",
"self",
".",
"wink",
".",
"state",
"(",
")"
] | [
905,
4
] | [
907,
32
] | python | ca | ['nl', 'ca', 'en'] | False |
WinkNimbusDialDevice.name | (self) | Return the name of the device. | Return the name of the device. | def name(self):
"""Return the name of the device."""
return f"{self.parent.name()} dial {self.wink.index() + 1}" | [
"def",
"name",
"(",
"self",
")",
":",
"return",
"f\"{self.parent.name()} dial {self.wink.index() + 1}\""
] | [
910,
4
] | [
912,
67
] | python | en | ['en', 'en', 'en'] | True |
WinkNimbusDialDevice.device_state_attributes | (self) | Return the device state attributes. | Return the device state attributes. | def device_state_attributes(self):
"""Return the device state attributes."""
attributes = super().device_state_attributes
dial_attributes = self.dial_attributes()
return {**attributes, **dial_attributes} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"attributes",
"=",
"super",
"(",
")",
".",
"device_state_attributes",
"dial_attributes",
"=",
"self",
".",
"dial_attributes",
"(",
")",
"return",
"{",
"*",
"*",
"attributes",
",",
"*",
"*",
"dial_attributes",
"}"
] | [
915,
4
] | [
920,
48
] | python | en | ['en', 'en', 'en'] | True |
WinkNimbusDialDevice.dial_attributes | (self) | Return the dial only attributes. | Return the dial only attributes. | def dial_attributes(self):
"""Return the dial only attributes."""
return {
"labels": self.wink.labels(),
"position": self.wink.position(),
"rotation": self.wink.rotation(),
"max_value": self.wink.max_value(),
"min_value": self.wink.min_value(),
"num_ticks": self.wink.ticks(),
"scale_type": self.wink.scale(),
"max_position": self.wink.max_position(),
"min_position": self.wink.min_position(),
} | [
"def",
"dial_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"labels\"",
":",
"self",
".",
"wink",
".",
"labels",
"(",
")",
",",
"\"position\"",
":",
"self",
".",
"wink",
".",
"position",
"(",
")",
",",
"\"rotation\"",
":",
"self",
".",
"wink",
".",
"rotation",
"(",
")",
",",
"\"max_value\"",
":",
"self",
".",
"wink",
".",
"max_value",
"(",
")",
",",
"\"min_value\"",
":",
"self",
".",
"wink",
".",
"min_value",
"(",
")",
",",
"\"num_ticks\"",
":",
"self",
".",
"wink",
".",
"ticks",
"(",
")",
",",
"\"scale_type\"",
":",
"self",
".",
"wink",
".",
"scale",
"(",
")",
",",
"\"max_position\"",
":",
"self",
".",
"wink",
".",
"max_position",
"(",
")",
",",
"\"min_position\"",
":",
"self",
".",
"wink",
".",
"min_position",
"(",
")",
",",
"}"
] | [
922,
4
] | [
934,
9
] | python | en | ['en', 'en', 'en'] | True |
WinkNimbusDialDevice.set_configuration | (self, **kwargs) |
Set the dial config.
Anything not sent will default to current setting.
|
Set the dial config. | def set_configuration(self, **kwargs):
"""
Set the dial config.
Anything not sent will default to current setting.
"""
attributes = {**self.dial_attributes(), **kwargs}
min_value = attributes["min_value"]
max_value = attributes["max_value"]
rotation = attributes["rotation"]
ticks = attributes["num_ticks"]
scale = attributes["scale_type"]
min_position = attributes["min_position"]
max_position = attributes["max_position"]
self.wink.set_configuration(
min_value,
max_value,
rotation,
scale=scale,
ticks=ticks,
min_position=min_position,
max_position=max_position,
) | [
"def",
"set_configuration",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"attributes",
"=",
"{",
"*",
"*",
"self",
".",
"dial_attributes",
"(",
")",
",",
"*",
"*",
"kwargs",
"}",
"min_value",
"=",
"attributes",
"[",
"\"min_value\"",
"]",
"max_value",
"=",
"attributes",
"[",
"\"max_value\"",
"]",
"rotation",
"=",
"attributes",
"[",
"\"rotation\"",
"]",
"ticks",
"=",
"attributes",
"[",
"\"num_ticks\"",
"]",
"scale",
"=",
"attributes",
"[",
"\"scale_type\"",
"]",
"min_position",
"=",
"attributes",
"[",
"\"min_position\"",
"]",
"max_position",
"=",
"attributes",
"[",
"\"max_position\"",
"]",
"self",
".",
"wink",
".",
"set_configuration",
"(",
"min_value",
",",
"max_value",
",",
"rotation",
",",
"scale",
"=",
"scale",
",",
"ticks",
"=",
"ticks",
",",
"min_position",
"=",
"min_position",
",",
"max_position",
"=",
"max_position",
",",
")"
] | [
936,
4
] | [
960,
9
] | python | en | ['en', 'error', 'th'] | False |
setup | (hass, config) | Set up the Nissan Leaf component. | Set up the Nissan Leaf component. | def setup(hass, config):
"""Set up the Nissan Leaf component."""
async def async_handle_update(service):
"""Handle service to update leaf data from Nissan servers."""
# It would be better if this was changed to use nickname, or
# an entity name rather than a vin.
vin = service.data[ATTR_VIN]
if vin in hass.data[DATA_LEAF]:
data_store = hass.data[DATA_LEAF][vin]
await data_store.async_update_data(utcnow())
else:
_LOGGER.debug("Vin %s not recognised for update", vin)
async def async_handle_start_charge(service):
"""Handle service to start charging."""
# It would be better if this was changed to use nickname, or
# an entity name rather than a vin.
vin = service.data[ATTR_VIN]
if vin in hass.data[DATA_LEAF]:
data_store = hass.data[DATA_LEAF][vin]
# Send the command to request charging is started to Nissan
# servers. If that completes OK then trigger a fresh update to
# pull the charging status from the car after waiting a minute
# for the charging request to reach the car.
result = await hass.async_add_executor_job(data_store.leaf.start_charging)
if result:
_LOGGER.debug("Start charging sent, request updated data in 1 minute")
check_charge_at = utcnow() + timedelta(minutes=1)
data_store.next_update = check_charge_at
async_track_point_in_utc_time(
hass, data_store.async_update_data, check_charge_at
)
else:
_LOGGER.debug("Vin %s not recognised for update", vin)
def setup_leaf(car_config):
"""Set up a car."""
_LOGGER.debug("Logging into You+Nissan...")
username = car_config[CONF_USERNAME]
password = car_config[CONF_PASSWORD]
region = car_config[CONF_REGION]
leaf = None
try:
# This might need to be made async (somehow) causes
# homeassistant to be slow to start
sess = Session(username, password, region)
leaf = sess.get_leaf()
except KeyError:
_LOGGER.error(
"Unable to fetch car details..."
" do you actually have a Leaf connected to your account?"
)
return False
except CarwingsError:
_LOGGER.error(
"An unknown error occurred while connecting to Nissan: %s",
sys.exc_info()[0],
)
return False
_LOGGER.warning(
"WARNING: This may poll your Leaf too often, and drain the 12V"
" battery. If you drain your cars 12V battery it WILL NOT START"
" as the drive train battery won't connect."
" Don't set the intervals too low"
)
data_store = LeafDataStore(hass, leaf, car_config)
hass.data[DATA_LEAF][leaf.vin] = data_store
for component in LEAF_COMPONENTS:
load_platform(hass, component, DOMAIN, {}, car_config)
async_track_point_in_utc_time(
hass, data_store.async_update_data, utcnow() + INITIAL_UPDATE
)
hass.data[DATA_LEAF] = {}
for car in config[DOMAIN]:
setup_leaf(car)
hass.services.register(
DOMAIN, SERVICE_UPDATE_LEAF, async_handle_update, schema=UPDATE_LEAF_SCHEMA
)
hass.services.register(
DOMAIN,
SERVICE_START_CHARGE_LEAF,
async_handle_start_charge,
schema=START_CHARGE_LEAF_SCHEMA,
)
return True | [
"def",
"setup",
"(",
"hass",
",",
"config",
")",
":",
"async",
"def",
"async_handle_update",
"(",
"service",
")",
":",
"\"\"\"Handle service to update leaf data from Nissan servers.\"\"\"",
"# It would be better if this was changed to use nickname, or",
"# an entity name rather than a vin.",
"vin",
"=",
"service",
".",
"data",
"[",
"ATTR_VIN",
"]",
"if",
"vin",
"in",
"hass",
".",
"data",
"[",
"DATA_LEAF",
"]",
":",
"data_store",
"=",
"hass",
".",
"data",
"[",
"DATA_LEAF",
"]",
"[",
"vin",
"]",
"await",
"data_store",
".",
"async_update_data",
"(",
"utcnow",
"(",
")",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Vin %s not recognised for update\"",
",",
"vin",
")",
"async",
"def",
"async_handle_start_charge",
"(",
"service",
")",
":",
"\"\"\"Handle service to start charging.\"\"\"",
"# It would be better if this was changed to use nickname, or",
"# an entity name rather than a vin.",
"vin",
"=",
"service",
".",
"data",
"[",
"ATTR_VIN",
"]",
"if",
"vin",
"in",
"hass",
".",
"data",
"[",
"DATA_LEAF",
"]",
":",
"data_store",
"=",
"hass",
".",
"data",
"[",
"DATA_LEAF",
"]",
"[",
"vin",
"]",
"# Send the command to request charging is started to Nissan",
"# servers. If that completes OK then trigger a fresh update to",
"# pull the charging status from the car after waiting a minute",
"# for the charging request to reach the car.",
"result",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"data_store",
".",
"leaf",
".",
"start_charging",
")",
"if",
"result",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Start charging sent, request updated data in 1 minute\"",
")",
"check_charge_at",
"=",
"utcnow",
"(",
")",
"+",
"timedelta",
"(",
"minutes",
"=",
"1",
")",
"data_store",
".",
"next_update",
"=",
"check_charge_at",
"async_track_point_in_utc_time",
"(",
"hass",
",",
"data_store",
".",
"async_update_data",
",",
"check_charge_at",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Vin %s not recognised for update\"",
",",
"vin",
")",
"def",
"setup_leaf",
"(",
"car_config",
")",
":",
"\"\"\"Set up a car.\"\"\"",
"_LOGGER",
".",
"debug",
"(",
"\"Logging into You+Nissan...\"",
")",
"username",
"=",
"car_config",
"[",
"CONF_USERNAME",
"]",
"password",
"=",
"car_config",
"[",
"CONF_PASSWORD",
"]",
"region",
"=",
"car_config",
"[",
"CONF_REGION",
"]",
"leaf",
"=",
"None",
"try",
":",
"# This might need to be made async (somehow) causes",
"# homeassistant to be slow to start",
"sess",
"=",
"Session",
"(",
"username",
",",
"password",
",",
"region",
")",
"leaf",
"=",
"sess",
".",
"get_leaf",
"(",
")",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Unable to fetch car details...\"",
"\" do you actually have a Leaf connected to your account?\"",
")",
"return",
"False",
"except",
"CarwingsError",
":",
"_LOGGER",
".",
"error",
"(",
"\"An unknown error occurred while connecting to Nissan: %s\"",
",",
"sys",
".",
"exc_info",
"(",
")",
"[",
"0",
"]",
",",
")",
"return",
"False",
"_LOGGER",
".",
"warning",
"(",
"\"WARNING: This may poll your Leaf too often, and drain the 12V\"",
"\" battery. If you drain your cars 12V battery it WILL NOT START\"",
"\" as the drive train battery won't connect.\"",
"\" Don't set the intervals too low\"",
")",
"data_store",
"=",
"LeafDataStore",
"(",
"hass",
",",
"leaf",
",",
"car_config",
")",
"hass",
".",
"data",
"[",
"DATA_LEAF",
"]",
"[",
"leaf",
".",
"vin",
"]",
"=",
"data_store",
"for",
"component",
"in",
"LEAF_COMPONENTS",
":",
"load_platform",
"(",
"hass",
",",
"component",
",",
"DOMAIN",
",",
"{",
"}",
",",
"car_config",
")",
"async_track_point_in_utc_time",
"(",
"hass",
",",
"data_store",
".",
"async_update_data",
",",
"utcnow",
"(",
")",
"+",
"INITIAL_UPDATE",
")",
"hass",
".",
"data",
"[",
"DATA_LEAF",
"]",
"=",
"{",
"}",
"for",
"car",
"in",
"config",
"[",
"DOMAIN",
"]",
":",
"setup_leaf",
"(",
"car",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_UPDATE_LEAF",
",",
"async_handle_update",
",",
"schema",
"=",
"UPDATE_LEAF_SCHEMA",
")",
"hass",
".",
"services",
".",
"register",
"(",
"DOMAIN",
",",
"SERVICE_START_CHARGE_LEAF",
",",
"async_handle_start_charge",
",",
"schema",
"=",
"START_CHARGE_LEAF_SCHEMA",
",",
")",
"return",
"True"
] | [
96,
0
] | [
194,
15
] | python | en | ['en', 'da', 'en'] | True |
LeafDataStore.__init__ | (self, hass, leaf, car_config) | Initialise the data store. | Initialise the data store. | def __init__(self, hass, leaf, car_config):
"""Initialise the data store."""
self.hass = hass
self.leaf = leaf
self.car_config = car_config
self.force_miles = car_config[CONF_FORCE_MILES]
self.data = {}
self.data[DATA_CLIMATE] = False
self.data[DATA_BATTERY] = 0
self.data[DATA_CHARGING] = False
self.data[DATA_RANGE_AC] = 0
self.data[DATA_RANGE_AC_OFF] = 0
self.data[DATA_PLUGGED_IN] = False
self.next_update = None
self.last_check = None
self.request_in_progress = False
# Timestamp of last successful response from battery or climate.
self.last_battery_response = None
self.last_climate_response = None
self._remove_listener = None | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"leaf",
",",
"car_config",
")",
":",
"self",
".",
"hass",
"=",
"hass",
"self",
".",
"leaf",
"=",
"leaf",
"self",
".",
"car_config",
"=",
"car_config",
"self",
".",
"force_miles",
"=",
"car_config",
"[",
"CONF_FORCE_MILES",
"]",
"self",
".",
"data",
"=",
"{",
"}",
"self",
".",
"data",
"[",
"DATA_CLIMATE",
"]",
"=",
"False",
"self",
".",
"data",
"[",
"DATA_BATTERY",
"]",
"=",
"0",
"self",
".",
"data",
"[",
"DATA_CHARGING",
"]",
"=",
"False",
"self",
".",
"data",
"[",
"DATA_RANGE_AC",
"]",
"=",
"0",
"self",
".",
"data",
"[",
"DATA_RANGE_AC_OFF",
"]",
"=",
"0",
"self",
".",
"data",
"[",
"DATA_PLUGGED_IN",
"]",
"=",
"False",
"self",
".",
"next_update",
"=",
"None",
"self",
".",
"last_check",
"=",
"None",
"self",
".",
"request_in_progress",
"=",
"False",
"# Timestamp of last successful response from battery or climate.",
"self",
".",
"last_battery_response",
"=",
"None",
"self",
".",
"last_climate_response",
"=",
"None",
"self",
".",
"_remove_listener",
"=",
"None"
] | [
200,
4
] | [
219,
36
] | python | en | ['en', 'en', 'en'] | True |
LeafDataStore.async_update_data | (self, now) | Update data from nissan leaf. | Update data from nissan leaf. | async def async_update_data(self, now):
"""Update data from nissan leaf."""
# Prevent against a previously scheduled update and an ad-hoc update
# started from an update from both being triggered.
if self._remove_listener:
self._remove_listener()
self._remove_listener = None
# Clear next update whilst this update is underway
self.next_update = None
await self.async_refresh_data(now)
self.next_update = self.get_next_interval()
_LOGGER.debug("Next update=%s", self.next_update)
self._remove_listener = async_track_point_in_utc_time(
self.hass, self.async_update_data, self.next_update
) | [
"async",
"def",
"async_update_data",
"(",
"self",
",",
"now",
")",
":",
"# Prevent against a previously scheduled update and an ad-hoc update",
"# started from an update from both being triggered.",
"if",
"self",
".",
"_remove_listener",
":",
"self",
".",
"_remove_listener",
"(",
")",
"self",
".",
"_remove_listener",
"=",
"None",
"# Clear next update whilst this update is underway",
"self",
".",
"next_update",
"=",
"None",
"await",
"self",
".",
"async_refresh_data",
"(",
"now",
")",
"self",
".",
"next_update",
"=",
"self",
".",
"get_next_interval",
"(",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Next update=%s\"",
",",
"self",
".",
"next_update",
")",
"self",
".",
"_remove_listener",
"=",
"async_track_point_in_utc_time",
"(",
"self",
".",
"hass",
",",
"self",
".",
"async_update_data",
",",
"self",
".",
"next_update",
")"
] | [
221,
4
] | [
237,
9
] | python | en | ['en', 'en', 'en'] | True |
LeafDataStore.get_next_interval | (self) | Calculate when the next update should occur. | Calculate when the next update should occur. | def get_next_interval(self):
"""Calculate when the next update should occur."""
base_interval = self.car_config[CONF_INTERVAL]
climate_interval = self.car_config[CONF_CLIMATE_INTERVAL]
charging_interval = self.car_config[CONF_CHARGING_INTERVAL]
# The 12V battery is used when communicating with Nissan servers.
# The 12V battery is charged from the traction battery when not
# connected and when the traction battery has enough charge. To
# avoid draining the 12V battery we shall restrict the update
# frequency if low battery detected.
if (
self.last_battery_response is not None
and self.data[DATA_CHARGING] is False
and self.data[DATA_BATTERY] <= RESTRICTED_BATTERY
):
_LOGGER.debug(
"Low battery so restricting refresh frequency (%s)", self.leaf.nickname
)
interval = RESTRICTED_INTERVAL
else:
intervals = [base_interval]
if self.data[DATA_CHARGING]:
intervals.append(charging_interval)
if self.data[DATA_CLIMATE]:
intervals.append(climate_interval)
interval = min(intervals)
return utcnow() + interval | [
"def",
"get_next_interval",
"(",
"self",
")",
":",
"base_interval",
"=",
"self",
".",
"car_config",
"[",
"CONF_INTERVAL",
"]",
"climate_interval",
"=",
"self",
".",
"car_config",
"[",
"CONF_CLIMATE_INTERVAL",
"]",
"charging_interval",
"=",
"self",
".",
"car_config",
"[",
"CONF_CHARGING_INTERVAL",
"]",
"# The 12V battery is used when communicating with Nissan servers.",
"# The 12V battery is charged from the traction battery when not",
"# connected and when the traction battery has enough charge. To",
"# avoid draining the 12V battery we shall restrict the update",
"# frequency if low battery detected.",
"if",
"(",
"self",
".",
"last_battery_response",
"is",
"not",
"None",
"and",
"self",
".",
"data",
"[",
"DATA_CHARGING",
"]",
"is",
"False",
"and",
"self",
".",
"data",
"[",
"DATA_BATTERY",
"]",
"<=",
"RESTRICTED_BATTERY",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Low battery so restricting refresh frequency (%s)\"",
",",
"self",
".",
"leaf",
".",
"nickname",
")",
"interval",
"=",
"RESTRICTED_INTERVAL",
"else",
":",
"intervals",
"=",
"[",
"base_interval",
"]",
"if",
"self",
".",
"data",
"[",
"DATA_CHARGING",
"]",
":",
"intervals",
".",
"append",
"(",
"charging_interval",
")",
"if",
"self",
".",
"data",
"[",
"DATA_CLIMATE",
"]",
":",
"intervals",
".",
"append",
"(",
"climate_interval",
")",
"interval",
"=",
"min",
"(",
"intervals",
")",
"return",
"utcnow",
"(",
")",
"+",
"interval"
] | [
239,
4
] | [
270,
34
] | python | en | ['en', 'en', 'en'] | True |
LeafDataStore.async_refresh_data | (self, now) | Refresh the leaf data and update the datastore. | Refresh the leaf data and update the datastore. | async def async_refresh_data(self, now):
"""Refresh the leaf data and update the datastore."""
if self.request_in_progress:
_LOGGER.debug("Refresh currently in progress for %s", self.leaf.nickname)
return
_LOGGER.debug("Updating Nissan Leaf Data")
self.last_check = datetime.today()
self.request_in_progress = True
server_response = await self.async_get_battery()
if server_response is not None:
_LOGGER.debug("Server Response: %s", server_response.__dict__)
if server_response.answer["status"] == HTTP_OK:
self.data[DATA_BATTERY] = server_response.battery_percent
# pycarwings2 library doesn't always provide cruising rnages
# so we have to check if they exist before we can use them.
# Root cause: the nissan servers don't always send the data.
if hasattr(server_response, "cruising_range_ac_on_km"):
self.data[DATA_RANGE_AC] = server_response.cruising_range_ac_on_km
else:
self.data[DATA_RANGE_AC] = None
if hasattr(server_response, "cruising_range_ac_off_km"):
self.data[
DATA_RANGE_AC_OFF
] = server_response.cruising_range_ac_off_km
else:
self.data[DATA_RANGE_AC_OFF] = None
self.data[DATA_PLUGGED_IN] = server_response.is_connected
self.data[DATA_CHARGING] = server_response.is_charging
async_dispatcher_send(self.hass, SIGNAL_UPDATE_LEAF)
self.last_battery_response = utcnow()
# Climate response only updated if battery data updated first.
if server_response is not None:
try:
climate_response = await self.async_get_climate()
if climate_response is not None:
_LOGGER.debug(
"Got climate data for Leaf: %s", climate_response.__dict__
)
self.data[DATA_CLIMATE] = climate_response.is_hvac_running
self.last_climate_response = utcnow()
except CarwingsError:
_LOGGER.error("Error fetching climate info")
self.request_in_progress = False
async_dispatcher_send(self.hass, SIGNAL_UPDATE_LEAF) | [
"async",
"def",
"async_refresh_data",
"(",
"self",
",",
"now",
")",
":",
"if",
"self",
".",
"request_in_progress",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Refresh currently in progress for %s\"",
",",
"self",
".",
"leaf",
".",
"nickname",
")",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Updating Nissan Leaf Data\"",
")",
"self",
".",
"last_check",
"=",
"datetime",
".",
"today",
"(",
")",
"self",
".",
"request_in_progress",
"=",
"True",
"server_response",
"=",
"await",
"self",
".",
"async_get_battery",
"(",
")",
"if",
"server_response",
"is",
"not",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Server Response: %s\"",
",",
"server_response",
".",
"__dict__",
")",
"if",
"server_response",
".",
"answer",
"[",
"\"status\"",
"]",
"==",
"HTTP_OK",
":",
"self",
".",
"data",
"[",
"DATA_BATTERY",
"]",
"=",
"server_response",
".",
"battery_percent",
"# pycarwings2 library doesn't always provide cruising rnages",
"# so we have to check if they exist before we can use them.",
"# Root cause: the nissan servers don't always send the data.",
"if",
"hasattr",
"(",
"server_response",
",",
"\"cruising_range_ac_on_km\"",
")",
":",
"self",
".",
"data",
"[",
"DATA_RANGE_AC",
"]",
"=",
"server_response",
".",
"cruising_range_ac_on_km",
"else",
":",
"self",
".",
"data",
"[",
"DATA_RANGE_AC",
"]",
"=",
"None",
"if",
"hasattr",
"(",
"server_response",
",",
"\"cruising_range_ac_off_km\"",
")",
":",
"self",
".",
"data",
"[",
"DATA_RANGE_AC_OFF",
"]",
"=",
"server_response",
".",
"cruising_range_ac_off_km",
"else",
":",
"self",
".",
"data",
"[",
"DATA_RANGE_AC_OFF",
"]",
"=",
"None",
"self",
".",
"data",
"[",
"DATA_PLUGGED_IN",
"]",
"=",
"server_response",
".",
"is_connected",
"self",
".",
"data",
"[",
"DATA_CHARGING",
"]",
"=",
"server_response",
".",
"is_charging",
"async_dispatcher_send",
"(",
"self",
".",
"hass",
",",
"SIGNAL_UPDATE_LEAF",
")",
"self",
".",
"last_battery_response",
"=",
"utcnow",
"(",
")",
"# Climate response only updated if battery data updated first.",
"if",
"server_response",
"is",
"not",
"None",
":",
"try",
":",
"climate_response",
"=",
"await",
"self",
".",
"async_get_climate",
"(",
")",
"if",
"climate_response",
"is",
"not",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Got climate data for Leaf: %s\"",
",",
"climate_response",
".",
"__dict__",
")",
"self",
".",
"data",
"[",
"DATA_CLIMATE",
"]",
"=",
"climate_response",
".",
"is_hvac_running",
"self",
".",
"last_climate_response",
"=",
"utcnow",
"(",
")",
"except",
"CarwingsError",
":",
"_LOGGER",
".",
"error",
"(",
"\"Error fetching climate info\"",
")",
"self",
".",
"request_in_progress",
"=",
"False",
"async_dispatcher_send",
"(",
"self",
".",
"hass",
",",
"SIGNAL_UPDATE_LEAF",
")"
] | [
272,
4
] | [
326,
60
] | python | en | ['en', 'en', 'en'] | True |
LeafDataStore._extract_start_date | (battery_info) | Extract the server date from the battery response. | Extract the server date from the battery response. | def _extract_start_date(battery_info):
"""Extract the server date from the battery response."""
try:
return battery_info.answer["BatteryStatusRecords"]["OperationDateAndTime"]
except KeyError:
return None | [
"def",
"_extract_start_date",
"(",
"battery_info",
")",
":",
"try",
":",
"return",
"battery_info",
".",
"answer",
"[",
"\"BatteryStatusRecords\"",
"]",
"[",
"\"OperationDateAndTime\"",
"]",
"except",
"KeyError",
":",
"return",
"None"
] | [
329,
4
] | [
334,
23
] | python | en | ['en', 'en', 'en'] | True |
LeafDataStore.async_get_battery | (self) | Request battery update from Nissan servers. | Request battery update from Nissan servers. | async def async_get_battery(self):
"""Request battery update from Nissan servers."""
try:
# Request battery update from the car
_LOGGER.debug("Requesting battery update, %s", self.leaf.vin)
request = await self.hass.async_add_executor_job(self.leaf.request_update)
if not request:
_LOGGER.error("Battery update request failed")
return None
for attempt in range(MAX_RESPONSE_ATTEMPTS):
_LOGGER.debug(
"Waiting %s seconds for battery update (%s) (%s)",
PYCARWINGS2_SLEEP,
self.leaf.vin,
attempt,
)
await asyncio.sleep(PYCARWINGS2_SLEEP)
# We don't use the response from get_status_from_update
# apart from knowing that the car has responded saying it
# has given the latest battery status to Nissan.
check_result_info = await self.hass.async_add_executor_job(
self.leaf.get_status_from_update, request
)
if check_result_info is not None:
# Get the latest battery status from Nissan servers.
# This has the SOC in it.
server_info = await self.hass.async_add_executor_job(
self.leaf.get_latest_battery_status
)
return server_info
_LOGGER.debug(
"%s attempts exceeded return latest data from server",
MAX_RESPONSE_ATTEMPTS,
)
# Get the latest data from the nissan servers, even though
# it may be out of date, it's better than nothing.
server_info = await self.hass.async_add_executor_job(
self.leaf.get_latest_battery_status
)
return server_info
except CarwingsError:
_LOGGER.error("An error occurred getting battery status")
return None
except KeyError:
_LOGGER.error("An error occurred parsing response from server")
return None | [
"async",
"def",
"async_get_battery",
"(",
"self",
")",
":",
"try",
":",
"# Request battery update from the car",
"_LOGGER",
".",
"debug",
"(",
"\"Requesting battery update, %s\"",
",",
"self",
".",
"leaf",
".",
"vin",
")",
"request",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"leaf",
".",
"request_update",
")",
"if",
"not",
"request",
":",
"_LOGGER",
".",
"error",
"(",
"\"Battery update request failed\"",
")",
"return",
"None",
"for",
"attempt",
"in",
"range",
"(",
"MAX_RESPONSE_ATTEMPTS",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Waiting %s seconds for battery update (%s) (%s)\"",
",",
"PYCARWINGS2_SLEEP",
",",
"self",
".",
"leaf",
".",
"vin",
",",
"attempt",
",",
")",
"await",
"asyncio",
".",
"sleep",
"(",
"PYCARWINGS2_SLEEP",
")",
"# We don't use the response from get_status_from_update",
"# apart from knowing that the car has responded saying it",
"# has given the latest battery status to Nissan.",
"check_result_info",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"leaf",
".",
"get_status_from_update",
",",
"request",
")",
"if",
"check_result_info",
"is",
"not",
"None",
":",
"# Get the latest battery status from Nissan servers.",
"# This has the SOC in it.",
"server_info",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"leaf",
".",
"get_latest_battery_status",
")",
"return",
"server_info",
"_LOGGER",
".",
"debug",
"(",
"\"%s attempts exceeded return latest data from server\"",
",",
"MAX_RESPONSE_ATTEMPTS",
",",
")",
"# Get the latest data from the nissan servers, even though",
"# it may be out of date, it's better than nothing.",
"server_info",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"leaf",
".",
"get_latest_battery_status",
")",
"return",
"server_info",
"except",
"CarwingsError",
":",
"_LOGGER",
".",
"error",
"(",
"\"An error occurred getting battery status\"",
")",
"return",
"None",
"except",
"KeyError",
":",
"_LOGGER",
".",
"error",
"(",
"\"An error occurred parsing response from server\"",
")",
"return",
"None"
] | [
336,
4
] | [
386,
23
] | python | en | ['en', 'en', 'en'] | True |
LeafDataStore.async_get_climate | (self) | Request climate data from Nissan servers. | Request climate data from Nissan servers. | async def async_get_climate(self):
"""Request climate data from Nissan servers."""
try:
return await self.hass.async_add_executor_job(
self.leaf.get_latest_hvac_status
)
except CarwingsError:
_LOGGER.error(
"An error occurred communicating with the car %s", self.leaf.vin
)
return None | [
"async",
"def",
"async_get_climate",
"(",
"self",
")",
":",
"try",
":",
"return",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"leaf",
".",
"get_latest_hvac_status",
")",
"except",
"CarwingsError",
":",
"_LOGGER",
".",
"error",
"(",
"\"An error occurred communicating with the car %s\"",
",",
"self",
".",
"leaf",
".",
"vin",
")",
"return",
"None"
] | [
388,
4
] | [
399,
23
] | python | en | ['en', 'en', 'en'] | True |
LeafDataStore.async_set_climate | (self, toggle) | Set climate control mode via Nissan servers. | Set climate control mode via Nissan servers. | async def async_set_climate(self, toggle):
"""Set climate control mode via Nissan servers."""
climate_result = None
if toggle:
_LOGGER.debug("Requesting climate turn on for %s", self.leaf.vin)
set_function = self.leaf.start_climate_control
result_function = self.leaf.get_start_climate_control_result
else:
_LOGGER.debug("Requesting climate turn off for %s", self.leaf.vin)
set_function = self.leaf.stop_climate_control
result_function = self.leaf.get_stop_climate_control_result
request = await self.hass.async_add_executor_job(set_function)
for attempt in range(MAX_RESPONSE_ATTEMPTS):
if attempt > 0:
_LOGGER.debug(
"Climate data not in yet (%s) (%s). Waiting (%s) seconds",
self.leaf.vin,
attempt,
PYCARWINGS2_SLEEP,
)
await asyncio.sleep(PYCARWINGS2_SLEEP)
climate_result = await self.hass.async_add_executor_job(
result_function, request
)
if climate_result is not None:
break
if climate_result is not None:
_LOGGER.debug("Climate result: %s", climate_result.__dict__)
async_dispatcher_send(self.hass, SIGNAL_UPDATE_LEAF)
return climate_result.is_hvac_running == toggle
_LOGGER.debug("Climate result not returned by Nissan servers")
return False | [
"async",
"def",
"async_set_climate",
"(",
"self",
",",
"toggle",
")",
":",
"climate_result",
"=",
"None",
"if",
"toggle",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Requesting climate turn on for %s\"",
",",
"self",
".",
"leaf",
".",
"vin",
")",
"set_function",
"=",
"self",
".",
"leaf",
".",
"start_climate_control",
"result_function",
"=",
"self",
".",
"leaf",
".",
"get_start_climate_control_result",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Requesting climate turn off for %s\"",
",",
"self",
".",
"leaf",
".",
"vin",
")",
"set_function",
"=",
"self",
".",
"leaf",
".",
"stop_climate_control",
"result_function",
"=",
"self",
".",
"leaf",
".",
"get_stop_climate_control_result",
"request",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"set_function",
")",
"for",
"attempt",
"in",
"range",
"(",
"MAX_RESPONSE_ATTEMPTS",
")",
":",
"if",
"attempt",
">",
"0",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Climate data not in yet (%s) (%s). Waiting (%s) seconds\"",
",",
"self",
".",
"leaf",
".",
"vin",
",",
"attempt",
",",
"PYCARWINGS2_SLEEP",
",",
")",
"await",
"asyncio",
".",
"sleep",
"(",
"PYCARWINGS2_SLEEP",
")",
"climate_result",
"=",
"await",
"self",
".",
"hass",
".",
"async_add_executor_job",
"(",
"result_function",
",",
"request",
")",
"if",
"climate_result",
"is",
"not",
"None",
":",
"break",
"if",
"climate_result",
"is",
"not",
"None",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Climate result: %s\"",
",",
"climate_result",
".",
"__dict__",
")",
"async_dispatcher_send",
"(",
"self",
".",
"hass",
",",
"SIGNAL_UPDATE_LEAF",
")",
"return",
"climate_result",
".",
"is_hvac_running",
"==",
"toggle",
"_LOGGER",
".",
"debug",
"(",
"\"Climate result not returned by Nissan servers\"",
")",
"return",
"False"
] | [
401,
4
] | [
437,
20
] | python | en | ['fr', 'pt', 'en'] | False |
LeafEntity.__init__ | (self, car) | Store LeafDataStore upon init. | Store LeafDataStore upon init. | def __init__(self, car):
"""Store LeafDataStore upon init."""
self.car = car | [
"def",
"__init__",
"(",
"self",
",",
"car",
")",
":",
"self",
".",
"car",
"=",
"car"
] | [
443,
4
] | [
445,
22
] | python | en | ['en', 'la', 'en'] | True |
LeafEntity.log_registration | (self) | Log registration. | Log registration. | def log_registration(self):
"""Log registration."""
_LOGGER.debug(
"Registered %s integration for VIN %s",
self.__class__.__name__,
self.car.leaf.vin,
) | [
"def",
"log_registration",
"(",
"self",
")",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Registered %s integration for VIN %s\"",
",",
"self",
".",
"__class__",
".",
"__name__",
",",
"self",
".",
"car",
".",
"leaf",
".",
"vin",
",",
")"
] | [
447,
4
] | [
453,
9
] | python | da | ['da', 'da', 'en'] | False |
LeafEntity.device_state_attributes | (self) | Return default attributes for Nissan leaf entities. | Return default attributes for Nissan leaf entities. | def device_state_attributes(self):
"""Return default attributes for Nissan leaf entities."""
return {
"next_update": self.car.next_update,
"last_attempt": self.car.last_check,
"updated_on": self.car.last_battery_response,
"update_in_progress": self.car.request_in_progress,
"vin": self.car.leaf.vin,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"next_update\"",
":",
"self",
".",
"car",
".",
"next_update",
",",
"\"last_attempt\"",
":",
"self",
".",
"car",
".",
"last_check",
",",
"\"updated_on\"",
":",
"self",
".",
"car",
".",
"last_battery_response",
",",
"\"update_in_progress\"",
":",
"self",
".",
"car",
".",
"request_in_progress",
",",
"\"vin\"",
":",
"self",
".",
"car",
".",
"leaf",
".",
"vin",
",",
"}"
] | [
456,
4
] | [
464,
9
] | python | da | ['da', 'da', 'en'] | True |
LeafEntity.async_added_to_hass | (self) | Register callbacks. | Register callbacks. | async def async_added_to_hass(self):
"""Register callbacks."""
self.log_registration()
self.async_on_remove(
async_dispatcher_connect(
self.car.hass, SIGNAL_UPDATE_LEAF, self._update_callback
)
) | [
"async",
"def",
"async_added_to_hass",
"(",
"self",
")",
":",
"self",
".",
"log_registration",
"(",
")",
"self",
".",
"async_on_remove",
"(",
"async_dispatcher_connect",
"(",
"self",
".",
"car",
".",
"hass",
",",
"SIGNAL_UPDATE_LEAF",
",",
"self",
".",
"_update_callback",
")",
")"
] | [
466,
4
] | [
473,
9
] | python | en | ['en', 'no', 'en'] | False |
LeafEntity._update_callback | (self) | Update the state. | Update the state. | def _update_callback(self):
"""Update the state."""
self.async_schedule_update_ha_state(True) | [
"def",
"_update_callback",
"(",
"self",
")",
":",
"self",
".",
"async_schedule_update_ha_state",
"(",
"True",
")"
] | [
476,
4
] | [
478,
49
] | python | en | ['en', 'en', 'en'] | True |
get_scanner | (hass, config) | Validate the configuration and return a Ubee scanner. | Validate the configuration and return a Ubee scanner. | def get_scanner(hass, config):
"""Validate the configuration and return a Ubee scanner."""
info = config[DOMAIN]
host = info[CONF_HOST]
username = info[CONF_USERNAME]
password = info[CONF_PASSWORD]
model = info[CONF_MODEL]
ubee = Ubee(host, username, password, model)
if not ubee.login():
_LOGGER.error("Login failed")
return None
scanner = UbeeDeviceScanner(ubee)
return scanner | [
"def",
"get_scanner",
"(",
"hass",
",",
"config",
")",
":",
"info",
"=",
"config",
"[",
"DOMAIN",
"]",
"host",
"=",
"info",
"[",
"CONF_HOST",
"]",
"username",
"=",
"info",
"[",
"CONF_USERNAME",
"]",
"password",
"=",
"info",
"[",
"CONF_PASSWORD",
"]",
"model",
"=",
"info",
"[",
"CONF_MODEL",
"]",
"ubee",
"=",
"Ubee",
"(",
"host",
",",
"username",
",",
"password",
",",
"model",
")",
"if",
"not",
"ubee",
".",
"login",
"(",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Login failed\"",
")",
"return",
"None",
"scanner",
"=",
"UbeeDeviceScanner",
"(",
"ubee",
")",
"return",
"scanner"
] | [
38,
0
] | [
52,
18
] | python | en | ['en', 'en', 'en'] | True |
UbeeDeviceScanner.__init__ | (self, ubee) | Initialize the Ubee scanner. | Initialize the Ubee scanner. | def __init__(self, ubee):
"""Initialize the Ubee scanner."""
self._ubee = ubee
self._mac2name = {} | [
"def",
"__init__",
"(",
"self",
",",
"ubee",
")",
":",
"self",
".",
"_ubee",
"=",
"ubee",
"self",
".",
"_mac2name",
"=",
"{",
"}"
] | [
58,
4
] | [
61,
27
] | python | en | ['en', 'en', 'en'] | True |
UbeeDeviceScanner.scan_devices | (self) | Scan for new devices and return a list with found device IDs. | Scan for new devices and return a list with found device IDs. | def scan_devices(self):
"""Scan for new devices and return a list with found device IDs."""
devices = self._get_connected_devices()
self._mac2name = devices
return list(devices) | [
"def",
"scan_devices",
"(",
"self",
")",
":",
"devices",
"=",
"self",
".",
"_get_connected_devices",
"(",
")",
"self",
".",
"_mac2name",
"=",
"devices",
"return",
"list",
"(",
"devices",
")"
] | [
63,
4
] | [
67,
28
] | python | en | ['en', 'en', 'en'] | True |
UbeeDeviceScanner.get_device_name | (self, device) | Return the name of the given device or None if we don't know. | Return the name of the given device or None if we don't know. | def get_device_name(self, device):
"""Return the name of the given device or None if we don't know."""
return self._mac2name.get(device) | [
"def",
"get_device_name",
"(",
"self",
",",
"device",
")",
":",
"return",
"self",
".",
"_mac2name",
".",
"get",
"(",
"device",
")"
] | [
69,
4
] | [
71,
41
] | python | en | ['en', 'en', 'en'] | True |
UbeeDeviceScanner._get_connected_devices | (self) | List connected devices with pyubee. | List connected devices with pyubee. | def _get_connected_devices(self):
"""List connected devices with pyubee."""
if not self._ubee.session_active():
self._ubee.login()
return self._ubee.get_connected_devices() | [
"def",
"_get_connected_devices",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ubee",
".",
"session_active",
"(",
")",
":",
"self",
".",
"_ubee",
".",
"login",
"(",
")",
"return",
"self",
".",
"_ubee",
".",
"get_connected_devices",
"(",
")"
] | [
73,
4
] | [
78,
49
] | python | en | ['en', 'en', 'en'] | True |
split_text | (text: str, n=100, character=" ") | Split the text every ``n``-th occurrence of ``character`` | Split the text every ``n``-th occurrence of ``character`` | def split_text(text: str, n=100, character=" ") -> List[str]:
"""Split the text every ``n``-th occurrence of ``character``"""
text = text.split(character)
return [character.join(text[i : i + n]).strip() for i in range(0, len(text), n)] | [
"def",
"split_text",
"(",
"text",
":",
"str",
",",
"n",
"=",
"100",
",",
"character",
"=",
"\" \"",
")",
"->",
"List",
"[",
"str",
"]",
":",
"text",
"=",
"text",
".",
"split",
"(",
"character",
")",
"return",
"[",
"character",
".",
"join",
"(",
"text",
"[",
"i",
":",
"i",
"+",
"n",
"]",
")",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"text",
")",
",",
"n",
")",
"]"
] | [
27,
0
] | [
30,
84
] | python | en | ['en', 'en', 'en'] | True |
split_documents | (documents: dict) | Split documents into passages | Split documents into passages | def split_documents(documents: dict) -> dict:
"""Split documents into passages"""
titles, texts = [], []
for title, text in zip(documents["title"], documents["text"]):
if text is not None:
for passage in split_text(text):
titles.append(title if title is not None else "")
texts.append(passage)
return {"title": titles, "text": texts} | [
"def",
"split_documents",
"(",
"documents",
":",
"dict",
")",
"->",
"dict",
":",
"titles",
",",
"texts",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"title",
",",
"text",
"in",
"zip",
"(",
"documents",
"[",
"\"title\"",
"]",
",",
"documents",
"[",
"\"text\"",
"]",
")",
":",
"if",
"text",
"is",
"not",
"None",
":",
"for",
"passage",
"in",
"split_text",
"(",
"text",
")",
":",
"titles",
".",
"append",
"(",
"title",
"if",
"title",
"is",
"not",
"None",
"else",
"\"\"",
")",
"texts",
".",
"append",
"(",
"passage",
")",
"return",
"{",
"\"title\"",
":",
"titles",
",",
"\"text\"",
":",
"texts",
"}"
] | [
33,
0
] | [
41,
43
] | python | en | ['en', 'fr', 'en'] | True |
embed | (documents: dict, ctx_encoder: DPRContextEncoder, ctx_tokenizer: DPRContextEncoderTokenizerFast) | Compute the DPR embeddings of document passages | Compute the DPR embeddings of document passages | def embed(documents: dict, ctx_encoder: DPRContextEncoder, ctx_tokenizer: DPRContextEncoderTokenizerFast) -> dict:
"""Compute the DPR embeddings of document passages"""
input_ids = ctx_tokenizer(
documents["title"], documents["text"], truncation=True, padding="longest", return_tensors="pt"
)["input_ids"]
embeddings = ctx_encoder(input_ids.to(device=device), return_dict=True).pooler_output
return {"embeddings": embeddings.detach().cpu().numpy()} | [
"def",
"embed",
"(",
"documents",
":",
"dict",
",",
"ctx_encoder",
":",
"DPRContextEncoder",
",",
"ctx_tokenizer",
":",
"DPRContextEncoderTokenizerFast",
")",
"->",
"dict",
":",
"input_ids",
"=",
"ctx_tokenizer",
"(",
"documents",
"[",
"\"title\"",
"]",
",",
"documents",
"[",
"\"text\"",
"]",
",",
"truncation",
"=",
"True",
",",
"padding",
"=",
"\"longest\"",
",",
"return_tensors",
"=",
"\"pt\"",
")",
"[",
"\"input_ids\"",
"]",
"embeddings",
"=",
"ctx_encoder",
"(",
"input_ids",
".",
"to",
"(",
"device",
"=",
"device",
")",
",",
"return_dict",
"=",
"True",
")",
".",
"pooler_output",
"return",
"{",
"\"embeddings\"",
":",
"embeddings",
".",
"detach",
"(",
")",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
"}"
] | [
44,
0
] | [
50,
60
] | python | en | ['en', 'en', 'en'] | True |
test_from_event_to_db_event | () | Test converting event to db event. | Test converting event to db event. | def test_from_event_to_db_event():
"""Test converting event to db event."""
event = ha.Event("test_event", {"some_data": 15})
assert event == Events.from_event(event).to_native() | [
"def",
"test_from_event_to_db_event",
"(",
")",
":",
"event",
"=",
"ha",
".",
"Event",
"(",
"\"test_event\"",
",",
"{",
"\"some_data\"",
":",
"15",
"}",
")",
"assert",
"event",
"==",
"Events",
".",
"from_event",
"(",
"event",
")",
".",
"to_native",
"(",
")"
] | [
23,
0
] | [
26,
56
] | python | en | ['en', 'en', 'en'] | True |
test_from_event_to_db_state | () | Test converting event to db state. | Test converting event to db state. | def test_from_event_to_db_state():
"""Test converting event to db state."""
state = ha.State("sensor.temperature", "18")
event = ha.Event(
EVENT_STATE_CHANGED,
{"entity_id": "sensor.temperature", "old_state": None, "new_state": state},
context=state.context,
)
# We don't restore context unless we need it by joining the
# events table on the event_id for state_changed events
state.context = ha.Context(id=None)
assert state == States.from_event(event).to_native() | [
"def",
"test_from_event_to_db_state",
"(",
")",
":",
"state",
"=",
"ha",
".",
"State",
"(",
"\"sensor.temperature\"",
",",
"\"18\"",
")",
"event",
"=",
"ha",
".",
"Event",
"(",
"EVENT_STATE_CHANGED",
",",
"{",
"\"entity_id\"",
":",
"\"sensor.temperature\"",
",",
"\"old_state\"",
":",
"None",
",",
"\"new_state\"",
":",
"state",
"}",
",",
"context",
"=",
"state",
".",
"context",
",",
")",
"# We don't restore context unless we need it by joining the",
"# events table on the event_id for state_changed events",
"state",
".",
"context",
"=",
"ha",
".",
"Context",
"(",
"id",
"=",
"None",
")",
"assert",
"state",
"==",
"States",
".",
"from_event",
"(",
"event",
")",
".",
"to_native",
"(",
")"
] | [
29,
0
] | [
40,
56
] | python | en | ['en', 'en', 'en'] | True |
test_from_event_to_delete_state | () | Test converting deleting state event to db state. | Test converting deleting state event to db state. | def test_from_event_to_delete_state():
"""Test converting deleting state event to db state."""
event = ha.Event(
EVENT_STATE_CHANGED,
{
"entity_id": "sensor.temperature",
"old_state": ha.State("sensor.temperature", "18"),
"new_state": None,
},
)
db_state = States.from_event(event)
assert db_state.entity_id == "sensor.temperature"
assert db_state.domain == "sensor"
assert db_state.state == ""
assert db_state.last_changed == event.time_fired
assert db_state.last_updated == event.time_fired | [
"def",
"test_from_event_to_delete_state",
"(",
")",
":",
"event",
"=",
"ha",
".",
"Event",
"(",
"EVENT_STATE_CHANGED",
",",
"{",
"\"entity_id\"",
":",
"\"sensor.temperature\"",
",",
"\"old_state\"",
":",
"ha",
".",
"State",
"(",
"\"sensor.temperature\"",
",",
"\"18\"",
")",
",",
"\"new_state\"",
":",
"None",
",",
"}",
",",
")",
"db_state",
"=",
"States",
".",
"from_event",
"(",
"event",
")",
"assert",
"db_state",
".",
"entity_id",
"==",
"\"sensor.temperature\"",
"assert",
"db_state",
".",
"domain",
"==",
"\"sensor\"",
"assert",
"db_state",
".",
"state",
"==",
"\"\"",
"assert",
"db_state",
".",
"last_changed",
"==",
"event",
".",
"time_fired",
"assert",
"db_state",
".",
"last_updated",
"==",
"event",
".",
"time_fired"
] | [
43,
0
] | [
59,
52
] | python | en | ['en', 'en', 'en'] | True |
test_entity_ids | () | Test if entity ids helper method works. | Test if entity ids helper method works. | def test_entity_ids():
"""Test if entity ids helper method works."""
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
session_factory = sessionmaker(bind=engine)
session = scoped_session(session_factory)
session.query(Events).delete()
session.query(States).delete()
session.query(RecorderRuns).delete()
run = RecorderRuns(
start=datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC),
end=datetime(2016, 7, 9, 23, 0, 0, tzinfo=dt.UTC),
closed_incorrect=False,
created=datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC),
)
session.add(run)
session.commit()
before_run = datetime(2016, 7, 9, 8, 0, 0, tzinfo=dt.UTC)
in_run = datetime(2016, 7, 9, 13, 0, 0, tzinfo=dt.UTC)
in_run2 = datetime(2016, 7, 9, 15, 0, 0, tzinfo=dt.UTC)
in_run3 = datetime(2016, 7, 9, 18, 0, 0, tzinfo=dt.UTC)
after_run = datetime(2016, 7, 9, 23, 30, 0, tzinfo=dt.UTC)
assert run.to_native() == run
assert run.entity_ids() == []
session.add(
States(
entity_id="sensor.temperature",
state="20",
last_changed=before_run,
last_updated=before_run,
)
)
session.add(
States(
entity_id="sensor.sound",
state="10",
last_changed=after_run,
last_updated=after_run,
)
)
session.add(
States(
entity_id="sensor.humidity",
state="76",
last_changed=in_run,
last_updated=in_run,
)
)
session.add(
States(
entity_id="sensor.lux",
state="5",
last_changed=in_run3,
last_updated=in_run3,
)
)
assert sorted(run.entity_ids()) == ["sensor.humidity", "sensor.lux"]
assert run.entity_ids(in_run2) == ["sensor.humidity"] | [
"def",
"test_entity_ids",
"(",
")",
":",
"engine",
"=",
"create_engine",
"(",
"\"sqlite://\"",
")",
"Base",
".",
"metadata",
".",
"create_all",
"(",
"engine",
")",
"session_factory",
"=",
"sessionmaker",
"(",
"bind",
"=",
"engine",
")",
"session",
"=",
"scoped_session",
"(",
"session_factory",
")",
"session",
".",
"query",
"(",
"Events",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"States",
")",
".",
"delete",
"(",
")",
"session",
".",
"query",
"(",
"RecorderRuns",
")",
".",
"delete",
"(",
")",
"run",
"=",
"RecorderRuns",
"(",
"start",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
",",
"end",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"23",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
",",
"closed_incorrect",
"=",
"False",
",",
"created",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
",",
")",
"session",
".",
"add",
"(",
"run",
")",
"session",
".",
"commit",
"(",
")",
"before_run",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"8",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"in_run",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"13",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"in_run2",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"15",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"in_run3",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"18",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"after_run",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"23",
",",
"30",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"assert",
"run",
".",
"to_native",
"(",
")",
"==",
"run",
"assert",
"run",
".",
"entity_ids",
"(",
")",
"==",
"[",
"]",
"session",
".",
"add",
"(",
"States",
"(",
"entity_id",
"=",
"\"sensor.temperature\"",
",",
"state",
"=",
"\"20\"",
",",
"last_changed",
"=",
"before_run",
",",
"last_updated",
"=",
"before_run",
",",
")",
")",
"session",
".",
"add",
"(",
"States",
"(",
"entity_id",
"=",
"\"sensor.sound\"",
",",
"state",
"=",
"\"10\"",
",",
"last_changed",
"=",
"after_run",
",",
"last_updated",
"=",
"after_run",
",",
")",
")",
"session",
".",
"add",
"(",
"States",
"(",
"entity_id",
"=",
"\"sensor.humidity\"",
",",
"state",
"=",
"\"76\"",
",",
"last_changed",
"=",
"in_run",
",",
"last_updated",
"=",
"in_run",
",",
")",
")",
"session",
".",
"add",
"(",
"States",
"(",
"entity_id",
"=",
"\"sensor.lux\"",
",",
"state",
"=",
"\"5\"",
",",
"last_changed",
"=",
"in_run3",
",",
"last_updated",
"=",
"in_run3",
",",
")",
")",
"assert",
"sorted",
"(",
"run",
".",
"entity_ids",
"(",
")",
")",
"==",
"[",
"\"sensor.humidity\"",
",",
"\"sensor.lux\"",
"]",
"assert",
"run",
".",
"entity_ids",
"(",
"in_run2",
")",
"==",
"[",
"\"sensor.humidity\"",
"]"
] | [
62,
0
] | [
127,
57
] | python | en | ['en', 'cy', 'en'] | True |
test_states_from_native_invalid_entity_id | () | Test loading a state from an invalid entity ID. | Test loading a state from an invalid entity ID. | def test_states_from_native_invalid_entity_id():
"""Test loading a state from an invalid entity ID."""
state = States()
state.entity_id = "test.invalid__id"
state.attributes = "{}"
with pytest.raises(InvalidEntityFormatError):
state = state.to_native()
state = state.to_native(validate_entity_id=False)
assert state.entity_id == "test.invalid__id" | [
"def",
"test_states_from_native_invalid_entity_id",
"(",
")",
":",
"state",
"=",
"States",
"(",
")",
"state",
".",
"entity_id",
"=",
"\"test.invalid__id\"",
"state",
".",
"attributes",
"=",
"\"{}\"",
"with",
"pytest",
".",
"raises",
"(",
"InvalidEntityFormatError",
")",
":",
"state",
"=",
"state",
".",
"to_native",
"(",
")",
"state",
"=",
"state",
".",
"to_native",
"(",
"validate_entity_id",
"=",
"False",
")",
"assert",
"state",
".",
"entity_id",
"==",
"\"test.invalid__id\""
] | [
130,
0
] | [
139,
48
] | python | en | ['en', 'en', 'en'] | True |
test_process_timestamp | () | Test processing time stamp to UTC. | Test processing time stamp to UTC. | async def test_process_timestamp():
"""Test processing time stamp to UTC."""
datetime_with_tzinfo = datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC)
datetime_without_tzinfo = datetime(2016, 7, 9, 11, 0, 0)
est = pytz.timezone("US/Eastern")
datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est)
nst = pytz.timezone("Canada/Newfoundland")
datetime_nst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=nst)
hst = pytz.timezone("US/Hawaii")
datetime_hst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=hst)
assert process_timestamp(datetime_with_tzinfo) == datetime(
2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC
)
assert process_timestamp(datetime_without_tzinfo) == datetime(
2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC
)
assert process_timestamp(datetime_est_timezone) == datetime(
2016, 7, 9, 15, 56, tzinfo=dt.UTC
)
assert process_timestamp(datetime_nst_timezone) == datetime(
2016, 7, 9, 14, 31, tzinfo=dt.UTC
)
assert process_timestamp(datetime_hst_timezone) == datetime(
2016, 7, 9, 21, 31, tzinfo=dt.UTC
)
assert process_timestamp(None) is None | [
"async",
"def",
"test_process_timestamp",
"(",
")",
":",
"datetime_with_tzinfo",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"datetime_without_tzinfo",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
")",
"est",
"=",
"pytz",
".",
"timezone",
"(",
"\"US/Eastern\"",
")",
"datetime_est_timezone",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"est",
")",
"nst",
"=",
"pytz",
".",
"timezone",
"(",
"\"Canada/Newfoundland\"",
")",
"datetime_nst_timezone",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"nst",
")",
"hst",
"=",
"pytz",
".",
"timezone",
"(",
"\"US/Hawaii\"",
")",
"datetime_hst_timezone",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"hst",
")",
"assert",
"process_timestamp",
"(",
"datetime_with_tzinfo",
")",
"==",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"assert",
"process_timestamp",
"(",
"datetime_without_tzinfo",
")",
"==",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"assert",
"process_timestamp",
"(",
"datetime_est_timezone",
")",
"==",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"15",
",",
"56",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"assert",
"process_timestamp",
"(",
"datetime_nst_timezone",
")",
"==",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"14",
",",
"31",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"assert",
"process_timestamp",
"(",
"datetime_hst_timezone",
")",
"==",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"21",
",",
"31",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"assert",
"process_timestamp",
"(",
"None",
")",
"is",
"None"
] | [
142,
0
] | [
168,
42
] | python | en | ['en', 'en', 'en'] | True |
test_process_timestamp_to_utc_isoformat | () | Test processing time stamp to UTC isoformat. | Test processing time stamp to UTC isoformat. | async def test_process_timestamp_to_utc_isoformat():
"""Test processing time stamp to UTC isoformat."""
datetime_with_tzinfo = datetime(2016, 7, 9, 11, 0, 0, tzinfo=dt.UTC)
datetime_without_tzinfo = datetime(2016, 7, 9, 11, 0, 0)
est = pytz.timezone("US/Eastern")
datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est)
est = pytz.timezone("US/Eastern")
datetime_est_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=est)
nst = pytz.timezone("Canada/Newfoundland")
datetime_nst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=nst)
hst = pytz.timezone("US/Hawaii")
datetime_hst_timezone = datetime(2016, 7, 9, 11, 0, 0, tzinfo=hst)
assert (
process_timestamp_to_utc_isoformat(datetime_with_tzinfo)
== "2016-07-09T11:00:00+00:00"
)
assert (
process_timestamp_to_utc_isoformat(datetime_without_tzinfo)
== "2016-07-09T11:00:00+00:00"
)
assert (
process_timestamp_to_utc_isoformat(datetime_est_timezone)
== "2016-07-09T15:56:00+00:00"
)
assert (
process_timestamp_to_utc_isoformat(datetime_nst_timezone)
== "2016-07-09T14:31:00+00:00"
)
assert (
process_timestamp_to_utc_isoformat(datetime_hst_timezone)
== "2016-07-09T21:31:00+00:00"
)
assert process_timestamp_to_utc_isoformat(None) is None | [
"async",
"def",
"test_process_timestamp_to_utc_isoformat",
"(",
")",
":",
"datetime_with_tzinfo",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"dt",
".",
"UTC",
")",
"datetime_without_tzinfo",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
")",
"est",
"=",
"pytz",
".",
"timezone",
"(",
"\"US/Eastern\"",
")",
"datetime_est_timezone",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"est",
")",
"est",
"=",
"pytz",
".",
"timezone",
"(",
"\"US/Eastern\"",
")",
"datetime_est_timezone",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"est",
")",
"nst",
"=",
"pytz",
".",
"timezone",
"(",
"\"Canada/Newfoundland\"",
")",
"datetime_nst_timezone",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"nst",
")",
"hst",
"=",
"pytz",
".",
"timezone",
"(",
"\"US/Hawaii\"",
")",
"datetime_hst_timezone",
"=",
"datetime",
"(",
"2016",
",",
"7",
",",
"9",
",",
"11",
",",
"0",
",",
"0",
",",
"tzinfo",
"=",
"hst",
")",
"assert",
"(",
"process_timestamp_to_utc_isoformat",
"(",
"datetime_with_tzinfo",
")",
"==",
"\"2016-07-09T11:00:00+00:00\"",
")",
"assert",
"(",
"process_timestamp_to_utc_isoformat",
"(",
"datetime_without_tzinfo",
")",
"==",
"\"2016-07-09T11:00:00+00:00\"",
")",
"assert",
"(",
"process_timestamp_to_utc_isoformat",
"(",
"datetime_est_timezone",
")",
"==",
"\"2016-07-09T15:56:00+00:00\"",
")",
"assert",
"(",
"process_timestamp_to_utc_isoformat",
"(",
"datetime_nst_timezone",
")",
"==",
"\"2016-07-09T14:31:00+00:00\"",
")",
"assert",
"(",
"process_timestamp_to_utc_isoformat",
"(",
"datetime_hst_timezone",
")",
"==",
"\"2016-07-09T21:31:00+00:00\"",
")",
"assert",
"process_timestamp_to_utc_isoformat",
"(",
"None",
")",
"is",
"None"
] | [
171,
0
] | [
204,
59
] | python | en | ['en', 'en', 'en'] | True |
test_event_to_db_model | () | Test we can round trip Event conversion. | Test we can round trip Event conversion. | async def test_event_to_db_model():
"""Test we can round trip Event conversion."""
event = ha.Event(
"state_changed", {"some": "attr"}, ha.EventOrigin.local, dt_util.utcnow()
)
native = Events.from_event(event).to_native()
assert native == event
native = Events.from_event(event, event_data="{}").to_native()
event.data = {}
assert native == event | [
"async",
"def",
"test_event_to_db_model",
"(",
")",
":",
"event",
"=",
"ha",
".",
"Event",
"(",
"\"state_changed\"",
",",
"{",
"\"some\"",
":",
"\"attr\"",
"}",
",",
"ha",
".",
"EventOrigin",
".",
"local",
",",
"dt_util",
".",
"utcnow",
"(",
")",
")",
"native",
"=",
"Events",
".",
"from_event",
"(",
"event",
")",
".",
"to_native",
"(",
")",
"assert",
"native",
"==",
"event",
"native",
"=",
"Events",
".",
"from_event",
"(",
"event",
",",
"event_data",
"=",
"\"{}\"",
")",
".",
"to_native",
"(",
")",
"event",
".",
"data",
"=",
"{",
"}",
"assert",
"native",
"==",
"event"
] | [
207,
0
] | [
217,
26
] | python | en | ['en', 'en', 'en'] | True |
async_setup | (hass, config) |
Ecobee uses config flow for configuration.
But, an "ecobee:" entry in configuration.yaml will trigger an import flow
if a config entry doesn't already exist. If ecobee.conf exists, the import
flow will attempt to import it and create a config entry, to assist users
migrating from the old ecobee component. Otherwise, the user will have to
continue setting up the integration via the config flow.
|
Ecobee uses config flow for configuration. | async def async_setup(hass, config):
"""
Ecobee uses config flow for configuration.
But, an "ecobee:" entry in configuration.yaml will trigger an import flow
if a config entry doesn't already exist. If ecobee.conf exists, the import
flow will attempt to import it and create a config entry, to assist users
migrating from the old ecobee component. Otherwise, the user will have to
continue setting up the integration via the config flow.
"""
hass.data[DATA_ECOBEE_CONFIG] = config.get(DOMAIN, {})
if not hass.config_entries.async_entries(DOMAIN) and hass.data[DATA_ECOBEE_CONFIG]:
# No config entry exists and configuration.yaml config exists, trigger the import flow.
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}
)
)
return True | [
"async",
"def",
"async_setup",
"(",
"hass",
",",
"config",
")",
":",
"hass",
".",
"data",
"[",
"DATA_ECOBEE_CONFIG",
"]",
"=",
"config",
".",
"get",
"(",
"DOMAIN",
",",
"{",
"}",
")",
"if",
"not",
"hass",
".",
"config_entries",
".",
"async_entries",
"(",
"DOMAIN",
")",
"and",
"hass",
".",
"data",
"[",
"DATA_ECOBEE_CONFIG",
"]",
":",
"# No config entry exists and configuration.yaml config exists, trigger the import flow.",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"flow",
".",
"async_init",
"(",
"DOMAIN",
",",
"context",
"=",
"{",
"\"source\"",
":",
"SOURCE_IMPORT",
"}",
")",
")",
"return",
"True"
] | [
27,
0
] | [
47,
15
] | python | en | ['en', 'error', 'th'] | False |
async_setup_entry | (hass, entry) | Set up ecobee via a config entry. | Set up ecobee via a config entry. | async def async_setup_entry(hass, entry):
"""Set up ecobee via a config entry."""
api_key = entry.data[CONF_API_KEY]
refresh_token = entry.data[CONF_REFRESH_TOKEN]
data = EcobeeData(hass, entry, api_key=api_key, refresh_token=refresh_token)
if not await data.refresh():
return False
await data.update()
if data.ecobee.thermostats is None:
_LOGGER.error("No ecobee devices found to set up")
return False
hass.data[DOMAIN] = data
for component in ECOBEE_PLATFORMS:
hass.async_create_task(
hass.config_entries.async_forward_entry_setup(entry, component)
)
return True | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
",",
"entry",
")",
":",
"api_key",
"=",
"entry",
".",
"data",
"[",
"CONF_API_KEY",
"]",
"refresh_token",
"=",
"entry",
".",
"data",
"[",
"CONF_REFRESH_TOKEN",
"]",
"data",
"=",
"EcobeeData",
"(",
"hass",
",",
"entry",
",",
"api_key",
"=",
"api_key",
",",
"refresh_token",
"=",
"refresh_token",
")",
"if",
"not",
"await",
"data",
".",
"refresh",
"(",
")",
":",
"return",
"False",
"await",
"data",
".",
"update",
"(",
")",
"if",
"data",
".",
"ecobee",
".",
"thermostats",
"is",
"None",
":",
"_LOGGER",
".",
"error",
"(",
"\"No ecobee devices found to set up\"",
")",
"return",
"False",
"hass",
".",
"data",
"[",
"DOMAIN",
"]",
"=",
"data",
"for",
"component",
"in",
"ECOBEE_PLATFORMS",
":",
"hass",
".",
"async_create_task",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_setup",
"(",
"entry",
",",
"component",
")",
")",
"return",
"True"
] | [
50,
0
] | [
73,
15
] | python | en | ['en', 'pt', 'en'] | True |
async_unload_entry | (hass, config_entry) | Unload the config entry and platforms. | Unload the config entry and platforms. | async def async_unload_entry(hass, config_entry):
"""Unload the config entry and platforms."""
hass.data.pop(DOMAIN)
tasks = []
for platform in ECOBEE_PLATFORMS:
tasks.append(
hass.config_entries.async_forward_entry_unload(config_entry, platform)
)
return all(await asyncio.gather(*tasks)) | [
"async",
"def",
"async_unload_entry",
"(",
"hass",
",",
"config_entry",
")",
":",
"hass",
".",
"data",
".",
"pop",
"(",
"DOMAIN",
")",
"tasks",
"=",
"[",
"]",
"for",
"platform",
"in",
"ECOBEE_PLATFORMS",
":",
"tasks",
".",
"append",
"(",
"hass",
".",
"config_entries",
".",
"async_forward_entry_unload",
"(",
"config_entry",
",",
"platform",
")",
")",
"return",
"all",
"(",
"await",
"asyncio",
".",
"gather",
"(",
"*",
"tasks",
")",
")"
] | [
117,
0
] | [
127,
44
] | python | en | ['en', 'en', 'en'] | True |
EcobeeData.__init__ | (self, hass, entry, api_key, refresh_token) | Initialize the Ecobee data object. | Initialize the Ecobee data object. | def __init__(self, hass, entry, api_key, refresh_token):
"""Initialize the Ecobee data object."""
self._hass = hass
self._entry = entry
self.ecobee = Ecobee(
config={ECOBEE_API_KEY: api_key, ECOBEE_REFRESH_TOKEN: refresh_token}
) | [
"def",
"__init__",
"(",
"self",
",",
"hass",
",",
"entry",
",",
"api_key",
",",
"refresh_token",
")",
":",
"self",
".",
"_hass",
"=",
"hass",
"self",
".",
"_entry",
"=",
"entry",
"self",
".",
"ecobee",
"=",
"Ecobee",
"(",
"config",
"=",
"{",
"ECOBEE_API_KEY",
":",
"api_key",
",",
"ECOBEE_REFRESH_TOKEN",
":",
"refresh_token",
"}",
")"
] | [
83,
4
] | [
89,
9
] | python | en | ['en', 'en', 'en'] | True |
EcobeeData.update | (self) | Get the latest data from ecobee.com. | Get the latest data from ecobee.com. | async def update(self):
"""Get the latest data from ecobee.com."""
try:
await self._hass.async_add_executor_job(self.ecobee.update)
_LOGGER.debug("Updating ecobee")
except ExpiredTokenError:
_LOGGER.debug("Refreshing expired ecobee tokens")
await self.refresh() | [
"async",
"def",
"update",
"(",
"self",
")",
":",
"try",
":",
"await",
"self",
".",
"_hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"ecobee",
".",
"update",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Updating ecobee\"",
")",
"except",
"ExpiredTokenError",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Refreshing expired ecobee tokens\"",
")",
"await",
"self",
".",
"refresh",
"(",
")"
] | [
92,
4
] | [
99,
32
] | python | en | ['en', 'en', 'en'] | True |
EcobeeData.refresh | (self) | Refresh ecobee tokens and update config entry. | Refresh ecobee tokens and update config entry. | async def refresh(self) -> bool:
"""Refresh ecobee tokens and update config entry."""
_LOGGER.debug("Refreshing ecobee tokens and updating config entry")
if await self._hass.async_add_executor_job(self.ecobee.refresh_tokens):
self._hass.config_entries.async_update_entry(
self._entry,
data={
CONF_API_KEY: self.ecobee.config[ECOBEE_API_KEY],
CONF_REFRESH_TOKEN: self.ecobee.config[ECOBEE_REFRESH_TOKEN],
},
)
return True
_LOGGER.error("Error refreshing ecobee tokens")
return False | [
"async",
"def",
"refresh",
"(",
"self",
")",
"->",
"bool",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Refreshing ecobee tokens and updating config entry\"",
")",
"if",
"await",
"self",
".",
"_hass",
".",
"async_add_executor_job",
"(",
"self",
".",
"ecobee",
".",
"refresh_tokens",
")",
":",
"self",
".",
"_hass",
".",
"config_entries",
".",
"async_update_entry",
"(",
"self",
".",
"_entry",
",",
"data",
"=",
"{",
"CONF_API_KEY",
":",
"self",
".",
"ecobee",
".",
"config",
"[",
"ECOBEE_API_KEY",
"]",
",",
"CONF_REFRESH_TOKEN",
":",
"self",
".",
"ecobee",
".",
"config",
"[",
"ECOBEE_REFRESH_TOKEN",
"]",
",",
"}",
",",
")",
"return",
"True",
"_LOGGER",
".",
"error",
"(",
"\"Error refreshing ecobee tokens\"",
")",
"return",
"False"
] | [
101,
4
] | [
114,
20
] | python | en | ['en', 'en', 'en'] | True |
MultiAgentWrapper.load_model | (self, model_dict: dict) | Load models from memory for each agent. | Load models from memory for each agent. | def load_model(self, model_dict: dict):
"""Load models from memory for each agent."""
for agent_id, model in model_dict.items():
self.agent_dict[agent_id].load_model(model) | [
"def",
"load_model",
"(",
"self",
",",
"model_dict",
":",
"dict",
")",
":",
"for",
"agent_id",
",",
"model",
"in",
"model_dict",
".",
"items",
"(",
")",
":",
"self",
".",
"agent_dict",
"[",
"agent_id",
"]",
".",
"load_model",
"(",
"model",
")"
] | [
28,
4
] | [
31,
55
] | python | en | ['en', 'en', 'en'] | True |
MultiAgentWrapper.dump_model | (self, agent_ids: Union[str, List[str]] = None) | Get agents' underlying models.
This is usually used in distributed mode where models need to be broadcast to remote roll-out actors.
| Get agents' underlying models. | def dump_model(self, agent_ids: Union[str, List[str]] = None):
"""Get agents' underlying models.
This is usually used in distributed mode where models need to be broadcast to remote roll-out actors.
"""
if agent_ids is None:
return {agent_id: agent.dump_model() for agent_id, agent in self.agent_dict.items()}
elif isinstance(agent_ids, str):
return self.agent_dict[agent_ids].dump_model()
else:
return {agent_id: self.agent_dict[agent_id].dump_model() for agent_id in self.agent_dict} | [
"def",
"dump_model",
"(",
"self",
",",
"agent_ids",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
":",
"if",
"agent_ids",
"is",
"None",
":",
"return",
"{",
"agent_id",
":",
"agent",
".",
"dump_model",
"(",
")",
"for",
"agent_id",
",",
"agent",
"in",
"self",
".",
"agent_dict",
".",
"items",
"(",
")",
"}",
"elif",
"isinstance",
"(",
"agent_ids",
",",
"str",
")",
":",
"return",
"self",
".",
"agent_dict",
"[",
"agent_ids",
"]",
".",
"dump_model",
"(",
")",
"else",
":",
"return",
"{",
"agent_id",
":",
"self",
".",
"agent_dict",
"[",
"agent_id",
"]",
".",
"dump_model",
"(",
")",
"for",
"agent_id",
"in",
"self",
".",
"agent_dict",
"}"
] | [
33,
4
] | [
43,
101
] | python | en | ['en', 'da', 'en'] | True |
MultiAgentWrapper.load_model_from_file | (self, dir_path) | Load models from disk for each agent. | Load models from disk for each agent. | def load_model_from_file(self, dir_path):
"""Load models from disk for each agent."""
for agent_id, agent in self.agent_dict.items():
agent.load_model_from_file(os.path.join(dir_path, agent_id)) | [
"def",
"load_model_from_file",
"(",
"self",
",",
"dir_path",
")",
":",
"for",
"agent_id",
",",
"agent",
"in",
"self",
".",
"agent_dict",
".",
"items",
"(",
")",
":",
"agent",
".",
"load_model_from_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"agent_id",
")",
")"
] | [
45,
4
] | [
48,
72
] | python | en | ['en', 'en', 'en'] | True |
MultiAgentWrapper.dump_model_to_file | (self, dir_path: str, agent_ids: Union[str, List[str]] = None) | Dump agents' models to disk.
Each agent will use its own name to create a separate file under ``dir_path`` for dumping.
| Dump agents' models to disk. | def dump_model_to_file(self, dir_path: str, agent_ids: Union[str, List[str]] = None):
"""Dump agents' models to disk.
Each agent will use its own name to create a separate file under ``dir_path`` for dumping.
"""
os.makedirs(dir_path, exist_ok=True)
if agent_ids is None:
for agent_id, agent in self.agent_dict.items():
agent.dump_model_to_file(os.path.join(dir_path, agent_id))
elif isinstance(agent_ids, str):
self.agent_dict[agent_ids].dump_model_to_file(os.path.join(dir_path, agent_ids))
else:
for agent_id in agent_ids:
self.agent_dict[agent_id].dump_model_to_file(os.path.join(dir_path, agent_id)) | [
"def",
"dump_model_to_file",
"(",
"self",
",",
"dir_path",
":",
"str",
",",
"agent_ids",
":",
"Union",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
":",
"os",
".",
"makedirs",
"(",
"dir_path",
",",
"exist_ok",
"=",
"True",
")",
"if",
"agent_ids",
"is",
"None",
":",
"for",
"agent_id",
",",
"agent",
"in",
"self",
".",
"agent_dict",
".",
"items",
"(",
")",
":",
"agent",
".",
"dump_model_to_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"agent_id",
")",
")",
"elif",
"isinstance",
"(",
"agent_ids",
",",
"str",
")",
":",
"self",
".",
"agent_dict",
"[",
"agent_ids",
"]",
".",
"dump_model_to_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"agent_ids",
")",
")",
"else",
":",
"for",
"agent_id",
"in",
"agent_ids",
":",
"self",
".",
"agent_dict",
"[",
"agent_id",
"]",
".",
"dump_model_to_file",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_path",
",",
"agent_id",
")",
")"
] | [
50,
4
] | [
63,
94
] | python | en | ['en', 'da', 'en'] | True |
test_services | (hass, config_entry, aioclient_mock_fixture, aioclient_mock) | Test Flo services. | Test Flo services. | async def test_services(hass, config_entry, aioclient_mock_fixture, aioclient_mock):
"""Test Flo services."""
config_entry.add_to_hass(hass)
assert await async_setup_component(
hass, FLO_DOMAIN, {CONF_USERNAME: TEST_USER_ID, CONF_PASSWORD: TEST_PASSWORD}
)
await hass.async_block_till_done()
assert len(hass.data[FLO_DOMAIN][config_entry.entry_id]["devices"]) == 1
assert aioclient_mock.call_count == 4
await hass.services.async_call(
FLO_DOMAIN,
SERVICE_RUN_HEALTH_TEST,
{ATTR_ENTITY_ID: SWITCH_ENTITY_ID},
blocking=True,
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 5
await hass.services.async_call(
FLO_DOMAIN,
SERVICE_SET_AWAY_MODE,
{ATTR_ENTITY_ID: SWITCH_ENTITY_ID},
blocking=True,
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 6
await hass.services.async_call(
FLO_DOMAIN,
SERVICE_SET_HOME_MODE,
{ATTR_ENTITY_ID: SWITCH_ENTITY_ID},
blocking=True,
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 7
await hass.services.async_call(
FLO_DOMAIN,
SERVICE_SET_SLEEP_MODE,
{
ATTR_ENTITY_ID: SWITCH_ENTITY_ID,
ATTR_REVERT_TO_MODE: SYSTEM_MODE_HOME,
ATTR_SLEEP_MINUTES: 120,
},
blocking=True,
)
await hass.async_block_till_done()
assert aioclient_mock.call_count == 8 | [
"async",
"def",
"test_services",
"(",
"hass",
",",
"config_entry",
",",
"aioclient_mock_fixture",
",",
"aioclient_mock",
")",
":",
"config_entry",
".",
"add_to_hass",
"(",
"hass",
")",
"assert",
"await",
"async_setup_component",
"(",
"hass",
",",
"FLO_DOMAIN",
",",
"{",
"CONF_USERNAME",
":",
"TEST_USER_ID",
",",
"CONF_PASSWORD",
":",
"TEST_PASSWORD",
"}",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"len",
"(",
"hass",
".",
"data",
"[",
"FLO_DOMAIN",
"]",
"[",
"config_entry",
".",
"entry_id",
"]",
"[",
"\"devices\"",
"]",
")",
"==",
"1",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"4",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"FLO_DOMAIN",
",",
"SERVICE_RUN_HEALTH_TEST",
",",
"{",
"ATTR_ENTITY_ID",
":",
"SWITCH_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"5",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"FLO_DOMAIN",
",",
"SERVICE_SET_AWAY_MODE",
",",
"{",
"ATTR_ENTITY_ID",
":",
"SWITCH_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"6",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"FLO_DOMAIN",
",",
"SERVICE_SET_HOME_MODE",
",",
"{",
"ATTR_ENTITY_ID",
":",
"SWITCH_ENTITY_ID",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"7",
"await",
"hass",
".",
"services",
".",
"async_call",
"(",
"FLO_DOMAIN",
",",
"SERVICE_SET_SLEEP_MODE",
",",
"{",
"ATTR_ENTITY_ID",
":",
"SWITCH_ENTITY_ID",
",",
"ATTR_REVERT_TO_MODE",
":",
"SYSTEM_MODE_HOME",
",",
"ATTR_SLEEP_MINUTES",
":",
"120",
",",
"}",
",",
"blocking",
"=",
"True",
",",
")",
"await",
"hass",
".",
"async_block_till_done",
"(",
")",
"assert",
"aioclient_mock",
".",
"call_count",
"==",
"8"
] | [
19,
0
] | [
68,
41
] | python | en | ['it', 'fr', 'en'] | False |
setup_platform | (hass, config, add_entities, discovery_info=None) | Set up the file size sensor. | Set up the file size sensor. | def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the file size sensor."""
setup_reload_service(hass, DOMAIN, PLATFORMS)
sensors = []
for path in config.get(CONF_FILE_PATHS):
if not hass.config.is_allowed_path(path):
_LOGGER.error("Filepath %s is not valid or allowed", path)
continue
sensors.append(Filesize(path))
if sensors:
add_entities(sensors, True) | [
"def",
"setup_platform",
"(",
"hass",
",",
"config",
",",
"add_entities",
",",
"discovery_info",
"=",
"None",
")",
":",
"setup_reload_service",
"(",
"hass",
",",
"DOMAIN",
",",
"PLATFORMS",
")",
"sensors",
"=",
"[",
"]",
"for",
"path",
"in",
"config",
".",
"get",
"(",
"CONF_FILE_PATHS",
")",
":",
"if",
"not",
"hass",
".",
"config",
".",
"is_allowed_path",
"(",
"path",
")",
":",
"_LOGGER",
".",
"error",
"(",
"\"Filepath %s is not valid or allowed\"",
",",
"path",
")",
"continue",
"sensors",
".",
"append",
"(",
"Filesize",
"(",
"path",
")",
")",
"if",
"sensors",
":",
"add_entities",
"(",
"sensors",
",",
"True",
")"
] | [
26,
0
] | [
39,
35
] | python | en | ['en', 'da', 'en'] | True |
Filesize.__init__ | (self, path) | Initialize the data object. | Initialize the data object. | def __init__(self, path):
"""Initialize the data object."""
self._path = path # Need to check its a valid path
self._size = None
self._last_updated = None
self._name = path.split("/")[-1]
self._unit_of_measurement = DATA_MEGABYTES | [
"def",
"__init__",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"_path",
"=",
"path",
"# Need to check its a valid path",
"self",
".",
"_size",
"=",
"None",
"self",
".",
"_last_updated",
"=",
"None",
"self",
".",
"_name",
"=",
"path",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"self",
".",
"_unit_of_measurement",
"=",
"DATA_MEGABYTES"
] | [
45,
4
] | [
51,
50
] | python | en | ['en', 'en', 'en'] | True |
Filesize.update | (self) | Update the sensor. | Update the sensor. | def update(self):
"""Update the sensor."""
statinfo = os.stat(self._path)
self._size = statinfo.st_size
last_updated = datetime.datetime.fromtimestamp(statinfo.st_mtime)
self._last_updated = last_updated.isoformat() | [
"def",
"update",
"(",
"self",
")",
":",
"statinfo",
"=",
"os",
".",
"stat",
"(",
"self",
".",
"_path",
")",
"self",
".",
"_size",
"=",
"statinfo",
".",
"st_size",
"last_updated",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"statinfo",
".",
"st_mtime",
")",
"self",
".",
"_last_updated",
"=",
"last_updated",
".",
"isoformat",
"(",
")"
] | [
53,
4
] | [
58,
53
] | python | en | ['en', 'nl', 'en'] | True |
Filesize.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"
] | [
61,
4
] | [
63,
25
] | python | en | ['en', 'mi', 'en'] | True |
Filesize.state | (self) | Return the size of the file in MB. | Return the size of the file in MB. | def state(self):
"""Return the size of the file in MB."""
decimals = 2
state_mb = round(self._size / 1e6, decimals)
return state_mb | [
"def",
"state",
"(",
"self",
")",
":",
"decimals",
"=",
"2",
"state_mb",
"=",
"round",
"(",
"self",
".",
"_size",
"/",
"1e6",
",",
"decimals",
")",
"return",
"state_mb"
] | [
66,
4
] | [
70,
23
] | python | en | ['en', 'en', 'en'] | True |
Filesize.icon | (self) | Icon to use in the frontend, if any. | Icon to use in the frontend, if any. | def icon(self):
"""Icon to use in the frontend, if any."""
return ICON | [
"def",
"icon",
"(",
"self",
")",
":",
"return",
"ICON"
] | [
73,
4
] | [
75,
19
] | python | en | ['en', 'en', 'en'] | True |
Filesize.device_state_attributes | (self) | Return other details about the sensor state. | Return other details about the sensor state. | def device_state_attributes(self):
"""Return other details about the sensor state."""
return {
"path": self._path,
"last_updated": self._last_updated,
"bytes": self._size,
} | [
"def",
"device_state_attributes",
"(",
"self",
")",
":",
"return",
"{",
"\"path\"",
":",
"self",
".",
"_path",
",",
"\"last_updated\"",
":",
"self",
".",
"_last_updated",
",",
"\"bytes\"",
":",
"self",
".",
"_size",
",",
"}"
] | [
78,
4
] | [
84,
9
] | python | en | ['en', 'en', 'en'] | True |
Filesize.unit_of_measurement | (self) | Return the unit of measurement of this entity, if any. | Return the unit of measurement of this entity, if any. | def unit_of_measurement(self):
"""Return the unit of measurement of this entity, if any."""
return self._unit_of_measurement | [
"def",
"unit_of_measurement",
"(",
"self",
")",
":",
"return",
"self",
".",
"_unit_of_measurement"
] | [
87,
4
] | [
89,
40
] | python | en | ['en', 'en', 'en'] | True |
get_service | (hass, config, discovery_info=None) | Get the CiscoWebexTeams notification service. | Get the CiscoWebexTeams notification service. | def get_service(hass, config, discovery_info=None):
"""Get the CiscoWebexTeams notification service."""
client = WebexTeamsAPI(access_token=config[CONF_TOKEN])
try:
# Validate the token & room_id
client.rooms.get(config[CONF_ROOM_ID])
except exceptions.ApiError as error:
_LOGGER.error(error)
return None
return CiscoWebexTeamsNotificationService(client, config[CONF_ROOM_ID]) | [
"def",
"get_service",
"(",
"hass",
",",
"config",
",",
"discovery_info",
"=",
"None",
")",
":",
"client",
"=",
"WebexTeamsAPI",
"(",
"access_token",
"=",
"config",
"[",
"CONF_TOKEN",
"]",
")",
"try",
":",
"# Validate the token & room_id",
"client",
".",
"rooms",
".",
"get",
"(",
"config",
"[",
"CONF_ROOM_ID",
"]",
")",
"except",
"exceptions",
".",
"ApiError",
"as",
"error",
":",
"_LOGGER",
".",
"error",
"(",
"error",
")",
"return",
"None",
"return",
"CiscoWebexTeamsNotificationService",
"(",
"client",
",",
"config",
"[",
"CONF_ROOM_ID",
"]",
")"
] | [
23,
0
] | [
34,
75
] | python | en | ['en', 'es', 'en'] | True |
CiscoWebexTeamsNotificationService.__init__ | (self, client, room) | Initialize the service. | Initialize the service. | def __init__(self, client, room):
"""Initialize the service."""
self.room = room
self.client = client | [
"def",
"__init__",
"(",
"self",
",",
"client",
",",
"room",
")",
":",
"self",
".",
"room",
"=",
"room",
"self",
".",
"client",
"=",
"client"
] | [
40,
4
] | [
43,
28
] | python | en | ['en', 'en', 'en'] | True |
CiscoWebexTeamsNotificationService.send_message | (self, message="", **kwargs) | Send a message to a user. | Send a message to a user. | def send_message(self, message="", **kwargs):
"""Send a message to a user."""
title = ""
if kwargs.get(ATTR_TITLE) is not None:
title = f"{kwargs.get(ATTR_TITLE)}<br>"
try:
self.client.messages.create(roomId=self.room, html=f"{title}{message}")
except ApiError as api_error:
_LOGGER.error(
"Could not send CiscoWebexTeams notification. Error: %s", api_error
) | [
"def",
"send_message",
"(",
"self",
",",
"message",
"=",
"\"\"",
",",
"*",
"*",
"kwargs",
")",
":",
"title",
"=",
"\"\"",
"if",
"kwargs",
".",
"get",
"(",
"ATTR_TITLE",
")",
"is",
"not",
"None",
":",
"title",
"=",
"f\"{kwargs.get(ATTR_TITLE)}<br>\"",
"try",
":",
"self",
".",
"client",
".",
"messages",
".",
"create",
"(",
"roomId",
"=",
"self",
".",
"room",
",",
"html",
"=",
"f\"{title}{message}\"",
")",
"except",
"ApiError",
"as",
"api_error",
":",
"_LOGGER",
".",
"error",
"(",
"\"Could not send CiscoWebexTeams notification. Error: %s\"",
",",
"api_error",
")"
] | [
45,
4
] | [
57,
13
] | python | en | ['en', 'en', 'en'] | True |
wsdiscovery | () | Get ONVIF Profile S devices from network. | Get ONVIF Profile S devices from network. | def wsdiscovery() -> List[Service]:
"""Get ONVIF Profile S devices from network."""
discovery = WSDiscovery(ttl=4)
discovery.start()
services = discovery.searchServices(
scopes=[Scope("onvif://www.onvif.org/Profile/Streaming")]
)
discovery.stop()
return services | [
"def",
"wsdiscovery",
"(",
")",
"->",
"List",
"[",
"Service",
"]",
":",
"discovery",
"=",
"WSDiscovery",
"(",
"ttl",
"=",
"4",
")",
"discovery",
".",
"start",
"(",
")",
"services",
"=",
"discovery",
".",
"searchServices",
"(",
"scopes",
"=",
"[",
"Scope",
"(",
"\"onvif://www.onvif.org/Profile/Streaming\"",
")",
"]",
")",
"discovery",
".",
"stop",
"(",
")",
"return",
"services"
] | [
38,
0
] | [
46,
19
] | python | en | ['en', 'en', 'en'] | True |
async_discovery | (hass) | Return if there are devices that can be discovered. | Return if there are devices that can be discovered. | async def async_discovery(hass) -> bool:
"""Return if there are devices that can be discovered."""
LOGGER.debug("Starting ONVIF discovery...")
services = await hass.async_add_executor_job(wsdiscovery)
devices = []
for service in services:
url = urlparse(service.getXAddrs()[0])
device = {
CONF_DEVICE_ID: None,
CONF_NAME: service.getEPR(),
CONF_HOST: url.hostname,
CONF_PORT: url.port or 80,
}
for scope in service.getScopes():
scope_str = scope.getValue()
if scope_str.lower().startswith("onvif://www.onvif.org/name"):
device[CONF_NAME] = scope_str.split("/")[-1]
if scope_str.lower().startswith("onvif://www.onvif.org/mac"):
device[CONF_DEVICE_ID] = scope_str.split("/")[-1]
devices.append(device)
return devices | [
"async",
"def",
"async_discovery",
"(",
"hass",
")",
"->",
"bool",
":",
"LOGGER",
".",
"debug",
"(",
"\"Starting ONVIF discovery...\"",
")",
"services",
"=",
"await",
"hass",
".",
"async_add_executor_job",
"(",
"wsdiscovery",
")",
"devices",
"=",
"[",
"]",
"for",
"service",
"in",
"services",
":",
"url",
"=",
"urlparse",
"(",
"service",
".",
"getXAddrs",
"(",
")",
"[",
"0",
"]",
")",
"device",
"=",
"{",
"CONF_DEVICE_ID",
":",
"None",
",",
"CONF_NAME",
":",
"service",
".",
"getEPR",
"(",
")",
",",
"CONF_HOST",
":",
"url",
".",
"hostname",
",",
"CONF_PORT",
":",
"url",
".",
"port",
"or",
"80",
",",
"}",
"for",
"scope",
"in",
"service",
".",
"getScopes",
"(",
")",
":",
"scope_str",
"=",
"scope",
".",
"getValue",
"(",
")",
"if",
"scope_str",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"onvif://www.onvif.org/name\"",
")",
":",
"device",
"[",
"CONF_NAME",
"]",
"=",
"scope_str",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"if",
"scope_str",
".",
"lower",
"(",
")",
".",
"startswith",
"(",
"\"onvif://www.onvif.org/mac\"",
")",
":",
"device",
"[",
"CONF_DEVICE_ID",
"]",
"=",
"scope_str",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"devices",
".",
"append",
"(",
"device",
")",
"return",
"devices"
] | [
49,
0
] | [
71,
18
] | python | en | ['en', 'en', 'en'] | True |
OnvifFlowHandler.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 OnvifOptionsFlowHandler(config_entry) | [
"def",
"async_get_options_flow",
"(",
"config_entry",
")",
":",
"return",
"OnvifOptionsFlowHandler",
"(",
"config_entry",
")"
] | [
82,
4
] | [
84,
52
] | python | en | ['en', 'en', 'en'] | True |
OnvifFlowHandler.__init__ | (self) | Initialize the ONVIF config flow. | Initialize the ONVIF config flow. | def __init__(self):
"""Initialize the ONVIF config flow."""
self.device_id = None
self.devices = []
self.onvif_config = {} | [
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"device_id",
"=",
"None",
"self",
".",
"devices",
"=",
"[",
"]",
"self",
".",
"onvif_config",
"=",
"{",
"}"
] | [
86,
4
] | [
90,
30
] | python | en | ['en', 'en', 'en'] | True |
OnvifFlowHandler.async_step_user | (self, user_input=None) | Handle user flow. | Handle user flow. | async def async_step_user(self, user_input=None):
"""Handle user flow."""
if user_input is not None:
return await self.async_step_device()
return self.async_show_form(step_id="user") | [
"async",
"def",
"async_step_user",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
"is",
"not",
"None",
":",
"return",
"await",
"self",
".",
"async_step_device",
"(",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"user\"",
")"
] | [
92,
4
] | [
97,
51
] | python | da | ['da', 'nl', 'en'] | False |
OnvifFlowHandler.async_step_device | (self, user_input=None) | Handle WS-Discovery.
Let user choose between discovered devices and manual configuration.
If no device is found allow user to manually input configuration.
| Handle WS-Discovery. | async def async_step_device(self, user_input=None):
"""Handle WS-Discovery.
Let user choose between discovered devices and manual configuration.
If no device is found allow user to manually input configuration.
"""
if user_input:
if CONF_MANUAL_INPUT == user_input[CONF_HOST]:
return await self.async_step_manual_input()
for device in self.devices:
name = f"{device[CONF_NAME]} ({device[CONF_HOST]})"
if name == user_input[CONF_HOST]:
self.device_id = device[CONF_DEVICE_ID]
self.onvif_config = {
CONF_NAME: device[CONF_NAME],
CONF_HOST: device[CONF_HOST],
CONF_PORT: device[CONF_PORT],
}
return await self.async_step_auth()
discovery = await async_discovery(self.hass)
for device in discovery:
configured = any(
entry.unique_id == device[CONF_DEVICE_ID]
for entry in self._async_current_entries()
)
if not configured:
self.devices.append(device)
LOGGER.debug("Discovered ONVIF devices %s", pformat(self.devices))
if self.devices:
names = [
f"{device[CONF_NAME]} ({device[CONF_HOST]})" for device in self.devices
]
names.append(CONF_MANUAL_INPUT)
return self.async_show_form(
step_id="device",
data_schema=vol.Schema({vol.Optional(CONF_HOST): vol.In(names)}),
)
return await self.async_step_manual_input() | [
"async",
"def",
"async_step_device",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
":",
"if",
"CONF_MANUAL_INPUT",
"==",
"user_input",
"[",
"CONF_HOST",
"]",
":",
"return",
"await",
"self",
".",
"async_step_manual_input",
"(",
")",
"for",
"device",
"in",
"self",
".",
"devices",
":",
"name",
"=",
"f\"{device[CONF_NAME]} ({device[CONF_HOST]})\"",
"if",
"name",
"==",
"user_input",
"[",
"CONF_HOST",
"]",
":",
"self",
".",
"device_id",
"=",
"device",
"[",
"CONF_DEVICE_ID",
"]",
"self",
".",
"onvif_config",
"=",
"{",
"CONF_NAME",
":",
"device",
"[",
"CONF_NAME",
"]",
",",
"CONF_HOST",
":",
"device",
"[",
"CONF_HOST",
"]",
",",
"CONF_PORT",
":",
"device",
"[",
"CONF_PORT",
"]",
",",
"}",
"return",
"await",
"self",
".",
"async_step_auth",
"(",
")",
"discovery",
"=",
"await",
"async_discovery",
"(",
"self",
".",
"hass",
")",
"for",
"device",
"in",
"discovery",
":",
"configured",
"=",
"any",
"(",
"entry",
".",
"unique_id",
"==",
"device",
"[",
"CONF_DEVICE_ID",
"]",
"for",
"entry",
"in",
"self",
".",
"_async_current_entries",
"(",
")",
")",
"if",
"not",
"configured",
":",
"self",
".",
"devices",
".",
"append",
"(",
"device",
")",
"LOGGER",
".",
"debug",
"(",
"\"Discovered ONVIF devices %s\"",
",",
"pformat",
"(",
"self",
".",
"devices",
")",
")",
"if",
"self",
".",
"devices",
":",
"names",
"=",
"[",
"f\"{device[CONF_NAME]} ({device[CONF_HOST]})\"",
"for",
"device",
"in",
"self",
".",
"devices",
"]",
"names",
".",
"append",
"(",
"CONF_MANUAL_INPUT",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"device\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Optional",
"(",
"CONF_HOST",
")",
":",
"vol",
".",
"In",
"(",
"names",
")",
"}",
")",
",",
")",
"return",
"await",
"self",
".",
"async_step_manual_input",
"(",
")"
] | [
99,
4
] | [
145,
51
] | python | en | ['en', 'en', 'en'] | False |
OnvifFlowHandler.async_step_manual_input | (self, user_input=None) | Manual configuration. | Manual configuration. | async def async_step_manual_input(self, user_input=None):
"""Manual configuration."""
if user_input:
self.onvif_config = user_input
return await self.async_step_auth()
return self.async_show_form(
step_id="manual_input",
data_schema=vol.Schema(
{
vol.Required(CONF_NAME): str,
vol.Required(CONF_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
}
),
) | [
"async",
"def",
"async_step_manual_input",
"(",
"self",
",",
"user_input",
"=",
"None",
")",
":",
"if",
"user_input",
":",
"self",
".",
"onvif_config",
"=",
"user_input",
"return",
"await",
"self",
".",
"async_step_auth",
"(",
")",
"return",
"self",
".",
"async_show_form",
"(",
"step_id",
"=",
"\"manual_input\"",
",",
"data_schema",
"=",
"vol",
".",
"Schema",
"(",
"{",
"vol",
".",
"Required",
"(",
"CONF_NAME",
")",
":",
"str",
",",
"vol",
".",
"Required",
"(",
"CONF_HOST",
")",
":",
"str",
",",
"vol",
".",
"Required",
"(",
"CONF_PORT",
",",
"default",
"=",
"DEFAULT_PORT",
")",
":",
"int",
",",
"}",
")",
",",
")"
] | [
147,
4
] | [
162,
9
] | python | en | ['en', 'sm', 'en'] | False |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.